* fix(browser): import Chromium cookies from Network DBs (#6875) * fix(browser): complete Chromium cookie import paths Co-authored-by: Orca <help@stably.ai> --------- Co-authored-by: Jinwoo-H <jinwoo0825@gmail.com> Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
co-authored by
Orca
Jinwoo-H
parent
3a3e33f14b
commit
693ac1fb25
@@ -0,0 +1,82 @@
|
||||
import { createCipheriv, pbkdf2Sync } from 'node:crypto'
|
||||
import { mkdirSync } from 'node:fs'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { join } from 'node:path'
|
||||
|
||||
type ChromiumCookieTestRow = {
|
||||
name: string
|
||||
value: string
|
||||
encryptedValue?: Buffer
|
||||
}
|
||||
|
||||
export function createChromiumCookieTestDatabase(
|
||||
databasePath: string,
|
||||
rows: ChromiumCookieTestRow[],
|
||||
options: { journalMode?: 'wal' } = {}
|
||||
): DatabaseSync {
|
||||
mkdirSync(join(databasePath, '..'), { recursive: true })
|
||||
const database = new DatabaseSync(databasePath)
|
||||
if (options.journalMode === 'wal') {
|
||||
database.exec('PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0')
|
||||
}
|
||||
database.exec(`
|
||||
CREATE TABLE cookies (
|
||||
creation_utc INTEGER NOT NULL,
|
||||
host_key TEXT NOT NULL,
|
||||
top_frame_site_key TEXT NOT NULL DEFAULT '',
|
||||
name TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
encrypted_value BLOB NOT NULL DEFAULT X'',
|
||||
path TEXT NOT NULL,
|
||||
expires_utc INTEGER NOT NULL,
|
||||
is_secure INTEGER NOT NULL,
|
||||
is_httponly INTEGER NOT NULL,
|
||||
samesite INTEGER NOT NULL,
|
||||
source_scheme INTEGER NOT NULL DEFAULT 0,
|
||||
source_port INTEGER NOT NULL DEFAULT -1,
|
||||
last_update_utc INTEGER NOT NULL DEFAULT 0,
|
||||
has_cross_site_ancestor INTEGER NOT NULL DEFAULT 0,
|
||||
UNIQUE(host_key, top_frame_site_key, name, path, source_scheme, source_port)
|
||||
)
|
||||
`)
|
||||
const insert = database.prepare(`
|
||||
INSERT INTO cookies (
|
||||
creation_utc,
|
||||
host_key,
|
||||
top_frame_site_key,
|
||||
name,
|
||||
value,
|
||||
encrypted_value,
|
||||
path,
|
||||
expires_utc,
|
||||
is_secure,
|
||||
is_httponly,
|
||||
samesite,
|
||||
source_scheme,
|
||||
source_port,
|
||||
last_update_utc,
|
||||
has_cross_site_ancestor
|
||||
) VALUES (?, ?, '', ?, ?, ?, '/', 0, 0, 0, 0, 0, -1, ?, 0)
|
||||
`)
|
||||
rows.forEach((row, index) => {
|
||||
insert.run(
|
||||
133_000_000_000_000 + index,
|
||||
'.example.com',
|
||||
row.name,
|
||||
row.value,
|
||||
row.encryptedValue ?? Buffer.alloc(0),
|
||||
0
|
||||
)
|
||||
})
|
||||
return database
|
||||
}
|
||||
|
||||
export function encryptMacChromiumCookie(value: string, password: string): Buffer {
|
||||
const key = pbkdf2Sync(password, 'saltysalt', 1003, 16, 'sha1')
|
||||
const cipher = createCipheriv('aes-128-cbc', key, Buffer.alloc(16, ' '))
|
||||
return Buffer.concat([
|
||||
Buffer.from('v10'),
|
||||
cipher.update(Buffer.from(value, 'latin1')),
|
||||
cipher.final()
|
||||
])
|
||||
}
|
||||
@@ -1,11 +1,34 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as NodeFs from 'node:fs'
|
||||
|
||||
const { sessionFromPartitionMock, dialogShowOpenDialogMock } = vi.hoisted(() => ({
|
||||
const {
|
||||
appGetPathMock,
|
||||
copyFileSyncMock,
|
||||
execFileSyncMock,
|
||||
sessionFromPartitionMock,
|
||||
dialogShowOpenDialogMock
|
||||
} = vi.hoisted(() => ({
|
||||
appGetPathMock: vi.fn(),
|
||||
copyFileSyncMock: vi.fn(),
|
||||
execFileSyncMock: vi.fn(),
|
||||
sessionFromPartitionMock: vi.fn(),
|
||||
dialogShowOpenDialogMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('node:child_process', () => ({ execFileSync: execFileSyncMock }))
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof NodeFs>()
|
||||
return {
|
||||
...actual,
|
||||
copyFileSync: (...args: Parameters<typeof actual.copyFileSync>) => {
|
||||
copyFileSyncMock(...args)
|
||||
return actual.copyFileSync(...args)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: appGetPathMock },
|
||||
BrowserWindow: { fromWebContents: vi.fn() },
|
||||
dialog: { showOpenDialog: dialogShowOpenDialogMock },
|
||||
session: { fromPartition: sessionFromPartitionMock }
|
||||
@@ -20,10 +43,26 @@ import {
|
||||
type ChromiumCookieColumnInfo,
|
||||
type DetectedBrowser
|
||||
} from './browser-cookie-import'
|
||||
import { writeFileSync, mkdtempSync, rmSync } from 'node:fs'
|
||||
import {
|
||||
createChromiumCookieTestDatabase,
|
||||
encryptMacChromiumCookie
|
||||
} from './browser-cookie-import-test-database'
|
||||
import { existsSync, writeFileSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
|
||||
function chromeBrowser(cookiesPath: string): DetectedBrowser {
|
||||
return {
|
||||
family: 'chrome',
|
||||
label: 'Google Chrome',
|
||||
cookiesPath,
|
||||
keychainService: 'Chrome Safe Storage',
|
||||
keychainAccount: 'Chrome',
|
||||
profiles: [{ name: 'Default', directory: 'Default' }],
|
||||
selectedProfile: 'Default'
|
||||
}
|
||||
}
|
||||
|
||||
const LARGE_SAFARI_COOKIE_COUNT = 150_000
|
||||
|
||||
describe('summarizeCookieImportError', () => {
|
||||
@@ -327,6 +366,147 @@ describe('importCookiesFromBrowser Safari', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('importCookiesFromBrowser Chromium', () => {
|
||||
let tmpDir: string
|
||||
let cookiesSetMock: ReturnType<typeof vi.fn>
|
||||
let cookiesRemoveMock: ReturnType<typeof vi.fn>
|
||||
let cookiesFlushStoreMock: ReturnType<typeof vi.fn>
|
||||
let clearStorageDataMock: ReturnType<typeof vi.fn>
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = mkdtempSync(join(tmpdir(), 'orca-chromium-cookie-test-'))
|
||||
cookiesSetMock = vi.fn().mockResolvedValue(undefined)
|
||||
cookiesRemoveMock = vi.fn().mockResolvedValue(undefined)
|
||||
cookiesFlushStoreMock = vi.fn().mockResolvedValue(undefined)
|
||||
clearStorageDataMock = vi.fn().mockResolvedValue(undefined)
|
||||
appGetPathMock.mockReset()
|
||||
appGetPathMock.mockReturnValue(join(tmpDir, 'userData'))
|
||||
copyFileSyncMock.mockClear()
|
||||
execFileSyncMock.mockReset()
|
||||
execFileSyncMock.mockImplementation(() => {
|
||||
throw new Error('OS credential commands are unavailable in this test')
|
||||
})
|
||||
sessionFromPartitionMock.mockReset()
|
||||
sessionFromPartitionMock.mockReturnValue({
|
||||
cookies: {
|
||||
set: cookiesSetMock,
|
||||
remove: cookiesRemoveMock,
|
||||
flushStore: cookiesFlushStoreMock
|
||||
},
|
||||
clearStorageData: clearStorageDataMock
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('imports from a live Chromium source DB into a Network/Cookies target profile', async () => {
|
||||
const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies')
|
||||
const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies')
|
||||
// Why: keeping the WAL writer open proves import reads Chromium's live SQLite
|
||||
// state instead of relying on a closed-file snapshot.
|
||||
const sourceDb = createChromiumCookieTestDatabase(
|
||||
sourceCookiesPath,
|
||||
[{ name: 'sid', value: 'source-value' }],
|
||||
{ journalMode: 'wal' }
|
||||
)
|
||||
createChromiumCookieTestDatabase(targetCookiesPath, [
|
||||
{ name: 'old', value: 'target-value' }
|
||||
]).close()
|
||||
|
||||
const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')
|
||||
try {
|
||||
expect(existsSync(`${sourceCookiesPath}-wal`)).toBe(true)
|
||||
|
||||
const result = await importCookiesFromBrowser(
|
||||
chromeBrowser(sourceCookiesPath),
|
||||
'persist:test'
|
||||
)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(cookiesSetMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
domain: '.example.com',
|
||||
name: 'sid',
|
||||
value: 'source-value'
|
||||
})
|
||||
)
|
||||
expect(execFileSyncMock.mock.calls.some(([command]) => command === 'security')).toBe(false)
|
||||
expect(copyFileSyncMock.mock.calls.some(([source]) => source === sourceCookiesPath)).toBe(
|
||||
false
|
||||
)
|
||||
expect(cookiesRemoveMock).not.toHaveBeenCalled()
|
||||
expect(clearStorageDataMock).toHaveBeenCalledWith({ storages: ['cookies'] })
|
||||
} finally {
|
||||
platformSpy.mockRestore()
|
||||
sourceDb.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('uses the OS key for encrypted Chromium rows', async () => {
|
||||
const password = 'test-password'
|
||||
const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies')
|
||||
const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies')
|
||||
createChromiumCookieTestDatabase(sourceCookiesPath, [
|
||||
{
|
||||
name: 'sid',
|
||||
value: '',
|
||||
encryptedValue: encryptMacChromiumCookie('encrypted-value', password)
|
||||
}
|
||||
]).close()
|
||||
createChromiumCookieTestDatabase(targetCookiesPath, []).close()
|
||||
execFileSyncMock.mockImplementation((command: string) => {
|
||||
if (command === 'security') {
|
||||
return `${password}\n`
|
||||
}
|
||||
throw new Error(`Unexpected command: ${command}`)
|
||||
})
|
||||
const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')
|
||||
|
||||
try {
|
||||
const result = await importCookiesFromBrowser(
|
||||
chromeBrowser(sourceCookiesPath),
|
||||
'persist:test'
|
||||
)
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
expect(execFileSyncMock).toHaveBeenCalledWith(
|
||||
'security',
|
||||
expect.any(Array),
|
||||
expect.any(Object)
|
||||
)
|
||||
expect(cookiesSetMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'sid', value: 'encrypted-value' })
|
||||
)
|
||||
} finally {
|
||||
platformSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('removes staging data when the OS key is unavailable', async () => {
|
||||
const sourceCookiesPath = join(tmpDir, 'Chrome', 'Default', 'Network', 'Cookies')
|
||||
const targetCookiesPath = join(tmpDir, 'userData', 'Partitions', 'test', 'Network', 'Cookies')
|
||||
createChromiumCookieTestDatabase(sourceCookiesPath, [
|
||||
{ name: 'sid', value: '', encryptedValue: Buffer.from('v10-encrypted') }
|
||||
]).close()
|
||||
createChromiumCookieTestDatabase(targetCookiesPath, []).close()
|
||||
const platformSpy = vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')
|
||||
|
||||
try {
|
||||
const result = await importCookiesFromBrowser(
|
||||
chromeBrowser(sourceCookiesPath),
|
||||
'persist:test'
|
||||
)
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
expect(readdirSync(join(tmpDir, 'userData', 'cookie-import-staging'))).toEqual([])
|
||||
} finally {
|
||||
platformSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('detectInstalledBrowsers', () => {
|
||||
it('returns an array of detected browsers', () => {
|
||||
const browsers = detectInstalledBrowsers()
|
||||
|
||||
@@ -78,6 +78,7 @@ import type {
|
||||
} from '../../shared/types'
|
||||
import { browserSessionRegistry } from './browser-session-registry'
|
||||
import { setupClientHintsOverride } from './browser-session-ua'
|
||||
import { resolveChromiumCookiesPath } from './chromium-cookie-path'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Browser detection
|
||||
@@ -192,20 +193,6 @@ function browserRootPath(def: ChromiumBrowserDef): string | null {
|
||||
return join(configHome, def.linuxRoot)
|
||||
}
|
||||
|
||||
// Why: Chromium 96+ moved the cookies DB from <Profile>/Cookies to
|
||||
// <Profile>/Network/Cookies. Try the newer path first, fall back to legacy.
|
||||
function resolveCookiesPath(profileDir: string): string | null {
|
||||
const networkPath = join(profileDir, 'Network', 'Cookies')
|
||||
if (existsSync(networkPath)) {
|
||||
return networkPath
|
||||
}
|
||||
const legacyPath = join(profileDir, 'Cookies')
|
||||
if (existsSync(legacyPath)) {
|
||||
return legacyPath
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function isSafeBrowserProfileDirectory(directory: string): boolean {
|
||||
return (
|
||||
directory.length > 0 &&
|
||||
@@ -373,7 +360,7 @@ export function detectInstalledBrowsers(): DetectedBrowser[] {
|
||||
// Use the first profile with a valid cookies path as the default selection.
|
||||
for (const profile of profiles) {
|
||||
const profileDir = join(root, profile.directory)
|
||||
const cookiesPath = resolveCookiesPath(profileDir)
|
||||
const cookiesPath = resolveChromiumCookiesPath(profileDir)
|
||||
if (cookiesPath) {
|
||||
detected.push({
|
||||
family: browser.family,
|
||||
@@ -434,7 +421,7 @@ export function selectBrowserProfile(
|
||||
return null
|
||||
}
|
||||
const profileDir = join(root, profileDirectory)
|
||||
const cookiesPath = resolveCookiesPath(profileDir)
|
||||
const cookiesPath = resolveChromiumCookiesPath(profileDir)
|
||||
if (!cookiesPath) {
|
||||
return null
|
||||
}
|
||||
@@ -1468,36 +1455,8 @@ export async function importCookiesFromBrowser(
|
||||
return importCookiesFromSafari(browser, targetPartition)
|
||||
}
|
||||
|
||||
// Why: the browser may hold a lock on the Cookies file. Copying to a temp
|
||||
// location avoids lock contention and ensures we read a consistent snapshot.
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'orca-cookie-import-'))
|
||||
const tmpCookiesPath = join(tmpDir, 'Cookies')
|
||||
|
||||
try {
|
||||
copyFileSync(browser.cookiesPath, tmpCookiesPath)
|
||||
// Why: when the source browser is running, it uses WAL journal mode. The most
|
||||
// recently written cookies (including fresh auth tokens) may only exist in the
|
||||
// WAL sidecar file, not yet flushed to the main DB. Copying WAL + SHM ensures
|
||||
// our snapshot reflects the browser's current state.
|
||||
for (const suffix of ['-wal', '-shm'] as const) {
|
||||
const sidecar = browser.cookiesPath + suffix
|
||||
if (existsSync(sidecar)) {
|
||||
try {
|
||||
copyFileSync(sidecar, tmpCookiesPath + suffix)
|
||||
} catch {
|
||||
// Why: sidecar copy is best-effort. The main DB alone may still have
|
||||
// enough cookies for a usable session; missing the WAL just means
|
||||
// we might miss the very latest writes.
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
return {
|
||||
ok: false,
|
||||
reason: `Could not copy ${browser.label} cookies database. Try closing ${browser.label} first.`
|
||||
}
|
||||
}
|
||||
// Why: SQLite can coordinate with Chromium's live WAL locks without a pre-copy.
|
||||
const sourceCookiesPath = browser.cookiesPath
|
||||
|
||||
// Why: Electron's cookies.set() API rejects many valid cookie values (binary
|
||||
// bytes > 0x7F etc). Instead, decrypt from the source browser and write
|
||||
@@ -1508,16 +1467,6 @@ export async function importCookiesFromBrowser(
|
||||
// In packaged builds where os_crypt IS active, CookieMonster will re-encrypt
|
||||
// plaintext cookies on its next flush, so this approach is safe in both modes.
|
||||
|
||||
// Why: only Chromium browsers reach this point — Firefox/Safari dispatched above.
|
||||
const sourceKey = getEncryptionKey(browser.keychainService!, browser.keychainAccount!, browser)
|
||||
if (!sourceKey) {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
return {
|
||||
ok: false,
|
||||
reason: `Could not access ${browser.label} encryption key. The OS may have denied access.`
|
||||
}
|
||||
}
|
||||
|
||||
// Why: CookieMonster holds the live DB's data in memory and overwrites it
|
||||
// on flush/shutdown. Writing directly to the live DB is futile. Instead,
|
||||
// copy the live DB to a staging location, populate it there, and let the
|
||||
@@ -1526,13 +1475,14 @@ export async function importCookiesFromBrowser(
|
||||
await targetSession.cookies.flushStore()
|
||||
|
||||
const partitionName = targetPartition.replace('persist:', '')
|
||||
const liveCookiesPath = join(app.getPath('userData'), 'Partitions', partitionName, 'Cookies')
|
||||
const partitionDir = join(app.getPath('userData'), 'Partitions', partitionName)
|
||||
let liveCookiesPath = resolveChromiumCookiesPath(partitionDir)
|
||||
|
||||
// Why: Electron only creates the partition's Cookies SQLite file after the
|
||||
// session has actually stored a cookie. For newly created profiles that have
|
||||
// never been used by a webview, the file won't exist yet. Setting and
|
||||
// removing a throwaway cookie forces Electron to initialize the database.
|
||||
if (!existsSync(liveCookiesPath)) {
|
||||
if (!liveCookiesPath) {
|
||||
try {
|
||||
await targetSession.cookies.set({ url: 'https://localhost', name: '__init', value: '1' })
|
||||
await targetSession.cookies.remove('https://localhost', '__init')
|
||||
@@ -1540,10 +1490,10 @@ export async function importCookiesFromBrowser(
|
||||
} catch {
|
||||
// ignore — the set/remove may fail but flushStore should still create the file
|
||||
}
|
||||
liveCookiesPath = resolveChromiumCookiesPath(partitionDir)
|
||||
}
|
||||
|
||||
if (!existsSync(liveCookiesPath)) {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
if (!liveCookiesPath) {
|
||||
return { ok: false, reason: 'Target cookie database not found. Open a browser tab first.' }
|
||||
}
|
||||
|
||||
@@ -1557,7 +1507,6 @@ export async function importCookiesFromBrowser(
|
||||
mkdirSync(stagingDir, { recursive: true })
|
||||
copyFileSync(liveCookiesPath, stagingCookiesPath)
|
||||
} catch {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
return { ok: false, reason: 'Could not create staging cookie database.' }
|
||||
}
|
||||
|
||||
@@ -1567,7 +1516,7 @@ export async function importCookiesFromBrowser(
|
||||
try {
|
||||
// Why: Chromium stores timestamps as microseconds since 1601, which can exceed
|
||||
// Number.MAX_SAFE_INTEGER (~9e15). readBigInts ensures no precision loss.
|
||||
sourceDb = new DatabaseSync(tmpCookiesPath, { readOnly: true, readBigInts: true })
|
||||
sourceDb = new DatabaseSync(sourceCookiesPath, { readOnly: true, readBigInts: true })
|
||||
stagingDb = new DatabaseSync(stagingCookiesPath)
|
||||
|
||||
const targetColumnInfo = stagingDb
|
||||
@@ -1590,10 +1539,37 @@ export async function importCookiesFromBrowser(
|
||||
if (sourceRows.length === 0) {
|
||||
stagingDb.close()
|
||||
stagingDb = null
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
try {
|
||||
unlinkSync(stagingCookiesPath)
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
return { ok: false, reason: `No cookies found in ${browser.label}.` }
|
||||
}
|
||||
|
||||
const needsSourceKey = sourceRows.some((sourceRow) => {
|
||||
const encRaw = sourceRow.encrypted_value
|
||||
return encRaw instanceof Uint8Array && encRaw.length > 0
|
||||
})
|
||||
const sourceKey = needsSourceKey
|
||||
? getEncryptionKey(browser.keychainService!, browser.keychainAccount!, browser)
|
||||
: null
|
||||
if (needsSourceKey && !sourceKey) {
|
||||
stagingDb.close()
|
||||
stagingDb = null
|
||||
// Why: key denial happens after staging, so failed retries must not leave
|
||||
// one full target database copy behind each time.
|
||||
try {
|
||||
unlinkSync(stagingCookiesPath)
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
reason: `Could not access ${browser.label} encryption key. The OS may have denied access.`
|
||||
}
|
||||
}
|
||||
|
||||
// Why: Google's integrity cookies (SIDCC, __Secure-*PSIDCC, __Secure-STRP)
|
||||
// are cryptographically bound to the source browser's TLS fingerprint and
|
||||
// environment. Importing them into a different browser causes
|
||||
@@ -1652,7 +1628,7 @@ export async function importCookiesFromBrowser(
|
||||
|
||||
let decryptedValue: Buffer
|
||||
if (encBuf && encBuf.length > 0) {
|
||||
const raw = decryptCookieValueRaw(encBuf, sourceKey)
|
||||
const raw = sourceKey ? decryptCookieValueRaw(encBuf, sourceKey) : null
|
||||
if (!raw) {
|
||||
skipped++
|
||||
continue
|
||||
@@ -1709,7 +1685,6 @@ export async function importCookiesFromBrowser(
|
||||
stagingDb.close()
|
||||
stagingDb = null
|
||||
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
diag(` SQLite staging complete: ${imported} cookies, ${domainSet.size} domains`)
|
||||
|
||||
// Why: clearing the session's in-memory cookie store before loading imported
|
||||
@@ -1795,7 +1770,6 @@ export async function importCookiesFromBrowser(
|
||||
} catch {
|
||||
/* may already be closed */
|
||||
}
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
// Why: if the import fails after the staging DB was created, clean it up
|
||||
// to avoid a stale staged import being applied on the next cold start.
|
||||
try {
|
||||
|
||||
@@ -157,6 +157,31 @@ describe('BrowserSessionRegistry persistence', () => {
|
||||
expect(fsState.present.has('/user-data/Partitions/orca-browser/Cookies')).toBe(true)
|
||||
})
|
||||
|
||||
it('replays pending cookies into an existing Network database', async () => {
|
||||
const stagedPath = '/staged/network-import'
|
||||
const networkPath = '/user-data/Partitions/orca-browser/Network/Cookies'
|
||||
const legacyPath = '/user-data/Partitions/orca-browser/Cookies'
|
||||
const fsState = createFsState()
|
||||
seedMeta(fsState, {
|
||||
defaultSource: null,
|
||||
userAgent: null,
|
||||
pendingCookieDbPath: stagedPath,
|
||||
profiles: []
|
||||
})
|
||||
fsState.files.set(stagedPath, 'imported cookies')
|
||||
fsState.files.set(networkPath, 'old cookies')
|
||||
fsState.present.add(stagedPath)
|
||||
fsState.present.add(networkPath)
|
||||
|
||||
installModuleMocks(fsState)
|
||||
const { browserSessionRegistry } = await import('./browser-session-registry')
|
||||
|
||||
browserSessionRegistry.applyPendingCookieImport()
|
||||
|
||||
expect(fsState.files.get(networkPath)).toBe('imported cookies')
|
||||
expect(fsState.present.has(legacyPath)).toBe(false)
|
||||
})
|
||||
|
||||
it('persists new browser session profiles under the active Orca profile directory', async () => {
|
||||
const fsState = createFsState()
|
||||
const profileMetaPath = '/user-data/profiles/local-work/browser-session-meta.json'
|
||||
|
||||
@@ -26,6 +26,7 @@ import type { BrowserSessionProfile, BrowserSessionProfileScope } from '../../sh
|
||||
import { browserManager } from './browser-manager'
|
||||
import { hasSystemMediaAccess, requestSystemMediaAccess } from './browser-media-access'
|
||||
import { cleanElectronUserAgent, setupClientHintsOverride } from './browser-session-ua'
|
||||
import { resolveChromiumCookiesPath } from './chromium-cookie-path'
|
||||
import { isAutoGrantedBrowserSessionPermission } from './browser-session-permission-policy'
|
||||
import {
|
||||
allowsBrowserWebAuthnPermission,
|
||||
@@ -101,7 +102,10 @@ class BrowserSessionRegistry {
|
||||
|
||||
private static partitionCookiesPath(partition: string): string {
|
||||
const partitionName = partition.replace('persist:', '')
|
||||
return join(app.getPath('userData'), 'Partitions', partitionName, 'Cookies')
|
||||
const partitionDir = join(app.getPath('userData'), 'Partitions', partitionName)
|
||||
// Why: replay must overwrite the same modern or legacy database that the
|
||||
// importing Electron partition already uses.
|
||||
return resolveChromiumCookiesPath(partitionDir) ?? join(partitionDir, 'Cookies')
|
||||
}
|
||||
|
||||
// Why: write-to-temp-then-rename is atomic on all supported platforms.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
// Why: Chromium 96+ moved the cookie DB under Network, while older profiles
|
||||
// still use the profile root. Every reader and replay writer must agree.
|
||||
export function resolveChromiumCookiesPath(profileDir: string): string | null {
|
||||
const networkPath = join(profileDir, 'Network', 'Cookies')
|
||||
if (existsSync(networkPath)) {
|
||||
return networkPath
|
||||
}
|
||||
const legacyPath = join(profileDir, 'Cookies')
|
||||
return existsSync(legacyPath) ? legacyPath : null
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type {
|
||||
OrcaCloudCapabilities,
|
||||
OrcaCloudOrgSummary
|
||||
} from '../../shared/orca-profiles'
|
||||
import type { OrcaCloudCapabilities, OrcaCloudOrgSummary } from '../../shared/orca-profiles'
|
||||
import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange'
|
||||
|
||||
const DEV_SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
||||
|
||||
@@ -138,9 +138,7 @@ describe('Orca cloud profile auth-failure retry', () => {
|
||||
safeStorageMock.encryptString.mockReset()
|
||||
safeStorageMock.isEncryptionAvailable.mockReset()
|
||||
safeStorageMock.decryptString.mockImplementation((value: Buffer) => value.toString('utf-8'))
|
||||
safeStorageMock.encryptString.mockImplementation((value: string) =>
|
||||
Buffer.from(value, 'utf-8')
|
||||
)
|
||||
safeStorageMock.encryptString.mockImplementation((value: string) => Buffer.from(value, 'utf-8'))
|
||||
safeStorageMock.isEncryptionAvailable.mockReturnValue(true)
|
||||
vi.unstubAllEnvs()
|
||||
vi.stubEnv('ORCA_CLOUD_API_URL', '')
|
||||
|
||||
@@ -123,9 +123,7 @@ describe('Orca cloud profile service session refresh', () => {
|
||||
safeStorageMock.encryptString.mockReset()
|
||||
safeStorageMock.isEncryptionAvailable.mockReset()
|
||||
safeStorageMock.decryptString.mockImplementation((value: Buffer) => value.toString('utf-8'))
|
||||
safeStorageMock.encryptString.mockImplementation((value: string) =>
|
||||
Buffer.from(value, 'utf-8')
|
||||
)
|
||||
safeStorageMock.encryptString.mockImplementation((value: string) => Buffer.from(value, 'utf-8'))
|
||||
safeStorageMock.isEncryptionAvailable.mockReturnValue(true)
|
||||
vi.unstubAllEnvs()
|
||||
vi.stubEnv('ORCA_CLOUD_API_URL', '')
|
||||
|
||||
@@ -114,9 +114,7 @@ describe('Orca cloud profile service', () => {
|
||||
safeStorageMock.encryptString.mockReset()
|
||||
safeStorageMock.isEncryptionAvailable.mockReset()
|
||||
safeStorageMock.decryptString.mockImplementation((value: Buffer) => value.toString('utf-8'))
|
||||
safeStorageMock.encryptString.mockImplementation((value: string) =>
|
||||
Buffer.from(value, 'utf-8')
|
||||
)
|
||||
safeStorageMock.encryptString.mockImplementation((value: string) => Buffer.from(value, 'utf-8'))
|
||||
safeStorageMock.isEncryptionAvailable.mockReturnValue(true)
|
||||
revokeOrcaCloudSessionMock.mockResolvedValue(undefined)
|
||||
vi.unstubAllEnvs()
|
||||
|
||||
Reference in New Issue
Block a user