From a92a1eb29af784def26199151a400a499739fcac Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 13 Sep 2026 17:29:51 -0700 Subject: [PATCH 01/40] feat(browser): process-wide browser identity, chosen before ready Electron resolves worker identity from a single process-global default, so two coherent identities cannot coexist in one process. This makes clean/native one app-wide decision read before `ready`, instead of a per-profile one that leaves documents on one identity and every worker request on the other. Both identities are load-bearing, measured across four origins at five reps: the cleaned identity clears an embedded Turnstile widget and WhatsApp's browser check where native is refused; native clears a full-page Cloudflare interstitial that the cleaned identity never clears. Base commit only: removing the per-profile field, its settings surface, and the migration notice follow. --- .../browser/browser-identity-mode-record.ts | 75 +++ .../browser/browser-process-user-agent.ts | 50 ++ .../browser-session-ua-cdp-collector.ts | 252 ++++++++ ...ession-ua-cloudflare-live.electron.test.ts | 402 ++++++++++++ ...-session-ua-wire-identity.electron.test.ts | 604 ++++++++++++------ .../browser-session-ua-wire-probe-server.ts | 256 ++++++++ 6 files changed, 1429 insertions(+), 210 deletions(-) create mode 100644 src/main/browser/browser-identity-mode-record.ts create mode 100644 src/main/browser/browser-process-user-agent.ts create mode 100644 src/main/browser/browser-session-ua-cdp-collector.ts create mode 100644 src/main/browser/browser-session-ua-cloudflare-live.electron.test.ts create mode 100644 src/main/browser/browser-session-ua-wire-probe-server.ts diff --git a/src/main/browser/browser-identity-mode-record.ts b/src/main/browser/browser-identity-mode-record.ts new file mode 100644 index 000000000000..67459dd48d2f --- /dev/null +++ b/src/main/browser/browser-identity-mode-record.ts @@ -0,0 +1,75 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { writeFileAtomically } from '../codex-accounts/fs-utils' +import type { BrowserSessionUserAgentMode } from '../../shared/browser-workspace-types' + +/** + * The browser's identity is one process-wide decision, not a per-profile one. + * + * Electron resolves worker identity from a single process-global default, so two coherent + * identities cannot coexist in one process: a per-profile native mode leaves documents on one + * identity and every worker request on the other, which is a sharper bot signal than either + * alone. The choice therefore lives here, is read before `ready`, and applies to the whole app. + * + * Both identities are load-bearing, which is why this is a choice and not a constant. Measured + * across four origins, five repetitions each: the cleaned identity clears an embedded Turnstile + * widget and WhatsApp's browser check while the native identity is refused by both; the native + * identity clears a full-page Cloudflare interstitial that the cleaned identity never clears. + * + * Read with `readFileSync` rather than through the settings store because the store loads long + * after `ready`, and by then every session and worker has already taken its default. + */ +export const BROWSER_IDENTITY_MODE_FILE = 'browser-identity-mode.json' +export const BROWSER_IDENTITY_MODE_VERSION = 1 + +export type BrowserIdentityModeRecord = { + version: typeof BROWSER_IDENTITY_MODE_VERSION + mode: BrowserSessionUserAgentMode + /** Profiles that carried the retired per-profile `native` mode, so the browser can say so once. */ + migratedNativeProfileIds?: string[] + /** Cleared once the user has been told their per-profile choice no longer exists. */ + migrationNoticePending?: boolean +} + +export function browserIdentityModeRecordPath(userDataPath: string): string { + return join(userDataPath, BROWSER_IDENTITY_MODE_FILE) +} + +function parseRecord(raw: string): BrowserIdentityModeRecord | null { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: JSON.parse is untyped; every member is checked below and an unrecognised shape returns null. + const parsed = JSON.parse(raw) as Partial + if (parsed.version !== BROWSER_IDENTITY_MODE_VERSION) { + return null + } + if (parsed.mode !== 'clean' && parsed.mode !== 'native') { + return null + } + return { + version: BROWSER_IDENTITY_MODE_VERSION, + mode: parsed.mode, + migratedNativeProfileIds: Array.isArray(parsed.migratedNativeProfileIds) + ? parsed.migratedNativeProfileIds.filter((id): id is string => typeof id === 'string') + : undefined, + migrationNoticePending: parsed.migrationNoticePending === true ? true : undefined + } +} + +/** Absent, unreadable, or unrecognised all mean `clean` — the default that keeps imported cookies alive. */ +export function readBrowserIdentityModeRecord(userDataPath: string): BrowserIdentityModeRecord { + try { + const parsed = parseRecord(readFileSync(browserIdentityModeRecordPath(userDataPath), 'utf-8')) + return parsed ?? { version: BROWSER_IDENTITY_MODE_VERSION, mode: 'clean' } + } catch { + return { version: BROWSER_IDENTITY_MODE_VERSION, mode: 'clean' } + } +} + +export function writeBrowserIdentityModeRecord( + userDataPath: string, + record: BrowserIdentityModeRecord +): void { + writeFileAtomically( + browserIdentityModeRecordPath(userDataPath), + `${JSON.stringify(record, null, 2)}\n` + ) +} diff --git a/src/main/browser/browser-process-user-agent.ts b/src/main/browser/browser-process-user-agent.ts new file mode 100644 index 000000000000..ed1af68a3ba5 --- /dev/null +++ b/src/main/browser/browser-process-user-agent.ts @@ -0,0 +1,50 @@ +import { app } from 'electron' +import type { BrowserSessionUserAgentMode } from '../../shared/browser-workspace-types' + +export type BrowserProcessUserAgentIdentity = Readonly<{ + mode: BrowserSessionUserAgentMode + /** What every document, frame and worker in this process presents. */ + userAgent: string +}> + +let identity: BrowserProcessUserAgentIdentity | null = null + +// Why: Electron's default includes its runtime and app tokens, which invalidate Chrome-imported sessions. +export function cleanElectronUserAgent(userAgent: string): string { + return userAgent.replace(/\s+Electron\/\S+/, '').replace(/(\)\s+)\S+\s+(Chrome\/)/, '$1$2') +} + +/** + * Fix the whole process's browser identity before anything can read it. + * + * `app.userAgentFallback` is the one default every renderer, frame and worker inherits, so this + * must land before `ready`: a session or WebContents created first keeps the old value, and + * workers would then disagree with documents. `native` deliberately leaves the fallback alone + * rather than assigning the raw string back, so the engine keeps its own untouched default. + */ +export function initializeBrowserProcessUserAgent( + mode: BrowserSessionUserAgentMode +): BrowserProcessUserAgentIdentity { + if (identity) { + throw new Error('Browser process user agent was already initialized') + } + if (app.isReady()) { + throw new Error('Browser process user agent must be initialized before Electron readiness') + } + if (mode === 'clean') { + app.userAgentFallback = cleanElectronUserAgent(app.userAgentFallback) + } + identity = Object.freeze({ mode, userAgent: app.userAgentFallback }) + return identity +} + +export function getBrowserProcessUserAgentIdentity(): BrowserProcessUserAgentIdentity { + if (!identity) { + throw new Error('Browser process user agent is not initialized') + } + return identity +} + +export function resetBrowserProcessUserAgentForTests(): void { + identity = null +} diff --git a/src/main/browser/browser-session-ua-cdp-collector.ts b/src/main/browser/browser-session-ua-cdp-collector.ts new file mode 100644 index 000000000000..7df8e5afe551 --- /dev/null +++ b/src/main/browser/browser-session-ua-cdp-collector.ts @@ -0,0 +1,252 @@ +import WebSocket from 'ws' +import { cancelUnreadResponseBody } from '../lib/unread-response-body' + +export type BrowserSessionUaCdpRequest = Readonly<{ + targetType: string + resourceType: string + url: string + userAgent: string | null + clientHints: Readonly> +}> + +type PendingRequest = { + targetType: string + resourceType?: string + url?: string + headers?: Record +} + +// CDP payloads are untyped JSON. Narrow once behind a runtime check instead of asserting a +// shape at each read, so a protocol change surfaces as a missing value rather than a lie. +function readRecord(value: unknown): Record | undefined { + if (typeof value !== 'object' || value === null) { + return undefined + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: guarded by the object/null check above; every member is read back through its own typeof check. + return value as Record +} + +function readString(record: Record | undefined, key: string): string | undefined { + const value = record?.[key] + return typeof value === 'string' ? value : undefined +} + +function readStringRecord(value: unknown): Record | undefined { + const record = readRecord(value) + if (!record) { + return undefined + } + const strings: Record = {} + for (const [key, entry] of Object.entries(record)) { + if (typeof entry === 'string') { + strings[key] = entry + } + } + return strings +} + +type CdpMessage = { + id?: number + method?: string + params?: Record + result?: unknown + error?: { message?: string } + sessionId?: string +} + +export class BrowserSessionUaCdpCollector { + readonly diagnostics: string[] = [] + private readonly pendingCommands = new Map< + number, + { resolve: (value: unknown) => void; reject: (error: Error) => void } + >() + private readonly targetsBySessionId = new Map() + private readonly requests = new Map() + private readonly webSockets = new Map() + private nextCommandId = 1 + + private constructor(private readonly socket: WebSocket) { + socket.on('message', (data) => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: JSON.parse is untyped; CdpMessage is all-optional, so every member is still guarded before use in handleMessage. + this.handleMessage(JSON.parse(data.toString()) as CdpMessage) + ) + } + + static async connect(port: number): Promise { + const version = readRecord( + await fetch(`http://127.0.0.1:${port}/json/version`).then((response) => response.json()) + ) + const webSocketDebuggerUrl = readString(version, 'webSocketDebuggerUrl') + if (!webSocketDebuggerUrl) { + throw new Error('cdp_version_missing_websocket_debugger_url') + } + const socket = new WebSocket(webSocketDebuggerUrl) + await new Promise((resolve, reject) => { + socket.once('open', resolve) + socket.once('error', reject) + }) + return new BrowserSessionUaCdpCollector(socket) + } + + async installAutoAttach(): Promise { + await this.send('Target.setDiscoverTargets', { discover: true }) + await this.send('Target.setAutoAttach', { + autoAttach: true, + waitForDebuggerOnStart: true, + flatten: true + }) + } + + snapshot(): BrowserSessionUaCdpRequest[] { + const result: BrowserSessionUaCdpRequest[] = [] + const requests = [...this.requests.values()].flat() + for (const request of [...requests, ...this.webSockets.values()]) { + if (!request.url || !request.headers) { + continue + } + const normalizedHeaders = Object.fromEntries( + Object.entries(request.headers).map(([key, value]) => [key.toLowerCase(), String(value)]) + ) + result.push({ + targetType: request.targetType, + resourceType: request.resourceType ?? 'Other', + url: request.url, + userAgent: normalizedHeaders['user-agent'] ?? null, + clientHints: Object.fromEntries( + Object.entries(normalizedHeaders).filter(([key]) => key.startsWith('sec-ch-ua')) + ) + }) + } + return result + } + + async close(): Promise { + if (this.socket.readyState === WebSocket.CLOSED) { + return + } + await new Promise((resolve) => { + this.socket.once('close', () => resolve()) + this.socket.close() + }) + } + + private send( + method: string, + params: Record, + sessionId?: string + ): Promise { + const id = this.nextCommandId++ + const promise = new Promise((resolve, reject) => { + this.pendingCommands.set(id, { resolve, reject }) + }) + this.socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })) + return promise + } + + private handleMessage(message: CdpMessage): void { + if (this.diagnostics.length < 50 && message.method) { + this.diagnostics.push(`event:${message.method}:${message.sessionId ?? 'root'}`) + } + if (message.id !== undefined) { + const pending = this.pendingCommands.get(message.id) + if (!pending) { + return + } + this.pendingCommands.delete(message.id) + if (message.error) { + pending.reject(new Error(message.error.message ?? 'CDP command failed')) + } else { + pending.resolve(message.result) + } + return + } + if (message.method === 'Target.attachedToTarget') { + const params = readRecord(message.params) + const attachedSessionId = readString(params, 'sessionId') + if (attachedSessionId) { + const targetType = readString(readRecord(params?.targetInfo), 'type') ?? 'unknown' + this.diagnostics.push(`attached:${targetType}:${attachedSessionId}`) + this.targetsBySessionId.set(attachedSessionId, targetType) + void this.prepareTarget(attachedSessionId) + } + return + } + const sessionId = message.sessionId ?? 'browser' + const params = message.params ?? {} + if (message.method === 'Runtime.exceptionThrown') { + this.diagnostics.push(`exception:${JSON.stringify(params)}`) + return + } + const requestId = typeof params.requestId === 'string' ? params.requestId : undefined + if (!requestId) { + return + } + const key = `${sessionId}:${requestId}` + if (message.method === 'Network.requestWillBeSent') { + const request = readRecord(params.request) + const hops = this.requests.get(key) ?? [] + const pending = hops.find((candidate) => candidate.url === undefined) + const hop = pending ?? this.createPending(sessionId) + if (!pending) { + hops.push(hop) + } + hop.url = readString(request, 'url') + hop.resourceType = typeof params.type === 'string' ? params.type : 'Other' + this.requests.set(key, hops) + } else if (message.method === 'Network.requestWillBeSentExtraInfo') { + const hops = this.requests.get(key) ?? [] + const pending = hops.find((candidate) => candidate.headers === undefined) + const hop = pending ?? this.createPending(sessionId) + if (!pending) { + hops.push(hop) + } + hop.headers = readStringRecord(params.headers) ?? {} + this.requests.set(key, hops) + } else if (message.method === 'Network.webSocketCreated') { + const pending = this.webSockets.get(key) ?? this.createPending(sessionId) + pending.url = typeof params.url === 'string' ? params.url : undefined + pending.resourceType = 'WebSocket' + this.webSockets.set(key, pending) + } else if (message.method === 'Network.webSocketWillSendHandshakeRequest') { + const pending = this.webSockets.get(key) ?? this.createPending(sessionId) + pending.headers = readStringRecord(readRecord(params.request)?.headers) ?? {} + this.webSockets.set(key, pending) + } + } + + private createPending(sessionId: string): PendingRequest { + return { targetType: this.targetsBySessionId.get(sessionId) ?? 'unknown' } + } + + private async prepareTarget(sessionId: string): Promise { + // Paused Electron targets acknowledge queued domain enables only after Runtime resumes them. + const network = this.send('Network.enable', {}, sessionId) + const runtime = this.send('Runtime.enable', {}, sessionId) + await this.send('Runtime.runIfWaitingForDebugger', {}, sessionId).catch((error: unknown) => { + this.diagnostics.push(`resume-error:${sessionId}:${String(error)}`) + }) + const enabled = await Promise.allSettled([network, runtime]) + this.diagnostics.push( + `enabled:${sessionId}:${enabled.map((result) => result.status).join(',')}` + ) + this.diagnostics.push(`resumed:${sessionId}`) + } +} + +export async function waitForBrowserCdpEndpoint(port: number): Promise { + const deadline = Date.now() + 15_000 + while (Date.now() < deadline) { + try { + const targets = await fetch(`http://127.0.0.1:${port}/json/version`) + // The probe only needs the status; an unread body can crash the process (orca#8695). + await cancelUnreadResponseBody(targets) + if (targets.ok) { + return + } + } catch { + // Electron has not opened the debugger endpoint yet. + } + await new Promise((resolve) => setTimeout(resolve, 25)) + } + throw new Error('browser_cdp_endpoint_timeout') +} diff --git a/src/main/browser/browser-session-ua-cloudflare-live.electron.test.ts b/src/main/browser/browser-session-ua-cloudflare-live.electron.test.ts new file mode 100644 index 000000000000..7daf121fb84f --- /dev/null +++ b/src/main/browser/browser-session-ua-cloudflare-live.electron.test.ts @@ -0,0 +1,402 @@ +import { spawn, type ChildProcess } from 'node:child_process' +import { createServer } from 'node:net' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import { chromium } from 'playwright' +import { afterAll, describe, expect, it } from 'vitest' +import { build as buildVite } from 'vite' +import { + BrowserSessionUaCdpCollector, + waitForBrowserCdpEndpoint +} from './browser-session-ua-cdp-collector' + +const electronBinary = createRequire(import.meta.url)('electron') as string +const fixtureRoots: string[] = [] +const enabled = process.env.ORCA_UA_CLOUDFLARE_LIVE === '1' +let liveTargetUrl = 'https://dash.cloudflare.com/login' +const repetitions = Number(process.env.ORCA_UA_CLOUDFLARE_REPETITIONS ?? 5) +const failureText = 'There was a problem with verification. Please reload and try again.' + +// Several independent challenge deployments, not one origin. `native` runs on every site as a +// positive control: if it fails too, that site proves nothing and its rows are void. +const LIVE_SITES: { key: string; url: string }[] = [ + { key: 'cf-dash', url: 'https://dash.cloudflare.com/login' }, + { key: 'cf-nopecha', url: 'https://nopecha.com/demo/cloudflare' }, + { key: 'cf-scrapingcourse', url: 'https://www.scrapingcourse.com/cloudflare-challenge' }, + { key: 'ua-sniff-whatsapp', url: 'https://web.whatsapp.com/' } +] + +// Why signal matching instead of one hardcoded failure string: each deployment words its block +// differently, and inventing per-site strings is how a rig silently reports garbage. Capture the +// evidence and compare arms. +const BLOCK_SIGNALS = [ + 'problem with verification', + 'just a moment', + 'verify you are human', + 'verifying you are human', + 'checking your browser', + 'enable javascript and cookies', + 'unsupported browser', + 'update your browser', + 'is not supported' +] + +function blockSignals(bodyText: string): string[] { + const haystack = bodyText.toLowerCase() + return BLOCK_SIGNALS.filter((signal) => haystack.includes(signal)) +} + +type LiveArm = 'origin-main' | 'branch' | 'native' +type LiveSite = string + +type LiveRun = Readonly<{ + arm: LiveArm + site: LiveSite + repetition: number + cleanUserAgent: string + nativeUserAgent: string + firefoxUserAgent: string + navigatorUserAgent: string | null + bodyText: string + requests: ReturnType + diagnostics: readonly string[] +}> + +afterAll(() => { + for (const root of fixtureRoots) { + rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } +}) + +describe.skipIf(!enabled)('Cloudflare live user-agent compatibility', () => { + it('interleaves origin/main and branch with isolated profiles', async () => { + expect(Number.isInteger(repetitions) && repetitions >= 5).toBe(true) + const results: LiveRun[] = [] + for (const { key, url } of LIVE_SITES) { + liveTargetUrl = url + for (let repetition = 1; repetition <= repetitions; repetition += 1) { + // Rotate so no arm always runs first: IP reputation and challenge state drift within a run. + const rotations: LiveArm[][] = [ + ['origin-main', 'branch', 'native'], + ['branch', 'native', 'origin-main'], + ['native', 'origin-main', 'branch'] + ] + const arms: LiveArm[] = rotations[(repetition - 1) % rotations.length]! + for (const arm of arms) { + results.push(await runLiveProbe(arm, repetition, key)) + } + } + } + const report = results.map(summarizeLiveRun) + console.info(`ORCA_UA_CLOUDFLARE_REPORT=${JSON.stringify(report)}`) + const reportPath = process.env.ORCA_UA_CLOUDFLARE_REPORT_PATH + if (reportPath) { + writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`) + } + + for (const run of results.filter(({ arm }) => arm === 'branch')) { + const userAgents = distinctUserAgents(run.requests) + expect(userAgents, JSON.stringify(summarizeLiveRun(run))).toEqual([run.cleanUserAgent]) + expect( + run.requests.filter(({ userAgent }) => userAgent === run.nativeUserAgent) + ).toHaveLength(0) + } + }, 3_600_000) + + it.skip('compares the Google auth document and cross-host resources', async () => { + const results = await Promise.all([ + runLiveProbe('origin-main', 1, 'google-auth'), + runLiveProbe('branch', 1, 'google-auth') + ]) + const report = results.map(summarizeGoogleAuthRun) + console.info(`ORCA_UA_GOOGLE_AUTH_REPORT=${JSON.stringify(report)}`) + const reportPath = process.env.ORCA_UA_GOOGLE_AUTH_REPORT_PATH + if (reportPath) { + writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`) + } + + const branch = results.find(({ arm }) => arm === 'branch')! + const relevant = googleAuthRequests(branch) + expect(relevant.length).toBeGreaterThan(0) + expect(distinctUserAgents(relevant)).toEqual([branch.firefoxUserAgent]) + expect(relevant.filter(({ userAgent }) => userAgent === branch.cleanUserAgent)).toHaveLength(0) + expect(branch.navigatorUserAgent).toBe(branch.firefoxUserAgent) + }, 90_000) +}) + +async function runLiveProbe(arm: LiveArm, repetition: number, site: LiveSite): Promise { + const root = mkdtempSync(join(tmpdir(), `orca-cloudflare-${arm}-${repetition}-`)) + fixtureRoots.push(root) + const processIdentityModulePath = join(root, 'browser-process-user-agent.cjs') + const exceptionModulePath = join(root, 'browser-session-ua.cjs') + await Promise.all([ + buildModule('src/main/browser/browser-process-user-agent.ts', processIdentityModulePath), + buildModule('src/main/browser/browser-session-ua.ts', exceptionModulePath) + ]) + const barrierPath = join(root, 'continue') + const resultPath = join(root, 'result.json') + const fixturePath = join(root, 'main.cjs') + const cdpPort = await reservePort() + writeFileSync( + fixturePath, + fixtureMain({ + arm, + barrierPath, + exceptionModulePath, + processIdentityModulePath, + resultPath, + site, + targetUrl: liveTargetUrl + }) + ) + let child: ChildProcess | null = null + let collector: BrowserSessionUaCdpCollector | null = null + let browser: Awaited> | null = null + try { + child = launchFixture(fixturePath, root, cdpPort) + await waitForBrowserCdpEndpoint(cdpPort) + browser = await chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`) + collector = await BrowserSessionUaCdpCollector.connect(cdpPort) + await collector.installAutoAttach() + writeFileSync(barrierPath, '') + const processResult = await waitForProcess(child) + const fixtureResult = existsSync(resultPath) ? readFileSync(resultPath, 'utf8') : 'no result' + expect(processResult.code, `${fixtureResult}\n${processResult.stderr}`).toBe(0) + await new Promise((resolve) => setTimeout(resolve, 100)) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: JSON.parse is untyped; the fixture writes exactly this shape with JSON.stringify, and the assertions below fail loudly on a missing member. + const parsed = JSON.parse(fixtureResult) as Omit< + LiveRun, + 'arm' | 'site' | 'repetition' | 'requests' | 'diagnostics' + > + return { + arm, + site, + repetition, + ...parsed, + requests: collector.snapshot().filter(({ url, userAgent }) => { + if (!userAgent) { + return false + } + try { + return new URL(url).protocol.startsWith('http') + } catch { + return false + } + }), + diagnostics: [...collector.diagnostics] + } + } finally { + await collector?.close().catch(() => {}) + await browser?.close().catch(() => {}) + if (child && child.exitCode === null) { + child.kill('SIGTERM') + } + } +} + +async function buildModule(entry: string, outputPath: string): Promise { + await buildVite({ + configFile: false, + logLevel: 'silent', + build: { + emptyOutDir: false, + lib: { + entry: join(process.cwd(), entry), + formats: ['cjs'], + fileName: () => basename(outputPath) + }, + outDir: join(outputPath, '..'), + target: 'node20', + rollupOptions: { external: ['electron', /^node:/] } + } + }) +} + +function fixtureMain(options: { + arm: LiveArm + barrierPath: string + exceptionModulePath: string + processIdentityModulePath: string + resultPath: string + site: LiveSite + targetUrl: string +}): string { + return String.raw` +const { app, BrowserWindow, session } = require('electron') +const { existsSync, writeFileSync } = require('node:fs') +const processIdentity = require(${JSON.stringify(options.processIdentityModulePath)}) +const { installBrowserSessionUserAgentExceptions } = require(${JSON.stringify(options.exceptionModulePath)}) +const arm = ${JSON.stringify(options.arm)} +const site = ${JSON.stringify(options.site)} +app.setName('OrcaCloudflareLiveProbe') +const clean = userAgent => userAgent.replace(/\s+Electron\/\S+/, '').replace(/(\)\s+)\S+\s+(Chrome\/)/, '$1$2') +let identity +if (arm === 'branch') identity = processIdentity.initializeBrowserProcessUserAgent() +const waitForBarrier = async () => { + const deadline = Date.now() + 15000 + while (!existsSync(${JSON.stringify(options.barrierPath)})) { + if (Date.now() >= deadline) throw new Error('startup barrier timeout') + await new Promise(resolve => setTimeout(resolve, 20)) + } +} +async function run() { + await app.whenReady() + await waitForBarrier() + const sess = session.fromPartition('persist:cloudflare-live-probe') + const nativeUserAgent = identity?.nativeUserAgent ?? sess.getUserAgent() + const cleanUserAgent = identity?.cleanUserAgent ?? clean(nativeUserAgent) + const firefoxUserAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:140.0) Gecko/20100101 Firefox/140.0' + if (arm === 'origin-main') sess.setUserAgent(cleanUserAgent) + if (arm === 'branch') { + installBrowserSessionUserAgentExceptions(sess, request => { + if (request.resourceType !== 'mainFrame' && (request.currentUserAgent === firefoxUserAgent || request.effectiveUserAgent === firefoxUserAgent)) { + return { userAgent: firefoxUserAgent } + } + if (request.resourceType === 'mainFrame' && request.currentUserAgent === firefoxUserAgent) { + return { userAgent: cleanUserAgent } + } + return undefined + }) + } else if (arm === 'origin-main') { + sess.webRequest.onBeforeSendHeaders({ urls: ['https://*/*'] }, (details, callback) => { + const headers = details.requestHeaders + const key = Object.keys(headers).find(candidate => candidate.toLowerCase() === 'user-agent') || 'User-Agent' + const auth = (() => { try { const url = new URL(details.url); return url.protocol === 'https:' && (url.hostname === 'accounts.google.com' || url.hostname === 'accounts.youtube.com') } catch { return false } })() + if (auth) headers[key] = firefoxUserAgent + if (auth || headers[key] === firefoxUserAgent) { + for (const candidate of Object.keys(headers)) if (candidate.toLowerCase().startsWith('sec-ch-ua')) delete headers[candidate] + } + callback({ requestHeaders: headers }) + }) + } + const window = new BrowserWindow({ show: false, webPreferences: { partition: 'persist:cloudflare-live-probe', sandbox: true } }) + if (site === 'google-auth') window.webContents.setUserAgent(firefoxUserAgent) + let loadError = null + const targetUrl = ${JSON.stringify(options.targetUrl)} + await window.loadURL(targetUrl).catch(error => { loadError = String(error?.message || error) }) + await new Promise(resolve => setTimeout(resolve, 12000)) + const bodyText = await window.webContents.executeJavaScript('document.body?.innerText || ""').catch(() => '') + const navigatorUserAgent = await window.webContents.executeJavaScript('navigator.userAgent').catch(() => null) + writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ nativeUserAgent, cleanUserAgent, firefoxUserAgent, navigatorUserAgent, bodyText, loadError })) + window.destroy() + app.exit(0) +} +run().catch(error => { writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ error: String(error?.stack || error) })); app.exit(1) }) +` +} + +function summarizeLiveRun(run: LiveRun) { + const byResourceType: Record> = {} + for (const request of run.requests) { + const userAgent = request.userAgent ?? '' + byResourceType[request.resourceType] ??= {} + byResourceType[request.resourceType]![userAgent] = + (byResourceType[request.resourceType]![userAgent] ?? 0) + 1 + } + return { + arm: run.arm, + site: run.site, + repetition: run.repetition, + requestCount: run.requests.length, + distinctUserAgents: distinctUserAgents(run.requests), + nativeLeakCount: run.requests.filter(({ userAgent }) => userAgent === run.nativeUserAgent) + .length, + navigatorUserAgent: run.navigatorUserAgent, + verificationFailure: run.bodyText.includes(failureText), + blockSignals: blockSignals(run.bodyText), + bodySnippet: run.bodyText.replace(/\s+/g, ' ').slice(0, 220), + byResourceType, + attachedTargetTypes: run.diagnostics + .filter((message) => message.startsWith('attached:')) + .map((message) => message.split(':')[1]) + } +} + +function summarizeGoogleAuthRun(run: LiveRun) { + const relevant = googleAuthRequests(run) + const byHost: Record = {} + for (const request of relevant) { + const host = new URL(request.url).hostname + byHost[host] = (byHost[host] ?? 0) + 1 + } + return { + arm: run.arm, + requestCount: relevant.length, + distinctUserAgents: distinctUserAgents(relevant), + cleanChromeCount: relevant.filter(({ userAgent }) => userAgent === run.cleanUserAgent).length, + firefoxCount: relevant.filter(({ userAgent }) => userAgent === run.firefoxUserAgent).length, + navigatorUserAgent: run.navigatorUserAgent, + byHost + } +} + +function googleAuthRequests(run: LiveRun) { + const hosts = new Set([ + 'accounts.google.com', + 'accounts.youtube.com', + 'www.gstatic.com', + 'fonts.gstatic.com', + 'play.google.com' + ]) + return run.requests.filter(({ url }) => { + try { + return hosts.has(new URL(url).hostname) + } catch { + return false + } + }) +} + +function distinctUserAgents(records: readonly { userAgent: string | null }[]): (string | null)[] { + return [...new Set(records.map(({ userAgent }) => userAgent))].sort() +} + +function launchFixture(fixturePath: string, root: string, cdpPort: number): ChildProcess { + const { ELECTRON_RUN_AS_NODE: _electronRunAsNode, ...env } = process.env + return spawn( + process.platform === 'linux' ? 'xvfb-run' : electronBinary, + process.platform === 'linux' + ? [ + '--auto-servernum', + electronBinary, + fixturePath, + `--user-data-dir=${join(root, 'profile')}`, + `--remote-debugging-port=${cdpPort}`, + '--no-sandbox' + ] + : [ + fixturePath, + `--user-data-dir=${join(root, 'profile')}`, + `--remote-debugging-port=${cdpPort}` + ], + { env: { ...env, ORCA_BACKGROUND_LAUNCH: '1' }, stdio: ['ignore', 'pipe', 'pipe'] } + ) +} + +async function reservePort(): Promise { + const server = createServer() + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', resolve) + }) + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('cdp port unavailable') + } + await new Promise((resolve) => server.close(() => resolve())) + return address.port +} + +function waitForProcess(child: ChildProcess): Promise<{ code: number | null; stderr: string }> { + let stderr = '' + child.stderr?.setEncoding('utf8') + child.stderr?.on('data', (chunk: string) => { + stderr += chunk + }) + return new Promise((resolve, reject) => { + child.once('error', reject) + child.once('exit', (code) => resolve({ code, stderr })) + }) +} diff --git a/src/main/browser/browser-session-ua-wire-identity.electron.test.ts b/src/main/browser/browser-session-ua-wire-identity.electron.test.ts index 9fc1c7606433..bd7bc3031e0b 100644 --- a/src/main/browser/browser-session-ua-wire-identity.electron.test.ts +++ b/src/main/browser/browser-session-ua-wire-identity.electron.test.ts @@ -1,23 +1,22 @@ -import { spawnSync } from 'node:child_process' +import { spawn, type ChildProcess } from 'node:child_process' +import { createServer } from 'node:net' import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { basename, join } from 'node:path' +import { chromium } from 'playwright' import { afterAll, describe, expect, it } from 'vitest' import { build as buildVite } from 'vite' import { - LOCAL_HTTPS_TEST_CERTIFICATE, - LOCAL_HTTPS_TEST_PRIVATE_KEY -} from './browser-local-https-test-certificate' - -// Why this runs a real Electron: sites that hold a transplanted session re-check the browser -// identity that minted it, and an `Orca/x.y.z … Electron/x.y.z` UA is not one any browser sends — -// LinkedIn and x.com revoked live sessions over it (STA-7147). The header layer is the only place -// that identity can be proven, and the vm-based unit tests cannot see Chromium's header emission -// at all. Every clean-mode partition must therefore strip the Electron and app tokens on the -// wire for ordinary hosts and present the Firefox identity on Google's sign-in hosts only. This -// focused revocation fix does not claim full Chrome fingerprint parity; native mode remains the -// fallback for sites that reject the cleaned identity, including some Turnstile deployments. + BrowserSessionUaCdpCollector, + type BrowserSessionUaCdpRequest, + waitForBrowserCdpEndpoint +} from './browser-session-ua-cdp-collector' +import { + startBrowserSessionUaWireProbeServer, + type WireProbeJavaScriptIdentity, + type WireProbeReceipt +} from './browser-session-ua-wire-probe-server' const electronBinary = createRequire(import.meta.url)('electron') as string const fixtureRoots: string[] = [] @@ -28,241 +27,426 @@ afterAll(() => { } }) -// Retry once when Electron startup times out before `ready`; keep later failures fatal. -const FIXTURE_LAUNCH_ATTEMPTS = 2 - -type CapturedRequest = { - url: string - userAgent: string | null - clientHints: Record -} +type ProbeArm = 'clean' | 'late-session-setter' | 'mobile' | 'mixed-mobile' | 'native' -type UserAgentBrand = { - brand: string - version: string -} - -type NavigatorUserAgentData = { - brands: UserAgentBrand[] - highEntropy: { fullVersionList?: UserAgentBrand[] } -} - -type FixtureResult = { +type ProbeResult = Readonly<{ + arm: ProbeArm rawUserAgent: string + cleanUserAgent: string + mobileUserAgent: string sessionUserAgent: string navigatorUserAgent: string - navigatorUserAgentData: NavigatorUserAgentData | null - requests: CapturedRequest[] -} + fallbackAfterReadyNameChange: string + startupMarks: readonly string[] + receipts: readonly WireProbeReceipt[] + identities: readonly WireProbeJavaScriptIdentity[] + cdpRequests: readonly BrowserSessionUaCdpRequest[] + cdpDiagnostics: readonly string[] +}> -function neverReachedElectronReady(fixtureResult: string): boolean { - try { - return (JSON.parse(fixtureResult) as { step?: string }).step === 'timed out after starting' - } catch { - return false - } -} +const requiredPaths = [ + '/', + '/document-fetch', + '/document-xhr', + '/document-image', + '/frame', + '/blob-fetch', + '/blob-xhr', + '/blob-image', + '/shared-worker-fetch-a', + '/shared-worker-fetch-b', + '/service-worker-fetch', + '/popup', + '/popup-fetch', + '/no-header-fill', + '/default-session-fill', + '/isolated-session-fill', + '/default-window', + '/isolated-window', + '/plain-ws', + '/secure-ws' +] as const -function buildFixtureMain(modulePath: string, resultPath: string): string { - return ` -const { app, BrowserWindow, session } = require('electron') -const { createServer } = require('node:https') -const { writeFileSync } = require('node:fs') -const { cleanElectronUserAgent, setupGoogleAuthUserAgentOverride } = require(${JSON.stringify(modulePath)}) -const resultPath = ${JSON.stringify(resultPath)} -// Why: production's UA carries an app token ("Orca/1.4.198") between the engine comment and -// Chrome/, and an unnamed fixture emits none — which would leave half of cleanElectronUserAgent -// unexercised while the test still passed. -app.setName('OrcaWireIdentityFixture') -let currentStep = 'starting' -const mark = (step) => { - currentStep = step - writeFileSync(resultPath, JSON.stringify({ step })) -} +describe('browser session wire identity under Electron', () => { + it('uses one process-clean identity for documents, blob frames, workers, HTTP, and WebSockets', async () => { + const result = await runProbe('clean') + assertCoverage(result) + expect(result.rawUserAgent).toMatch(/ Electron\/\d/) + expect(result.rawUserAgent).toMatch(/\(KHTML, like Gecko\) \S+ Chrome\//) + expect(result.cleanUserAgent).not.toContain('Electron/') + expect(result.startupMarks).toEqual(['fallback', 'ready', 'session', 'webContents']) + expect(result.fallbackAfterReadyNameChange).toBe(result.cleanUserAgent) + expect(distinctUserAgents(result.receipts)).toEqual([result.cleanUserAgent]) + expect(distinctUserAgents(result.cdpRequests)).toEqual([result.cleanUserAgent]) + expect(distinctJavaScriptUserAgents(result.identities)).toEqual([result.cleanUserAgent]) + }, 40_000) -async function run() { - const timeout = setTimeout(() => { - writeFileSync(resultPath, JSON.stringify({ step: 'timed out after ' + currentStep })) - app.exit(1) - }, 15000) - await app.whenReady() - mark('ready') - const partition = 'persist:wire-identity-test' - const sess = session.fromPartition(partition) - // Mirrors installBrowserSessionPartitionPolicies for a non-native profile. - const rawUserAgent = sess.getUserAgent() - const cleanUa = cleanElectronUserAgent(rawUserAgent) - sess.setUserAgent(cleanUa) - setupGoogleAuthUserAgentOverride(sess) - mark('clean identity installed') + it('goes red without the pre-ready process fallback even when the Session setter is restored', async () => { + const result = await runProbe('late-session-setter') + assertCoverage(result) + expect(distinctUserAgents(result.receipts)).toContain(result.rawUserAgent) + expect(distinctUserAgents(result.receipts)).toContain(result.cleanUserAgent) + expect(identityViolations(result)).not.toEqual([]) + expect(result.receipts.some(({ userAgent }) => /Firefox\//.test(userAgent ?? ''))).toBe(false) + }, 40_000) - sess.setCertificateVerifyProc((_request, callback) => callback(0)) - const requests = [] - sess.webRequest.onSendHeaders({ urls: ['https://*/*'] }, (details) => { - const headers = details.requestHeaders || {} - const uaKey = Object.keys(headers).find((key) => key.toLowerCase() === 'user-agent') - const clientHints = {} - for (const [key, value] of Object.entries(headers)) { - if (key.toLowerCase().startsWith('sec-ch-ua')) { - clientHints[key.toLowerCase()] = value - } - } - requests.push({ - url: details.url, - userAgent: uaKey ? headers[uaKey] : null, - clientHints - }) - }) + it('keeps mobile traffic CriOS while an unmapped numeric popup stays desktop-clean', async () => { + const result = await runProbe('mobile') + assertCoverage(result) + const mobilePaths = [ + '/', + '/blob-fetch', + '/blob-xhr', + '/blob-image', + '/shared-worker-fetch-a', + '/shared-worker-fetch-b', + '/service-worker-fetch', + '/plain-ws', + '/secure-ws' + ] + expect(distinctUserAgents(receiptsForPaths(result.receipts, mobilePaths))).toEqual([ + result.mobileUserAgent + ]) + expect(userAgentForPath(result.receipts, '/popup')).toBe(result.cleanUserAgent) + expect(identityForContext(result.identities, 'popup').userAgent).toBe(result.cleanUserAgent) + expect(identityForContext(result.identities, 'document').userAgent).toBe(result.mobileUserAgent) + }, 40_000) - const server = createServer( - { - cert: ${JSON.stringify(LOCAL_HTTPS_TEST_CERTIFICATE)}, - key: ${JSON.stringify(LOCAL_HTTPS_TEST_PRIVATE_KEY)} - }, - (_request, response) => { - response.setHeader('Accept-CH', 'Sec-CH-UA-Full-Version-List') - response.end('identity') - } - ) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', resolve) - }) - const origin = 'https://127.0.0.1:' + server.address().port - const window = new BrowserWindow({ show: false, webPreferences: { partition } }) - mark('window created') - let navigatorUserAgent - let navigatorUserAgentData - try { - await window.loadURL(origin + '/') - navigatorUserAgent = await window.webContents.executeJavaScript('navigator.userAgent') - navigatorUserAgentData = await window.webContents.executeJavaScript( - "(async () => { const data = navigator.userAgentData; return data ? { brands: data.brands, highEntropy: await data.getHighEntropyValues(['fullVersionList']) } : null })()" + it('makes the shared-session mobile worker contract explicit with a desktop peer', async () => { + const result = await runProbe('mixed-mobile') + assertCoverage(result) + expect(identityForContext(result.identities, 'document').userAgent).toBe(result.mobileUserAgent) + expect(identityForContext(result.identities, 'desktop-peer').userAgent).toBe( + result.cleanUserAgent ) - await window.webContents.executeJavaScript( - 'fetch("/hints").then((response) => response.text())' - ) - } finally { - await new Promise((resolve) => server.close(resolve)) - } - - // Dispatch a real auth-host request without allowing it to reach the Internet. - await sess.setProxy({ proxyRules: 'http://127.0.0.1:9', proxyBypassRules: '<-loopback>' }) - await window.loadURL('https://accounts.google.com/v3/signin/identifier').catch(() => {}) - mark('navigations attempted') - clearTimeout(timeout) - writeFileSync(resultPath, JSON.stringify({ - rawUserAgent, - sessionUserAgent: sess.getUserAgent(), - navigatorUserAgent, - navigatorUserAgentData, - requests - })) - window.destroy() - app.exit(0) -} + expect(userAgentForPath(result.receipts, '/desktop-peer')).toBe(result.cleanUserAgent) + expect( + distinctUserAgents( + receiptsForPaths(result.receipts, ['/shared-worker-fetch-a', '/shared-worker-fetch-b']) + ) + ).toEqual([result.mobileUserAgent]) + expect( + result.identities + .filter(({ context }) => context === 'shared-worker') + .map(({ userAgent }) => userAgent) + ).toEqual([result.cleanUserAgent, result.cleanUserAgent]) + }, 40_000) -run().catch((error) => { - writeFileSync(resultPath, JSON.stringify({ step: currentStep, error: String(error?.stack || error) })) - app.exit(1) + it('makes the B1 native split deterministic', async () => { + const result = await runProbe('native') + assertCoverage(result) + expect(identityForContext(result.identities, 'document').userAgent).toBe(result.rawUserAgent) + expect(identityForContext(result.identities, 'blob').userAgent).toBe(result.rawUserAgent) + expect(identityForContext(result.identities, 'shared-worker').userAgent).toBe( + result.cleanUserAgent + ) + expect(identityForContext(result.identities, 'service-worker').userAgent).toBe( + result.cleanUserAgent + ) + expect(userAgentForPath(result.receipts, '/')).toBe(result.rawUserAgent) + expect(userAgentForPath(result.receipts, '/blob-fetch')).toBe(result.rawUserAgent) + expect(userAgentForPath(result.receipts, '/shared-worker-fetch-a')).toBe(result.cleanUserAgent) + expect(userAgentForPath(result.receipts, '/service-worker-fetch')).toBe(result.cleanUserAgent) + expect(userAgentForPath(result.receipts, '/no-header-fill')).toBe(result.cleanUserAgent) + }, 40_000) }) -` -} -async function runFixture(): Promise { - const root = mkdtempSync(join(tmpdir(), 'orca-wire-identity-')) +async function runProbe(arm: ProbeArm): Promise { + const root = mkdtempSync(join(tmpdir(), `orca-wire-identity-${arm}-`)) fixtureRoots.push(root) - const modulePath = join(root, 'browser-session-ua.cjs') + const processIdentityModulePath = join(root, 'browser-process-user-agent.cjs') + const exceptionModulePath = join(root, 'browser-session-ua.cjs') + await Promise.all([ + buildModule('src/main/browser/browser-process-user-agent.ts', processIdentityModulePath), + buildModule('src/main/browser/browser-session-ua.ts', exceptionModulePath) + ]) + const server = await startBrowserSessionUaWireProbeServer() const resultPath = join(root, 'result.json') + const barrierPath = join(root, 'continue') const fixturePath = join(root, 'main.cjs') + const cdpPort = await reservePort() + writeFileSync( + fixturePath, + fixtureMain({ + arm, + barrierPath, + exceptionModulePath, + httpOrigin: server.httpOrigin, + processIdentityModulePath, + resultPath + }) + ) + let process: ChildProcess | null = null + let collector: BrowserSessionUaCdpCollector | null = null + let browser: Awaited> | null = null + try { + process = launchFixture(fixturePath, root, cdpPort) + await waitForBrowserCdpEndpoint(cdpPort) + browser = await chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`) + collector = await BrowserSessionUaCdpCollector.connect(cdpPort) + await collector.installAutoAttach() + writeFileSync(barrierPath, '') + const processResult = await waitForProcess(process) + const fixtureResult = existsSync(resultPath) ? readFileSync(resultPath, 'utf8') : 'no result' + expect( + processResult.code, + `${fixtureResult}\n${processResult.stderr}\n${JSON.stringify({ diagnostics: collector.diagnostics, receipts: server.receipts, identities: server.identities })}` + ).toBe(0) + await new Promise((resolve) => setTimeout(resolve, 100)) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: JSON.parse is untyped; the fixture writes exactly this shape with JSON.stringify, and the assertions below fail loudly on a missing member. + const parsed = JSON.parse(fixtureResult) as Omit< + ProbeResult, + 'receipts' | 'identities' | 'cdpRequests' | 'cdpDiagnostics' + > + return { + ...parsed, + receipts: [...server.receipts], + identities: [...server.identities], + cdpDiagnostics: [...collector.diagnostics], + cdpRequests: collector + .snapshot() + .filter( + ({ url }) => url.startsWith(server.httpOrigin) || url.startsWith(server.httpsOrigin) + ) + } + } finally { + await collector?.close().catch(() => {}) + await browser?.close().catch(() => {}) + await server.close() + if (process && process.exitCode === null) { + process.kill('SIGTERM') + } + } +} + +async function buildModule(entry: string, outputPath: string): Promise { await buildVite({ configFile: false, logLevel: 'silent', build: { emptyOutDir: false, lib: { - entry: join(process.cwd(), 'src/main/browser/browser-session-ua.ts'), + entry: join(process.cwd(), entry), formats: ['cjs'], - fileName: () => 'browser-session-ua.cjs' + fileName: () => basename(outputPath) }, - outDir: root, + outDir: join(outputPath, '..'), target: 'node20', rollupOptions: { external: ['electron', /^node:/] } } }) - writeFileSync(fixturePath, buildFixtureMain(modulePath, resultPath)) +} + +function launchFixture(fixturePath: string, root: string, cdpPort: number): ChildProcess { const { ELECTRON_RUN_AS_NODE: _electronRunAsNode, ...env } = process.env - const executable = process.platform === 'linux' ? 'xvfb-run' : electronBinary - for (let attempt = 1; ; attempt += 1) { - rmSync(resultPath, { force: true }) - // Why a fresh profile per attempt: a launch that never reached `ready` may have left the - // Chromium profile mid-initialization, and reusing it would bias the retry. - const electronArgs = [fixturePath, `--user-data-dir=${join(root, `profile-${attempt}`)}`] - const run = spawnSync( - executable, - process.platform === 'linux' - ? ['--auto-servernum', electronBinary, ...electronArgs, '--no-sandbox'] - : electronArgs, - { encoding: 'utf8', env, timeout: 60_000 } - ) - const fixtureResult = existsSync(resultPath) ? readFileSync(resultPath, 'utf8') : 'no result' - if (attempt < FIXTURE_LAUNCH_ATTEMPTS && neverReachedElectronReady(fixtureResult)) { - continue + return spawn( + process.platform === 'linux' ? 'xvfb-run' : electronBinary, + process.platform === 'linux' + ? [ + '--auto-servernum', + electronBinary, + fixturePath, + `--user-data-dir=${join(root, 'profile')}`, + `--remote-debugging-port=${cdpPort}`, + '--no-sandbox' + ] + : [ + fixturePath, + `--user-data-dir=${join(root, 'profile')}`, + `--remote-debugging-port=${cdpPort}` + ], + { + env: { ...env, ORCA_BACKGROUND_LAUNCH: '1' }, + stdio: ['ignore', 'pipe', 'pipe'] } - expect(run.error).toBeUndefined() - expect(run.status, `${fixtureResult}\n${run.stdout}\n${run.stderr}`).toBe(0) - return JSON.parse(fixtureResult) as FixtureResult - } + ) } -function parseClientHintBrands(value: string): UserAgentBrand[] { - return [...value.matchAll(/"([^"]+)";v="([^"]+)"/g)].map((match) => ({ - brand: match[1], - version: match[2] +function fixtureMain(options: { + arm: ProbeArm + barrierPath: string + exceptionModulePath: string + httpOrigin: string + processIdentityModulePath: string + resultPath: string +}): string { + return String.raw` +const { app, BrowserWindow, net, session } = require('electron') +const { existsSync, writeFileSync } = require('node:fs') +const processIdentity = require(${JSON.stringify(options.processIdentityModulePath)}) +const { cleanElectronUserAgent, installBrowserSessionUserAgentExceptions } = require(${JSON.stringify(options.exceptionModulePath)}) +const arm = ${JSON.stringify(options.arm)} +const startupMarks = [] +app.setName('OrcaWireIdentityFixture') +let identity +if (arm !== 'late-session-setter') { + identity = processIdentity.initializeBrowserProcessUserAgent() + startupMarks.push('fallback') +} +const waitForBarrier = async () => { + const deadline = Date.now() + 15000 + while (!existsSync(${JSON.stringify(options.barrierPath)})) { + if (Date.now() >= deadline) throw new Error('startup barrier timeout') + await new Promise(resolve => setTimeout(resolve, 20)) + } +} +const requestWithoutUserAgent = (sess, url) => new Promise((resolve, reject) => { + const request = net.request({ session: sess, url }) + request.on('response', response => { response.on('data', () => {}); response.on('end', resolve) }) + request.on('error', reject) + request.end() +}) +async function run() { + const timeout = setTimeout(() => { writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ error: 'timeout', startupMarks })); app.exit(2) }, 10000) + await app.whenReady() + startupMarks.push('ready') + app.setName('OrcaWireIdentityFixtureAfterReady') + const fallbackAfterReadyNameChange = app.userAgentFallback + await waitForBarrier() + const sess = session.fromPartition('persist:wire-identity-test') + startupMarks.push('session') + const rawUserAgent = identity?.nativeUserAgent ?? sess.getUserAgent() + const cleanUserAgent = identity?.cleanUserAgent ?? cleanElectronUserAgent(rawUserAgent) + if (arm === 'late-session-setter') sess.setUserAgent(cleanUserAgent) + sess.setCertificateVerifyProc((_request, callback) => callback(0)) + const chromeVersion = cleanUserAgent.match(/Chrome\/([\d.]+)/)?.[1] || process.versions.chrome + const major = chromeVersion.split('.')[0] + const mobileUserAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/' + chromeVersion + ' Mobile/15E148 Safari/604.1' + let mainWebContentsId + if (arm === 'clean' || arm === 'mobile' || arm === 'mixed-mobile') { + installBrowserSessionUserAgentExceptions(sess, request => { + if (arm !== 'mobile' && arm !== 'mixed-mobile') return undefined + if (request.webContentsId !== undefined && request.webContentsId !== mainWebContentsId) return undefined + return { userAgent: mobileUserAgent, userAgentMetadata: { brands: [{ brand: 'Chromium', version: major }, { brand: 'Google Chrome', version: major }, { brand: 'Not/A)Brand', version: '24' }], fullVersionList: [{ brand: 'Chromium', version: chromeVersion }, { brand: 'Google Chrome', version: chromeVersion }, { brand: 'Not/A)Brand', version: '24.0.0.0' }], fullVersion: chromeVersion, platform: 'iOS', platformVersion: '18.5.0', architecture: '', model: 'iPhone', mobile: true } } + }) + } + const windows = [] + const window = new BrowserWindow({ show: false, webPreferences: { partition: 'persist:wire-identity-test', sandbox: true } }) + windows.push(window) + startupMarks.push('webContents') + mainWebContentsId = window.webContents.id + const pageIdentity = arm === 'native' ? rawUserAgent : arm === 'mobile' || arm === 'mixed-mobile' ? mobileUserAgent : cleanUserAgent + if (arm === 'native' || arm === 'mobile' || arm === 'mixed-mobile') window.webContents.setUserAgent(pageIdentity) + window.webContents.setWindowOpenHandler(() => ({ + action: 'allow', + createWindow: options => { + const popup = new BrowserWindow({ ...options, show: false }) + popup.webContents.setUserAgent(arm === 'native' ? rawUserAgent : cleanUserAgent) + windows.push(popup) + return popup.webContents + } })) + await window.loadURL(${JSON.stringify(options.httpOrigin)} + '/') + const [navigatorUserAgent] = await Promise.all([ + window.webContents.executeJavaScript('navigator.userAgent'), + window.webContents.executeJavaScript('window.probePromise'), + requestWithoutUserAgent(sess, ${JSON.stringify(options.httpOrigin)} + '/no-header-fill') + ]) + if (arm === 'mixed-mobile') { + const peer = new BrowserWindow({ show: false, webPreferences: { partition: 'persist:wire-identity-test', sandbox: true } }) + windows.push(peer) + await peer.loadURL(${JSON.stringify(options.httpOrigin)} + '/desktop-peer') + await peer.webContents.executeJavaScript('window.peerProbePromise') + } + const defaultWindow = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }) + windows.push(defaultWindow) + await defaultWindow.loadURL(${JSON.stringify(options.httpOrigin)} + '/default-window') + const appIsolatedWindow = new BrowserWindow({ show: false, webPreferences: { partition: 'persist:app-surface', sandbox: true } }) + windows.push(appIsolatedWindow) + await appIsolatedWindow.loadURL(${JSON.stringify(options.httpOrigin)} + '/isolated-window') + await Promise.all([ + requestWithoutUserAgent(session.defaultSession, ${JSON.stringify(options.httpOrigin)} + '/default-session-fill'), + requestWithoutUserAgent(session.fromPartition('persist:app-surface'), ${JSON.stringify(options.httpOrigin)} + '/isolated-session-fill') + ]) + await new Promise(resolve => setTimeout(resolve, 250)) + clearTimeout(timeout) + writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ arm, rawUserAgent, cleanUserAgent, mobileUserAgent, sessionUserAgent: sess.getUserAgent(), navigatorUserAgent, fallbackAfterReadyNameChange, startupMarks })) + for (const candidate of windows) if (!candidate.isDestroyed()) candidate.destroy() + app.exit(0) +} +run().catch(error => { writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ error: String(error?.stack || error), startupMarks })); app.exit(1) }) +` } -describe('browser session wire identity under Electron', () => { - it('strips the Electron and app tokens for ordinary hosts and sends Firefox to Google auth hosts', async () => { - const result = await runFixture() +function assertCoverage(result: ProbeResult): void { + const paths = new Set(result.receipts.map(({ path }) => path)) + for (const path of requiredPaths) { + expect( + paths, + `${result.arm} omitted ${path}: ${JSON.stringify(result.cdpDiagnostics)}` + ).toContain(path) + } + const cdpUrls = result.cdpRequests.map(({ url }) => new URL(url).pathname) + expect(cdpUrls).toContain('/blob-fetch') + expect(result.cdpDiagnostics.some((message) => message.includes('attached:shared_worker:'))).toBe( + true + ) + const expectedContexts = ['blob', 'document', 'frame', 'popup', 'service-worker', 'shared-worker'] + if (result.arm === 'mixed-mobile') { + expectedContexts.push('desktop-peer', 'shared-worker') + } + expect(result.identities.map(({ context }) => context).sort()).toEqual(expectedContexts.sort()) +} - // Presence precondition: the raw identity really does carry the tokens, so the absence - // assertions below cannot pass vacuously on an empty or already-clean UA. - expect(result.rawUserAgent).toMatch(/ Electron\/\d/) - expect(result.rawUserAgent).toMatch(/\(KHTML, like Gecko\) \S+ Chrome\//) +function identityViolations(result: ProbeResult): string[] { + return result.receipts + .filter(({ userAgent }) => userAgent !== result.cleanUserAgent) + .map(({ protocol, path }) => `${protocol}:${path}`) +} - // The whole point of STA-7147: nothing between the engine comment and Chrome/, and no - // Electron token anywhere — the shape a real Chrome sends. - expect(result.sessionUserAgent).not.toContain('Electron/') - expect(result.sessionUserAgent).toMatch(/\(KHTML, like Gecko\) Chrome\/[\d.]+ Safari\/537\.36$/) +function distinctUserAgents(records: readonly { userAgent: string | null }[]): (string | null)[] { + return [...new Set(records.map(({ userAgent }) => userAgent))].sort() +} - const ordinary = result.requests.find((request) => request.url.endsWith('/hints')) - expect(ordinary, JSON.stringify(result.requests)).toBeDefined() - expect(ordinary?.userAgent).toBe(result.sessionUserAgent) - expect(result.navigatorUserAgent).toBe(result.sessionUserAgent) - expect(result.navigatorUserAgentData).not.toBeNull() +function distinctJavaScriptUserAgents(records: readonly WireProbeJavaScriptIdentity[]): string[] { + return [...new Set(records.map(({ userAgent }) => userAgent))].sort() +} - // Chromium owns both client-hint surfaces. Rewriting only the request headers would make this - // comparison fail while leaving the legacy UA assertions above green. - const wireBrands = parseClientHintBrands(ordinary?.clientHints['sec-ch-ua'] ?? '') - expect(wireBrands).toEqual(result.navigatorUserAgentData?.brands) - expect(wireBrands.some(({ brand }) => /Electron|Orca/i.test(brand))).toBe(false) - const chromeMajor = result.sessionUserAgent.match(/Chrome\/(\d+)/)?.[1] - expect(wireBrands.find(({ brand }) => brand === 'Chromium')?.version).toBe(chromeMajor) +function receiptsForPaths( + receipts: readonly WireProbeReceipt[], + paths: readonly string[] +): WireProbeReceipt[] { + const selected = new Set(paths) + return receipts.filter(({ path }) => selected.has(path)) +} - const fullVersionList = ordinary?.clientHints['sec-ch-ua-full-version-list'] - if (fullVersionList) { - expect(parseClientHintBrands(fullVersionList)).toEqual( - result.navigatorUserAgentData?.highEntropy.fullVersionList - ) - } +function userAgentForPath(receipts: readonly WireProbeReceipt[], path: string): string | null { + const values = distinctUserAgents(receipts.filter((receipt) => receipt.path === path)) + expect(values, path).toHaveLength(1) + return values[0] ?? null +} - const auth = result.requests.find((request) => - request.url.startsWith('https://accounts.google.com/') - ) - expect(auth, JSON.stringify(result.requests)).toBeDefined() - expect(auth?.userAgent).toMatch(/Firefox\/\d/) - expect(auth?.userAgent).not.toContain('Chrome') - expect(auth?.clientHints).toEqual({}) +function identityForContext( + identities: readonly WireProbeJavaScriptIdentity[], + context: string +): WireProbeJavaScriptIdentity { + const matches = identities.filter((identity) => identity.context === context) + expect(matches, context).toHaveLength(1) + return matches[0]! +} + +async function reservePort(): Promise { + const server = createServer() + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', resolve) }) -}) + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('cdp port unavailable') + } + await new Promise((resolve) => server.close(() => resolve())) + return address.port +} + +function waitForProcess(process: ChildProcess): Promise<{ code: number | null; stderr: string }> { + let stderr = '' + process.stderr?.setEncoding('utf8') + process.stderr?.on('data', (chunk: string) => { + stderr += chunk + }) + return new Promise((resolve, reject) => { + process.once('error', reject) + process.once('exit', (code) => resolve({ code, stderr })) + }) +} diff --git a/src/main/browser/browser-session-ua-wire-probe-server.ts b/src/main/browser/browser-session-ua-wire-probe-server.ts new file mode 100644 index 000000000000..9a1012491c4a --- /dev/null +++ b/src/main/browser/browser-session-ua-wire-probe-server.ts @@ -0,0 +1,256 @@ +import { createHash } from 'node:crypto' +import { + createServer as createHttpServer, + type IncomingMessage, + type ServerResponse +} from 'node:http' +import { createServer as createHttpsServer } from 'node:https' +import type { AddressInfo } from 'node:net' +import type { Duplex } from 'node:stream' +import { + LOCAL_HTTPS_TEST_CERTIFICATE, + LOCAL_HTTPS_TEST_PRIVATE_KEY +} from './browser-local-https-test-certificate' + +export type WireProbeReceipt = Readonly<{ + protocol: 'http' | 'https' | 'ws' | 'wss' + path: string + userAgent: string | null +}> + +export type WireProbeJavaScriptIdentity = Readonly<{ + context: string + userAgent: string + userAgentData: unknown +}> + +export type BrowserSessionUaWireProbeServer = Readonly<{ + httpOrigin: string + httpsOrigin: string + receipts: WireProbeReceipt[] + identities: WireProbeJavaScriptIdentity[] + close: () => Promise +}> + +// A server listening on a TCP port always reports an AddressInfo; a string or null means the +// listen never took effect, which is worth failing on loudly rather than building a bad origin. +function boundPort(server: { address: () => AddressInfo | string | null }): number { + const address = server.address() + if (address === null || typeof address === 'string') { + throw new Error('wire_probe_server_not_listening_on_tcp') + } + return address.port +} + +export async function startBrowserSessionUaWireProbeServer(): Promise { + const receipts: WireProbeReceipt[] = [] + const identities: WireProbeJavaScriptIdentity[] = [] + const upgradedSockets = new Set() + let origins: { http: string; https: string } | null = null + const respond = + (protocol: 'http' | 'https') => + async (request: IncomingMessage, response: ServerResponse): Promise => { + const path = new URL(request.url ?? '/', 'http://probe.invalid').pathname + receipts.push({ + protocol, + path, + userAgent: + typeof request.headers['user-agent'] === 'string' ? request.headers['user-agent'] : null + }) + if (path.startsWith('/report/')) { + const body = await readBody(request) + identities.push({ context: path.slice('/report/'.length), ...JSON.parse(body) }) + respondText(response, 'ok') + return + } + if (path === '/shared-worker.js') { + respondScript(response, sharedWorkerScript(origins?.http ?? '')) + return + } + if (path === '/service-worker.js') { + response.setHeader('Service-Worker-Allowed', '/') + respondScript(response, serviceWorkerScript(origins?.http ?? '')) + return + } + if (path === '/frame') { + respondHtml(response, childPage('frame', origins?.http ?? '')) + return + } + if (path === '/popup') { + respondHtml(response, childPage('popup', origins?.http ?? '', true)) + return + } + if (path === '/desktop-peer') { + respondHtml(response, desktopPeerPage(origins?.http ?? '')) + return + } + if (path.endsWith('-image')) { + response.writeHead(200, { 'Cache-Control': 'no-store', 'Content-Type': 'image/gif' }) + response.end(Buffer.from('R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=', 'base64')) + return + } + if (path === '/') { + respondHtml(response, probePage(origins?.http ?? '', origins?.https ?? '')) + return + } + respondText(response, path) + } + const http = createHttpServer((request, response) => void respond('http')(request, response)) + const https = createHttpsServer( + { cert: LOCAL_HTTPS_TEST_CERTIFICATE, key: LOCAL_HTTPS_TEST_PRIVATE_KEY }, + (request, response) => void respond('https')(request, response) + ) + installWebSocketResponder(http, 'ws', receipts, upgradedSockets) + installWebSocketResponder(https, 'wss', receipts, upgradedSockets) + await Promise.all([listen(http), listen(https)]) + origins = { + http: `http://127.0.0.1:${boundPort(http)}`, + https: `https://127.0.0.1:${boundPort(https)}` + } + return { + httpOrigin: origins.http, + httpsOrigin: origins.https, + receipts, + identities, + close: async () => { + for (const socket of upgradedSockets) { + socket.destroy() + } + await Promise.all([closeServer(http), closeServer(https)]) + } + } +} + +function probePage(httpOrigin: string, httpsOrigin: string): string { + const blobScript = contextScript('blob', httpOrigin, ['/blob-fetch', '/blob-xhr', '/blob-image']) + const blobDocument = `` + const serializedBlobDocument = JSON.stringify(blobDocument).replace('', '<\\/script>') + return `UA wire probe` +} + +function childPage(context: string, httpOrigin: string, popup = false): string { + const extra = popup ? `await fetch(${JSON.stringify(httpOrigin)} + '/popup-fetch')` : '' + return `` +} + +function desktopPeerPage(httpOrigin: string): string { + return `` +} + +function contextScript(context: string, httpOrigin: string, routes: string[]): string { + return `(async () => { const identity = { userAgent: navigator.userAgent, userAgentData: navigator.userAgentData ? { brands: navigator.userAgentData.brands, mobile: navigator.userAgentData.mobile, platform: navigator.userAgentData.platform } : null }; await fetch(${JSON.stringify(httpOrigin)} + '/report/${context}', { method: 'POST', body: JSON.stringify(identity) }); await fetch(${JSON.stringify(httpOrigin + routes[0])}); await new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', ${JSON.stringify(httpOrigin + routes[1])}); xhr.onload = resolve; xhr.onerror = reject; xhr.send() }); await new Promise((resolve, reject) => { const image = new Image(); image.onload = resolve; image.onerror = reject; image.src = ${JSON.stringify(httpOrigin + routes[2])} }); parent.postMessage({ context: '${context}' }, '*') })()` +} + +function sharedWorkerScript(httpOrigin: string): string { + return `onconnect = event => { const port = event.ports[0]; (async () => { const identity = { userAgent: navigator.userAgent, userAgentData: navigator.userAgentData ? { brands: navigator.userAgentData.brands, mobile: navigator.userAgentData.mobile, platform: navigator.userAgentData.platform } : null }; await fetch(${JSON.stringify(httpOrigin)} + '/report/shared-worker', { method: 'POST', body: JSON.stringify(identity) }); await fetch(${JSON.stringify(httpOrigin)} + '/shared-worker-fetch-a'); await fetch(${JSON.stringify(httpOrigin)} + '/shared-worker-fetch-b'); port.postMessage({ context: 'shared-worker' }) })() }` +} + +function serviceWorkerScript(httpOrigin: string): string { + return `addEventListener('install', event => event.waitUntil(skipWaiting())); addEventListener('activate', event => event.waitUntil(clients.claim())); addEventListener('message', event => { if (event.data !== 'probe') return; event.waitUntil((async () => { const identity = { userAgent: navigator.userAgent, userAgentData: navigator.userAgentData ? { brands: navigator.userAgentData.brands, mobile: navigator.userAgentData.mobile, platform: navigator.userAgentData.platform } : null }; await fetch(${JSON.stringify(httpOrigin)} + '/report/service-worker', { method: 'POST', body: JSON.stringify(identity) }); await fetch(${JSON.stringify(httpOrigin)} + '/service-worker-fetch'); event.source.postMessage({ context: 'service-worker' }) })()) })` +} + +function installWebSocketResponder( + server: ReturnType | ReturnType, + protocol: 'ws' | 'wss', + receipts: WireProbeReceipt[], + upgradedSockets: Set +): void { + server.on('upgrade', (request, socket) => { + upgradedSockets.add(socket) + socket.once('close', () => upgradedSockets.delete(socket)) + const key = request.headers['sec-websocket-key'] + receipts.push({ + protocol, + path: new URL(request.url ?? '/', 'http://probe.invalid').pathname, + userAgent: + typeof request.headers['user-agent'] === 'string' ? request.headers['user-agent'] : null + }) + if (typeof key !== 'string') { + socket.destroy() + return + } + const accept = createHash('sha1') + .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) + .digest('base64') + socket.end( + `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n` + ) + }) +} + +function listen(server: ReturnType): Promise { + return new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', () => { + server.off('error', reject) + resolve() + }) + }) +} + +function closeServer(server: ReturnType): Promise { + server.closeAllConnections() + return new Promise((resolve) => server.close(() => resolve())) +} + +function readBody(request: IncomingMessage): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = [] + request.on('data', (chunk: Buffer) => chunks.push(chunk)) + request.once('end', () => resolve(Buffer.concat(chunks).toString('utf8'))) + request.once('error', reject) + }) +} + +function respondText(response: ServerResponse, body: string): void { + response.writeHead(200, { 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store' }) + response.end(body) +} + +function respondHtml(response: ServerResponse, body: string): void { + response.writeHead(200, { 'Cache-Control': 'no-store', 'Content-Type': 'text/html' }) + response.end(body) +} + +function respondScript(response: ServerResponse, body: string): void { + response.writeHead(200, { + 'Cache-Control': 'no-store', + 'Content-Type': 'application/javascript' + }) + response.end(body) +} From 3bf2fb8614edd7c1f2e0e524c35f564f0c51fdb8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 13 Sep 2026 17:59:44 -0700 Subject: [PATCH 02/40] test(browser): cover cross-context UA wire identity --- .../browser-session-ua-cdp-collector.ts | 26 +- ...re-identity-cross-context.electron.test.ts | 417 ++++++++++++++++++ .../browser-session-ua-wire-probe-server.ts | 83 +++- 3 files changed, 509 insertions(+), 17 deletions(-) create mode 100644 src/main/browser/browser-session-ua-wire-identity-cross-context.electron.test.ts diff --git a/src/main/browser/browser-session-ua-cdp-collector.ts b/src/main/browser/browser-session-ua-cdp-collector.ts index 7df8e5afe551..9cfb49bcf1dd 100644 --- a/src/main/browser/browser-session-ua-cdp-collector.ts +++ b/src/main/browser/browser-session-ua-cdp-collector.ts @@ -160,12 +160,34 @@ export class BrowserSessionUaCdpCollector { } return } + if (message.method === 'Target.targetCreated') { + const targetInfo = readRecord(message.params)?.targetInfo + const info = readRecord(targetInfo) + const targetType = readString(info, 'type') ?? 'unknown' + const targetId = readString(info, 'targetId') ?? 'unknown' + const targetUrl = readString(info, 'url') ?? '' + this.diagnostics.push(`target-created:${targetType}:${targetId}:${targetUrl}`) + if ((targetType === 'iframe' || targetType === 'worker') && targetId !== 'unknown') { + // Electron can report an isolated target before its automatic flattened attachment; attach + // explicitly so the frame/worker Network events remain target-scoped and auditable. + void this.send('Target.attachToTarget', { targetId, flatten: true }).catch( + (error: unknown) => { + this.diagnostics.push(`${targetType}-attach-error:${String(error)}`) + } + ) + } + } if (message.method === 'Target.attachedToTarget') { const params = readRecord(message.params) const attachedSessionId = readString(params, 'sessionId') if (attachedSessionId) { - const targetType = readString(readRecord(params?.targetInfo), 'type') ?? 'unknown' - this.diagnostics.push(`attached:${targetType}:${attachedSessionId}`) + const targetInfo = readRecord(params?.targetInfo) + const targetType = readString(targetInfo, 'type') ?? 'unknown' + const targetId = readString(targetInfo, 'targetId') ?? 'unknown' + const targetUrl = readString(targetInfo, 'url') ?? '' + this.diagnostics.push( + `attached:${targetType}:${targetId}:${targetUrl}:${attachedSessionId}` + ) this.targetsBySessionId.set(attachedSessionId, targetType) void this.prepareTarget(attachedSessionId) } diff --git a/src/main/browser/browser-session-ua-wire-identity-cross-context.electron.test.ts b/src/main/browser/browser-session-ua-wire-identity-cross-context.electron.test.ts new file mode 100644 index 000000000000..44f027225448 --- /dev/null +++ b/src/main/browser/browser-session-ua-wire-identity-cross-context.electron.test.ts @@ -0,0 +1,417 @@ +import { spawn, type ChildProcess } from 'node:child_process' +import { createServer } from 'node:net' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import { chromium } from 'playwright' +import { afterAll, describe, expect, it } from 'vitest' +import { build as buildVite } from 'vite' +import { + BrowserSessionUaCdpCollector, + type BrowserSessionUaCdpRequest, + waitForBrowserCdpEndpoint +} from './browser-session-ua-cdp-collector' +import { + startBrowserSessionUaWireProbeServer, + type WireProbeJavaScriptIdentity, + type WireProbeReceipt +} from './browser-session-ua-wire-probe-server' + +// This file is deliberately independent from the broad identity test. Its two arms make the +// pre-ready fallback itself the control variable for the cross-site and dedicated-worker probes. +const electronBinary = createRequire(import.meta.url)('electron') as string +const fixtureRoots: string[] = [] + +afterAll(() => { + for (const root of fixtureRoots) { + rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } +}) + +type ProbeArm = 'clean' | 'fallback-disabled' + +type ProbeResult = Readonly<{ + arm: ProbeArm + rawUserAgent: string + cleanUserAgent: string + navigatorUserAgent: string + receipts: readonly WireProbeReceipt[] + identities: readonly WireProbeJavaScriptIdentity[] + cdpRequests: readonly BrowserSessionUaCdpRequest[] + cdpDiagnostics: readonly string[] +}> + +describe('browser session wire identity in cross-site frames and dedicated workers', () => { + it('keeps OOPIF, dedicated-worker, and client-hint identities clean', async () => { + const result = await runProbe('clean') + assertCapturedContexts(result) + const checks = identityChecks(result) + expect(checks.crossSiteDocument).toBe(true) + expect(checks.crossSiteFetch).toBe(true) + expect(checks.dedicatedWorkerScript).toBe(true) + expect(checks.dedicatedWorkerFetch).toBe(true) + expect(checks.clientHints, JSON.stringify(receiptForPath(result.receipts, '/'))).toBe(true) + }, 60_000) + + it('turns every new clean-identity check red when the process fallback is removed', async () => { + const result = await runProbe('fallback-disabled') + assertCapturedContexts(result) + // These are explicit ablation controls: each predicate is the assertion used by the clean arm, + // and must be false when app.userAgentFallback is never assigned. + const checks = identityChecks(result) + expect(checks.crossSiteDocument).toBe(false) + expect(checks.crossSiteFetch).toBe(false) + expect(checks.dedicatedWorkerScript).toBe(false) + expect(checks.dedicatedWorkerFetch).toBe(false) + expect(checks.clientHints).toBe(false) + }, 60_000) +}) + +async function runProbe(arm: ProbeArm): Promise { + const root = mkdtempSync(join(tmpdir(), `orca-wire-cross-context-${arm}-`)) + fixtureRoots.push(root) + const processIdentityModulePath = join(root, 'browser-process-user-agent.cjs') + const exceptionModulePath = join(root, 'browser-session-ua.cjs') + await Promise.all([ + buildModule('src/main/browser/browser-process-user-agent.ts', processIdentityModulePath), + buildModule('src/main/browser/browser-session-ua.ts', exceptionModulePath) + ]) + const server = await startBrowserSessionUaWireProbeServer() + const resultPath = join(root, 'result.json') + const barrierPath = join(root, 'continue') + const fixturePath = join(root, 'main.cjs') + const cdpPort = await reservePort() + writeFileSync( + fixturePath, + fixtureMain({ + arm, + barrierPath, + exceptionModulePath, + httpOrigin: server.httpOrigin, + processIdentityModulePath, + resultPath + }) + ) + let process: ChildProcess | null = null + let collector: BrowserSessionUaCdpCollector | null = null + let browser: Awaited> | null = null + try { + process = launchFixture(fixturePath, root, cdpPort) + await waitForBrowserCdpEndpoint(cdpPort) + browser = await chromium.connectOverCDP(`http://127.0.0.1:${cdpPort}`) + collector = await BrowserSessionUaCdpCollector.connect(cdpPort) + await collector.installAutoAttach() + writeFileSync(barrierPath, '') + const processResult = await waitForProcess(process) + const fixtureResult = existsSync(resultPath) ? readFileSync(resultPath, 'utf8') : 'no result' + expect( + processResult.code, + `${fixtureResult}\n${processResult.stderr}\n${JSON.stringify({ diagnostics: collector.diagnostics, receipts: server.receipts, identities: server.identities })}` + ).toBe(0) + await new Promise((resolve) => setTimeout(resolve, 250)) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: JSON.parse is untyped; the fixture writes this exact shape before exiting. + const parsed = JSON.parse(fixtureResult) as Omit< + ProbeResult, + 'receipts' | 'identities' | 'cdpRequests' | 'cdpDiagnostics' + > + return { + ...parsed, + receipts: [...server.receipts], + identities: [...server.identities], + cdpDiagnostics: [...collector.diagnostics], + cdpRequests: collector.snapshot().filter(({ url }) => { + return ( + url.startsWith(server.httpOrigin) || + url.startsWith(server.crossSiteOrigin) || + url.startsWith(server.httpsOrigin) + ) + }) + } + } finally { + await collector?.close().catch(() => {}) + await browser?.close().catch(() => {}) + await server.close() + if (process && process.exitCode === null) { + process.kill('SIGTERM') + } + } +} + +async function buildModule(entry: string, outputPath: string): Promise { + await buildVite({ + configFile: false, + logLevel: 'silent', + build: { + emptyOutDir: false, + lib: { + entry: join(process.cwd(), entry), + formats: ['cjs'], + fileName: () => basename(outputPath) + }, + outDir: join(outputPath, '..'), + target: 'node20', + rollupOptions: { external: ['electron', /^node:/] } + } + }) +} + +function launchFixture(fixturePath: string, root: string, cdpPort: number): ChildProcess { + const { ELECTRON_RUN_AS_NODE: _electronRunAsNode, ...env } = process.env + const args = [ + fixturePath, + `--user-data-dir=${join(root, 'profile')}`, + `--remote-debugging-port=${cdpPort}`, + '--site-per-process' + ] + if (process.platform === 'linux') { + args.push('--no-sandbox') + } + return spawn( + process.platform === 'linux' ? 'xvfb-run' : electronBinary, + process.platform === 'linux' ? ['--auto-servernum', electronBinary, ...args] : args, + { + env: { ...env, ORCA_BACKGROUND_LAUNCH: '1' }, + stdio: ['ignore', 'pipe', 'pipe'] + } + ) +} + +function fixtureMain(options: { + arm: ProbeArm + barrierPath: string + exceptionModulePath: string + httpOrigin: string + processIdentityModulePath: string + resultPath: string +}): string { + return String.raw` +const { app, BrowserWindow, session } = require('electron') +const { existsSync, writeFileSync } = require('node:fs') +const processIdentity = require(${JSON.stringify(options.processIdentityModulePath)}) +const { cleanElectronUserAgent } = require(${JSON.stringify(options.exceptionModulePath)}) +const arm = ${JSON.stringify(options.arm)} +app.setName('OrcaCrossContextFixture') +app.commandLine.appendSwitch('site-per-process') +const rawUserAgent = app.userAgentFallback +if (arm === 'clean') processIdentity.initializeBrowserProcessUserAgent('clean') +const waitForBarrier = async () => { + const deadline = Date.now() + 15000 + while (!existsSync(${JSON.stringify(options.barrierPath)})) { + if (Date.now() >= deadline) throw new Error('startup barrier timeout') + await new Promise(resolve => setTimeout(resolve, 20)) + } +} +async function run() { + const timeout = setTimeout(() => { writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ error: 'timeout' })); app.exit(2) }, 20000) + await app.whenReady() + await waitForBarrier() + const sess = session.fromPartition('persist:wire-cross-context') + sess.setCertificateVerifyProc((_request, callback) => callback(0)) + const windows = [] + const window = new BrowserWindow({ show: false, webPreferences: { partition: 'persist:wire-cross-context', sandbox: true } }) + windows.push(window) + window.webContents.setWindowOpenHandler(() => ({ + action: 'allow', + createWindow: options => { + const popup = new BrowserWindow({ ...options, show: false }) + windows.push(popup) + return popup.webContents + } + })) + await window.loadURL(${JSON.stringify(options.httpOrigin)} + '/?cross-context=1') + const [navigatorUserAgent] = await Promise.all([ + window.webContents.executeJavaScript('navigator.userAgent'), + window.webContents.executeJavaScript('window.probePromise') + ]) + // Let Target.attachedToTarget and its Network events flush for the isolated frame before the + // fixture exits; the frame's own report/fetch receipts are the request-level proof. + await new Promise(resolve => setTimeout(resolve, 1500)) + clearTimeout(timeout) + writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ arm, rawUserAgent, cleanUserAgent: cleanElectronUserAgent(rawUserAgent), navigatorUserAgent })) + for (const candidate of windows) if (!candidate.isDestroyed()) candidate.destroy() + app.exit(0) +} +run().catch(error => { writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ error: String(error?.stack || error) })); app.exit(1) }) +` +} + +function assertCapturedContexts(result: ProbeResult): void { + const paths = new Set(result.receipts.map(({ path }) => path)) + for (const path of [ + '/', + '/cross-site-frame', + '/cross-site-frame-fetch', + '/dedicated-worker.js', + '/dedicated-worker-fetch', + '/report/cross-site-frame', + '/report/dedicated-worker' + ]) { + expect( + paths, + `${result.arm} omitted ${path}: ${JSON.stringify(result.cdpDiagnostics)}` + ).toContain(path) + } + expect( + result.cdpDiagnostics.some((message) => message.startsWith('attached:iframe:')), + JSON.stringify(result.cdpDiagnostics) + ).toBe(true) + expect( + result.cdpDiagnostics.some((message) => message.startsWith('attached:worker:')), + JSON.stringify(result.cdpDiagnostics) + ).toBe(true) + expect( + result.receipts + .filter(({ path }) => path === '/cross-site-frame') + .map(({ protocol }) => protocol) + ).toEqual(['https']) + expect( + result.receipts + .filter(({ path }) => path === '/cross-site-frame-fetch') + .map(({ protocol }) => protocol) + ).toEqual(['https']) + expect( + result.cdpRequests.some(({ url, targetType }) => { + return new URL(url).pathname === '/cross-site-frame-fetch' && targetType === 'iframe' + }), + JSON.stringify(result.cdpRequests.filter(({ url }) => url.includes('cross-site-frame-fetch'))) + ).toBe(true) +} + +function identityChecks(result: ProbeResult): Readonly> { + const frameIdentity = identityForContext(result.identities, 'cross-site-frame') + const workerIdentity = identityForContext(result.identities, 'dedicated-worker') + const frameReceipt = receiptForPath(result.receipts, '/cross-site-frame-fetch') + const workerScriptReceipt = receiptForPath(result.receipts, '/dedicated-worker.js') + const workerFetchReceipt = receiptForPath(result.receipts, '/dedicated-worker-fetch') + // Chromium omits client hints on the initial navigation but sends them on the document's + // subsequent fetch; use that captured wire request to compare sec-ch-ua with the same document's + // navigator.userAgentData. + const rootReceipt = receiptForPath(result.receipts, '/report/document') + return { + crossSiteDocument: frameIdentity.userAgent === result.cleanUserAgent, + crossSiteFetch: frameReceipt.userAgent === result.cleanUserAgent, + dedicatedWorkerScript: workerScriptReceipt.userAgent === result.cleanUserAgent, + dedicatedWorkerFetch: + workerIdentity.userAgent === result.cleanUserAgent && + workerFetchReceipt.userAgent === result.cleanUserAgent, + clientHints: clientHintIdentityIsClean( + rootReceipt, + identityForContext(result.identities, 'document'), + result.cleanUserAgent + ) + } +} + +function clientHintIdentityIsClean( + receipt: WireProbeReceipt, + identity: WireProbeJavaScriptIdentity, + cleanUserAgent: string +): boolean { + // Electron's stock UA-CH remains Chromium-shaped even when the fallback is disabled. Compare + // its brands exactly, but require the same wire request to carry the clean legacy UA too; this is + // the strongest true one-identity invariant and makes the ablation red on the Electron token. + const secChUa = receipt.clientHints['sec-ch-ua'] + const wireBrands = parseSecChUa(secChUa) + const navigatorBrands = readNavigatorBrands(identity.userAgentData) + if (!secChUa || wireBrands.length === 0 || navigatorBrands.length === 0) { + return false + } + const token = /electron|orca/i + return ( + receipt.userAgent === cleanUserAgent && + !token.test(receipt.userAgent ?? '') && + !token.test(secChUa) && + !navigatorBrands.some(({ brand, version }) => token.test(brand) || token.test(version)) && + sameBrands(wireBrands, navigatorBrands) + ) +} + +function parseSecChUa(value: string | undefined): { brand: string; version: string }[] { + if (!value) { + return [] + } + const brands: { brand: string; version: string }[] = [] + const pattern = /"([^"]+)"\s*;\s*v="([^"]*)"/g + for (const match of value.matchAll(pattern)) { + const brand = match[1] + const version = match[2] + if (brand !== undefined && version !== undefined) { + brands.push({ brand, version }) + } + } + return brands +} + +function readNavigatorBrands(value: unknown): { brand: string; version: string }[] { + if (typeof value !== 'object' || value === null) { + return [] + } + const brandsValue = Object.entries(value).find(([key]) => key === 'brands')?.[1] + if (!Array.isArray(brandsValue)) { + return [] + } + const brands: { brand: string; version: string }[] = [] + for (const entry of brandsValue) { + if (typeof entry !== 'object' || entry === null) { + continue + } + const fields = Object.fromEntries(Object.entries(entry)) + const brand = fields.brand + const version = fields.version + if (typeof brand === 'string' && typeof version === 'string') { + brands.push({ brand, version }) + } + } + return brands +} + +function sameBrands( + left: readonly { brand: string; version: string }[], + right: readonly { brand: string; version: string }[] +): boolean { + const normalize = (brands: readonly { brand: string; version: string }[]) => + brands.map(({ brand, version }) => `${brand}\u0000${version}`).sort() + return JSON.stringify(normalize(left)) === JSON.stringify(normalize(right)) +} + +function identityForContext( + identities: readonly WireProbeJavaScriptIdentity[], + context: string +): WireProbeJavaScriptIdentity { + const matches = identities.filter((identity) => identity.context === context) + expect(matches, context).toHaveLength(1) + return matches[0]! +} + +function receiptForPath(receipts: readonly WireProbeReceipt[], path: string): WireProbeReceipt { + const matches = receipts.filter((receipt) => receipt.path === path) + expect(matches, path).not.toHaveLength(0) + return matches[0]! +} + +async function reservePort(): Promise { + const server = createServer() + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(0, '127.0.0.1', resolve) + }) + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('cdp port unavailable') + } + await new Promise((resolve) => server.close(() => resolve())) + return address.port +} + +function waitForProcess(process: ChildProcess): Promise<{ code: number | null; stderr: string }> { + let stderr = '' + process.stderr?.setEncoding('utf8') + process.stderr?.on('data', (chunk: string) => { + stderr += chunk + }) + return new Promise((resolve, reject) => { + process.once('error', reject) + process.once('exit', (code) => resolve({ code, stderr })) + }) +} diff --git a/src/main/browser/browser-session-ua-wire-probe-server.ts b/src/main/browser/browser-session-ua-wire-probe-server.ts index 9a1012491c4a..d00117ad86b8 100644 --- a/src/main/browser/browser-session-ua-wire-probe-server.ts +++ b/src/main/browser/browser-session-ua-wire-probe-server.ts @@ -16,6 +16,7 @@ export type WireProbeReceipt = Readonly<{ protocol: 'http' | 'https' | 'ws' | 'wss' path: string userAgent: string | null + clientHints: Readonly> }> export type WireProbeJavaScriptIdentity = Readonly<{ @@ -26,14 +27,12 @@ export type WireProbeJavaScriptIdentity = Readonly<{ export type BrowserSessionUaWireProbeServer = Readonly<{ httpOrigin: string + crossSiteOrigin: string httpsOrigin: string receipts: WireProbeReceipt[] identities: WireProbeJavaScriptIdentity[] close: () => Promise }> - -// A server listening on a TCP port always reports an AddressInfo; a string or null means the -// listen never took effect, which is worth failing on loudly rather than building a bad origin. function boundPort(server: { address: () => AddressInfo | string | null }): number { const address = server.address() if (address === null || typeof address === 'string') { @@ -41,7 +40,6 @@ function boundPort(server: { address: () => AddressInfo | string | null }): numb } return address.port } - export async function startBrowserSessionUaWireProbeServer(): Promise { const receipts: WireProbeReceipt[] = [] const identities: WireProbeJavaScriptIdentity[] = [] @@ -55,7 +53,8 @@ export async function startBrowserSessionUaWireProbeServer(): Promise` const serializedBlobDocument = JSON.stringify(blobDocument).replace('', '<\\/script>') + const crossSiteFrameScript = crossContext + ? `const crossSiteFrame = document.createElement('iframe'); crossSiteFrame.src = ${JSON.stringify(crossSiteOrigin)} + '/cross-site-frame'; document.body.append(crossSiteFrame)` + : '' + const dedicatedWorkerScriptText = crossContext + ? `const dedicatedDone = message('dedicated-worker'); const dedicated = new Worker(${JSON.stringify(httpOrigin)} + '/dedicated-worker.js'); dedicated.onmessage = event => postMessage(event.data, '*')` + : '' return `UA wire probe` } - -function childPage(context: string, httpOrigin: string, popup = false): string { +function childPage( + context: string, + httpOrigin: string, + popup = false, + fetchOrigin = httpOrigin +): string { const extra = popup ? `await fetch(${JSON.stringify(httpOrigin)} + '/popup-fetch')` : '' - return `` + const crossSiteFetch = + context === 'cross-site-frame' + ? `await fetch(${JSON.stringify(fetchOrigin)} + '/cross-site-frame-fetch')` + : '' + return `` } function desktopPeerPage(httpOrigin: string): string { @@ -171,14 +212,15 @@ function desktopPeerPage(httpOrigin: string): string { })() ` } - function contextScript(context: string, httpOrigin: string, routes: string[]): string { return `(async () => { const identity = { userAgent: navigator.userAgent, userAgentData: navigator.userAgentData ? { brands: navigator.userAgentData.brands, mobile: navigator.userAgentData.mobile, platform: navigator.userAgentData.platform } : null }; await fetch(${JSON.stringify(httpOrigin)} + '/report/${context}', { method: 'POST', body: JSON.stringify(identity) }); await fetch(${JSON.stringify(httpOrigin + routes[0])}); await new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', ${JSON.stringify(httpOrigin + routes[1])}); xhr.onload = resolve; xhr.onerror = reject; xhr.send() }); await new Promise((resolve, reject) => { const image = new Image(); image.onload = resolve; image.onerror = reject; image.src = ${JSON.stringify(httpOrigin + routes[2])} }); parent.postMessage({ context: '${context}' }, '*') })()` } - function sharedWorkerScript(httpOrigin: string): string { return `onconnect = event => { const port = event.ports[0]; (async () => { const identity = { userAgent: navigator.userAgent, userAgentData: navigator.userAgentData ? { brands: navigator.userAgentData.brands, mobile: navigator.userAgentData.mobile, platform: navigator.userAgentData.platform } : null }; await fetch(${JSON.stringify(httpOrigin)} + '/report/shared-worker', { method: 'POST', body: JSON.stringify(identity) }); await fetch(${JSON.stringify(httpOrigin)} + '/shared-worker-fetch-a'); await fetch(${JSON.stringify(httpOrigin)} + '/shared-worker-fetch-b'); port.postMessage({ context: 'shared-worker' }) })() }` } +function dedicatedWorkerScript(httpOrigin: string): string { + return `const identity = { userAgent: navigator.userAgent, userAgentData: navigator.userAgentData ? { brands: navigator.userAgentData.brands, mobile: navigator.userAgentData.mobile, platform: navigator.userAgentData.platform } : null }; (async () => { await fetch(${JSON.stringify(httpOrigin)} + '/report/dedicated-worker', { method: 'POST', body: JSON.stringify(identity) }); await fetch(${JSON.stringify(httpOrigin)} + '/dedicated-worker-fetch'); postMessage({ context: 'dedicated-worker' }); })();` +} function serviceWorkerScript(httpOrigin: string): string { return `addEventListener('install', event => event.waitUntil(skipWaiting())); addEventListener('activate', event => event.waitUntil(clients.claim())); addEventListener('message', event => { if (event.data !== 'probe') return; event.waitUntil((async () => { const identity = { userAgent: navigator.userAgent, userAgentData: navigator.userAgentData ? { brands: navigator.userAgentData.brands, mobile: navigator.userAgentData.mobile, platform: navigator.userAgentData.platform } : null }; await fetch(${JSON.stringify(httpOrigin)} + '/report/service-worker', { method: 'POST', body: JSON.stringify(identity) }); await fetch(${JSON.stringify(httpOrigin)} + '/service-worker-fetch'); event.source.postMessage({ context: 'service-worker' }) })()) })` @@ -198,7 +240,8 @@ function installWebSocketResponder( protocol, path: new URL(request.url ?? '/', 'http://probe.invalid').pathname, userAgent: - typeof request.headers['user-agent'] === 'string' ? request.headers['user-agent'] : null + typeof request.headers['user-agent'] === 'string' ? request.headers['user-agent'] : null, + clientHints: requestClientHints(request) }) if (typeof key !== 'string') { socket.destroy() @@ -242,6 +285,16 @@ function respondText(response: ServerResponse, body: string): void { response.end(body) } +function requestClientHints(request: IncomingMessage): Record { + return Object.fromEntries( + Object.entries(request.headers).flatMap(([key, value]) => + key.toLowerCase().startsWith('sec-ch-ua') && typeof value === 'string' + ? [[key.toLowerCase(), value]] + : [] + ) + ) +} + function respondHtml(response: ServerResponse, body: string): void { response.writeHead(200, { 'Cache-Control': 'no-store', 'Content-Type': 'text/html' }) response.end(body) From 02b0ed1816f9b0c94aaa51d6e1d2d980c5781d3d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 13 Sep 2026 18:30:23 -0700 Subject: [PATCH 03/40] refactor(browser): make user agent identity app-wide --- docs/site/content/docs/browser/overview.mdx | 2 +- docs/site/content/docs/browser/profiles.mdx | 11 +- src/cli/browser-format.ts | 3 +- src/cli/browser.test.ts | 50 ----- src/cli/handlers/browser-profile.ts | 3 +- src/cli/help.ts | 1 - src/cli/root-help-text-secondary.ts | 1 - src/cli/specs/browser-basic.ts | 5 +- src/main/browser/browser-google-auth-ua.ts | 13 ++ .../browser/browser-identity-mode-record.ts | 52 ++++- .../browser-manager-auth-user-agent.test.ts | 108 ++--------- ...rowser-manager-load-failure-replay.test.ts | 7 + .../browser/browser-manager-navigation.ts | 90 +++++++-- .../browser/browser-manager-registration.ts | 20 +- src/main/browser/browser-manager-state.ts | 36 +++- src/main/browser/browser-manager-types.ts | 3 - .../browser-manager-viewport-override.test.ts | 43 +++-- src/main/browser/browser-manager-viewport.ts | 19 +- .../browser/browser-process-user-agent.ts | 6 +- ...browser-session-partition-policies.test.ts | 10 +- .../browser-session-partition-policies.ts | 62 +++--- ...er-session-partition-proxy-install.test.ts | 11 +- ...er-session-persisted-profile-validation.ts | 31 ++- .../browser-session-profile-retirement.ts | 2 - ...owser-session-registry.persistence.test.ts | 128 ++++++------- .../browser/browser-session-registry.test.ts | 34 ++-- src/main/browser/browser-session-registry.ts | 39 ++-- .../browser/browser-session-route-policies.ts | 2 - src/main/browser/browser-session-ua.ts | 147 ++++++++++---- .../browser-session-user-agent-mode.ts | 22 --- .../browser/browser-viewport-user-agent.ts | 3 +- .../browser-webauthn-profile-delete.test.ts | 6 + src/main/browser/doc-preview-protocol.test.ts | 2 +- src/main/browser/doc-preview-protocol.ts | 3 +- src/main/browser/offscreen-browser-backend.ts | 1 - .../ipc/browser-session-profile-ipc.test.ts | 14 +- src/main/ipc/browser-session-profile-ipc.ts | 31 ++- src/main/ipc/browser.ts | 3 - .../applying-settings/settings-update.ts | 6 + .../normalize-loaded-global-settings.ts | 2 + src/main/runtime/orca-runtime-browser.test.ts | 15 +- src/main/runtime/rpc/methods/browser.test.ts | 12 +- ...rowser-commands-browser-tab-set-profile.ts | 6 +- ...rowser-process-user-agent-ordering.test.ts | 180 ++++++++++++++++++ src/main/startup/main-process-preflight.ts | 18 +- .../startup/main-process-ready-foundation.ts | 6 + src/preload/api/browser-api.ts | 13 +- ...er-bridge-page-interaction-and-sessions.ts | 11 +- .../assemble-chrome/BrowserToolbarMenu.tsx | 12 +- .../browser-toolbar-profile-dialogs.tsx | 11 -- .../browser-user-agent-migration-notice.ts | 38 ++++ .../browser-page-webview-guest-session.ts | 2 + ...browser-profile-user-agent-option.test.tsx | 43 ----- .../browser-profile-user-agent-option.tsx | 43 ----- .../settings/BrowserNewProfileDialog.tsx | 15 +- .../src/components/settings/BrowserPane.tsx | 6 + .../components/settings/BrowserProfileRow.tsx | 9 +- .../settings/BrowserUserAgentSetting.tsx | 62 ++++++ .../settings/browser-search.test.ts | 3 +- .../src/components/settings/browser-search.ts | 15 ++ .../src/lib/settings-navigation-types.ts | 1 + .../slices/browser-session-profiles.test.ts | 23 +-- .../browser/browser-profile-list-actions.ts | 11 +- .../slices/browser/browser-slice-contract.ts | 4 +- src/shared/browser-user-agent-mode.ts | 5 + src/shared/browser-workspace-types.ts | 7 - src/shared/default-global-settings.ts | 1 + src/shared/global-settings-types.ts | 3 + src/shared/rpc-contract/browser-params.ts | 3 +- 69 files changed, 937 insertions(+), 673 deletions(-) delete mode 100644 src/main/browser/browser-session-user-agent-mode.ts create mode 100644 src/main/startup/browser-process-user-agent-ordering.test.ts create mode 100644 src/renderer/src/components/browser-pane/browser-user-agent-migration-notice.ts delete mode 100644 src/renderer/src/components/browser-profile-user-agent-option.test.tsx delete mode 100644 src/renderer/src/components/browser-profile-user-agent-option.tsx create mode 100644 src/renderer/src/components/settings/BrowserUserAgentSetting.tsx create mode 100644 src/shared/browser-user-agent-mode.ts diff --git a/docs/site/content/docs/browser/overview.mdx b/docs/site/content/docs/browser/overview.mdx index d248318da694..93890cf98bdf 100644 --- a/docs/site/content/docs/browser/overview.mdx +++ b/docs/site/content/docs/browser/overview.mdx @@ -62,4 +62,4 @@ The browser is also scriptable by agents via the [Orca CLI](/docs/cli/overview) ## Next steps - [Design Mode](/docs/browser/design-mode) — turn the browser into a pointer-to-code feedback loop. -- [Browser-use profiles](/docs/browser/profiles) — run the browser with a specific login, cookie jar, or user agent. +- [Browser-use profiles](/docs/browser/profiles) — run the browser with a specific login or cookie jar. diff --git a/docs/site/content/docs/browser/profiles.mdx b/docs/site/content/docs/browser/profiles.mdx index fd9af7176e25..83efdf2faf54 100644 --- a/docs/site/content/docs/browser/profiles.mdx +++ b/docs/site/content/docs/browser/profiles.mdx @@ -2,16 +2,19 @@ title: Browser-use profiles --- -Browser-use profiles let you run the Orca browser with a specific identity — a logged-in user, a particular cookie jar, a custom user-agent. Useful when an agent needs to log in, reproduce a session-specific bug, or emulate multiple users. +Browser-use profiles let you run the Orca browser with a specific identity — a logged-in user or a particular cookie jar. Useful when an agent needs to log in, reproduce a session-specific bug, or emulate multiple users. ## Create a profile 1. Open [Settings → Browser → Profiles](/docs/settings). 1. Click **Add profile**, give it a name. -1. Optionally seed it with cookies, a user-agent, and a viewport size. -1. Default profiles remove Orca and Electron tokens from the browser engine's user agent, preserving the Chrome-shaped identity expected by imported sessions. This focused compatibility measure does not make the embedded browser identical to Chrome. Google sign-in hosts use a scoped Firefox identity. If a site rejects the cleaned identity, including some Cloudflare-protected sites, create a profile that keeps the **native Electron user agent** instead. +1. Optionally seed it with cookies and a viewport size. -You can also create a no-spoof profile from the CLI with `orca tab profile create --no-ua-spoof` when you script browser setup. +## Browser identity + +The browser user agent is an app-wide choice because documents and web workers must present one coherent identity. Open **Settings → Browser → Browser identity** to choose between the cleaned identity and Electron's native identity. The change takes effect after you restart Orca. + +The cleaned identity removes Orca and Electron tokens from the browser engine's user agent, preserving the Chrome-shaped identity expected by imported sessions. This focused compatibility measure does not make the embedded browser identical to Chrome. Google sign-in hosts use a scoped Firefox identity. If a site rejects the cleaned identity, including some Cloudflare-protected sites, switch the app-wide setting to **Native** and restart Orca. ## Cookie import and Google sign-in diff --git a/src/cli/browser-format.ts b/src/cli/browser-format.ts index 76fdc18db752..0c4466e97558 100644 --- a/src/cli/browser-format.ts +++ b/src/cli/browser-format.ts @@ -47,8 +47,7 @@ export function formatBrowserProfileList(result: BrowserProfileListResult): stri .map((profile) => { const marker = profile.scope === 'default' ? '* ' : ' ' const source = profile.source?.browserFamily ?? 'none' - const userAgent = profile.userAgentMode === 'native' ? ' ua:native' : '' - return `${marker}${profile.id} ${profile.label} ${profile.scope} source:${source}${userAgent}` + return `${marker}${profile.id} ${profile.label} ${profile.scope} source:${source}` }) .join('\n') } diff --git a/src/cli/browser.test.ts b/src/cli/browser.test.ts index f1dff8bc3027..04a6363f2cca 100644 --- a/src/cli/browser.test.ts +++ b/src/cli/browser.test.ts @@ -435,29 +435,6 @@ describe('orca cli browser tab profiles', () => { expect(logSpy).toHaveBeenCalledWith('No browser profiles found.') }) - it('marks native-UA profiles in text output', async () => { - queueFixtures( - callMock, - okFixture('req_profiles_native_ua', { - profiles: [ - { - id: 'google', - scope: 'isolated', - label: 'Google', - partition: 'persist:orca-browser-session-google', - source: null, - userAgentMode: 'native' - } - ] - }) - ) - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main(['tab', 'profile', 'list'], '/tmp/not-an-orca-worktree') - - expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('ua:native')) - }) - it('creates isolated browser tab profiles by default', async () => { queueFixtures( callMock, @@ -509,33 +486,6 @@ describe('orca cli browser tab profiles', () => { }) }) - it('creates a profile with the native user agent when requested', async () => { - queueFixtures( - callMock, - okFixture('req_profile_native_ua', { - profile: { - id: 'google', - scope: 'isolated', - label: 'Google', - partition: 'persist:orca-browser-session-google', - userAgentMode: 'native' - } - }) - ) - vi.spyOn(console, 'log').mockImplementation(() => {}) - - await main( - ['tab', 'profile', 'create', '--label', 'Google', '--no-ua-spoof', '--json'], - '/tmp/not-an-orca-worktree' - ) - - expect(callMock).toHaveBeenCalledWith('browser.profileCreate', { - label: 'Google', - scope: 'isolated', - userAgentMode: 'native' - }) - }) - it('rejects unknown --scope values instead of silently defaulting to isolated', async () => { const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) diff --git a/src/cli/handlers/browser-profile.ts b/src/cli/handlers/browser-profile.ts index 769980f2d319..4dc8ad731b3d 100644 --- a/src/cli/handlers/browser-profile.ts +++ b/src/cli/handlers/browser-profile.ts @@ -38,8 +38,7 @@ export const BROWSER_PROFILE_HANDLERS: Record = { const scope = parseScopeFlag(flags) const result = await client.call('browser.profileCreate', { label, - scope, - ...(flags.get('no-ua-spoof') === true ? { userAgentMode: 'native' } : {}) + scope }) if (result.result.profile === null) { // Why: registry refuses non-isolated/imported scopes; we already validated diff --git a/src/cli/help.ts b/src/cli/help.ts index 9d722388ae47..6e15d8014e72 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -285,7 +285,6 @@ export function formatFlagHelp(flag: string): string { page: '--page Stable browser page id from `orca tab list --json`', profile: '--profile Browser profile id', 'show-profile': '--show-profile Include tab profile in text output', - 'no-ua-spoof': "--no-ua-spoof Keep Electron's native user agent", format: '--format Screenshot image format' } diff --git a/src/cli/root-help-text-secondary.ts b/src/cli/root-help-text-secondary.ts index 50a1a76de7d1..e9a672969151 100644 --- a/src/cli/root-help-text-secondary.ts +++ b/src/cli/root-help-text-secondary.ts @@ -142,7 +142,6 @@ export const ROOT_HELP_TEXT_SECONDARY = [ ' --page Stable browser page id (preferred for concurrent workflows)', ' --profile Browser profile id', " --show-profile Include the tab's browser profile in text output", - " --no-ua-spoof Keep Electron's native user agent for a new profile", ' --format Screenshot image format', ' --from Drag source element ref', ' --to Drag target element ref', diff --git a/src/cli/specs/browser-basic.ts b/src/cli/specs/browser-basic.ts index 7e3bb4a5770b..7691946824ec 100644 --- a/src/cli/specs/browser-basic.ts +++ b/src/cli/specs/browser-basic.ts @@ -196,9 +196,8 @@ export const BROWSER_BASIC_COMMAND_SPECS: CommandSpec[] = [ { path: ['tab', 'profile', 'create'], summary: 'Create a browser session profile for browser tabs', - usage: - 'orca tab profile create --label [--scope ] [--no-ua-spoof] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'label', 'scope', 'no-ua-spoof'] + usage: 'orca tab profile create --label [--scope ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'label', 'scope'] }, { path: ['tab', 'profile', 'delete'], diff --git a/src/main/browser/browser-google-auth-ua.ts b/src/main/browser/browser-google-auth-ua.ts index e9b802f6d70f..150412415454 100644 --- a/src/main/browser/browser-google-auth-ua.ts +++ b/src/main/browser/browser-google-auth-ua.ts @@ -20,6 +20,19 @@ export function isGoogleAuthUrl(rawUrl: string): boolean { } } +export function shouldUseGoogleAuthIdentity( + url: string, + referrer: string, + resourceType: string +): boolean { + if (isGoogleAuthUrl(url)) { + return true + } + // Why: early cross-host subresources can leave before the WebContents Firefox override lands; + // the auth referrer identifies their owning flow. Main-frame exits restore the process identity. + return resourceType !== 'mainFrame' && isGoogleAuthUrl(referrer) +} + // Why: rv:/Gecko/Firefox tokens must line up with a real released build and the // platform token must match the host OS, or the UA is internally inconsistent and // itself a bot tell. diff --git a/src/main/browser/browser-identity-mode-record.ts b/src/main/browser/browser-identity-mode-record.ts index 67459dd48d2f..00ca30e2c16c 100644 --- a/src/main/browser/browser-identity-mode-record.ts +++ b/src/main/browser/browser-identity-mode-record.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { writeFileAtomically } from '../codex-accounts/fs-utils' -import type { BrowserSessionUserAgentMode } from '../../shared/browser-workspace-types' +import type { BrowserUserAgentMode } from '../../shared/browser-user-agent-mode' /** * The browser's identity is one process-wide decision, not a per-profile one. @@ -24,10 +24,10 @@ export const BROWSER_IDENTITY_MODE_VERSION = 1 export type BrowserIdentityModeRecord = { version: typeof BROWSER_IDENTITY_MODE_VERSION - mode: BrowserSessionUserAgentMode + mode: BrowserUserAgentMode /** Profiles that carried the retired per-profile `native` mode, so the browser can say so once. */ migratedNativeProfileIds?: string[] - /** Cleared once the user has been told their per-profile choice no longer exists. */ + /** Cleared after the renderer confirms it displayed the migration notice. */ migrationNoticePending?: boolean } @@ -73,3 +73,49 @@ export function writeBrowserIdentityModeRecord( `${JSON.stringify(record, null, 2)}\n` ) } + +export function updateBrowserIdentityMode(userDataPath: string, mode: BrowserUserAgentMode): void { + const current = readBrowserIdentityModeRecord(userDataPath) + if (current.mode === mode) { + return + } + writeBrowserIdentityModeRecord(userDataPath, { ...current, mode }) +} + +export function recordRetiredNativeBrowserProfiles( + userDataPath: string, + profileIds: readonly string[] +): void { + if (profileIds.length === 0) { + return + } + const current = readBrowserIdentityModeRecord(userDataPath) + const migratedNativeProfileIds = [ + ...new Set([...(current.migratedNativeProfileIds ?? []), ...profileIds]) + ] + writeBrowserIdentityModeRecord(userDataPath, { + ...current, + migratedNativeProfileIds, + migrationNoticePending: true + }) +} + +export function readPendingBrowserIdentityMigrationNotice(userDataPath: string): string[] | null { + const current = readBrowserIdentityModeRecord(userDataPath) + if (current.migrationNoticePending !== true) { + return null + } + return current.migratedNativeProfileIds ?? [] +} + +export function clearBrowserIdentityMigrationNotice(userDataPath: string): boolean { + const current = readBrowserIdentityModeRecord(userDataPath) + if (current.migrationNoticePending !== true) { + return false + } + writeBrowserIdentityModeRecord(userDataPath, { + ...current, + migrationNoticePending: undefined + }) + return true +} diff --git a/src/main/browser/browser-manager-auth-user-agent.test.ts b/src/main/browser/browser-manager-auth-user-agent.test.ts index 71e128a9c728..d85a785a8871 100644 --- a/src/main/browser/browser-manager-auth-user-agent.test.ts +++ b/src/main/browser/browser-manager-auth-user-agent.test.ts @@ -12,7 +12,9 @@ const browserMocks = vi.hoisted(() => ({ guestOpenDevToolsMock: vi.fn(), webContentsFromIdMock: vi.fn(), screenGetCursorScreenPointMock: vi.fn(() => ({ x: 0, y: 0 })), - openPopupWithOriginBarMock: vi.fn() + openPopupWithOriginBarMock: vi.fn(), + processUserAgentMode: 'clean', + processUserAgent: 'Mozilla/5.0 (Test) Chrome/140.0.0.0' })) vi.mock('electron', () => ({ @@ -39,9 +41,15 @@ vi.mock('./popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) +vi.mock('./browser-process-user-agent', () => ({ + getBrowserProcessUserAgentIdentity: () => ({ + mode: browserMocks.processUserAgentMode, + userAgent: browserMocks.processUserAgent + }) +})) + import { browserManager } from './browser-manager' import { googleAuthUserAgent } from './browser-google-auth-ua' -import { setBrowserSessionUserAgentMode } from './browser-session-user-agent-mode' import { guestBaseUserAgent, rendererWebContentsId, @@ -68,6 +76,8 @@ describe('browserManager', () => { beforeEach(() => { resetBrowserManagerMocks(browserMocks) resetBrowserManagerState() + browserMocks.processUserAgentMode = 'clean' + browserMocks.processUserAgent = guestBaseUserAgent }) afterEach(() => { @@ -133,7 +143,8 @@ describe('browserManager', () => { expect(setUserAgent).not.toHaveBeenCalled() }) - it('leaves the UA untouched on Google auth hosts for native-UA profiles', () => { + it('leaves the UA untouched on Google auth hosts in native process mode', () => { + browserMocks.processUserAgentMode = 'native' const setUserAgent = vi.fn() const guest = { id: 409, @@ -155,8 +166,7 @@ describe('browserManager', () => { browserManager.registerGuest({ browserPageId: 'browser-native-ua', webContentsId: guest.id, - rendererWebContentsId, - userAgentMode: 'native' + rendererWebContentsId }) const didStartNavigation = guestOnMock.mock.calls.find( ([event]) => event === 'did-start-navigation' @@ -167,93 +177,6 @@ describe('browserManager', () => { expect(setUserAgent).not.toHaveBeenCalled() }) - it('honors native session mode before the guest registration IPC arrives', () => { - const nativeSession = { getUserAgent: vi.fn(() => guestBaseUserAgent) } - setBrowserSessionUserAgentMode(nativeSession as never, 'native') - const setUserAgent = vi.fn() - const guest = { - id: 417, - isDestroyed: vi.fn(() => false), - getType: vi.fn(() => 'webview'), - setBackgroundThrottling: guestSetBackgroundThrottlingMock, - setWindowOpenHandler: guestSetWindowOpenHandlerMock, - on: guestOnMock, - off: guestOffMock, - openDevTools: guestOpenDevToolsMock, - getURL: vi.fn(() => 'https://accounts.google.com/'), - getUserAgent: vi.fn(() => guestBaseUserAgent), - setUserAgent, - session: nativeSession - } - - browserManager.attachGuestPolicies(guest as never) - const didStartNavigation = guestOnMock.mock.calls.find( - ([event]) => event === 'did-start-navigation' - )?.[1] as (event: unknown, url: string, isInPlace: boolean, isMainFrame: boolean) => void - - didStartNavigation(null, 'https://accounts.google.com/v3/signin/identifier', false, true) - expect(setUserAgent).not.toHaveBeenCalled() - }) - - // Why: popup child windows get attachGuestPolicies but are never entered into tabIdByWebContentsId, - // so a direct lookup of the UA mode misses the native opt-out. That is worse than doing nothing — - // native sessions skip setupGoogleAuthUserAgentOverride, so the popup would send the raw Electron UA on the - // wire while navigator.userAgent claimed Firefox. Google sign-in popups are a first-class surface. - it('leaves the UA untouched on auth hosts for a popup owned by a native-UA profile', () => { - const ownerGuest = { - id: 415, - isDestroyed: vi.fn(() => false), - getType: vi.fn(() => 'webview'), - setBackgroundThrottling: guestSetBackgroundThrottlingMock, - setWindowOpenHandler: guestSetWindowOpenHandlerMock, - on: guestOnMock, - off: guestOffMock, - openDevTools: guestOpenDevToolsMock, - getURL: vi.fn(() => 'https://accounts.google.com/'), - getUserAgent: vi.fn(() => guestBaseUserAgent), - setUserAgent: vi.fn(), - session: { getUserAgent: vi.fn(() => guestBaseUserAgent) } - } - webContentsFromIdMock.mockReturnValue(ownerGuest) - browserManager.attachGuestPolicies(ownerGuest as never) - browserManager.registerGuest({ - browserPageId: 'browser-native-popup-owner', - webContentsId: ownerGuest.id, - rendererWebContentsId, - userAgentMode: 'native' - }) - - // The popup carries its own listeners so its handler is unambiguous. - const popupOn = vi.fn() - const popupSetUserAgent = vi.fn() - const popupGuest = { - id: 416, - isDestroyed: vi.fn(() => false), - getType: vi.fn(() => 'window'), - setBackgroundThrottling: guestSetBackgroundThrottlingMock, - setWindowOpenHandler: guestSetWindowOpenHandlerMock, - on: popupOn, - off: guestOffMock, - openDevTools: guestOpenDevToolsMock, - getURL: vi.fn(() => 'https://accounts.google.com/'), - getUserAgent: vi.fn(() => guestBaseUserAgent), - setUserAgent: popupSetUserAgent, - session: { getUserAgent: vi.fn(() => guestBaseUserAgent) } - } - browserManager.attachGuestPolicies(popupGuest as never, { - browserTabId: 'browser-native-popup-owner', - rootGuestWebContentsId: ownerGuest.id - }) - - const popupDidStartNavigation = popupOn.mock.calls.find( - ([event]) => event === 'did-start-navigation' - )?.[1] as (event: unknown, url: string, isInPlace: boolean, isMainFrame: boolean) => void - expect(popupDidStartNavigation).toBeDefined() - - popupDidStartNavigation(null, 'https://accounts.google.com/v3/signin/identifier', false, true) - expect(popupSetUserAgent).not.toHaveBeenCalled() - }) - // Why: WebContents.setUserAgent() from will-redirect makes Chromium cancel the in-flight navigation // (ERR_ABORTED) and replay the original request. A "Sign in with Google" button POSTs to the // provider and lands on accounts.google.com only by redirect, so the replay never reproduces it and @@ -503,6 +426,7 @@ describe('browserManager', () => { // host — the wire UA saying Firefox while sec-ch-ua still says Chrome, the exact cross-layer tell // this scope exists to remove. it('keeps a viewport preset on the session identity after an auth-host visit', async () => { + browserMocks.processUserAgent = GUEST_CLEAN_UA const { guest, debuggerSendCommand } = makeViewportGuest(9001) webContentsFromIdMock.mockReturnValue(guest) browserManager.attachGuestPolicies(guest as never) diff --git a/src/main/browser/browser-manager-load-failure-replay.test.ts b/src/main/browser/browser-manager-load-failure-replay.test.ts index 569771f2ffa3..33f844766022 100644 --- a/src/main/browser/browser-manager-load-failure-replay.test.ts +++ b/src/main/browser/browser-manager-load-failure-replay.test.ts @@ -39,6 +39,13 @@ vi.mock('./popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) +vi.mock('./browser-process-user-agent', () => ({ + getBrowserProcessUserAgentIdentity: () => ({ + mode: 'clean', + userAgent: 'Mozilla/5.0 (Test) Chrome/140.0.0.0' + }) +})) + import { browserManager } from './browser-manager' import { guestUaMethods, diff --git a/src/main/browser/browser-manager-navigation.ts b/src/main/browser/browser-manager-navigation.ts index c11626fd5162..c04c71145a26 100644 --- a/src/main/browser/browser-manager-navigation.ts +++ b/src/main/browser/browser-manager-navigation.ts @@ -1,8 +1,11 @@ import { openPopupWithOriginBar, type PopupChildWindowOptions } from './popup-origin-bar-window' -import { cleanElectronUserAgent } from './browser-session-ua' -import { getBrowserSessionUserAgentMode } from './browser-session-user-agent-mode' +import { getBrowserProcessUserAgentIdentity } from './browser-process-user-agent' +import type { BrowserSessionRequestUserAgentResolver } from './browser-session-ua' import { googleAuthUserAgent, isGoogleAuthUrl } from './browser-google-auth-ua' -import { buildViewportUserAgentOverride } from './browser-viewport-user-agent' +import { + buildViewportUserAgentOverride, + type ViewportUserAgentOverride +} from './browser-viewport-user-agent' import { safeOrigin, type AuthUserAgentOverrideOperation, @@ -11,27 +14,75 @@ import { import { BrowserManagerVisibility } from './browser-manager-visibility' export abstract class BrowserManagerNavigation extends BrowserManagerVisibility { + resolveBrowserGuestRequestUserAgent( + request: Parameters[0] + ): ViewportUserAgentOverride { + const identity = getBrowserProcessUserAgentIdentity() + const firefoxUa = googleAuthUserAgent() + const pendingNavigation = + request.webContentsId === undefined + ? undefined + : this.pendingNavigationByGuestId.get(request.webContentsId) + // Native mode deliberately keeps the real Electron identity on Google auth hosts too. + const googleAuthEnabled = identity.mode === 'clean' + if ( + googleAuthEnabled && + request.currentUserAgent === firefoxUa && + (!pendingNavigation || isGoogleAuthUrl(pendingNavigation.currentUrl)) + ) { + return { userAgent: firefoxUa } + } + const overrideState = + request.webContentsId === undefined + ? undefined + : this.authUserAgentOverrideStateByGuestId.get(request.webContentsId) + const latestPendingOverride = overrideState?.pending.at(-1) + const currentOverride = + latestPendingOverride && + latestPendingOverride.sequence > (overrideState?.confirmed?.sequence ?? -1) + ? latestPendingOverride + : overrideState?.confirmed + if ( + googleAuthEnabled && + !currentOverride && + request.effectiveUserAgent === firefoxUa && + (!pendingNavigation || isGoogleAuthUrl(pendingNavigation.currentUrl)) + ) { + return { userAgent: firefoxUa } + } + if (googleAuthEnabled && currentOverride?.userAgent === firefoxUa) { + return { userAgent: firefoxUa } + } + const browserPageId = + request.webContentsId === undefined + ? undefined + : this.tabIdByWebContentsId.get(request.webContentsId) + const mobile = browserPageId + ? (this.viewportUaOverrideMobileByTabId.get(browserPageId) ?? false) + : this.hasSessionMobileViewportIntent(request.session) + return buildViewportUserAgentOverride({ + url: request.url, + mobile, + baseUserAgent: identity.userAgent, + googleAuthEnabled + }) + } + // Why: navigator.userAgent (read by Google's auth JS) reflects the WebContents UA, - // not the request header, so the header-level Firefox switch in setupGoogleAuthUserAgentOverride + // not the request header, so the Firefox switch in the session request hook // must be matched here per navigation or the two layers disagree — itself a bot tell. - // Restores the session's base identity off the auth hosts. Native-UA profiles opt out - // of the whole clean-UA path, so they keep their untouched identity everywhere. + // Native process mode skips only this Google exception; viewport identity still follows navigation. protected applyGoogleAuthUserAgent( guest: Electron.WebContents, url: string, options: { duringRedirect?: boolean } = {} ): void { const browserPageId = this.tabIdByWebContentsId.get(guest.id) - // Why: popup child windows get these policies but are never in tabIdByWebContentsId, so a direct - // lookup misses the native-UA opt-out and would hand a native profile's popup the Firefox UA. - // That is worse than doing nothing: native sessions skip setupGoogleAuthUserAgentOverride, so - // the popup would send the raw Electron UA on the wire while navigator.userAgent claims Firefox. - const ownerTabId = this.resolveBrowserTabIdForGuestWebContentsId(guest.id) - // Session state is authoritative before renderer registration and after a native profile imports a source UA. - const mode = - getBrowserSessionUserAgentMode(guest.session) ?? - (ownerTabId ? this.userAgentModeByPageId.get(ownerTabId) : undefined) - if (mode === 'native') { + const identity = getBrowserProcessUserAgentIdentity() + if (identity.mode === 'native') { + if (browserPageId) { + this.reapplyViewportUserAgentOverride(guest, browserPageId, url) + } return } const firefoxUa = googleAuthUserAgent() @@ -48,7 +99,7 @@ export abstract class BrowserManagerNavigation extends BrowserManagerVisibility : // Only restore when the auth-host override is actually in place, so normal // navigation never touches the session UA. currentUa === firefoxUa - ? guest.session.getUserAgent() + ? identity.userAgent : null let authOverrideIssuedOverCdp = false if (nextUa !== null && nextUa !== currentUa) { @@ -57,7 +108,7 @@ export abstract class BrowserManagerNavigation extends BrowserManagerVisibility // cannot survive — the sign-in lands on a blank tab. CDP retargets navigator.userAgent without // touching the navigation, and it outranks the WebContents UA from then on, so a guest that // switches to it stays on it. The wire UA never depended on this write: - // setupGoogleAuthUserAgentOverride rewrites User-Agent per request for auth-host URLs on its own. + // The session request hook rewrites User-Agent for auth-host URLs on its own. if (options.duringRedirect === true || overrideState !== undefined) { if (this.canOverrideUserAgentOverCdp(guest)) { authOverrideIssuedOverCdp = true @@ -222,7 +273,8 @@ export abstract class BrowserManagerNavigation extends BrowserManagerVisibility // Why: the session UA is the profile's stable base identity. guest.getUserAgent() is not: // applyGoogleAuthUserAgent leaves it pinned to the Firefox auth UA once a guest switches to // the CDP override, so reading it back here would republish that identity on ordinary hosts. - baseUserAgent: cleanElectronUserAgent(baseUserAgent ?? guest.session.getUserAgent()) + baseUserAgent: baseUserAgent ?? getBrowserProcessUserAgentIdentity().userAgent, + googleAuthEnabled: getBrowserProcessUserAgentIdentity().mode === 'clean' }) ) } diff --git a/src/main/browser/browser-manager-registration.ts b/src/main/browser/browser-manager-registration.ts index ba2ac8647eb3..7b49d5451e42 100644 --- a/src/main/browser/browser-manager-registration.ts +++ b/src/main/browser/browser-manager-registration.ts @@ -1,7 +1,6 @@ import { webContents } from 'electron' import { browserDownloadDestinationReservations } from './browser-download-destination' import { isWorkspaceDocPageId } from './doc-preview-guest-policy' -import type { BrowserSessionUserAgentMode } from '../../shared/browser-workspace-types' import type { BrowserGuestRegistration } from './browser-manager-types' import { BrowserManagerGuestPolicy } from './browser-manager-guest-policy' @@ -12,7 +11,6 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli workspaceId, worktreeId, sessionProfileId, - userAgentMode, webContentsId, rendererWebContentsId }: BrowserGuestRegistration): boolean { @@ -48,6 +46,7 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli const previousWebContentsId = this.webContentsIdByTabId.get(browserTabId) if (previousWebContentsId !== undefined && previousWebContentsId !== webContentsId) { this.retireStaleGuestWebContents(previousWebContentsId) + this.clearSessionMobileViewportIntent(browserTabId) this.viewportPresetActiveByTabId.delete(browserTabId) this.viewportScrollStateByTabId.delete(browserTabId) } @@ -57,11 +56,6 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli this.workspaceIdByPageId.set(browserTabId, workspaceId) } this.sessionProfileIdByPageId.set(browserTabId, sessionProfileId ?? null) - if (userAgentMode) { - this.userAgentModeByPageId.set(browserTabId, userAgentMode) - } else { - this.userAgentModeByPageId.delete(browserTabId) - } this.rendererWebContentsIdByTabId.set(browserTabId, rendererWebContentsId) if (worktreeId) { this.worktreeIdByTabId.set(browserTabId, worktreeId) @@ -129,10 +123,10 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli this.rendererWebContentsIdByTabId.delete(browserTabId) this.workspaceIdByPageId.delete(browserTabId) this.sessionProfileIdByPageId.delete(browserTabId) - this.userAgentModeByPageId.delete(browserTabId) this.worktreeIdByTabId.delete(browserTabId) // Why: drop the viewport-op chain so the Map doesn't retain a promise keyed to a destroyed guest. this.viewportOpsByTabId.delete(browserTabId) + this.clearSessionMobileViewportIntent(browserTabId) this.viewportUaOverrideMobileByTabId.delete(browserTabId) this.viewportPresetActiveByTabId.delete(browserTabId) this.viewportScrollStateByTabId.delete(browserTabId) @@ -147,13 +141,11 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli browserPageId, worktreeId, sessionProfileId, - userAgentMode, webContentsId }: { browserPageId: string worktreeId?: string sessionProfileId?: string | null - userAgentMode?: BrowserSessionUserAgentMode webContentsId: number }): boolean { // Why the same check on both registration doors: one id resolving in both halves is the exact @@ -171,17 +163,13 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli const previousWebContentsId = this.webContentsIdByTabId.get(browserPageId) if (previousWebContentsId !== undefined && previousWebContentsId !== webContentsId) { this.retireStaleGuestWebContents(previousWebContentsId) + this.clearSessionMobileViewportIntent(browserPageId) this.viewportPresetActiveByTabId.delete(browserPageId) this.viewportScrollStateByTabId.delete(browserPageId) } this.webContentsIdByTabId.set(browserPageId, webContentsId) this.tabIdByWebContentsId.set(webContentsId, browserPageId) this.sessionProfileIdByPageId.set(browserPageId, sessionProfileId ?? null) - if (userAgentMode) { - this.userAgentModeByPageId.set(browserPageId, userAgentMode) - } else { - this.userAgentModeByPageId.delete(browserPageId) - } if (worktreeId) { this.worktreeIdByTabId.set(browserPageId, worktreeId) } @@ -211,8 +199,8 @@ export abstract class BrowserManagerRegistration extends BrowserManagerGuestPoli this.pageInitiatedTabBudgetByRootGuestId.clear() this.worktreeIdByTabId.clear() this.sessionProfileIdByPageId.clear() - this.userAgentModeByPageId.clear() this.viewportUaOverrideMobileByTabId.clear() + this.mobileViewportTabIdsBySession.clear() this.viewportPresetActiveByTabId.clear() this.viewportScrollStateByTabId.clear() this.authUserAgentOverrideStateByGuestId.clear() diff --git a/src/main/browser/browser-manager-state.ts b/src/main/browser/browser-manager-state.ts index fef6eee3f9a9..333bab613e81 100644 --- a/src/main/browser/browser-manager-state.ts +++ b/src/main/browser/browser-manager-state.ts @@ -5,10 +5,7 @@ import { type PageInitiatedTabBudget } from './browser-page-initiated-tab-budget' import type { KeybindingOverrides } from '../../shared/keybindings' -import type { - BrowserLoadError, - BrowserSessionUserAgentMode -} from '../../shared/browser-workspace-types' +import type { BrowserLoadError } from '../../shared/browser-workspace-types' import { resolveBrowserRouteGuestPopupOpener } from './browser-route-guest-popup-ownership' import type { ActiveDownload, @@ -123,12 +120,14 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt // Why: guests are keyed by page id but renderer visibility by workspace id; bridge the mismatch to activate the right tab before capture. protected readonly workspaceIdByPageId = new Map() protected readonly sessionProfileIdByPageId = new Map() - protected readonly userAgentModeByPageId = new Map() // Why: serialize per-tab setViewportOverride so rapid toggles don't interleave CDP commands and leave emulation in a wrong state. protected readonly viewportOpsByTabId = new Map>() // Why: presence means the preset requires a CDP UA override (installed or in flight), so navigation // can re-issue it against the target URL's identity. protected readonly viewportUaOverrideMobileByTabId = new Map() + // Worker requests omit webContentsId, so retain mobile intent at the Session boundary where + // webRequest can still resolve it. Values contain only live tabs and clear with registration. + protected readonly mobileViewportTabIdsBySession = new Map>() // Why: the confirmed CDP identity outranks getUserAgent; pending intent keeps rapid navigations // ordered without claiming a failed write was installed. protected readonly authUserAgentOverrideStateByGuestId = new Map< @@ -163,6 +162,33 @@ export abstract class BrowserManagerState extends BrowserManagerViewportScrollSt protected readonly downloadsById = new Map() protected readonly grabSessionController = new BrowserGrabSessionController() + protected setSessionMobileViewportIntent( + browserTabId: string, + session: Electron.Session, + mobile: boolean + ): void { + this.clearSessionMobileViewportIntent(browserTabId) + if (!mobile) { + return + } + const tabIds = this.mobileViewportTabIdsBySession.get(session) ?? new Set() + tabIds.add(browserTabId) + this.mobileViewportTabIdsBySession.set(session, tabIds) + } + + protected clearSessionMobileViewportIntent(browserTabId: string): void { + for (const [session, tabIds] of this.mobileViewportTabIdsBySession) { + tabIds.delete(browserTabId) + if (tabIds.size === 0) { + this.mobileViewportTabIdsBySession.delete(session) + } + } + } + + protected hasSessionMobileViewportIntent(session: Electron.Session): boolean { + return (this.mobileViewportTabIdsBySession.get(session)?.size ?? 0) > 0 + } + setDictationShortcutForwardingPredicate(predicate: (() => boolean) | null): void { this.shouldForwardDictationShortcut = predicate } diff --git a/src/main/browser/browser-manager-types.ts b/src/main/browser/browser-manager-types.ts index b91e2b741fee..99f5280dd117 100644 --- a/src/main/browser/browser-manager-types.ts +++ b/src/main/browser/browser-manager-types.ts @@ -17,7 +17,6 @@ import type { PageInitiatedTabBudget } from './browser-page-initiated-tab-budget import type { BrowserCertificateFailure, BrowserLoadError, - BrowserSessionUserAgentMode, BrowserViewportOverride } from '../../shared/browser-workspace-types' import type { BrowserAnnotationViewportBridgeOptions } from '../../shared/browser-annotation-viewport-bridge' @@ -102,7 +101,6 @@ export type BrowserGuestRegistration = { workspaceId?: string worktreeId?: string sessionProfileId?: string | null - userAgentMode?: BrowserSessionUserAgentMode webContentsId: number rendererWebContentsId: number } @@ -221,7 +219,6 @@ export type { BrowserAnnotationViewportBridgeOptions, BrowserCertificateFailure, BrowserLoadError, - BrowserSessionUserAgentMode, BrowserViewportOverride, BrowserDownloadFinishedEvent, BrowserDownloadProgressEvent, diff --git a/src/main/browser/browser-manager-viewport-override.test.ts b/src/main/browser/browser-manager-viewport-override.test.ts index 0228d8f9ed83..41835a6cd3ea 100644 --- a/src/main/browser/browser-manager-viewport-override.test.ts +++ b/src/main/browser/browser-manager-viewport-override.test.ts @@ -12,7 +12,10 @@ const browserMocks = vi.hoisted(() => ({ guestOpenDevToolsMock: vi.fn(), webContentsFromIdMock: vi.fn(), screenGetCursorScreenPointMock: vi.fn(() => ({ x: 0, y: 0 })), - openPopupWithOriginBarMock: vi.fn() + openPopupWithOriginBarMock: vi.fn(), + processUserAgentMode: 'clean', + processUserAgent: + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36' })) vi.mock('electron', () => ({ @@ -39,6 +42,13 @@ vi.mock('./popup-origin-bar-window', () => ({ openPopupWithOriginBar: browserMocks.openPopupWithOriginBarMock })) +vi.mock('./browser-process-user-agent', () => ({ + getBrowserProcessUserAgentIdentity: () => ({ + mode: browserMocks.processUserAgentMode, + userAgent: browserMocks.processUserAgent + }) +})) + import { browserManager } from './browser-manager' import { googleAuthUserAgent } from './browser-google-auth-ua' import { @@ -66,6 +76,8 @@ describe('browserManager', () => { beforeEach(() => { resetBrowserManagerMocks(browserMocks) resetBrowserManagerState() + browserMocks.processUserAgentMode = 'clean' + browserMocks.processUserAgent = GUEST_CLEAN_UA }) afterEach(() => { @@ -117,15 +129,16 @@ describe('browserManager', () => { }) it.each([false, true])( - 'keeps the session UA for native-mode profiles when mobile=%s', + 'keeps native process identity coherent with mobile=%s', async (mobile) => { + browserMocks.processUserAgentMode = 'native' + browserMocks.processUserAgent = GUEST_ELECTRON_UA const { guest, debuggerSendCommand } = makeGuest(mobile ? 4244 : 4243) webContentsFromIdMock.mockReturnValue(guest) browserManager.attachGuestPolicies(guest as never) browserManager.registerGuest({ browserPageId: `tab-native-${mobile}`, sessionProfileId: 'native-profile', - userAgentMode: 'native', webContentsId: guest.id as number, rendererWebContentsId }) @@ -139,10 +152,12 @@ describe('browserManager', () => { }) ).resolves.toBe(true) - expect(debuggerSendCommand).not.toHaveBeenCalledWith( - 'Emulation.setUserAgentOverride', - expect.anything() - ) + const userAgentOverride = lastUserAgentOverride(debuggerSendCommand) + if (mobile) { + expect(userAgentOverride).toMatchObject({ userAgent: expect.stringContaining('iPhone') }) + } else { + expect(userAgentOverride).toEqual({ userAgent: GUEST_ELECTRON_UA }) + } } ) @@ -377,7 +392,7 @@ describe('browserManager', () => { didFailLoad(null, -3, 'Aborted', 'https://accounts.google.com/', true) await flushViewportOps() - expect(guest.setUserAgent).toHaveBeenLastCalledWith(GUEST_ELECTRON_UA) + expect(guest.setUserAgent).toHaveBeenLastCalledWith(GUEST_CLEAN_UA) expect(lastUserAgentOverride(debuggerSendCommand)).toEqual({ userAgent: GUEST_CLEAN_UA }) // A later preset must also resolve the committed, non-auth URL. @@ -776,14 +791,15 @@ describe('browserManager', () => { ) }) - it('leaves the UA override alone on navigation for native-UA profiles', async () => { + it('reapplies the native process identity instead of the Google exception', async () => { + browserMocks.processUserAgentMode = 'native' + browserMocks.processUserAgent = GUEST_ELECTRON_UA const { guest, debuggerSendCommand } = makeGuest(4250) webContentsFromIdMock.mockReturnValue(guest) browserManager.attachGuestPolicies(guest as never) browserManager.registerGuest({ browserPageId: 'tab-native-nav', sessionProfileId: 'native-profile', - userAgentMode: 'native', webContentsId: guest.id as number, rendererWebContentsId }) @@ -800,10 +816,9 @@ describe('browserManager', () => { debuggerSendCommand.mockClear() didStartNavigation(null, 'https://accounts.google.com/', false, true) await flushViewportOps() - expect(debuggerSendCommand).not.toHaveBeenCalledWith( - 'Emulation.setUserAgentOverride', - expect.anything() - ) + expect(debuggerSendCommand).toHaveBeenCalledWith('Emulation.setUserAgentOverride', { + userAgent: GUEST_ELECTRON_UA + }) }) it('clears device metrics and disables touch for override=null', async () => { diff --git a/src/main/browser/browser-manager-viewport.ts b/src/main/browser/browser-manager-viewport.ts index ce31dbe37e1e..48a2b5744565 100644 --- a/src/main/browser/browser-manager-viewport.ts +++ b/src/main/browser/browser-manager-viewport.ts @@ -7,6 +7,7 @@ import { import type { BrowserViewportOverride } from '../../shared/browser-workspace-types' import { googleAuthUserAgent, isGoogleAuthUrl } from './browser-google-auth-ua' import { BrowserManagerDownloadLifecycle } from './browser-manager-download-lifecycle' +import { getBrowserProcessUserAgentIdentity } from './browser-process-user-agent' export abstract class BrowserManagerViewport extends BrowserManagerDownloadLifecycle { // Why: guests are isolated from Orca's preload bridge, so main owns the devtools escape hatch after a tab→guest lookup. @@ -163,13 +164,10 @@ export abstract class BrowserManagerViewport extends BrowserManagerDownloadLifec enabled: override.mobile, maxTouchPoints: override.mobile ? 5 : 0 }) - // Why: viewport sizing must not override a profile's explicit native-UA identity. - if (this.userAgentModeByPageId.get(browserTabId) !== 'native') { - // Navigation must see the preset intent while the final CDP command is in flight. - this.viewportUaOverrideMobileByTabId.set(browserTabId, override.mobile) - // Why: same sender as the navigation path, so both resolve the tab's host identically. - await this.sendViewportUserAgentOverride(guest, override.mobile) - } + // Navigation and worker requests must see the preset while the final CDP write is in flight. + this.viewportUaOverrideMobileByTabId.set(browserTabId, override.mobile) + this.setSessionMobileViewportIntent(browserTabId, guest.session, override.mobile) + await this.sendViewportUserAgentOverride(guest, override.mobile) } else { await dbg.sendCommand('Emulation.clearDeviceMetricsOverride', {}) if (this.webContentsIdByTabId.get(browserTabId) === webContentsId) { @@ -185,14 +183,18 @@ export abstract class BrowserManagerViewport extends BrowserManagerDownloadLifec const trackedMobile = this.viewportUaOverrideMobileByTabId.get(browserTabId) // A navigation after this point must not re-install the override behind the clear. this.viewportUaOverrideMobileByTabId.delete(browserTabId) + this.clearSessionMobileViewportIntent(browserTabId) try { if (this.authUserAgentOverrideStateByGuestId.has(guest.id)) { const url = this.resolveTabNavigationUrl(guest) + const identity = getBrowserProcessUserAgentIdentity() const restored = await this.applyAuthUserAgentOverrideOverCdp( guest, false, url, - isGoogleAuthUrl(url) ? googleAuthUserAgent() : guest.session.getUserAgent() + identity.mode === 'clean' && isGoogleAuthUrl(url) + ? googleAuthUserAgent() + : identity.userAgent ) if (!restored) { throw new Error('Failed to preserve auth user agent') @@ -204,6 +206,7 @@ export abstract class BrowserManagerViewport extends BrowserManagerDownloadLifec } catch (error) { if (trackedMobile !== undefined) { this.viewportUaOverrideMobileByTabId.set(browserTabId, trackedMobile) + this.setSessionMobileViewportIntent(browserTabId, guest.session, trackedMobile) } throw error } diff --git a/src/main/browser/browser-process-user-agent.ts b/src/main/browser/browser-process-user-agent.ts index ed1af68a3ba5..79cd8c5bc3a4 100644 --- a/src/main/browser/browser-process-user-agent.ts +++ b/src/main/browser/browser-process-user-agent.ts @@ -1,8 +1,8 @@ import { app } from 'electron' -import type { BrowserSessionUserAgentMode } from '../../shared/browser-workspace-types' +import type { BrowserUserAgentMode } from '../../shared/browser-user-agent-mode' export type BrowserProcessUserAgentIdentity = Readonly<{ - mode: BrowserSessionUserAgentMode + mode: BrowserUserAgentMode /** What every document, frame and worker in this process presents. */ userAgent: string }> @@ -23,7 +23,7 @@ export function cleanElectronUserAgent(userAgent: string): string { * rather than assigning the raw string back, so the engine keeps its own untouched default. */ export function initializeBrowserProcessUserAgent( - mode: BrowserSessionUserAgentMode + mode: BrowserUserAgentMode ): BrowserProcessUserAgentIdentity { if (identity) { throw new Error('Browser process user agent was already initialized') diff --git a/src/main/browser/browser-session-partition-policies.test.ts b/src/main/browser/browser-session-partition-policies.test.ts index b092cc8344b4..ae9884a1abc4 100644 --- a/src/main/browser/browser-session-partition-policies.test.ts +++ b/src/main/browser/browser-session-partition-policies.test.ts @@ -82,11 +82,10 @@ vi.mock('./browser-media-access', () => ({ requestSystemMediaAccess: async () => false })) vi.mock('./browser-session-ua', () => ({ - cleanElectronUserAgent: (userAgent: string) => userAgent, - setupGoogleAuthUserAgentOverride: vi.fn() + installBrowserSessionUserAgentExceptions: vi.fn(() => vi.fn()) })) -vi.mock('./browser-session-user-agent-mode', () => ({ - setBrowserSessionUserAgentMode: vi.fn() +vi.mock('./browser-process-user-agent', () => ({ + getBrowserProcessUserAgentIdentity: () => ({ mode: 'clean', userAgent: 'Mozilla/5.0 Orca' }) })) vi.mock('./browser-webauthn-access', () => ({ allowsBrowserWebAuthnPermission: () => false, @@ -113,8 +112,7 @@ function profileFor(partition: string): BrowserSessionProfile { scope: 'isolated', partition, label: partition, - source: null, - userAgentMode: 'clean' + source: null } } diff --git a/src/main/browser/browser-session-partition-policies.ts b/src/main/browser/browser-session-partition-policies.ts index b70221851748..9fc3dadfebd2 100644 --- a/src/main/browser/browser-session-partition-policies.ts +++ b/src/main/browser/browser-session-partition-policies.ts @@ -9,8 +9,8 @@ import { } from './browser-session-proxy' import { hasSystemMediaAccess, requestSystemMediaAccess } from './browser-media-access' import { isAutoGrantedBrowserSessionPermission } from './browser-session-permission-policy' -import { cleanElectronUserAgent, setupGoogleAuthUserAgentOverride } from './browser-session-ua' -import { setBrowserSessionUserAgentMode } from './browser-session-user-agent-mode' +import { installBrowserSessionUserAgentExceptions } from './browser-session-ua' +import { getBrowserProcessUserAgentIdentity } from './browser-process-user-agent' import { allowsBrowserWebAuthnPermission, clearBrowserWebAuthnAccessHandlers, @@ -20,6 +20,33 @@ import { noticeDocPreviewDownloadBlocked } from './doc-preview-download-block-no // Why: one shared installer keeps every partition's deny-by-default permission/download policies from drifting apart. const configuredPartitions = new Set() +const userAgentPolicyDisposerBySession = new WeakMap void>() + +export function retireBrowserSessionUserAgentPolicy(sess: Session): void { + const dispose = userAgentPolicyDisposerBySession.get(sess) + if (!dispose) { + return + } + userAgentPolicyDisposerBySession.delete(sess) + dispose() +} + +function configureBrowserSessionUserAgentPolicy(sess: Session, installExceptions: boolean): void { + sess.setUserAgent(getBrowserProcessUserAgentIdentity().userAgent) + if (!installExceptions) { + retireBrowserSessionUserAgentPolicy(sess) + return + } + if (userAgentPolicyDisposerBySession.has(sess)) { + return + } + userAgentPolicyDisposerBySession.set( + sess, + installBrowserSessionUserAgentExceptions(sess, (request) => + browserManager.resolveBrowserGuestRequestUserAgent(request) + ) + ) +} /** Drop only the installer memo; retired-session guards remain fail-closed. */ export function forgetBrowserSessionPartitionConfiguration(partition: string): void { @@ -75,11 +102,12 @@ export function installBrowserSessionPartitionPolicies( downloads?: BrowserPartitionDownloadPolicy permissions?: BrowserPartitionPermissionPolicy applyAppWideProxy?: boolean + userAgentExceptions?: boolean } = {} ): Promise { const { partition } = profile const sess = session.fromPartition(partition) - setBrowserSessionUserAgentMode(sess, profile.userAgentMode ?? 'clean') + configureBrowserSessionUserAgentPolicy(sess, options.userAgentExceptions !== false) // Why: route partitions own a SOCKS transport policy that the app proxy must not overwrite. const proxyReady = ( options.applyAppWideProxy === false ? Promise.resolve() : applyProxyToBrowserSession(sess) @@ -92,11 +120,6 @@ export function installBrowserSessionPartitionPolicies( } browserManager.installCertificateRequestGuard(sess) - if (profile.userAgentMode !== 'native' && typeof sess.getUserAgent === 'function') { - const cleanUA = cleanElectronUserAgent(sess.getUserAgent()) - sess.setUserAgent(cleanUA) - setupGoogleAuthUserAgentOverride(sess) - } if (options?.permissions === 'deny') { sess.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false)) sess.setPermissionCheckHandler(() => false) @@ -170,6 +193,7 @@ export function installBrowserSessionPartitionPolicies( export function clearBrowserSessionPartitionPolicies(partition: string, sess: Session): void { // Why: the Electron Session survives partition deletion; clear callbacks/listeners so removed profiles don't retain closures. invalidateBrowserSessionProxyApplication(sess) + retireBrowserSessionUserAgentPolicy(sess) configuredPartitions.delete(partition) browserManager.removeCertificateRequestGuard(sess) sess.removeListener('will-download', handleWillDownload) @@ -179,25 +203,3 @@ export function clearBrowserSessionPartitionPolicies(partition: string, sess: Se sess.setPermissionCheckHandler(null) sess.setDisplayMediaRequestHandler(null) } - -export function applyBrowserSessionUserAgentModes(profiles: BrowserSessionProfile[]): void { - for (const profile of profiles) { - const partition = profile.partition - try { - const sess = session.fromPartition(partition) - const userAgentMode = profile.userAgentMode ?? 'clean' - setBrowserSessionUserAgentMode(sess, userAgentMode) - - if (profile.userAgentMode === 'native') { - continue - } - - // Why: imported sessions need the same Chrome-shaped identity after app restart. - const cleanUA = cleanElectronUserAgent(sess.getUserAgent()) - sess.setUserAgent(cleanUA) - setupGoogleAuthUserAgentOverride(sess) - } catch { - /* session not available yet (e.g. unit tests or pre-ready) */ - } - } -} diff --git a/src/main/browser/browser-session-partition-proxy-install.test.ts b/src/main/browser/browser-session-partition-proxy-install.test.ts index d0eee031ea0f..1d11220e8d33 100644 --- a/src/main/browser/browser-session-partition-proxy-install.test.ts +++ b/src/main/browser/browser-session-partition-proxy-install.test.ts @@ -44,12 +44,13 @@ vi.mock('./browser-media-access', () => ({ requestSystemMediaAccess: vi.fn(async () => false) })) vi.mock('./browser-session-ua', () => ({ - cleanElectronUserAgent: vi.fn((ua: string) => ua), - setupGoogleAuthUserAgentOverride: vi.fn() + installBrowserSessionUserAgentExceptions: vi.fn(() => vi.fn()) })) -vi.mock('./browser-session-user-agent-mode', () => ({ - setBrowserSessionUserAgentMode: vi.fn(), - clearBrowserSessionUserAgentMode: vi.fn() +vi.mock('./browser-process-user-agent', () => ({ + getBrowserProcessUserAgentIdentity: () => ({ + mode: 'clean', + userAgent: 'Mozilla/5.0 Chrome/150.0.0.0 Safari/537.36' + }) })) vi.mock('./browser-webauthn-access', () => ({ allowsBrowserWebAuthnPermission: vi.fn(() => false), diff --git a/src/main/browser/browser-session-persisted-profile-validation.ts b/src/main/browser/browser-session-persisted-profile-validation.ts index 31e4f69f9fbd..3b5c3bcd8889 100644 --- a/src/main/browser/browser-session-persisted-profile-validation.ts +++ b/src/main/browser/browser-session-persisted-profile-validation.ts @@ -19,13 +19,38 @@ export function isValidPersistedBrowserSessionProfile( typeof candidate.id === 'string' && typeof candidate.partition === 'string' && typeof candidate.label === 'string' && - (candidate.userAgentMode === undefined || - candidate.userAgentMode === 'clean' || - candidate.userAgentMode === 'native') && isProfileOwnedSessionPartition(candidate.id, candidate.partition, activeOrcaProfileId) ) } +function hasRetiredUserAgentMode(profile: BrowserSessionProfile): boolean { + return Object.hasOwn(profile, 'userAgentMode') +} + +function withoutRetiredUserAgentMode(profile: BrowserSessionProfile): BrowserSessionProfile { + if (!hasRetiredUserAgentMode(profile)) { + return profile + } + const migrated = { ...profile } + Reflect.deleteProperty(migrated, 'userAgentMode') + return migrated +} + +export function migrateRetiredBrowserSessionProfileUserAgentModes( + profiles: BrowserSessionProfile[], + activeOrcaProfileId: string +): { profiles: BrowserSessionProfile[]; nativeProfileIds: string[]; changed: boolean } { + const nativeProfileIds = profiles + .filter((profile) => isValidPersistedBrowserSessionProfile(profile, activeOrcaProfileId)) + .filter((profile) => Reflect.get(profile, 'userAgentMode') === 'native') + .map((profile) => profile.id) + return { + profiles: profiles.map(withoutRetiredUserAgentMode), + nativeProfileIds, + changed: profiles.some(hasRetiredUserAgentMode) + } +} + function isProfileOwnedSessionPartition( profileId: string, partition: string, diff --git a/src/main/browser/browser-session-profile-retirement.ts b/src/main/browser/browser-session-profile-retirement.ts index dbc59d7c1093..ee835806d90f 100644 --- a/src/main/browser/browser-session-profile-retirement.ts +++ b/src/main/browser/browser-session-profile-retirement.ts @@ -1,7 +1,6 @@ import type { Session } from 'electron' import { retireProxySessionApplication } from '../network/proxy-settings' import { clearBrowserSessionPartitionPolicies } from './browser-session-partition-policies' -import { clearBrowserSessionUserAgentMode } from './browser-session-user-agent-mode' export async function retireFailedBrowserSessionProfile( partition: string, @@ -9,7 +8,6 @@ export async function retireFailedBrowserSessionProfile( ): Promise { const retirement = retireProxySessionApplication(sess) try { - clearBrowserSessionUserAgentMode(sess) clearBrowserSessionPartitionPolicies(partition, sess) } catch { // Best-effort policy cleanup must not skip retirement. diff --git a/src/main/browser/browser-session-registry.persistence.test.ts b/src/main/browser/browser-session-registry.persistence.test.ts index b6495d3d1e10..9bf9037f42ef 100644 --- a/src/main/browser/browser-session-registry.persistence.test.ts +++ b/src/main/browser/browser-session-registry.persistence.test.ts @@ -2,8 +2,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const USER_DATA = '/user-data' const META_PATH = `${USER_DATA}/browser-session-meta.json` -const RAW_ELECTRON_USER_AGENT = - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Orca/1.4.198 Chrome/150.0.7871.224 Electron/43.4.1 Safari/537.36' const CLEAN_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.7871.224 Safari/537.36' @@ -31,8 +29,7 @@ function installModuleMocks( copyFailures = new Set() ): { sessionFromPartitionMock: ReturnType - cleanElectronUserAgentMock: ReturnType - setupGoogleAuthUserAgentOverrideMock: ReturnType + installBrowserSessionUserAgentExceptionsMock: ReturnType browserManagerHandleGuestWillDownloadMock: ReturnType browserManagerNotifyPermissionDeniedMock: ReturnType requestSystemMediaAccessMock: ReturnType @@ -40,7 +37,7 @@ function installModuleMocks( const sessionFromPartitionMock = vi.fn((partition: string) => ({ partition, setUserAgent: vi.fn(), - getUserAgent: vi.fn(() => RAW_ELECTRON_USER_AGENT), + getUserAgent: vi.fn(() => CLEAN_USER_AGENT), setPermissionRequestHandler: vi.fn(), setPermissionCheckHandler: vi.fn(), setDevicePermissionHandler: vi.fn(), @@ -50,8 +47,7 @@ function installModuleMocks( clearStorageData: vi.fn().mockResolvedValue(undefined), clearCache: vi.fn().mockResolvedValue(undefined) })) - const cleanElectronUserAgentMock = vi.fn(() => CLEAN_USER_AGENT) - const setupGoogleAuthUserAgentOverrideMock = vi.fn() + const installBrowserSessionUserAgentExceptionsMock = vi.fn(() => vi.fn()) const browserManagerHandleGuestWillDownloadMock = vi.fn() const browserManagerNotifyPermissionDeniedMock = vi.fn() const requestSystemMediaAccessMock = vi.fn().mockResolvedValue(true) @@ -125,8 +121,16 @@ function installModuleMocks( requestSystemMediaAccess: requestSystemMediaAccessMock })) vi.doMock('./browser-session-ua', () => ({ - cleanElectronUserAgent: cleanElectronUserAgentMock, - setupGoogleAuthUserAgentOverride: setupGoogleAuthUserAgentOverrideMock + installBrowserSessionUserAgentExceptions: installBrowserSessionUserAgentExceptionsMock + })) + vi.doMock('./browser-process-user-agent', () => ({ + getBrowserProcessUserAgentIdentity: () => ({ + mode: 'clean', + userAgent: CLEAN_USER_AGENT + }) + })) + vi.doMock('../persistence', () => ({ + getCanonicalUserDataPath: () => USER_DATA })) // This suite models replay with an in-memory filesystem. The real file-backed SQLite merge has // dedicated coverage; these fixtures are legacy unmarked images and keep the copy path. @@ -150,13 +154,17 @@ function installModuleMocks( if (value !== undefined) { fsState.files.set(targetKey, value) } + }), + writeFileAtomically: vi.fn((pathValue: string, data: string) => { + const key = fsKey(pathValue) + fsState.files.set(key, data) + fsState.present.add(key) }) })) return { sessionFromPartitionMock, - cleanElectronUserAgentMock, - setupGoogleAuthUserAgentOverrideMock, + installBrowserSessionUserAgentExceptionsMock, browserManagerHandleGuestWillDownloadMock, browserManagerNotifyPermissionDeniedMock, requestSystemMediaAccessMock @@ -226,9 +234,7 @@ describe('BrowserSessionRegistry persistence', () => { orcaProfileId: 'local-work', profileDirectory: '/user-data/profiles/local-work' }) - const profile = await browserSessionRegistry.createProfile('isolated', 'Work Browser', { - userAgentMode: 'native' - }) + const profile = await browserSessionRegistry.createProfile('isolated', 'Work Browser') expect(profile).not.toBeNull() expect(fsState.files.has(profileMetaPath)).toBe(true) @@ -236,45 +242,24 @@ describe('BrowserSessionRegistry persistence', () => { expect(JSON.parse(fsState.files.get(profileMetaPath) ?? '{}').profiles[0]).toMatchObject({ id: profile!.id, partition: profile!.partition, - label: 'Work Browser', - userAgentMode: 'native' + label: 'Work Browser' }) }) - it('keeps UA cleaning as the fallback for profiles without an override', async () => { + it('applies the process identity and request exceptions to new profiles', async () => { const fsState = createFsState() - const { - sessionFromPartitionMock, - cleanElectronUserAgentMock, - setupGoogleAuthUserAgentOverrideMock - } = installModuleMocks(fsState) + const { sessionFromPartitionMock, installBrowserSessionUserAgentExceptionsMock } = + installModuleMocks(fsState) const { browserSessionRegistry } = await import('./browser-session-registry') await browserSessionRegistry.createProfile('isolated', 'Default identity') const profileSession = sessionFromPartitionMock.mock.results.at(-1)?.value - expect(cleanElectronUserAgentMock).toHaveBeenCalledWith(RAW_ELECTRON_USER_AGENT) expect(profileSession.setUserAgent).toHaveBeenCalledWith(CLEAN_USER_AGENT) - expect(setupGoogleAuthUserAgentOverrideMock).toHaveBeenCalledWith(profileSession) - }) - - it('leaves UA and client hints untouched for native-mode profiles', async () => { - const fsState = createFsState() - const { - sessionFromPartitionMock, - cleanElectronUserAgentMock, - setupGoogleAuthUserAgentOverrideMock - } = installModuleMocks(fsState) - const { browserSessionRegistry } = await import('./browser-session-registry') - - await browserSessionRegistry.createProfile('isolated', 'Google', { userAgentMode: 'native' }) - - const profileSession = sessionFromPartitionMock.mock.results.at(-1)?.value - const { getBrowserSessionUserAgentMode } = await import('./browser-session-user-agent-mode') - expect(profileSession.setUserAgent).not.toHaveBeenCalled() - expect(cleanElectronUserAgentMock).not.toHaveBeenCalled() - expect(setupGoogleAuthUserAgentOverrideMock).not.toHaveBeenCalled() - expect(getBrowserSessionUserAgentMode(profileSession as never)).toBe('native') + expect(installBrowserSessionUserAgentExceptionsMock).toHaveBeenCalledWith( + profileSession, + expect.any(Function) + ) }) it('merges partition-keyed pending entries without clobbering unrelated entries', async () => { @@ -422,11 +407,8 @@ describe('BrowserSessionRegistry persistence', () => { ] }) - const { - sessionFromPartitionMock, - cleanElectronUserAgentMock, - setupGoogleAuthUserAgentOverrideMock - } = installModuleMocks(fsState) + const { sessionFromPartitionMock, installBrowserSessionUserAgentExceptionsMock } = + installModuleMocks(fsState) const { browserSessionRegistry } = await import('./browser-session-registry') browserSessionRegistry.initializeBrowserSessionsFromPersistedState() @@ -436,17 +418,13 @@ describe('BrowserSessionRegistry persistence', () => { ) expect(appliedUas).not.toContain(brokenUa) expect(appliedUas).not.toContain(validUa) - // Why: every non-native profile falls to Orca's own cleaned engine UA. + // Why: every partition inherits the one process identity rather than an imported value. expect(appliedUas.length).toBeGreaterThan(0) expect(appliedUas.every((ua) => ua === CLEAN_USER_AGENT)).toBe(true) - expect(cleanElectronUserAgentMock).toHaveBeenCalled() - expect( - cleanElectronUserAgentMock.mock.calls.every(([ua]) => ua === RAW_ELECTRON_USER_AGENT) - ).toBe(true) - expect(setupGoogleAuthUserAgentOverrideMock).toHaveBeenCalled() + expect(installBrowserSessionUserAgentExceptionsMock).toHaveBeenCalled() }) - it('never applies a legacy persisted UA to a native-mode profile', async () => { + it('migrates retired native profiles without choosing the app-wide identity', async () => { const importedPartition = 'persist:orca-browser-session-11111111-1111-4111-8111-111111111111' const importedUa = 'Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36' const fsState = createFsState() @@ -477,17 +455,29 @@ describe('BrowserSessionRegistry persistence', () => { .filter((_, idx) => sessionFromPartitionMock.mock.calls[idx]?.[0] === importedPartition) .map((r) => r.value) expect(importedSessions.length).toBeGreaterThan(0) - // Why: native mode means the engine UA stands untouched — no setUserAgent at all. - expect(importedSessions.every((s) => s.setUserAgent.mock.calls.length === 0)).toBe(true) - const { getBrowserSessionUserAgentMode } = await import('./browser-session-user-agent-mode') expect( - importedSessions.every( - (session) => getBrowserSessionUserAgentMode(session as never) === 'native' - ) + importedSessions.every((s) => s.setUserAgent.mock.calls[0]?.[0] === CLEAN_USER_AGENT) ).toBe(true) + const persistedMeta = JSON.parse(fsState.files.get(META_PATH) ?? '{}') + expect(persistedMeta.profiles[0]).not.toHaveProperty('userAgentMode') + expect( + JSON.parse(fsState.files.get(`${USER_DATA}/browser-identity-mode.json`) ?? '{}') + ).toEqual({ + version: 1, + mode: 'clean', + migratedNativeProfileIds: ['11111111-1111-4111-8111-111111111111'], + migrationNoticePending: true + }) + const { clearBrowserIdentityMigrationNotice, readPendingBrowserIdentityMigrationNotice } = + await import('./browser-identity-mode-record') + expect(readPendingBrowserIdentityMigrationNotice(USER_DATA)).toEqual([ + '11111111-1111-4111-8111-111111111111' + ]) + expect(clearBrowserIdentityMigrationNotice(USER_DATA)).toBe(true) + expect(readPendingBrowserIdentityMigrationNotice(USER_DATA)).toBeNull() }) - it('preserves native mode across hydration when no source UA was imported', async () => { + it('hydrates a retired native profile under the process identity', async () => { const importedPartition = 'persist:orca-browser-session-12121212-1212-4121-8121-121212121212' const fsState = createFsState() seedMeta(fsState, { @@ -508,7 +498,7 @@ describe('BrowserSessionRegistry persistence', () => { ] }) - const { sessionFromPartitionMock, setupGoogleAuthUserAgentOverrideMock } = + const { sessionFromPartitionMock, installBrowserSessionUserAgentExceptionsMock } = installModuleMocks(fsState) const { browserSessionRegistry } = await import('./browser-session-registry') @@ -518,16 +508,12 @@ describe('BrowserSessionRegistry persistence', () => { .filter((_, index) => sessionFromPartitionMock.mock.calls[index]?.[0] === importedPartition) .map((result) => result.value) expect(importedSessions.length).toBeGreaterThan(0) - expect(importedSessions.every((sess) => sess.setUserAgent.mock.calls.length === 0)).toBe(true) expect( - setupGoogleAuthUserAgentOverrideMock.mock.calls.some( - ([sess]) => (sess as { partition?: string }).partition === importedPartition - ) - ).toBe(false) - const { getBrowserSessionUserAgentMode } = await import('./browser-session-user-agent-mode') + importedSessions.every((sess) => sess.setUserAgent.mock.calls[0]?.[0] === CLEAN_USER_AGENT) + ).toBe(true) expect( - importedSessions.every( - (session) => getBrowserSessionUserAgentMode(session as never) === 'native' + installBrowserSessionUserAgentExceptionsMock.mock.calls.some( + ([sess]) => Reflect.get(sess, 'partition') === importedPartition ) ).toBe(true) }) diff --git a/src/main/browser/browser-session-registry.test.ts b/src/main/browser/browser-session-registry.test.ts index 5c6287237771..54d0d72342ce 100644 --- a/src/main/browser/browser-session-registry.test.ts +++ b/src/main/browser/browser-session-registry.test.ts @@ -22,6 +22,13 @@ vi.mock('electron', () => ({ } })) +vi.mock('./browser-process-user-agent', () => ({ + getBrowserProcessUserAgentIdentity: () => ({ + mode: 'clean', + userAgent: 'Mozilla/5.0 Chrome/150.0.0.0 Safari/537.36' + }) +})) + vi.mock('./browser-manager', () => ({ browserManager: { notifyPermissionDenied: vi.fn(), @@ -33,7 +40,7 @@ vi.mock('./browser-manager', () => ({ import { browserSessionRegistry } from './browser-session-registry' import { googleAuthUserAgent } from './browser-google-auth-ua' -import { setupGoogleAuthUserAgentOverride } from './browser-session-ua' +import { installBrowserSessionUserAgentExceptions } from './browser-session-ua' import { setBrowserNetworkProxySettingsResolver } from './browser-session-proxy' import { handleElectronProxyLogin } from '../network/electron-proxy-credentials' import { applyProxySettingsToSession } from '../network/proxy-settings' @@ -54,6 +61,8 @@ describe('BrowserSessionRegistry', () => { askForMediaAccessMock.mockResolvedValue(true) getMediaAccessStatusMock.mockReturnValue('granted') sessionFromPartitionMock.mockReturnValue({ + setUserAgent: vi.fn(), + webRequest: { onBeforeSendHeaders: vi.fn() }, setPermissionRequestHandler: vi.fn(), setPermissionCheckHandler: vi.fn(), setDevicePermissionHandler: vi.fn(), @@ -194,13 +203,6 @@ describe('BrowserSessionRegistry', () => { expect(profile).toBeNull() }) - it('rejects invalid user-agent modes at the registry boundary', async () => { - const profile = await browserSessionRegistry.createProfile('isolated', 'Invalid UA', { - userAgentMode: 'rotating' as never - }) - expect(profile).toBeNull() - }) - it('allows created profile partitions', async () => { const profile = await browserSessionRegistry.createProfile('isolated', 'Allowed') expect(profile).not.toBeNull() @@ -344,8 +346,7 @@ describe('BrowserSessionRegistry', () => { scope: 'isolated', partition: claimedPartition, label: 'Conflicting identity', - source: null, - userAgentMode: 'native' + source: null } ]) @@ -528,12 +529,19 @@ describe('BrowserSessionRegistry', () => { }) }) - describe('setupGoogleAuthUserAgentOverride', () => { + describe('installBrowserSessionUserAgentExceptions', () => { function install(): (details: unknown, callback: ReturnType) => void { const onBeforeSendHeaders = vi.fn() - setupGoogleAuthUserAgentOverride({ webRequest: { onBeforeSendHeaders } } as never) + installBrowserSessionUserAgentExceptions( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook reads only the mocked webRequest member exercised here. + { webRequest: { onBeforeSendHeaders } } as never, + (request) => + request.currentUserAgent === googleAuthUserAgent() + ? { userAgent: googleAuthUserAgent() } + : undefined + ) expect(onBeforeSendHeaders).toHaveBeenCalledWith( - { urls: ['https://*/*'] }, + { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] }, expect.any(Function) ) return onBeforeSendHeaders.mock.calls[0][1] diff --git a/src/main/browser/browser-session-registry.ts b/src/main/browser/browser-session-registry.ts index d8c217bb54ae..c951d2a25afc 100644 --- a/src/main/browser/browser-session-registry.ts +++ b/src/main/browser/browser-session-registry.ts @@ -9,7 +9,6 @@ import { } from '../../shared/orca-profiles' import type { BrowserSessionProfile, - BrowserSessionProfileCreateOptions, BrowserSessionProfileScope } from '../../shared/browser-workspace-types' import { @@ -24,12 +23,13 @@ import { } from './browser-session-meta-store' import type { BrowserSessionMeta } from './browser-session-meta-store' import { - applyBrowserSessionUserAgentModes, forgetBrowserSessionPartitionConfiguration, installBrowserSessionPartitionPolicies } from './browser-session-partition-policies' -import { isValidPersistedBrowserSessionProfile } from './browser-session-persisted-profile-validation' -import { clearBrowserSessionUserAgentMode } from './browser-session-user-agent-mode' +import { + isValidPersistedBrowserSessionProfile, + migrateRetiredBrowserSessionProfileUserAgentModes +} from './browser-session-persisted-profile-validation' import { clearBrowserRoutePartitionPolicies, installBrowserRoutePartitionPolicies @@ -38,6 +38,8 @@ import { retireProxySessionApplication } from '../network/proxy-settings' import { invalidateBrowserSessionProxyApplication } from './browser-session-proxy' import { retireFailedBrowserSessionProfile } from './browser-session-profile-retirement' import { cancelBrowserWebAuthnAccountRequestsForSession } from './browser-webauthn-account-picker' +import { getCanonicalUserDataPath } from '../persistence' +import { recordRetiredNativeBrowserProfiles } from './browser-identity-mode-record' export type BrowserSessionRegistryProfileOptions = { orcaProfileId: string @@ -108,14 +110,23 @@ class BrowserSessionRegistry { // Why re-read defaultSource: the constructor may run before app.isReady() (userData path unavailable), so loadPersistedSource() returned null. initializeBrowserSessionsFromPersistedState(): void { const meta = this.loadPersistedMeta() + const migration = migrateRetiredBrowserSessionProfileUserAgentModes( + meta.profiles, + this.activeOrcaProfileId + ) + // Record the notice first so a metadata-write failure cannot erase the user's retired choice. + recordRetiredNativeBrowserProfiles(getCanonicalUserDataPath(), migration.nativeProfileIds) + if (migration.changed) { + this.persistMeta({ profiles: migration.profiles }) + } if (meta.defaultSource) { const current = this.profiles.get('default') if (current && current.source === null) { this.profiles.set('default', { ...current, source: meta.defaultSource }) } } - if (meta.profiles.length > 0) { - this.hydrateFromPersisted(meta.profiles) + if (migration.profiles.length > 0) { + this.hydrateFromPersisted(migration.profiles) } // Why: nothing else installs policies on the default partition (hydrate skips it), so without this its guest permissions would be denied. @@ -123,8 +134,6 @@ class BrowserSessionRegistry { void installBrowserSessionPartitionPolicies(defaultProfile).catch(() => { console.warn('[proxy] Failed to apply proxy to browser partition', defaultProfile.partition) }) - - applyBrowserSessionUserAgentModes(this.listProfiles()) } // Why: must run before any session.fromPartition() so CookieMonster reads the staged cookies instead of overwriting them from its in-memory DB. @@ -208,16 +217,10 @@ class BrowserSessionRegistry { async createProfile( scope: BrowserSessionProfileScope, - label: string, - options: BrowserSessionProfileCreateOptions = {} + label: string ): Promise { // Why: the registry is also an IPC boundary, so runtime types alone cannot keep invalid values out of persisted metadata. - if ( - (scope !== 'isolated' && scope !== 'imported') || - (options.userAgentMode !== undefined && - options.userAgentMode !== 'clean' && - options.userAgentMode !== 'native') - ) { + if (scope !== 'isolated' && scope !== 'imported') { return null } const id = randomUUID() @@ -228,8 +231,7 @@ class BrowserSessionRegistry { scope, partition, label, - source: null, - ...(options.userAgentMode ? { userAgentMode: options.userAgentMode } : {}) + source: null } try { await installBrowserSessionPartitionPolicies(profile) @@ -279,7 +281,6 @@ class BrowserSessionRegistry { // Why: clear the partition's storage so deleting a profile doesn't leave orphaned cookies/cache behind. try { const sess = session.fromPartition(profile.partition) - clearBrowserSessionUserAgentMode(sess) forgetBrowserSessionPartitionConfiguration(profile.partition) invalidateBrowserSessionProxyApplication(sess) const release = retireProxySessionApplication(sess) diff --git a/src/main/browser/browser-session-route-policies.ts b/src/main/browser/browser-session-route-policies.ts index 410bc9dedebc..483d8ddb162f 100644 --- a/src/main/browser/browser-session-route-policies.ts +++ b/src/main/browser/browser-session-route-policies.ts @@ -5,7 +5,6 @@ import { clearBrowserSessionPartitionPolicies, installBrowserSessionPartitionPolicies } from './browser-session-partition-policies' -import { clearBrowserSessionUserAgentMode } from './browser-session-user-agent-mode' export function installBrowserRoutePartitionPolicies( profile: BrowserSessionProfile, @@ -25,6 +24,5 @@ export function clearBrowserRoutePartitionPolicies(partition: string): void { return } const sess = session.fromPartition(partition) - clearBrowserSessionUserAgentMode(sess) clearBrowserSessionPartitionPolicies(partition, sess) } diff --git a/src/main/browser/browser-session-ua.ts b/src/main/browser/browser-session-ua.ts index b7fd26449f5e..bbbdd8f0b892 100644 --- a/src/main/browser/browser-session-ua.ts +++ b/src/main/browser/browser-session-ua.ts @@ -1,56 +1,125 @@ import type { Session } from 'electron' +import type { ViewportUserAgentOverride } from './browser-viewport-user-agent' +export { cleanElectronUserAgent } from './browser-process-user-agent' +import { getBrowserProcessUserAgentIdentity } from './browser-process-user-agent' import { currentUserAgent, googleAuthUserAgent, - isGoogleAuthUrl, setUserAgentHeader, + shouldUseGoogleAuthIdentity, stripClientHints } from './browser-google-auth-ua' -// Why: Electron's default UA includes "Electron/X.X.X" and the app name -// (e.g. "orca/1.2.3"), an impossible identity for sessions imported from Chrome. -// This focused revocation fix strips only those tokens; it does not attempt full Chrome -// impersonation, and Chromium's client-hint identity remains browser-owned. -export function cleanElectronUserAgent(ua: string): string { - return ( - ua - .replace(/\s+Electron\/\S+/, '') - // Why: \S+ matches any non-whitespace token (e.g. "orca/1.3.8-rc.0") - // including pre-release semver strings that [\d.]+ would miss. - .replace(/(\)\s+)\S+\s+(Chrome\/)/, '$1$2') - ) +export type BrowserSessionRequestUserAgentResolver = (args: { + session: Session + url: string + referrer?: string + resourceType?: string + webContentsId?: number + currentUserAgent?: string + effectiveUserAgent?: string +}) => ViewportUserAgentOverride | undefined + +function quoteClientHint(value: string): string { + return `"${value.replace(/["\\]/g, '\\$&')}"` } -// Why: Chromium already publishes one internally consistent client-hint identity through both -// request headers and navigator.userAgentData. This handler only owns the host-scoped Firefox -// exception; synthesizing Chrome brands here would make those two browser-owned surfaces disagree. -export function setupGoogleAuthUserAgentOverride(sess: Session): void { - const firefoxUa = googleAuthUserAgent() +function formatClientHintBrands(brands: { brand: string; version: string }[]): string { + return brands + .map(({ brand, version }) => `${quoteClientHint(brand)};v=${quoteClientHint(version)}`) + .join(', ') +} - sess.webRequest.onBeforeSendHeaders({ urls: ['https://*/*'] }, (details, callback) => { - const headers = details.requestHeaders - if (isGoogleAuthUrl(details.url)) { - // Why: present a Firefox identity on Google's sign-in hosts so the user logs - // in inside the app and Google issues self-refreshing bound cookies. Strip - // sec-ch-ua* because real Firefox sends none. - setUserAgentHeader(headers, firefoxUa) - stripClientHints(headers) - callback({ requestHeaders: headers }) - return +function applyUserAgentMetadataHeaders( + headers: Record, + metadata: NonNullable +): void { + const values: Record = { + 'sec-ch-ua': formatClientHintBrands(metadata.brands), + 'sec-ch-ua-full-version-list': formatClientHintBrands(metadata.fullVersionList), + 'sec-ch-ua-full-version': quoteClientHint(metadata.fullVersion), + 'sec-ch-ua-platform': quoteClientHint(metadata.platform), + 'sec-ch-ua-platform-version': quoteClientHint(metadata.platformVersion), + 'sec-ch-ua-arch': quoteClientHint(metadata.architecture), + 'sec-ch-ua-model': quoteClientHint(metadata.model), + 'sec-ch-ua-mobile': metadata.mobile ? '?1' : '?0' + } + for (const key of Object.keys(headers)) { + const lowerKey = key.toLowerCase() + if (!lowerKey.startsWith('sec-ch-ua')) { + continue } - if (currentUserAgent(headers) === firefoxUa) { - // Why: while the auth document is on screen the WebContents UA is Firefox, - // so its cross-host subresource/XHR requests (gstatic, play.google.com, the - // sign-in challenge endpoints) reach here carrying the Firefox UA yet still - // bearing Chromium client hints. Rewriting those to Chrome pairs a Firefox - // UA with Chrome hints — a sharper cross-host identity tell than either - // alone, which can stall Google's password-submit challenge. Real Firefox - // sends no client hints, so strip them to keep one identity for the flow. - stripClientHints(headers) + const value = values[lowerKey] + if (value === undefined) { + delete headers[key] + } else { + headers[key] = value + } + } +} + +// Desktop client hints remain browser-owned. Mobile overrides carry the same metadata CDP used, +// so worker requests replace only hints Chromium already chose to emit without inventing them. +export function installBrowserSessionUserAgentExceptions( + sess: Session, + resolveRequestUserAgent?: BrowserSessionRequestUserAgentResolver +): () => void { + const firefoxUa = googleAuthUserAgent() + sess.webRequest.onBeforeSendHeaders( + { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] }, + (details, callback) => { + const headers = details.requestHeaders + const requestUserAgent = currentUserAgent(headers) + let effectiveUserAgent: string | undefined + try { + effectiveUserAgent = details.webContents?.getUserAgent() + } catch { + // The request can race guest teardown; the header and manager state still provide a fallback. + } + if ( + // Native is an app-wide request to keep Electron's identity, including on Google auth hosts. + getBrowserProcessUserAgentIdentity().mode === 'clean' && + shouldUseGoogleAuthIdentity(details.url, details.referrer ?? '', details.resourceType ?? '') + ) { + setUserAgentHeader(headers, firefoxUa) + stripClientHints(headers) + callback({ requestHeaders: headers }) + return + } + const identity = resolveRequestUserAgent?.({ + session: sess, + url: details.url, + referrer: details.referrer, + resourceType: details.resourceType, + webContentsId: details.webContentsId, + currentUserAgent: requestUserAgent, + effectiveUserAgent + }) + if (!identity) { + callback({ requestHeaders: headers }) + return + } + if (identity.userAgent) { + setUserAgentHeader(headers, identity.userAgent) + } + if (identity.userAgent === firefoxUa) { + stripClientHints(headers) + callback({ requestHeaders: headers }) + return + } + if (identity.userAgentMetadata) { + applyUserAgentMetadataHeaders(headers, identity.userAgentMetadata) + } callback({ requestHeaders: headers }) + } + ) + let disposed = false + return (): void => { + if (disposed) { return } - callback({ requestHeaders: headers }) - }) + disposed = true + sess.webRequest.onBeforeSendHeaders(null) + } } diff --git a/src/main/browser/browser-session-user-agent-mode.ts b/src/main/browser/browser-session-user-agent-mode.ts deleted file mode 100644 index 94051d12ff78..000000000000 --- a/src/main/browser/browser-session-user-agent-mode.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { Session } from 'electron' - -import type { BrowserSessionUserAgentMode } from '../../shared/browser-workspace-types' - -const userAgentModeBySession = new WeakMap() - -export function setBrowserSessionUserAgentMode( - session: Session, - mode: BrowserSessionUserAgentMode -): void { - userAgentModeBySession.set(session, mode) -} - -export function getBrowserSessionUserAgentMode( - session: Session -): BrowserSessionUserAgentMode | undefined { - return userAgentModeBySession.get(session) -} - -export function clearBrowserSessionUserAgentMode(session: Session): void { - userAgentModeBySession.delete(session) -} diff --git a/src/main/browser/browser-viewport-user-agent.ts b/src/main/browser/browser-viewport-user-agent.ts index 691ed0b88a8d..31c06307b463 100644 --- a/src/main/browser/browser-viewport-user-agent.ts +++ b/src/main/browser/browser-viewport-user-agent.ts @@ -37,8 +37,9 @@ export function buildViewportUserAgentOverride(args: { url: string mobile: boolean baseUserAgent: string + googleAuthEnabled?: boolean }): ViewportUserAgentOverride { - if (isGoogleAuthUrl(args.url)) { + if (args.googleAuthEnabled !== false && isGoogleAuthUrl(args.url)) { // Why: match the header-level Firefox switch exactly, and send no userAgentMetadata — real // Firefox emits no client hints, so Chrome brands here would contradict the stripped headers. return { userAgent: googleAuthUserAgent() } diff --git a/src/main/browser/browser-webauthn-profile-delete.test.ts b/src/main/browser/browser-webauthn-profile-delete.test.ts index 3c471fe2dc22..18e2d58de5cc 100644 --- a/src/main/browser/browser-webauthn-profile-delete.test.ts +++ b/src/main/browser/browser-webauthn-profile-delete.test.ts @@ -33,6 +33,10 @@ vi.mock('./browser-manager', () => ({ } })) +vi.mock('./browser-process-user-agent', () => ({ + getBrowserProcessUserAgentIdentity: () => ({ mode: 'clean', userAgent: 'Mozilla/5.0 Test' }) +})) + import { browserSessionRegistry } from './browser-session-registry' import { cancelAllBrowserWebAuthnAccountRequests, @@ -42,6 +46,7 @@ import { type MockSession = Electron.Session & EventEmitter function mockSession(): MockSession { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this focused Electron Session double implements every member the exercised policy and WebAuthn paths read. return Object.assign(new EventEmitter(), { clearCache: vi.fn().mockResolvedValue(undefined), clearStorageData: vi.fn().mockResolvedValue(undefined), @@ -49,6 +54,7 @@ function mockSession(): MockSession { setDisplayMediaRequestHandler: vi.fn(), setPermissionCheckHandler: vi.fn(), setPermissionRequestHandler: vi.fn(), + setUserAgent: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn() } }) as unknown as MockSession } diff --git a/src/main/browser/doc-preview-protocol.test.ts b/src/main/browser/doc-preview-protocol.test.ts index 32700be32fd9..bce257689600 100644 --- a/src/main/browser/doc-preview-protocol.test.ts +++ b/src/main/browser/doc-preview-protocol.test.ts @@ -267,7 +267,7 @@ describe('installDocPreviewProtocolHandler', () => { installDocPreviewProtocolHandler() expect(mocks.installBrowserSessionPartitionPolicies).toHaveBeenCalledWith( - expect.objectContaining({ partition: 'orca-doc-preview', userAgentMode: 'clean' }), + expect.objectContaining({ partition: 'orca-doc-preview' }), expect.anything() ) }) diff --git a/src/main/browser/doc-preview-protocol.ts b/src/main/browser/doc-preview-protocol.ts index fd60817ff362..8ea26fe7aa9e 100644 --- a/src/main/browser/doc-preview-protocol.ts +++ b/src/main/browser/doc-preview-protocol.ts @@ -134,8 +134,7 @@ export function installDocPreviewProtocolHandler(): void { scope: 'isolated', partition: DOC_PREVIEW_PARTITION, label: 'Document preview', - source: null, - userAgentMode: 'clean' + source: null }, // Why downloads are the one policy that does not carry over: the browser download flow needs a // page to attribute the file to, and a previewed document is not one. Routed here it would diff --git a/src/main/browser/offscreen-browser-backend.ts b/src/main/browser/offscreen-browser-backend.ts index 300a01e0b76d..039ed02b4bfa 100644 --- a/src/main/browser/offscreen-browser-backend.ts +++ b/src/main/browser/offscreen-browser-backend.ts @@ -76,7 +76,6 @@ export class OffscreenBrowserBackend implements BrowserBackend { browserPageId, worktreeId: params.worktreeId, sessionProfileId: profile?.id ?? null, - userAgentMode: profile?.userAgentMode, webContentsId: win.webContents.id }) if (!registered) { diff --git a/src/main/ipc/browser-session-profile-ipc.test.ts b/src/main/ipc/browser-session-profile-ipc.test.ts index 181241cdd52d..1b6199574118 100644 --- a/src/main/ipc/browser-session-profile-ipc.test.ts +++ b/src/main/ipc/browser-session-profile-ipc.test.ts @@ -111,22 +111,22 @@ describe('browser session profile IPC', () => { expect(detectBrowsersMock).not.toHaveBeenCalled() }) - it('forwards the user-agent mode from a trusted renderer', async () => { + it('creates a profile for a trusted renderer', async () => { const profile = { id: 'profile-google', scope: 'isolated', partition: 'persist:orca-browser-session-profile-google', label: 'Google', - source: null, - userAgentMode: 'native' + source: null } createProfileMock.mockReturnValue(profile) registerBrowserHandlers() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the registered test handler is selected by its exact channel and called with its declared boundary shape. const createHandler = handleMock.mock.calls.find( ([channel]) => channel === 'browser:session:createProfile' )?.[1] as ( event: { sender: Electron.WebContents }, - args: { scope: 'isolated'; label: string; userAgentMode: 'native' } + args: { scope: 'isolated'; label: string } ) => unknown const sender = { id: 91, @@ -136,10 +136,8 @@ describe('browser session profile IPC', () => { } as Electron.WebContents await expect( - createHandler({ sender }, { scope: 'isolated', label: 'Google', userAgentMode: 'native' }) + createHandler({ sender }, { scope: 'isolated', label: 'Google' }) ).resolves.toEqual(profile) - expect(createProfileMock).toHaveBeenCalledWith('isolated', 'Google', { - userAgentMode: 'native' - }) + expect(createProfileMock).toHaveBeenCalledWith('isolated', 'Google') }) }) diff --git a/src/main/ipc/browser-session-profile-ipc.ts b/src/main/ipc/browser-session-profile-ipc.ts index c4e0da963ca6..bf144e178fa9 100644 --- a/src/main/ipc/browser-session-profile-ipc.ts +++ b/src/main/ipc/browser-session-profile-ipc.ts @@ -14,14 +14,20 @@ import { import type { BrowserCookieImportResult, BrowserSessionProfile, - BrowserSessionProfileCreateOptions, BrowserSessionProfileScope } from '../../shared/browser-workspace-types' +import { + clearBrowserIdentityMigrationNotice, + readPendingBrowserIdentityMigrationNotice +} from '../browser/browser-identity-mode-record' +import { getCanonicalUserDataPath } from '../persistence' export function registerBrowserSessionProfileHandlers(): void { ipcMain.removeHandler('browser:session:listProfiles') ipcMain.removeHandler('browser:session:createProfile') ipcMain.removeHandler('browser:session:deleteProfile') + ipcMain.removeHandler('browser:session:readUserAgentMigrationNotice') + ipcMain.removeHandler('browser:session:clearUserAgentMigrationNotice') ipcMain.removeHandler('browser:session:importCookies') ipcMain.removeHandler('browser:session:resolvePartition') @@ -36,20 +42,29 @@ export function registerBrowserSessionProfileHandlers(): void { 'browser:session:createProfile', async ( event, - args: { - scope: BrowserSessionProfileScope - label: string - } & BrowserSessionProfileCreateOptions + args: { scope: BrowserSessionProfileScope; label: string } ): Promise => { if (!isTrustedBrowserRenderer(event.sender)) { return null } - return await browserSessionRegistry.createProfile(args.scope, args.label, { - userAgentMode: args.userAgentMode - }) + return await browserSessionRegistry.createProfile(args.scope, args.label) } ) + ipcMain.handle('browser:session:readUserAgentMigrationNotice', (event): string[] | null => { + if (!isTrustedBrowserRenderer(event.sender)) { + return null + } + return readPendingBrowserIdentityMigrationNotice(getCanonicalUserDataPath()) + }) + + ipcMain.handle('browser:session:clearUserAgentMigrationNotice', (event): boolean => { + if (!isTrustedBrowserRenderer(event.sender)) { + return false + } + return clearBrowserIdentityMigrationNotice(getCanonicalUserDataPath()) + }) + ipcMain.handle( 'browser:session:deleteProfile', async (event, args: { profileId: string }): Promise => { diff --git a/src/main/ipc/browser.ts b/src/main/ipc/browser.ts index d9aa0409c08e..2e74f42fd3a4 100644 --- a/src/main/ipc/browser.ts +++ b/src/main/ipc/browser.ts @@ -1,7 +1,6 @@ import { ipcMain, webContents } from 'electron' import { browserCertificateTrustController, browserManager } from '../browser/browser-manager' import type { AgentBrowserBridge } from '../browser/agent-browser-bridge' -import { browserSessionRegistry } from '../browser/browser-session-registry' import { isWorkspaceDocPageId } from '../browser/doc-preview-guest-policy' import { isTrustedBrowserRenderer } from './browser-renderer-trust' import { @@ -80,10 +79,8 @@ export function registerBrowserHandlers(): void { // with a new webContentsId. The bridge must destroy the old session's // proxy (its webContents is gone) and let the next command recreate it. const previousWcId = browserManager.getGuestWebContentsId(args.browserPageId) - const profile = browserSessionRegistry.getProfile(args.sessionProfileId ?? 'default') const registered = browserManager.registerGuest({ ...args, - userAgentMode: profile?.userAgentMode, rendererWebContentsId: event.sender.id }) if (!registered) { diff --git a/src/main/persistence/applying-settings/settings-update.ts b/src/main/persistence/applying-settings/settings-update.ts index e8a080763da6..c27879d6ca62 100644 --- a/src/main/persistence/applying-settings/settings-update.ts +++ b/src/main/persistence/applying-settings/settings-update.ts @@ -39,6 +39,7 @@ import { buildWorkspaceDirHistoryForUpdate, stripRetiredGlobalSettings } from './terminal-settings-migrations' +import { normalizeBrowserUserAgentMode } from '../../../shared/browser-user-agent-mode' export type SettingsMutationOperations = { state: PersistedState @@ -76,6 +77,11 @@ export function updateSettings( if ('agentSkillSharingEnabled' in updates) { sanitizedUpdates.agentSkillSharingEnabled = updates.agentSkillSharingEnabled === true } + if ('browserUserAgentMode' in updates) { + sanitizedUpdates.browserUserAgentMode = normalizeBrowserUserAgentMode( + updates.browserUserAgentMode + ) + } if ('nestedWorkerMaxDepth' in updates) { sanitizedUpdates.nestedWorkerMaxDepth = resolveNestedWorkerMaxDepth({ nestedWorkerMaxDepth: updates.nestedWorkerMaxDepth diff --git a/src/main/persistence/loading-store/normalize-loaded-global-settings.ts b/src/main/persistence/loading-store/normalize-loaded-global-settings.ts index 90678e9f8221..3066cacb0d1d 100644 --- a/src/main/persistence/loading-store/normalize-loaded-global-settings.ts +++ b/src/main/persistence/loading-store/normalize-loaded-global-settings.ts @@ -12,6 +12,7 @@ import { readLegacySidekickFlag } from '../applying-settings/onboarding-normaliz import type { PersistedState } from '../../../shared/persisted-state-types' import type { PreparedLoadedTerminalSettings } from './prepare-loaded-terminal-settings' import type { PreparedLoadedProfileSettings } from './prepare-loaded-profile-settings' +import { normalizeBrowserUserAgentMode } from '../../../shared/browser-user-agent-mode' export function normalizeLoadedGlobalSettings( parsed: PersistedState, @@ -107,6 +108,7 @@ export function normalizeLoadedGlobalSettings( terminalQuickCommands: normalizeTerminalQuickCommands(parsed.settings?.terminalQuickCommands), terminalCustomThemes: normalizeTerminalCustomThemes(parsed.settings?.terminalCustomThemes), appIcon: normalizeAppIconId(parsed.settings?.appIcon), + browserUserAgentMode: normalizeBrowserUserAgentMode(parsed.settings?.browserUserAgentMode), mobilePairingCustomAddress, mobilePairingCustomAddresses, // Why: persisted settings may be hand-edited or from older builds; keep tray-minimize false unless stored value is true. diff --git a/src/main/runtime/orca-runtime-browser.test.ts b/src/main/runtime/orca-runtime-browser.test.ts index 64b67ac9c95b..8996c031f752 100644 --- a/src/main/runtime/orca-runtime-browser.test.ts +++ b/src/main/runtime/orca-runtime-browser.test.ts @@ -138,29 +138,22 @@ describe('RuntimeBrowserCommands browser screencast', () => { browserSessionRegistryMock.createProfile.mockReset() }) - it('creates profiles with the requested user-agent mode', async () => { + it('creates profiles with the requested scope and label', async () => { const { RuntimeBrowserCommands } = await import('./orca-runtime-browser') const profile = { id: 'profile-google', scope: 'isolated', partition: 'persist:orca-browser-session-profile-google', label: 'Google', - source: null, - userAgentMode: 'native' + source: null } browserSessionRegistryMock.createProfile.mockReturnValue(profile) const commands = new RuntimeBrowserCommands(createHost()) await expect( - commands.browserProfileCreate({ - label: 'Google', - scope: 'isolated', - userAgentMode: 'native' - }) + commands.browserProfileCreate({ label: 'Google', scope: 'isolated' }) ).resolves.toEqual({ profile }) - expect(browserSessionRegistryMock.createProfile).toHaveBeenCalledWith('isolated', 'Google', { - userAgentMode: 'native' - }) + expect(browserSessionRegistryMock.createProfile).toHaveBeenCalledWith('isolated', 'Google') }) it('waits for explicit worktree browser registration after requesting a hidden mount', async () => { diff --git a/src/main/runtime/rpc/methods/browser.test.ts b/src/main/runtime/rpc/methods/browser.test.ts index cb104565c3d0..55ee1571e97c 100644 --- a/src/main/runtime/rpc/methods/browser.test.ts +++ b/src/main/runtime/rpc/methods/browser.test.ts @@ -68,16 +68,10 @@ describe('browser RPC methods', () => { }) }) - it('validates profile user-agent modes', () => { + it('ignores the retired profile user-agent field from older clients', () => { expect( - ProfileCreate.safeParse({ label: 'Google', scope: 'isolated', userAgentMode: 'native' }) - .success - ).toBe(true) - expect(ProfileCreate.safeParse({ label: 'Work', scope: 'isolated' }).success).toBe(true) - expect( - ProfileCreate.safeParse({ label: 'Bad', scope: 'isolated', userAgentMode: 'rotating' }) - .success - ).toBe(false) + ProfileCreate.parse({ label: 'Google', scope: 'isolated', userAgentMode: 'native' }) + ).toEqual({ label: 'Google', scope: 'isolated' }) }) it('routes core browser automation commands to the runtime server', async () => { diff --git a/src/main/runtime/runtime-browser-commands-browser-tab-set-profile.ts b/src/main/runtime/runtime-browser-commands-browser-tab-set-profile.ts index 3f701aea3471..482182a07697 100644 --- a/src/main/runtime/runtime-browser-commands-browser-tab-set-profile.ts +++ b/src/main/runtime/runtime-browser-commands-browser-tab-set-profile.ts @@ -16,7 +16,6 @@ import { browserManager } from '../browser/browser-manager' import { randomUUID } from 'node:crypto' import { ipcMain } from 'electron' import { waitForTabRegistration } from '../ipc/browser-tab-registration-wait' -import type { BrowserSessionUserAgentMode } from '../../shared/browser-workspace-types' import { detectInstalledBrowsers } from '../browser/browser-cookie-import' export class RuntimeBrowserCommandsWithBrowserTabSetProfile extends RuntimeBrowserCommandsWithBrowserTabCreate { @@ -158,12 +157,9 @@ export class RuntimeBrowserCommandsWithBrowserTabSetProfile extends RuntimeBrows async browserProfileCreate(params: { label: string scope: 'isolated' | 'imported' - userAgentMode?: BrowserSessionUserAgentMode }): Promise { return { - profile: await browserSessionRegistry.createProfile(params.scope, params.label, { - userAgentMode: params.userAgentMode - }) + profile: await browserSessionRegistry.createProfile(params.scope, params.label) } } diff --git a/src/main/startup/browser-process-user-agent-ordering.test.ts b/src/main/startup/browser-process-user-agent-ordering.test.ts new file mode 100644 index 000000000000..d58717544fa1 --- /dev/null +++ b/src/main/startup/browser-process-user-agent-ordering.test.ts @@ -0,0 +1,180 @@ +import { describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => { + const events: string[] = [] + let userAgent = 'Mozilla/5.0 (Test) Package/0.0.0 Chrome/150.0.0.0 Electron/43.0.0 Safari/537.36' + const app = { + isPackaged: false, + exit: vi.fn(), + getVersion: vi.fn(() => '1.0.0'), + getPath: vi.fn(() => '/canonical-user-data'), + get userAgentFallback(): string { + events.push('read-user-agent') + return userAgent + }, + set userAgentFallback(value: string) { + events.push('write-user-agent') + userAgent = value + }, + isReady: vi.fn(() => { + events.push('is-ready') + return false + }), + setName: vi.fn((name: string) => { + events.push(`set-name:${name}`) + }) + } + return { app, events, userAgent: () => userAgent } +}) + +vi.mock('electron', () => ({ + app: mocks.app, + ipcMain: {}, + powerMonitor: {}, + session: { defaultSession: {} } +})) +vi.mock('@electron-toolkit/utils', () => ({ is: { dev: true } })) +vi.mock('./cli-launch-redirect', () => ({ + maybeRedirectCliLaunch: () => ({ redirected: false, status: 0 }) +})) +vi.mock('./serve-mode-argv', () => ({ + argvRequestsServeMode: () => false, + normalizeServeModeArgv: (argv: string[]) => argv +})) +vi.mock('./configure-process', () => ({ + configureDevUserDataPath: vi.fn(), + configureElectronNetworkCompatibility: vi.fn(), + configureOrcaUserDataPathEnv: vi.fn(), + disableUnsupportedChromiumFeatures: vi.fn(), + enableMainProcessGpuFeatures: vi.fn(), + installDevParentDisconnectQuit: vi.fn(), + installDevParentSignalQuit: vi.fn(), + installDevParentWatchdog: vi.fn(), + optOutOfHiddenPageWakeUpThrottling: vi.fn(), + patchPackagedProcessPath: vi.fn() +})) +vi.mock('../serve-update-handoff', () => ({ installServeSupervisorDisconnectQuit: vi.fn() })) +vi.mock('./main-process-error-guards', () => ({ + installUncaughtPipeErrorGuard: vi.fn(), + installUnhandledRejectionLogging: vi.fn() +})) +vi.mock('./hydrate-shell-path') +vi.mock('../runtime/remote-server-updater', () => ({ configureRemoteServerUpdater: vi.fn() })) +vi.mock('../updater', () => ({ + getRemoteServerUpdaterSnapshot: vi.fn(), + checkForRemoteServerUpdate: vi.fn(), + downloadRemoteServerUpdate: vi.fn(), + installRemoteServerUpdate: vi.fn(), + isQuittingForUpdate: () => false +})) +vi.mock('./dev-instance-identity', () => ({ + getDevInstanceIdentity: () => ({ + isDev: true, + appName: 'Orca Development', + appUserModelId: 'com.orca.development' + }), + shouldApplyPreReadyAppName: () => true +})) +vi.mock('./renderer-heap-headroom') +vi.mock('./startup-diagnostics', () => ({ + isStartupDiagnosticsEnabled: () => { + mocks.events.push('continued-after-browser-identity') + throw new Error('preflight-test-stop') + }, + logStartupDiagnostic: vi.fn() +})) +vi.mock('./event-loop-stall-probe') +vi.mock('../diagnostics/main-thread-churn-probe') +vi.mock('../git/source-control/git-read-cache-invalidation', () => ({ + settledDiffCache: { stats: vi.fn() } +})) +vi.mock('../server/serve-stdout-boundary') +vi.mock('./serve-desktop-activation', () => ({ + createServeDesktopActivationGate: () => ({}) +})) +vi.mock('./single-instance-lock', () => ({ + shouldBypassSingleInstanceLock: () => false, + shouldSkipSingleInstanceLock: () => true, + acquireSingleInstanceLock: vi.fn(), + logSingleInstanceLockBypass: vi.fn(), + logSingleInstanceLockFailure: vi.fn(), + SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE: 1 +})) +vi.mock('../../shared/app-environment', () => ({ setAppEnvironment: vi.fn() })) +vi.mock('../host/electron-app-environment', () => ({ ElectronAppEnvironment: class {} })) +vi.mock('../own-chromium-tree-kill-guard') +vi.mock('../../shared/secret-store') +vi.mock('../host/electron-secret-store') +vi.mock('../ipc/pty-host-bindings') +vi.mock('../host/electron-runtime-desktop-surface') +vi.mock('../runtime/runtime-desktop-surface') +vi.mock('../host/electron-browser-commands') +vi.mock('../runtime/runtime-browser-commands-factory') +vi.mock('../host/electron-http-client') +vi.mock('../network/http-client') +vi.mock('../host/electron-speech-services') +vi.mock('../speech/speech-runtime-service') +vi.mock('../ipc/worktree-watcher-removal') +vi.mock('../ipc/filesystem-watcher') +vi.mock('../network/proxy-settings') +vi.mock('../persistence', () => ({ + initDataPath: () => mocks.events.push('init-data-path'), + getCanonicalUserDataPath: () => '/canonical-user-data' +})) +vi.mock('../macos-press-and-hold-default') +vi.mock('../ai-vault/session-parse-cache-persistence') +vi.mock('../orca-profiles/profile-index-store') +vi.mock('../stats/collector') +vi.mock('../claude-usage/store') +vi.mock('../codex-usage/store') +vi.mock('../opencode-usage/store') +vi.mock('../browser/doc-preview-protocol') +vi.mock('../crash-reporting/crashpad-capture') +vi.mock('../crash-reporting/crash-report-store') +vi.mock('../crash-reporting/crash-breadcrumb-store') +vi.mock('../crash-reporting/durable-crash-breadcrumb') +vi.mock('../crash-reporting/gpu-crash-diagnostics') +vi.mock('../crash-reporting/main-process-lifecycle-identity') +vi.mock('./ensure-virtual-display', () => ({ + ensureVirtualDisplayForHeadlessServe: vi.fn(), + hasUsableLinuxDisplay: () => true, + MISSING_LINUX_DISPLAY_MESSAGE: 'missing display' +})) +vi.mock('./gpu-lifecycle') +vi.mock('./main-process-state', () => ({ mainProcessState: {} })) +vi.mock('./synthetic-title-runtime') +vi.mock('../browser/browser-identity-mode-record', () => ({ + readBrowserIdentityModeRecord: (path: string) => { + mocks.events.push(`read-mode:${path}`) + return { version: 1, mode: 'clean' } + } +})) + +describe('browser process user-agent startup ordering', () => { + it('executes after the dev app name and before later preflight work', async () => { + const { getBrowserProcessUserAgentIdentity } = + await import('../browser/browser-process-user-agent') + const { runMainProcessPreflight } = await import('./main-process-preflight') + + expect(() => + runMainProcessPreflight({ + focusExistingWindow: vi.fn(), + requestDesktopActivation: vi.fn() + }) + ).toThrow('preflight-test-stop') + + const nameIndex = mocks.events.indexOf('set-name:Orca Development') + const modeIndex = mocks.events.indexOf('read-mode:/canonical-user-data') + const writeIndex = mocks.events.indexOf('write-user-agent') + const continuationIndex = mocks.events.indexOf('continued-after-browser-identity') + expect(mocks.events.indexOf('init-data-path')).toBeLessThan(nameIndex) + expect(nameIndex).toBeLessThan(modeIndex) + expect(modeIndex).toBeLessThan(writeIndex) + expect(writeIndex).toBeLessThan(continuationIndex) + expect(getBrowserProcessUserAgentIdentity()).toEqual({ + mode: 'clean', + userAgent: mocks.userAgent() + }) + expect(mocks.userAgent()).not.toMatch(/Electron|Package/) + }) +}) diff --git a/src/main/startup/main-process-preflight.ts b/src/main/startup/main-process-preflight.ts index 177a23574412..0d62d91cdf3b 100644 --- a/src/main/startup/main-process-preflight.ts +++ b/src/main/startup/main-process-preflight.ts @@ -86,6 +86,8 @@ import { import { maybeApplyGpuFallbackForThisLaunch, registerGpuLifecycleHandlers } from './gpu-lifecycle' import { mainProcessState as state } from './main-process-state' import { initializeSyntheticTitleRuntime } from './synthetic-title-runtime' +import { initializeBrowserProcessUserAgent } from '../browser/browser-process-user-agent' +import { readBrowserIdentityModeRecord } from '../browser/browser-identity-mode-record' export type MainProcessPreflightOptions = { focusExistingWindow: () => void @@ -178,6 +180,13 @@ export function runMainProcessPreflight(options: MainProcessPreflightOptions): b // Why captured now: after the dev/E2E override above, and before app.setName('Orca') (whenReady) // changes how userData resolves on a case-sensitive filesystem. See persistence.ts:20-28. initDataPath() + // Why: Electron resolves the macOS safeStorage Keychain service name from the app name before + // ready. Dev pins userData above, so applying its name here cannot shift the captured path. + if (state.devInstanceIdentity && shouldApplyPreReadyAppName(state.devInstanceIdentity)) { + app.setName(state.devInstanceIdentity.appName) + } + // Why: renderer and worker defaults are process-global and must be fixed before any session exists. + initializeBrowserProcessUserAgent(readBrowserIdentityModeRecord(getCanonicalUserDataPath()).mode) state.startupDiagnosticsEnabled = isStartupDiagnosticsEnabled() if (state.startupDiagnosticsEnabled) { logStartupDiagnostic('before-single-instance-lock', { @@ -275,15 +284,6 @@ export function runMainProcessPreflight(options: MainProcessPreflightOptions): b initClaudeUsagePath() initCodexUsagePath() initOpenCodeUsagePath() - // Why: Electron resolves the macOS safeStorage Keychain service name - // (" Safe Storage") before `ready`, so the setName in whenReady is - // too late to move it — dev otherwise lands on the package.json name. Dev-only - // so a packaged build keeps deriving the key from its own CFBundleName. - // Safe here: dev always pins userData via app.setPath (configure-process.ts), - // so setName cannot shift the paths captured just above. - if (state.devInstanceIdentity && shouldApplyPreReadyAppName(state.devInstanceIdentity)) { - app.setName(state.devInstanceIdentity.appName) - } // Why: Electron freezes the privileged scheme table at ready, so the doc-preview // scheme must be declared here or its webview loses fetch/secure-origin privileges. registerDocPreviewSchemePrivileges() diff --git a/src/main/startup/main-process-ready-foundation.ts b/src/main/startup/main-process-ready-foundation.ts index 3c0e01fe09eb..9f7901c87139 100644 --- a/src/main/startup/main-process-ready-foundation.ts +++ b/src/main/startup/main-process-ready-foundation.ts @@ -49,6 +49,7 @@ import { updateGpuAccelerationAboutPanel } from './gpu-lifecycle' import { reconcileManagedWslCliRegistrations } from '../cli/wsl-cli-registration-reconciliation' import { createWslCliReconciliationStartupBarrier } from './wsl-cli-reconciliation-startup-barrier' import { isAgentStatusHooksEnabled } from '../agent-hooks/managed-agent-hook-controls' +import { updateBrowserIdentityMode } from '../browser/browser-identity-mode-record' export async function initializeReadyFoundation(): Promise { logStartupMilestone('app-ready') @@ -199,6 +200,8 @@ export async function initializeReadyFoundation(): Promise { canonicalUserDataPath, store.getSettings().electronHttp1CompatibilityMode === true ) + // Why: the tiny pre-ready record mirrors this normal app setting for the next launch. + updateBrowserIdentityMode(canonicalUserDataPath, store.getSettings().browserUserAgentMode) // Why: apply initial fallback WSL distro from store settings for global git/CLI calls. setDefaultWslDistroOverride(store.getSettings().terminalWindowsWslDistro ?? null) store.onSettingsChanged((updates, settings) => { @@ -208,6 +211,9 @@ export async function initializeReadyFoundation(): Promise { settings.electronHttp1CompatibilityMode === true ) } + if ('browserUserAgentMode' in updates) { + updateBrowserIdentityMode(canonicalUserDataPath, settings.browserUserAgentMode) + } if ('terminalWindowsWslDistro' in updates) { // Why: synchronize fallback WSL distro updates to runner. setDefaultWslDistroOverride(settings.terminalWindowsWslDistro ?? null) diff --git a/src/preload/api/browser-api.ts b/src/preload/api/browser-api.ts index d541c32dfd89..7e44bac2eb6a 100644 --- a/src/preload/api/browser-api.ts +++ b/src/preload/api/browser-api.ts @@ -33,7 +33,6 @@ import type { BrowserCookieImportResult, BrowserLoadError, BrowserSessionProfile, - BrowserSessionProfileCreateOptions, BrowserSessionProfileScope, BrowserSessionProfileSource, BrowserViewportOverride, @@ -140,12 +139,12 @@ export type BrowserApi = { browserProfileId?: string skipProbe?: boolean }) => Promise<{ partition: string }> - sessionCreateProfile: ( - args: { - scope: BrowserSessionProfileScope - label: string - } & BrowserSessionProfileCreateOptions - ) => Promise + sessionCreateProfile: (args: { + scope: BrowserSessionProfileScope + label: string + }) => Promise + sessionReadUserAgentMigrationNotice: () => Promise + sessionClearUserAgentMigrationNotice: () => Promise sessionDeleteProfile: (args: { profileId: string }) => Promise sessionImportCookies: (args: { profileId: string }) => Promise sessionResolvePartition: (args: { profileId: string | null }) => Promise diff --git a/src/preload/api/browser-bridge-page-interaction-and-sessions.ts b/src/preload/api/browser-bridge-page-interaction-and-sessions.ts index c2f72ff7cb6a..782fea3bc560 100644 --- a/src/preload/api/browser-bridge-page-interaction-and-sessions.ts +++ b/src/preload/api/browser-bridge-page-interaction-and-sessions.ts @@ -117,11 +117,12 @@ export const browserPageInteractionAndSessionsApi = { skipProbe?: boolean }): Promise<{ partition: string }> => ipcRenderer.invoke('browser:prepareSshWorkspacePartition', args), - sessionCreateProfile: (args: { - scope: 'default' | 'isolated' | 'imported' - label: string - userAgentMode?: 'clean' | 'native' - }) => ipcRenderer.invoke('browser:session:createProfile', args), + sessionCreateProfile: (args: { scope: 'default' | 'isolated' | 'imported'; label: string }) => + ipcRenderer.invoke('browser:session:createProfile', args), + sessionReadUserAgentMigrationNotice: (): Promise => + ipcRenderer.invoke('browser:session:readUserAgentMigrationNotice'), + sessionClearUserAgentMigrationNotice: (): Promise => + ipcRenderer.invoke('browser:session:clearUserAgentMigrationNotice'), sessionDeleteProfile: (args: { profileId: string }): Promise => ipcRenderer.invoke('browser:session:deleteProfile', args), sessionImportCookies: (args: { profileId: string }) => diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserToolbarMenu.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserToolbarMenu.tsx index 42ce7ae52f5d..026931d2554f 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/BrowserToolbarMenu.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/BrowserToolbarMenu.tsx @@ -61,7 +61,6 @@ export function BrowserToolbarMenu({ const [newProfileDialogOpen, setNewProfileDialogOpen] = useState(false) const [newProfileName, setNewProfileName] = useState('') - const [useNativeUserAgent, setUseNativeUserAgent] = useState(false) const [isCreatingProfile, setIsCreatingProfile] = useState(false) const [pendingSwitchProfileId, setPendingSwitchProfileId] = useState( undefined @@ -86,7 +85,6 @@ export function BrowserToolbarMenu({ setNewProfileDialogOpen(open) if (!open) { setNewProfileName('') - setUseNativeUserAgent(false) } } @@ -138,11 +136,7 @@ export function BrowserToolbarMenu({ setIsCreatingProfile(true) try { - const profile = await createBrowserSessionProfile( - 'isolated', - trimmed, - useNativeUserAgent ? { userAgentMode: 'native' } : undefined - ) + const profile = await createBrowserSessionProfile('isolated', trimmed) if (!profile) { if (mountedRef.current) { toast.error( @@ -161,7 +155,6 @@ export function BrowserToolbarMenu({ setNewProfileDialogOpen(false) setNewProfileName('') - setUseNativeUserAgent(false) onDestroyWebview() switchBrowserTabProfile(workspaceId, profile.id, profile.partition) @@ -258,14 +251,11 @@ export function BrowserToolbarMenu({ onNewProfileDialogOpenChange={handleNewProfileDialogOpenChange} newProfileName={newProfileName} onNewProfileNameChange={setNewProfileName} - useNativeUserAgent={useNativeUserAgent} - onUseNativeUserAgentChange={setUseNativeUserAgent} isCreatingProfile={isCreatingProfile} onCreateProfile={() => void handleCreateProfile()} onCancelNewProfile={() => { setNewProfileDialogOpen(false) setNewProfileName('') - setUseNativeUserAgent(false) }} /> diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-toolbar-profile-dialogs.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-toolbar-profile-dialogs.tsx index 46b45a5b6a97..216062958d77 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-toolbar-profile-dialogs.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-toolbar-profile-dialogs.tsx @@ -9,7 +9,6 @@ import { DialogTitle } from '@/components/ui/dialog' import { translate } from '@/i18n/i18n' -import { BrowserProfileUserAgentOption } from '../../browser-profile-user-agent-option' type BrowserToolbarProfileDialogsProps = { pendingSwitchProfileId: string | null | undefined @@ -19,8 +18,6 @@ type BrowserToolbarProfileDialogsProps = { onNewProfileDialogOpenChange: (open: boolean) => void newProfileName: string onNewProfileNameChange: (value: string) => void - useNativeUserAgent: boolean - onUseNativeUserAgentChange: (value: boolean) => void isCreatingProfile: boolean onCreateProfile: () => void onCancelNewProfile: () => void @@ -34,8 +31,6 @@ export function BrowserToolbarProfileDialogs({ onNewProfileDialogOpenChange, newProfileName, onNewProfileNameChange, - useNativeUserAgent, - onUseNativeUserAgentChange, isCreatingProfile, onCreateProfile, onCancelNewProfile @@ -103,12 +98,6 @@ export function BrowserToolbarProfileDialogs({ maxLength={50} className="mb-3" /> -
- -