Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const {
getProfileMock,
getRouteIdentityMock,
importCookiesFromBrowserMock,
importCookiesFromFileMock,
requireRouteBrowserProfileMock,
updateProfileSourceMock
} = vi.hoisted(() => ({
Expand All @@ -24,13 +25,15 @@ const {
getProfileMock: vi.fn(),
getRouteIdentityMock: vi.fn(),
importCookiesFromBrowserMock: vi.fn(),
importCookiesFromFileMock: vi.fn(),
requireRouteBrowserProfileMock: vi.fn(),
updateProfileSourceMock: vi.fn()
}))

vi.mock('./browser-cookie-import', () => ({
detectInstalledBrowsers: detectInstalledBrowsersMock,
importCookiesFromBrowser: importCookiesFromBrowserMock,
importCookiesFromFile: importCookiesFromFileMock,
selectBrowserProfile: vi.fn()
}))
vi.mock('./browser-route-partition-binding-runtime', () => ({
Expand All @@ -47,7 +50,10 @@ vi.mock('./paired-runtime-browser-client-host-runtime', () => ({
getPairedRuntimeBrowserClientRouteIdentity: getRouteIdentityMock
}))

import { importCookiesIntoClientRoutePartition } from './browser-client-route-cookie-import'
import {
importCookiesIntoClientRoutePartition,
importCookieFileIntoClientRoutePartition
} from './browser-client-route-cookie-import'
import { BrowserClientNetworkRouteRegistry } from './browser-client-network-route-registry'
import {
browserAuthorityExecutionHostStorageIdentity,
Expand Down Expand Up @@ -188,3 +194,19 @@ describe('cookie-import target vs. client-hosted page partition', () => {
)
})
})

describe('manual file target vs. client-hosted page partition', () => {
it('writes the selected desktop file into the same jar as a page on the paired server', async () => {
const expected = await importPartition()
importCookiesFromFileMock.mockResolvedValue({ ok: true, summary: { importedCookies: 1 } })
const result = await importCookieFileIntoClientRoutePartition(
{ environmentId: 'env-a', browserProfileId },
async () => '/test/cookies.json'
)
expect(result).toMatchObject({ ok: true })
expect(importCookiesFromFileMock).toHaveBeenLastCalledWith('/test/cookies.json', expected)
expect(expected).toBe(
await pagePartition({ kind: 'native', runtimeId: authorityRuntimeId, revision: 1 })
)
})
})
71 changes: 70 additions & 1 deletion src/main/browser/browser-client-route-cookie-import.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
getProfileMock,
getRouteIdentityMock,
importCookiesFromBrowserMock,
importCookiesFromFileMock,
requireRouteBrowserProfileMock,
recordClientRouteImportSourceMock,
selectBrowserProfileMock
Expand All @@ -21,6 +22,7 @@ const {
getProfileMock: vi.fn(),
getRouteIdentityMock: vi.fn(),
importCookiesFromBrowserMock: vi.fn(),
importCookiesFromFileMock: vi.fn(),
requireRouteBrowserProfileMock: vi.fn(),
recordClientRouteImportSourceMock: vi.fn(),
selectBrowserProfileMock: vi.fn()
Expand All @@ -29,6 +31,7 @@ const {
vi.mock('./browser-cookie-import', () => ({
detectInstalledBrowsers: detectInstalledBrowsersMock,
importCookiesFromBrowser: importCookiesFromBrowserMock,
importCookiesFromFile: importCookiesFromFileMock,
selectBrowserProfile: selectBrowserProfileMock
}))
vi.mock('./browser-route-partition-binding-runtime', () => ({
Expand All @@ -47,7 +50,7 @@ vi.mock('./paired-runtime-browser-client-host-runtime', () => ({
getPairedRuntimeBrowserClientRouteIdentity: getRouteIdentityMock
}))

const { importCookiesIntoClientRoutePartition } =
const { importCookiesIntoClientRoutePartition, importCookieFileIntoClientRoutePartition } =
await import('./browser-client-route-cookie-import')

const routeIdentity = {
Expand Down Expand Up @@ -204,3 +207,69 @@ describe('importCookiesIntoClientRoutePartition', () => {
})
})
})

describe('importCookieFileIntoClientRoutePartition', () => {
it('imports a desktop file into the environment route jar, not the local profile jar', async () => {
importCookiesFromFileMock.mockResolvedValue({ ok: true, summary: { importedCookies: 3 } })
const chooseFile = vi.fn(async () => '/test/cookies.json')
expect(await importCookieFileIntoClientRoutePartition(request, chooseFile)).toMatchObject({
ok: true,
profileId: 'default'
})
expect(importCookiesFromFileMock).toHaveBeenCalledWith(
'/test/cookies.json',
expect.stringMatching(/^persist:orca-browser-v1-[a-f0-9]{64}$/)
)
expect(recordClientRouteImportSourceMock).toHaveBeenCalledWith({
environmentId: 'env-a',
profileId: 'default',
source: { browserFamily: 'manual', importedAt: expect.any(Number) }
})
expect(importCookiesFromBrowserMock).not.toHaveBeenCalled()
})

it('does not open the file picker for a non-client-hosted environment', async () => {
getRouteIdentityMock.mockReturnValue(null)
const chooseFile = vi.fn()
expect(await importCookieFileIntoClientRoutePartition(request, chooseFile)).toBeNull()
expect(chooseFile).not.toHaveBeenCalled()
})

it('preserves cancellation without importing or recording a source', async () => {
expect(await importCookieFileIntoClientRoutePartition(request, async () => null)).toEqual({
ok: false,
reason: 'canceled'
})
expect(importCookiesFromFileMock).not.toHaveBeenCalled()
expect(recordClientRouteImportSourceMock).not.toHaveBeenCalled()
})

it('preserves cancellation when the connection changes during the picker', async () => {
const result = await importCookieFileIntoClientRoutePartition(request, async () => {
getRouteIdentityMock.mockReturnValue(repairedRouteIdentity)
return null
})
expect(result).toEqual({ ok: false, reason: 'canceled' })
expect(importCookiesFromFileMock).not.toHaveBeenCalled()
expect(recordClientRouteImportSourceMock).not.toHaveBeenCalled()
})

it('never opens the picker when partition binding conflicts', async () => {
bindingStore.get.mockReturnValue('b'.repeat(64))
const chooseFile = vi.fn()
expect(await importCookieFileIntoClientRoutePartition(request, chooseFile)).toMatchObject({
ok: false
})
expect(chooseFile).not.toHaveBeenCalled()
})

it('does not badge a replacement connection if re-pairing occurs while the picker is open', async () => {
importCookiesFromFileMock.mockResolvedValue({ ok: true, summary: { importedCookies: 3 } })
const result = await importCookieFileIntoClientRoutePartition(request, async () => {
getRouteIdentityMock.mockReturnValue(repairedRouteIdentity)
return '/test/cookies.json'
})
expect(result).toMatchObject({ ok: false, reason: expect.stringContaining('re-paired') })
expect(recordClientRouteImportSourceMock).not.toHaveBeenCalled()
})
})
73 changes: 65 additions & 8 deletions src/main/browser/browser-client-route-cookie-import.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import type { BrowserCookieImportResult } from '../../shared/browser-workspace-types'
import type {
BrowserSessionProfileSource,
BrowserCookieImportResult
} from '../../shared/browser-workspace-types'
import {
detectInstalledBrowsers,
importCookiesFromBrowser,
importCookiesFromFile,
selectBrowserProfile,
type DetectedBrowser
} from './browser-cookie-import'
Expand All @@ -28,6 +32,57 @@ export type ClientRouteCookieImportRequest = {
*/
export async function importCookiesIntoClientRoutePartition(
request: ClientRouteCookieImportRequest
): Promise<BrowserCookieImportResult | null> {
return runClientRouteCookieImport(request, () => {
const browser = resolveImportSource(request)
if ('reason' in browser) {
return browser
}
return {
importIntoPartition: (partition: string) =>
importCookiesFromBrowser(browser.source, partition),
source: {
browserFamily: browser.source.family,
profileName: importedProfileName(browser.source)
}
}
})
}

type ClientRouteImportTarget = Pick<
ClientRouteCookieImportRequest,
'environmentId' | 'browserProfileId'
>
type ClientRouteImportSource = {
importIntoPartition: (partition: string) => Promise<BrowserCookieImportResult>
source: Omit<BrowserSessionProfileSource, 'importedAt'>
}

export async function importCookieFileIntoClientRoutePartition(
request: ClientRouteImportTarget,
chooseFile: () => Promise<string | null>
): Promise<BrowserCookieImportResult | null> {
return runClientRouteCookieImport(request, () => ({
importIntoPartition: async (partition) => {
const filePath = await chooseFile()
if (!filePath) {
return { ok: false, reason: 'canceled' }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
if (settledRoutePartition(request) !== partition) {
return {
ok: false,
reason: 'The browser connection changed while choosing a cookie file. Try again.'
}
}
return importCookiesFromFile(filePath, partition)
},
source: { browserFamily: 'manual' }
}))
}

async function runClientRouteCookieImport(
request: ClientRouteImportTarget,
resolveSource: () => ClientRouteImportSource | { ok: false; reason: string }
): Promise<BrowserCookieImportResult | null> {
const routeIdentity = getPairedRuntimeBrowserClientRouteIdentity(request.environmentId)
if (!routeIdentity) {
Expand All @@ -37,17 +92,20 @@ export async function importCookiesIntoClientRoutePartition(
if (!profile) {
return { ok: false, reason: 'Session profile not found.' }
}
const browser = resolveImportSource(request)
if ('reason' in browser) {
return browser
const source = resolveSource()
if ('reason' in source) {
return source
}
let partition: string
try {
partition = bindRoutePartition(routeIdentity, request.browserProfileId)
} catch (error) {
return { ok: false, reason: error instanceof Error ? error.message : String(error) }
}
const result = await importCookiesFromBrowser(browser.source, partition)
const result = await source.importIntoPartition(partition)
if (!result.ok && result.reason === 'canceled') {
return result
}
// Why: the import runs for seconds. A host replacement inside that window retargets the
// route, so reporting success here would badge a partition no page will ever read from.
const settled = settledRoutePartition(request)
Expand All @@ -70,16 +128,15 @@ export async function importCookiesIntoClientRoutePartition(
environmentId: request.environmentId,
profileId: request.browserProfileId,
source: {
browserFamily: browser.source.family,
profileName: importedProfileName(browser.source),
...source.source,
importedAt: Date.now()
}
})
return { ...result, profileId: request.browserProfileId }
}

/** Partition the route resolves to now, or null when the host no longer serves this environment. */
function settledRoutePartition(request: ClientRouteCookieImportRequest): string | null {
function settledRoutePartition(request: ClientRouteImportTarget): string | null {
const routeIdentity = getPairedRuntimeBrowserClientRouteIdentity(request.environmentId)
if (!routeIdentity) {
return null
Expand Down
46 changes: 46 additions & 0 deletions src/main/ipc/browser-session-profile-ipc.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'

const {
importCookieFileMock,
handleMock,
removeHandlerMock,
createProfileMock,
routeIdentityMock,
detectBrowsersMock,
setBrowserIdentityModeMock
} = vi.hoisted(() => ({
importCookieFileMock: vi.fn(),
handleMock: vi.fn(),
removeHandlerMock: vi.fn(),
createProfileMock: vi.fn(),
Expand All @@ -16,6 +18,11 @@ const {
setBrowserIdentityModeMock: vi.fn(async () => ({ ok: true }))
}))

vi.mock('../browser/browser-client-route-cookie-import', () => ({
importCookieFileIntoClientRoutePartition: importCookieFileMock,
importCookiesIntoClientRoutePartition: vi.fn()
}))

vi.mock('../browser/browser-identity-mode-store', () => ({
setBrowserIdentityMode: setBrowserIdentityModeMock,
getBrowserIdentityModeStatus: vi.fn(() => ({ identity: {}, migrationNotice: null }))
Expand Down Expand Up @@ -57,6 +64,7 @@ import { setTrustedBrowserRendererWebContentsId } from './browser-renderer-trust

describe('browser session profile IPC', () => {
beforeEach(() => {
importCookieFileMock.mockReset()
handleMock.mockReset()
removeHandlerMock.mockReset()
createProfileMock.mockReset()
Expand All @@ -77,6 +85,44 @@ describe('browser session profile IPC', () => {
} as Electron.WebContents
}

function manualImportHandler() {
registerBrowserHandlers()
return handleMock.mock.calls.find(
([channel]) => channel === 'browser:session:importCookies'
)?.[1]
}

it('routes manual imports to the named environment with a main-owned file picker', async () => {
setTrustedBrowserRendererWebContentsId(91)
importCookieFileMock.mockResolvedValue({ ok: false, reason: 'canceled' })
const handler = manualImportHandler()
expect(
await handler({ sender: trustedSender() }, { profileId: 'default', environmentId: 'env-a' })
).toEqual({ ok: false, reason: 'canceled' })
expect(importCookieFileMock).toHaveBeenCalledWith(
{ environmentId: 'env-a', browserProfileId: 'default' },
expect.any(Function)
)
})

it('does not fall through to a local profile when the environment is not client-hosted', async () => {
setTrustedBrowserRendererWebContentsId(91)
importCookieFileMock.mockResolvedValue(null)
const handler = manualImportHandler()
expect(
await handler({ sender: trustedSender() }, { profileId: 'default', environmentId: 'env-a' })
).toMatchObject({ ok: false, reason: expect.stringContaining('hosted on this device') })
})

it('rejects unauthorized manual environment imports', async () => {
setTrustedBrowserRendererWebContentsId(92)
const handler = manualImportHandler()
expect(
await handler({ sender: trustedSender() }, { profileId: 'default', environmentId: 'env-a' })
).toEqual({ ok: false, reason: 'Not authorized' })
expect(importCookieFileMock).not.toHaveBeenCalled()
})

function identitySetHandler(): (
event: { sender: Electron.WebContents },
mode: unknown
Expand Down
25 changes: 23 additions & 2 deletions src/main/ipc/browser-session-profile-ipc.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { BrowserWindow, ipcMain } from 'electron'
import { browserSessionRegistry } from '../browser/browser-session-registry'
import { importCookiesIntoClientRoutePartition } from '../browser/browser-client-route-cookie-import'
import {
importCookiesIntoClientRoutePartition,
importCookieFileIntoClientRoutePartition
} from '../browser/browser-client-route-cookie-import'
import { clientRouteCookieImportSources } from '../browser/client-route-cookie-import-source-store'
import { getPairedRuntimeBrowserClientRouteIdentity } from '../browser/paired-runtime-browser-client-host-runtime'
import { isTrustedBrowserRenderer } from './browser-renderer-trust'
Expand Down Expand Up @@ -83,10 +86,28 @@ export function registerBrowserSessionProfileHandlers(): void {

ipcMain.handle(
'browser:session:importCookies',
async (event, args: { profileId: string }): Promise<BrowserCookieImportResult> => {
async (
event,
args: { profileId: string; environmentId?: string }
): Promise<BrowserCookieImportResult> => {
if (!isTrustedBrowserRenderer(event.sender)) {
return { ok: false, reason: 'Not authorized' }
}
if (args.environmentId !== undefined) {
if (typeof args.environmentId !== 'string' || args.environmentId.length === 0) {
return { ok: false, reason: 'Invalid runtime environment.' }
}
const parent = BrowserWindow.fromWebContents(event.sender)
return (
(await importCookieFileIntoClientRoutePartition(
{ environmentId: args.environmentId, browserProfileId: args.profileId },
() => pickCookieFile(parent)
)) ?? {
ok: false,
reason: 'Cookie file import requires a browser hosted on this device.'
}
)
}
const profile = browserSessionRegistry.getProfile(args.profileId)
if (!profile) {
return { ok: false, reason: 'Session profile not found.' }
Expand Down
Loading