Skip to content

Commit 1e67cdc

Browse files
authored
fix(desktop): make continue-in-browser and bring-back reliable for every browser (#10721)
* fix(desktop): make continue-in-browser and bring-back reliable for every browser - Open Arc and Dia with a plain open instead of open -n, which started a second app instance; they open in their front profile, so the panel offers one choice per browser and bring-back reads every profile, taking the one that changed the site last - Bring-back imports what the browser has for the site right away and reloads the page; it waits (up to 30s, cancellable, after the Keychain prompt) only when the browser has nothing for the site yet - Keep the handoff pending after a bring-back so it can be brought back again; never write cookies once a cancel, newer continue, or sign-out retires it - Panel: busy state survives remounts, results and errors show inline, Cancel stays available while checking, clearer copy, passkey hint picks a browser and skips the AWS access portal, notices are announced * chore(desktop): keep cookieFailure module-private * fix(desktop): report cookies the built-in browser refused as nothing imported
1 parent f7530ab commit 1e67cdc

21 files changed

Lines changed: 961 additions & 300 deletions

File tree

‎apps/desktop/e2e/continue-sign-in.spec.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ test.describe('continue a sign-in in another browser', () => {
8383
pending: null,
8484
profiles: [],
8585
continued: { error: 'unknown' },
86-
broughtBack: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' },
86+
broughtBack: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown', retired: false },
8787
})
8888
})
8989

@@ -108,6 +108,6 @@ test.describe('continue a sign-in in another browser', () => {
108108
await page.locator('#back').click()
109109
await expect
110110
.poll(() => read('broughtBack'))
111-
.toEqual({ cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' })
111+
.toEqual({ cookiesImported: 0, cookiesSkipped: 0, error: 'unknown', retired: false })
112112
})
113113
})

‎apps/desktop/src/main/browser-import/browser-launch.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { execFile } from 'node:child_process'
22
import { join } from 'node:path'
33
import { promisify } from 'node:util'
44
import { app } from 'electron'
5+
import type { BrowserSource } from '@/main/browser-import/browser-sources'
56

67
const execFileAsync = promisify(execFile)
78

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

3031
/**
31-
* Opens `url` in one profile of an installed Chromium-family browser.
32+
* Opens `url` in one profile of an installed Chromium-family browser, or in
33+
* the browser's frontmost profile when it cannot be told which.
3234
*
3335
* `-n` launches a fresh instance whose command line Chromium's process
3436
* singleton forwards to the running browser; without it a running browser
35-
* drops `--args` and opens the page in whichever profile was last active.
37+
* drops `--args` and opens the page in whichever profile was last active. A
38+
* single-instance app shell (Arc, Dia) gets neither: a second instance is
39+
* refused, so the running one is just handed the page.
3640
*/
3741
export async function openInBrowserProfile(
38-
bundleId: string,
42+
source: Pick<BrowserSource, 'bundleId' | 'opensChosenProfile'>,
3943
profileDirectory: string,
4044
url: string
4145
): Promise<void> {
42-
await execFileAsync(
43-
'/usr/bin/open',
44-
['-n', '-b', bundleId, '--args', `--profile-directory=${profileDirectory}`, url],
45-
{ timeout: OPEN_TIMEOUT_MS }
46-
)
46+
const args = source.opensChosenProfile
47+
? ['-n', '-b', source.bundleId, '--args', `--profile-directory=${profileDirectory}`, url]
48+
: ['-b', source.bundleId, url]
49+
await execFileAsync('/usr/bin/open', args, { timeout: OPEN_TIMEOUT_MS })
4750
}

‎apps/desktop/src/main/browser-import/browser-sources.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ export interface BrowserSource {
2828
keychain: { service: string; account: string }
2929
/** The macOS bundle identifier, used to open a page in this browser. */
3030
bundleId: string
31+
/**
32+
* Whether a page can be opened in one chosen profile. Arc and Dia are app
33+
* shells around Chromium that allow a single instance and ignore
34+
* `--profile-directory`, so a page opens in whichever profile is in front.
35+
*/
36+
opensChosenProfile: boolean
3137
}
3238

3339
export const BROWSER_SOURCES: readonly BrowserSource[] = [
@@ -37,48 +43,55 @@ export const BROWSER_SOURCES: readonly BrowserSource[] = [
3743
userDataSegments: ['Library', 'Application Support', 'Google', 'Chrome'],
3844
keychain: { service: 'Chrome Safe Storage', account: 'Chrome' },
3945
bundleId: 'com.google.Chrome',
46+
opensChosenProfile: true,
4047
},
4148
{
4249
id: 'arc',
4350
label: 'Arc',
4451
userDataSegments: ['Library', 'Application Support', 'Arc', 'User Data'],
4552
keychain: { service: 'Arc Safe Storage', account: 'Arc' },
4653
bundleId: 'company.thebrowser.Browser',
54+
opensChosenProfile: false,
4755
},
4856
{
4957
id: 'dia',
5058
label: 'Dia',
5159
userDataSegments: ['Library', 'Application Support', 'Dia', 'User Data'],
5260
keychain: { service: 'Dia Safe Storage', account: 'Dia' },
5361
bundleId: 'company.thebrowser.dia',
62+
opensChosenProfile: false,
5463
},
5564
{
5665
id: 'brave',
5766
label: 'Brave',
5867
userDataSegments: ['Library', 'Application Support', 'BraveSoftware', 'Brave-Browser'],
5968
keychain: { service: 'Brave Safe Storage', account: 'Brave' },
6069
bundleId: 'com.brave.Browser',
70+
opensChosenProfile: true,
6171
},
6272
{
6373
id: 'edge',
6474
label: 'Microsoft Edge',
6575
userDataSegments: ['Library', 'Application Support', 'Microsoft Edge'],
6676
keychain: { service: 'Microsoft Edge Safe Storage', account: 'Microsoft Edge' },
6777
bundleId: 'com.microsoft.edgemac',
78+
opensChosenProfile: true,
6879
},
6980
{
7081
id: 'vivaldi',
7182
label: 'Vivaldi',
7283
userDataSegments: ['Library', 'Application Support', 'Vivaldi'],
7384
keychain: { service: 'Vivaldi Safe Storage', account: 'Vivaldi' },
7485
bundleId: 'com.vivaldi.Vivaldi',
86+
opensChosenProfile: true,
7587
},
7688
{
7789
id: 'chromium',
7890
label: 'Chromium',
7991
userDataSegments: ['Library', 'Application Support', 'Chromium'],
8092
keychain: { service: 'Chromium Safe Storage', account: 'Chromium' },
8193
bundleId: 'org.chromium.Chromium',
94+
opensChosenProfile: true,
8295
},
8396
] as const
8497

‎apps/desktop/src/main/browser-import/chromium-cookies.test.ts‎

Lines changed: 47 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ interface FixtureCookie {
6363
isSecure?: number
6464
sameSite?: number
6565
path?: string
66+
creationUtc?: bigint
67+
lastUpdateUtc?: bigint
6668
}
6769

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

78-
async function writeCookieDatabase(cookies: FixtureCookie[]): Promise<string> {
80+
/**
81+
* A cookie database in Chromium's shape. `schema` 18 added `last_update_utc`;
82+
* the default is an older one without it.
83+
*/
84+
async function writeCookieDatabase(
85+
cookies: FixtureCookie[],
86+
{ schema = 17 }: { schema?: 17 | 18 } = {}
87+
): Promise<string> {
7988
const { DatabaseSync } = await import('node:sqlite')
8089
const path = join(directory, 'Cookies')
8190
const database = new DatabaseSync(path)
91+
const lastUpdate = schema >= 18
8292
database.exec(`
8393
CREATE TABLE cookies (
8494
creation_utc INTEGER NOT NULL, host_key TEXT NOT NULL, name TEXT NOT NULL,
8595
value TEXT NOT NULL, path TEXT NOT NULL, expires_utc INTEGER NOT NULL,
8696
is_secure INTEGER NOT NULL, is_httponly INTEGER NOT NULL,
8797
has_expires INTEGER NOT NULL, is_persistent INTEGER NOT NULL,
8898
samesite INTEGER NOT NULL, encrypted_value BLOB
99+
${lastUpdate ? ', last_update_utc INTEGER NOT NULL' : ''}
89100
)
90101
`)
91102
const insert = database.prepare(`
92103
INSERT INTO cookies (creation_utc, host_key, name, value, path, expires_utc,
93-
is_secure, is_httponly, has_expires, is_persistent, samesite, encrypted_value)
94-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
104+
is_secure, is_httponly, has_expires, is_persistent, samesite, encrypted_value
105+
${lastUpdate ? ', last_update_utc' : ''})
106+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${lastUpdate ? ', ?' : ''})
95107
`)
96108
for (const cookie of cookies) {
97109
insert.run(
98-
chromeTime(NOW_SECONDS - 100),
110+
cookie.creationUtc ?? chromeTime(NOW_SECONDS - 100),
99111
cookie.hostKey,
100112
cookie.name,
101113
cookie.value ?? '',
@@ -106,7 +118,8 @@ async function writeCookieDatabase(cookies: FixtureCookie[]): Promise<string> {
106118
cookie.hasExpires ?? 1,
107119
cookie.isPersistent ?? 1,
108120
cookie.sameSite ?? 1,
109-
cookie.encryptedValue ?? null
121+
cookie.encryptedValue ?? null,
122+
...(lastUpdate ? [cookie.lastUpdateUtc ?? 0n] : [])
110123
)
111124
}
112125
database.close()
@@ -219,6 +232,35 @@ describe.skipIf(!sqliteAvailable)('readBrowserCookies', () => {
219232
expect(result.skipped['decrypt-failed']).toBe(0)
220233
})
221234

235+
it('reports when an in-scope cookie last changed, ignoring other sites', async () => {
236+
const scope = { domain: 'example.com', exact: false }
237+
const cookies: FixtureCookie[] = [
238+
{ hostKey: '.example.com', name: 'consent', creationUtc: chromeTime(NOW_SECONDS - 500) },
239+
{
240+
hostKey: 'console.example.com',
241+
name: 'session',
242+
creationUtc: chromeTime(NOW_SECONDS - 400),
243+
lastUpdateUtc: chromeTime(NOW_SECONDS - 10),
244+
},
245+
{ hostKey: 'other.com', name: 'tracker', creationUtc: chromeTime(NOW_SECONDS - 1) },
246+
].map((cookie) => ({ ...cookie, encryptedValue: encryptV10(Buffer.from('v')) }))
247+
248+
const current = await readBrowserCookies(
249+
await writeCookieDatabase(cookies, { schema: 18 }),
250+
KEY,
251+
{ nowSeconds: NOW_SECONDS, scope }
252+
)
253+
expect(current.newestChange).toBe(chromeTime(NOW_SECONDS - 10))
254+
255+
await rm(join(directory, 'Cookies'))
256+
const legacy = await readBrowserCookies(await writeCookieDatabase(cookies), KEY, {
257+
nowSeconds: NOW_SECONDS,
258+
scope,
259+
})
260+
expect(legacy.cookies).toHaveLength(2)
261+
expect(legacy.newestChange).toBe(chromeTime(NOW_SECONDS - 400))
262+
})
263+
222264
it('reports an unrecognised schema rather than guessing', async () => {
223265
const path = join(directory, 'Cookies')
224266
const { DatabaseSync } = await import('node:sqlite')

‎apps/desktop/src/main/browser-import/chromium-cookies.ts‎

Lines changed: 40 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { decryptChromiumValue } from '@/main/browser-import/chromium-crypto'
22
import { translateCookieRow } from '@/main/browser-import/cookie-translate'
33
import { isCookieHostInScope, type SiteScope } from '@/main/browser-import/site-scope'
4-
import { queryBrowserDatabase } from '@/main/browser-import/sqlite-source'
4+
import { allRows, readBrowserDatabase } from '@/main/browser-import/sqlite-source'
55
import {
66
type ChromiumCookieRow,
77
type CookieSkipCounts,
@@ -13,16 +13,11 @@ import {
1313

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

1919
const MAX_COOKIE_ROWS = 50_000
2020

21-
const COOKIE_COLUMNS = `
22-
SELECT host_key, name, path, expires_utc, is_secure, is_httponly,
23-
has_expires, is_persistent, samesite, encrypted_value, value
24-
FROM cookies`
25-
2621
/** `%`, `_`, and the escape itself are LIKE metacharacters; a hostname may carry `_`. */
2722
function escapeLike(value: string): string {
2823
return value.replace(/[\\%_]/g, '\\$&')
@@ -32,18 +27,31 @@ function escapeLike(value: string): string {
3227
* The cookie query, narrowed in SQL to a site's rows when there is a scope.
3328
* The narrowing is only an efficiency: {@link isCookieHostInScope} still
3429
* decides every row, since LIKE is case-insensitive and knows no labels.
30+
*
31+
* `changed_utc` is when a row last changed: Chromium added `last_update_utc`
32+
* in cookie schema 18 and leaves it 0 when unset, so the later of it and
33+
* `creation_utc` counts; an older database has only `creation_utc`.
3534
*/
36-
function cookieQuery(scope: SiteScope | undefined): { query: string; params: string[] } {
37-
if (!scope) return { query: `${COOKIE_COLUMNS} LIMIT ${MAX_COOKIE_ROWS}`, params: [] }
35+
function cookieQuery(
36+
scope: SiteScope | undefined,
37+
hasLastUpdate: boolean
38+
): { query: string; params: string[] } {
39+
const changedAt = hasLastUpdate ? 'max(creation_utc, last_update_utc)' : 'creation_utc'
40+
const columns = `
41+
SELECT host_key, name, path, expires_utc, is_secure, is_httponly,
42+
has_expires, is_persistent, samesite, encrypted_value, value,
43+
${changedAt} AS changed_utc
44+
FROM cookies`
45+
if (!scope) return { query: `${columns} LIMIT ${MAX_COOKIE_ROWS}`, params: [] }
3846
const exactHosts = [scope.domain, `.${scope.domain}`]
3947
if (scope.exact) {
4048
return {
41-
query: `${COOKIE_COLUMNS} WHERE host_key IN (?, ?) LIMIT ${MAX_COOKIE_ROWS}`,
49+
query: `${columns} WHERE host_key IN (?, ?) LIMIT ${MAX_COOKIE_ROWS}`,
4250
params: exactHosts,
4351
}
4452
}
4553
return {
46-
query: `${COOKIE_COLUMNS} WHERE host_key IN (?, ?) OR host_key LIKE ? ESCAPE '\\' LIMIT ${MAX_COOKIE_ROWS}`,
54+
query: `${columns} WHERE host_key IN (?, ?) OR host_key LIKE ? ESCAPE '\\' LIMIT ${MAX_COOKIE_ROWS}`,
4755
params: [...exactHosts, `%.${escapeLike(scope.domain)}`],
4856
}
4957
}
@@ -53,6 +61,8 @@ export interface ReadCookiesResult {
5361
skipped: CookieSkipCounts
5462
/** Rows examined, so the caller can tell "no cookies" from "none survived". */
5563
rowsSeen: number
64+
/** When the newest examined row last changed, in Chromium time; 0n with none. */
65+
newestChange: bigint
5666
}
5767

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

94104
for (const raw of rows) {
95105
const row = toRow(raw)
96106
if (scope && !isCookieHostInScope(row.hostKey, scope)) continue
97107
rowsSeen += 1
108+
if (typeof raw.changed_utc === 'bigint' && raw.changed_utc > newestChange) {
109+
newestChange = raw.changed_utc
110+
}
98111
const encrypted = raw.encrypted_value
99112
let value: string | null
100113
if (encrypted instanceof Uint8Array && encrypted.length > 0) {
@@ -116,5 +129,18 @@ export async function readBrowserCookies(
116129
}
117130
}
118131

119-
return { cookies, skipped, rowsSeen }
132+
return { cookies, skipped, rowsSeen, newestChange }
133+
}
134+
135+
function queryCookieRows(
136+
cookiesPath: string,
137+
scope: SiteScope | undefined
138+
): Promise<Record<string, unknown>[]> {
139+
return readBrowserDatabase(cookiesPath, 'Cookies', (database) => {
140+
const hasLastUpdate = allRows(database, 'SELECT name FROM pragma_table_info(?)', [
141+
'cookies',
142+
]).some(({ name }) => name === 'last_update_utc')
143+
const { query, params } = cookieQuery(scope, hasLastUpdate)
144+
return allRows(database, query, params)
145+
})
120146
}

0 commit comments

Comments
 (0)