Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions apps/desktop/e2e/continue-sign-in.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ test.describe('continue a sign-in in another browser', () => {
pending: null,
profiles: [],
continued: { error: 'unknown' },
broughtBack: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' },
broughtBack: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown', retired: false },
})
})

Expand All @@ -108,6 +108,6 @@ test.describe('continue a sign-in in another browser', () => {
await page.locator('#back').click()
await expect
.poll(() => read('broughtBack'))
.toEqual({ cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' })
.toEqual({ cookiesImported: 0, cookiesSkipped: 0, error: 'unknown', retired: false })
})
})
19 changes: 11 additions & 8 deletions apps/desktop/src/main/browser-import/browser-launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { execFile } from 'node:child_process'
import { join } from 'node:path'
import { promisify } from 'node:util'
import { app } from 'electron'
import type { BrowserSource } from '@/main/browser-import/browser-sources'

const execFileAsync = promisify(execFile)

Expand All @@ -28,20 +29,22 @@ export async function defaultBrowserBundleId(): Promise<string | null> {
}

/**
* Opens `url` in one profile of an installed Chromium-family browser.
* Opens `url` in one profile of an installed Chromium-family browser, or in
* the browser's frontmost profile when it cannot be told which.
*
* `-n` launches a fresh instance whose command line Chromium's process
* singleton forwards to the running browser; without it a running browser
* drops `--args` and opens the page in whichever profile was last active.
* drops `--args` and opens the page in whichever profile was last active. A
* single-instance app shell (Arc, Dia) gets neither: a second instance is
* refused, so the running one is just handed the page.
*/
export async function openInBrowserProfile(
bundleId: string,
source: Pick<BrowserSource, 'bundleId' | 'opensChosenProfile'>,
profileDirectory: string,
url: string
): Promise<void> {
await execFileAsync(
'/usr/bin/open',
['-n', '-b', bundleId, '--args', `--profile-directory=${profileDirectory}`, url],
{ timeout: OPEN_TIMEOUT_MS }
)
const args = source.opensChosenProfile
? ['-n', '-b', source.bundleId, '--args', `--profile-directory=${profileDirectory}`, url]
: ['-b', source.bundleId, url]
await execFileAsync('/usr/bin/open', args, { timeout: OPEN_TIMEOUT_MS })
}
13 changes: 13 additions & 0 deletions apps/desktop/src/main/browser-import/browser-sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ export interface BrowserSource {
keychain: { service: string; account: string }
/** The macOS bundle identifier, used to open a page in this browser. */
bundleId: string
/**
* Whether a page can be opened in one chosen profile. Arc and Dia are app
* shells around Chromium that allow a single instance and ignore
* `--profile-directory`, so a page opens in whichever profile is in front.
*/
opensChosenProfile: boolean
}

export const BROWSER_SOURCES: readonly BrowserSource[] = [
Expand All @@ -37,48 +43,55 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [
userDataSegments: ['Library', 'Application Support', 'Google', 'Chrome'],
keychain: { service: 'Chrome Safe Storage', account: 'Chrome' },
bundleId: 'com.google.Chrome',
opensChosenProfile: true,
},
{
id: 'arc',
label: 'Arc',
userDataSegments: ['Library', 'Application Support', 'Arc', 'User Data'],
keychain: { service: 'Arc Safe Storage', account: 'Arc' },
bundleId: 'company.thebrowser.Browser',
opensChosenProfile: false,
},
{
id: 'dia',
label: 'Dia',
userDataSegments: ['Library', 'Application Support', 'Dia', 'User Data'],
keychain: { service: 'Dia Safe Storage', account: 'Dia' },
bundleId: 'company.thebrowser.dia',
opensChosenProfile: false,
},
{
id: 'brave',
label: 'Brave',
userDataSegments: ['Library', 'Application Support', 'BraveSoftware', 'Brave-Browser'],
keychain: { service: 'Brave Safe Storage', account: 'Brave' },
bundleId: 'com.brave.Browser',
opensChosenProfile: true,
},
{
id: 'edge',
label: 'Microsoft Edge',
userDataSegments: ['Library', 'Application Support', 'Microsoft Edge'],
keychain: { service: 'Microsoft Edge Safe Storage', account: 'Microsoft Edge' },
bundleId: 'com.microsoft.edgemac',
opensChosenProfile: true,
},
{
id: 'vivaldi',
label: 'Vivaldi',
userDataSegments: ['Library', 'Application Support', 'Vivaldi'],
keychain: { service: 'Vivaldi Safe Storage', account: 'Vivaldi' },
bundleId: 'com.vivaldi.Vivaldi',
opensChosenProfile: true,
},
{
id: 'chromium',
label: 'Chromium',
userDataSegments: ['Library', 'Application Support', 'Chromium'],
keychain: { service: 'Chromium Safe Storage', account: 'Chromium' },
bundleId: 'org.chromium.Chromium',
opensChosenProfile: true,
},
] as const

Expand Down
52 changes: 47 additions & 5 deletions apps/desktop/src/main/browser-import/chromium-cookies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ interface FixtureCookie {
isSecure?: number
sameSite?: number
path?: string
creationUtc?: bigint
lastUpdateUtc?: bigint
}

let directory: string
Expand All @@ -75,27 +77,37 @@ afterEach(async () => {
await rm(directory, { recursive: true, force: true })
})

async function writeCookieDatabase(cookies: FixtureCookie[]): Promise<string> {
/**
* A cookie database in Chromium's shape. `schema` 18 added `last_update_utc`;
* the default is an older one without it.
*/
async function writeCookieDatabase(
cookies: FixtureCookie[],
{ schema = 17 }: { schema?: 17 | 18 } = {}
): Promise<string> {
const { DatabaseSync } = await import('node:sqlite')
const path = join(directory, 'Cookies')
const database = new DatabaseSync(path)
const lastUpdate = schema >= 18
database.exec(`
CREATE TABLE cookies (
creation_utc INTEGER NOT NULL, host_key TEXT NOT NULL, name TEXT NOT NULL,
value TEXT NOT NULL, path TEXT NOT NULL, expires_utc INTEGER NOT NULL,
is_secure INTEGER NOT NULL, is_httponly INTEGER NOT NULL,
has_expires INTEGER NOT NULL, is_persistent INTEGER NOT NULL,
samesite INTEGER NOT NULL, encrypted_value BLOB
${lastUpdate ? ', last_update_utc INTEGER NOT NULL' : ''}
)
`)
const insert = database.prepare(`
INSERT INTO cookies (creation_utc, host_key, name, value, path, expires_utc,
is_secure, is_httponly, has_expires, is_persistent, samesite, encrypted_value)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
is_secure, is_httponly, has_expires, is_persistent, samesite, encrypted_value
${lastUpdate ? ', last_update_utc' : ''})
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${lastUpdate ? ', ?' : ''})
`)
for (const cookie of cookies) {
insert.run(
chromeTime(NOW_SECONDS - 100),
cookie.creationUtc ?? chromeTime(NOW_SECONDS - 100),
cookie.hostKey,
cookie.name,
cookie.value ?? '',
Expand All @@ -106,7 +118,8 @@ async function writeCookieDatabase(cookies: FixtureCookie[]): Promise<string> {
cookie.hasExpires ?? 1,
cookie.isPersistent ?? 1,
cookie.sameSite ?? 1,
cookie.encryptedValue ?? null
cookie.encryptedValue ?? null,
...(lastUpdate ? [cookie.lastUpdateUtc ?? 0n] : [])
)
}
database.close()
Expand Down Expand Up @@ -219,6 +232,35 @@ describe.skipIf(!sqliteAvailable)('readBrowserCookies', () => {
expect(result.skipped['decrypt-failed']).toBe(0)
})

it('reports when an in-scope cookie last changed, ignoring other sites', async () => {
const scope = { domain: 'example.com', exact: false }
const cookies: FixtureCookie[] = [
{ hostKey: '.example.com', name: 'consent', creationUtc: chromeTime(NOW_SECONDS - 500) },
{
hostKey: 'console.example.com',
name: 'session',
creationUtc: chromeTime(NOW_SECONDS - 400),
lastUpdateUtc: chromeTime(NOW_SECONDS - 10),
},
{ hostKey: 'other.com', name: 'tracker', creationUtc: chromeTime(NOW_SECONDS - 1) },
].map((cookie) => ({ ...cookie, encryptedValue: encryptV10(Buffer.from('v')) }))

const current = await readBrowserCookies(
await writeCookieDatabase(cookies, { schema: 18 }),
KEY,
{ nowSeconds: NOW_SECONDS, scope }
)
expect(current.newestChange).toBe(chromeTime(NOW_SECONDS - 10))

await rm(join(directory, 'Cookies'))
const legacy = await readBrowserCookies(await writeCookieDatabase(cookies), KEY, {
nowSeconds: NOW_SECONDS,
scope,
})
expect(legacy.cookies).toHaveLength(2)
expect(legacy.newestChange).toBe(chromeTime(NOW_SECONDS - 400))
})

it('reports an unrecognised schema rather than guessing', async () => {
const path = join(directory, 'Cookies')
const { DatabaseSync } = await import('node:sqlite')
Expand Down
54 changes: 40 additions & 14 deletions apps/desktop/src/main/browser-import/chromium-cookies.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { decryptChromiumValue } from '@/main/browser-import/chromium-crypto'
import { translateCookieRow } from '@/main/browser-import/cookie-translate'
import { isCookieHostInScope, type SiteScope } from '@/main/browser-import/site-scope'
import { queryBrowserDatabase } from '@/main/browser-import/sqlite-source'
import { allRows, readBrowserDatabase } from '@/main/browser-import/sqlite-source'
import {
type ChromiumCookieRow,
type CookieSkipCounts,
Expand All @@ -13,16 +13,11 @@ import {

/**
* Decrypts a Chrome profile's cookies. The source database is copied and read
* read-only by {@link queryBrowserDatabase}; nothing here writes to Chrome.
* read-only by {@link readBrowserDatabase}; nothing here writes to Chrome.
*/

const MAX_COOKIE_ROWS = 50_000

const COOKIE_COLUMNS = `
SELECT host_key, name, path, expires_utc, is_secure, is_httponly,
has_expires, is_persistent, samesite, encrypted_value, value
FROM cookies`

/** `%`, `_`, and the escape itself are LIKE metacharacters; a hostname may carry `_`. */
function escapeLike(value: string): string {
return value.replace(/[\\%_]/g, '\\$&')
Expand All @@ -32,18 +27,31 @@ function escapeLike(value: string): string {
* The cookie query, narrowed in SQL to a site's rows when there is a scope.
* The narrowing is only an efficiency: {@link isCookieHostInScope} still
* decides every row, since LIKE is case-insensitive and knows no labels.
*
* `changed_utc` is when a row last changed: Chromium added `last_update_utc`
* in cookie schema 18 and leaves it 0 when unset, so the later of it and
* `creation_utc` counts; an older database has only `creation_utc`.
*/
function cookieQuery(scope: SiteScope | undefined): { query: string; params: string[] } {
if (!scope) return { query: `${COOKIE_COLUMNS} LIMIT ${MAX_COOKIE_ROWS}`, params: [] }
function cookieQuery(
scope: SiteScope | undefined,
hasLastUpdate: boolean
): { query: string; params: string[] } {
const changedAt = hasLastUpdate ? 'max(creation_utc, last_update_utc)' : 'creation_utc'
const columns = `
SELECT host_key, name, path, expires_utc, is_secure, is_httponly,
has_expires, is_persistent, samesite, encrypted_value, value,
${changedAt} AS changed_utc
FROM cookies`
if (!scope) return { query: `${columns} LIMIT ${MAX_COOKIE_ROWS}`, params: [] }
const exactHosts = [scope.domain, `.${scope.domain}`]
if (scope.exact) {
return {
query: `${COOKIE_COLUMNS} WHERE host_key IN (?, ?) LIMIT ${MAX_COOKIE_ROWS}`,
query: `${columns} WHERE host_key IN (?, ?) LIMIT ${MAX_COOKIE_ROWS}`,
params: exactHosts,
}
}
return {
query: `${COOKIE_COLUMNS} WHERE host_key IN (?, ?) OR host_key LIKE ? ESCAPE '\\' LIMIT ${MAX_COOKIE_ROWS}`,
query: `${columns} WHERE host_key IN (?, ?) OR host_key LIKE ? ESCAPE '\\' LIMIT ${MAX_COOKIE_ROWS}`,
params: [...exactHosts, `%.${escapeLike(scope.domain)}`],
}
}
Expand All @@ -53,6 +61,8 @@ export interface ReadCookiesResult {
skipped: CookieSkipCounts
/** Rows examined, so the caller can tell "no cookies" from "none survived". */
rowsSeen: number
/** When the newest examined row last changed, in Chromium time; 0n with none. */
newestChange: bigint
}

function toRow(raw: Record<string, unknown>): ChromiumCookieRow {
Expand Down Expand Up @@ -85,16 +95,19 @@ export async function readBrowserCookies(
key: Buffer,
{ nowSeconds = Date.now() / 1000, scope }: ReadCookiesOptions = {}
): Promise<ReadCookiesResult> {
const { query, params } = cookieQuery(scope)
const rows = await queryBrowserDatabase(cookiesPath, 'Cookies', query, params)
const rows = await queryCookieRows(cookiesPath, scope)
const cookies: ImportableCookie[] = []
const skipped = emptySkipCounts()
let rowsSeen = 0
let newestChange = 0n

for (const raw of rows) {
const row = toRow(raw)
if (scope && !isCookieHostInScope(row.hostKey, scope)) continue
rowsSeen += 1
if (typeof raw.changed_utc === 'bigint' && raw.changed_utc > newestChange) {
newestChange = raw.changed_utc
}
const encrypted = raw.encrypted_value
let value: string | null
if (encrypted instanceof Uint8Array && encrypted.length > 0) {
Expand All @@ -116,5 +129,18 @@ export async function readBrowserCookies(
}
}

return { cookies, skipped, rowsSeen }
return { cookies, skipped, rowsSeen, newestChange }
}

function queryCookieRows(
cookiesPath: string,
scope: SiteScope | undefined
): Promise<Record<string, unknown>[]> {
return readBrowserDatabase(cookiesPath, 'Cookies', (database) => {
const hasLastUpdate = allRows(database, 'SELECT name FROM pragma_table_info(?)', [
'cookies',
]).some(({ name }) => name === 'last_update_utc')
const { query, params } = cookieQuery(scope, hasLastUpdate)
return allRows(database, query, params)
})
}
Loading
Loading