mirror of
https://github.com/stablyai/orca.git
synced 2026-10-25 00:03:59 +00:00
* fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797) A native import (Settings -> Browser -> Import Cookies -> From Google Chrome) cleared the entire target partition's cookie jar, keeping only the non-transplantable google.com family. Every unrelated site the user was signed into in that partition was silently signed out, with no warning before and no disclosure after. Importing three sites signed you out of every other one. The stated rationale -- mixing stale and imported cookies makes sites reject the session -- reaches only as far as the domains being imported. Beyond them a clear has nothing to reconcile. The file/paste path already did the narrow thing via replaceCookiesForImportedDomains; the two import paths simply disagreed about scope, and the narrow one is the defensible shape. The clear now covers only the domains the import writes, through one shared predicate: - browser-cookie-import-policy.ts: importedDomainScope() / domainIsInImportedScope() are exported as the single scope definition used by all three clears, so they cannot drift apart. - browser-cookie-import-clear.ts: removeTransplantableCookies takes a required importScope. It is not defaulted -- a default would be the whole jar again. The scope test runs before the removal-URL derivation, so an unaddressable cookie parked in an unrelated corner of the jar no longer fails an import that was never going to touch it. - The bulk clearData shortcut is gone, and clearData leaves CookieClearSession for the same structural reason 'set' already had. clearData clears by exclusion, so the only scope it can express is "everything except google.com" -- the defect. An include list is no better: it matches at the registrable-domain boundary, so it would still take host-only siblings the import does not replace, and a partial delete followed by a rejection would destroy them with no identity to restore from. The frozen per-coordinate plan is now the only removal path, and it covers the imported domains rather than the jar. - browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the live jar that replaces it wholesale on the next cold start, so its DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe. Narrowing the live clear alone would have re-erased the partition one restart later. It now clears to the identical scope, through the identical predicate. The scope is named from the emitted plan, so the removal set is the write set. Google stays exempt by policy (STA-3811), unchanged. No wire or summary change: the summary's existing `domains` field already names the imported domains, which is now exactly the scope that was cleared. Tests: fixtures in this module start with an empty cookie jar, which is why a full gate stack passed a session-erasing defect before. browser-cookie-import- scope.test.ts uses a populated jar with a session for a site outside the import set, and reads the staged file itself so the restart path is observed rather than assumed. All three cases fail against pre-fix source. The real-Electron partition test now seeds both an in-scope stale cookie (still removed) and an out-of-scope live one (now survives). * refactor(browser): drop the unreachable removal-URL failure branch (STA-4797) Scoping the clear made the `Could not clear existing cookies` throw in removableCookieEntries dead: a cookie whose domain does not normalize is now skipped by the scope test above it, so nothing reaches the URL derivation with anything but an already-parsed hostname. Rather than leave a fail-closed branch that cannot fire — this module has been misread before when a dead safety leg looked like a live one — the impossibility is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and returns a string: `new URL` cannot throw on a host that already parsed as one, and assigning pathname never throws. Both callers lose their null branch, including the silent `if (url)` skip in replaceCookiesForImportedDomains, which would have narrowed a removal plan without saying so. The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched — that one is live and is what keeps the mutated set inside the restorable set. * test(browser): re-anchor the native concurrency detector on the scoped clear (STA-4797) #15095's detector read "has the second import started clearing yet?" off clearData call counts. Scoping the clear removed the bulk clearData path, so that signal is gone and the assertion measured nothing. It now reads the same question off the removals themselves, which is strictly more specific: the seeded jar holds a stale cookie for each import's own domain, so `remove:old-a` present with `remove:old-b` absent proves the first import cleared and the second has not — where a call count could not tell the two apart. The completed run then pins the exact removal sequence, which also records that each import clears only its own domain. The seed had to move onto the imported domains for the same reason its own comment already gave for not leaving the jar empty: under a scoped clear, a jar holding only an unrelated site is the empty-jar case wearing a disguise -- the clear returns having removed nothing and every assertion passes vacuously. Mutation-checked: with the per-partition lock removed this test still fails, so #15095's protection is intact and the re-anchoring did not hollow it out. * fix(browser): merge staged cookie imports by domain scope (STA-4797)
297 lines
10 KiB
TypeScript
297 lines
10 KiB
TypeScript
import { app, session } from 'electron'
|
|
import { randomUUID } from 'node:crypto'
|
|
import { join } from 'node:path'
|
|
import { ORCA_BROWSER_PARTITION } from '../../shared/constants'
|
|
import {
|
|
DEFAULT_LOCAL_ORCA_PROFILE_ID,
|
|
getOrcaProfileBrowserDefaultPartition,
|
|
getOrcaProfileBrowserSessionPartition
|
|
} from '../../shared/orca-profiles'
|
|
import type {
|
|
BrowserSessionProfile,
|
|
BrowserSessionProfileCreateOptions,
|
|
BrowserSessionProfileScope
|
|
} from '../../shared/browser-workspace-types'
|
|
import {
|
|
applyPendingBrowserCookieImports,
|
|
clearPendingBrowserCookieImport,
|
|
setPendingBrowserCookieImport
|
|
} from './browser-session-cookie-staging'
|
|
import {
|
|
BROWSER_SESSION_META_FILE_NAME,
|
|
loadBrowserSessionMeta,
|
|
persistBrowserSessionMeta
|
|
} from './browser-session-meta-store'
|
|
import type { BrowserSessionMeta } from './browser-session-meta-store'
|
|
import {
|
|
applyBrowserSessionUserAgentModes,
|
|
clearBrowserSessionPartitionPolicies,
|
|
installBrowserSessionPartitionPolicies
|
|
} from './browser-session-partition-policies'
|
|
import { isValidPersistedBrowserSessionProfile } from './browser-session-persisted-profile-validation'
|
|
import { clearBrowserSessionUserAgentMode } from './browser-session-user-agent-mode'
|
|
|
|
export type BrowserSessionRegistryProfileOptions = {
|
|
orcaProfileId: string
|
|
profileDirectory: string
|
|
}
|
|
|
|
// Why: source of truth for valid partitions; will-attach-webview consults it so a compromised renderer can't smuggle in an arbitrary partition.
|
|
|
|
class BrowserSessionRegistry {
|
|
private readonly profiles = new Map<string, BrowserSessionProfile>()
|
|
private activeOrcaProfileId = DEFAULT_LOCAL_ORCA_PROFILE_ID
|
|
private metadataPathOverride: string | null = null
|
|
private defaultPartition = ORCA_BROWSER_PARTITION
|
|
|
|
constructor() {
|
|
this.resetDefaultProfile()
|
|
}
|
|
|
|
configureForOrcaProfile(options: BrowserSessionRegistryProfileOptions): void {
|
|
this.activeOrcaProfileId = options.orcaProfileId
|
|
this.metadataPathOverride = join(options.profileDirectory, BROWSER_SESSION_META_FILE_NAME)
|
|
this.defaultPartition = getOrcaProfileBrowserDefaultPartition(options.orcaProfileId)
|
|
this.profiles.clear()
|
|
this.resetDefaultProfile()
|
|
}
|
|
|
|
private resetDefaultProfile(): void {
|
|
const persisted = this.loadPersistedSource()
|
|
this.profiles.set('default', {
|
|
id: 'default',
|
|
scope: 'default',
|
|
partition: this.defaultPartition,
|
|
label: 'Default',
|
|
source: persisted
|
|
})
|
|
}
|
|
|
|
// Why: source metadata must persist across restarts (for the Settings import status) since the registry is in-memory only.
|
|
private get metadataPath(): string {
|
|
return (
|
|
this.metadataPathOverride ?? join(app.getPath('userData'), BROWSER_SESSION_META_FILE_NAME)
|
|
)
|
|
}
|
|
|
|
private loadPersistedSource(): BrowserSessionProfile['source'] {
|
|
return this.loadPersistedMeta().defaultSource
|
|
}
|
|
|
|
private persistMeta(updates: Partial<BrowserSessionMeta>): void {
|
|
persistBrowserSessionMeta(() => this.metadataPath, this.defaultPartition, updates)
|
|
}
|
|
|
|
private persistSource(source: BrowserSessionProfile['source']): void {
|
|
this.persistMeta({ defaultSource: source })
|
|
}
|
|
|
|
// Why: non-default profiles are in-memory only; without this they vanish on restart.
|
|
private persistProfiles(): void {
|
|
const nonDefault = [...this.profiles.values()].filter((p) => p.id !== 'default')
|
|
this.persistMeta({ profiles: nonDefault })
|
|
}
|
|
|
|
private loadPersistedMeta(): BrowserSessionMeta {
|
|
return loadBrowserSessionMeta(() => this.metadataPath, this.defaultPartition)
|
|
}
|
|
|
|
// Why: run before any webview loads, and set the UA before the first request or Electron's default UA invalidates imported cookies.
|
|
// Why re-read defaultSource: the constructor may run before app.isReady() (userData path unavailable), so loadPersistedSource() returned null.
|
|
initializeBrowserSessionsFromPersistedState(): void {
|
|
const meta = this.loadPersistedMeta()
|
|
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)
|
|
}
|
|
|
|
// Why: nothing else installs policies on the default partition (hydrate skips it), so without this its guest permissions would be denied.
|
|
installBrowserSessionPartitionPolicies(this.getDefaultProfile())
|
|
|
|
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.
|
|
applyPendingCookieImport(): void {
|
|
applyPendingBrowserCookieImports({
|
|
resolveMetadataPath: () => this.metadataPath,
|
|
defaultPartition: this.defaultPartition,
|
|
activeOrcaProfileId: this.activeOrcaProfileId
|
|
})
|
|
}
|
|
|
|
setPendingCookieImport(partition: string, stagingDbPath: string): void {
|
|
setPendingBrowserCookieImport({
|
|
resolveMetadataPath: () => this.metadataPath,
|
|
defaultPartition: this.defaultPartition,
|
|
partition,
|
|
stagingDbPath
|
|
})
|
|
}
|
|
|
|
// Why: a degraded import still rewrites the live session, so an older staged DB must stop replaying over it.
|
|
clearPendingCookieImport(partition: string): void {
|
|
clearPendingBrowserCookieImport({
|
|
resolveMetadataPath: () => this.metadataPath,
|
|
defaultPartition: this.defaultPartition,
|
|
partition
|
|
})
|
|
}
|
|
|
|
getDefaultProfile(): BrowserSessionProfile {
|
|
return this.profiles.get('default')!
|
|
}
|
|
|
|
getProfile(profileId: string): BrowserSessionProfile | null {
|
|
return this.profiles.get(profileId) ?? null
|
|
}
|
|
|
|
listProfiles(): BrowserSessionProfile[] {
|
|
return [...this.profiles.values()]
|
|
}
|
|
|
|
isAllowedPartition(partition: string): boolean {
|
|
if (partition === this.defaultPartition) {
|
|
return true
|
|
}
|
|
return [...this.profiles.values()].some((p) => p.partition === partition)
|
|
}
|
|
|
|
resolvePartition(profileId: string | null | undefined): string {
|
|
if (!profileId) {
|
|
return this.defaultPartition
|
|
}
|
|
return this.profiles.get(profileId)?.partition ?? this.defaultPartition
|
|
}
|
|
|
|
resolveKnownPartition(profileId: string | null | undefined): string | null {
|
|
if (!profileId) {
|
|
// Why: use the active Orca profile's default partition, not the legacy constant, or profiles resolve local-default's cookie jar.
|
|
return this.defaultPartition
|
|
}
|
|
return this.profiles.get(profileId)?.partition ?? null
|
|
}
|
|
|
|
createProfile(
|
|
scope: BrowserSessionProfileScope,
|
|
label: string,
|
|
options: BrowserSessionProfileCreateOptions = {}
|
|
): BrowserSessionProfile | null {
|
|
// 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')
|
|
) {
|
|
return null
|
|
}
|
|
const id = randomUUID()
|
|
// Why: deterministic partition-from-id lets main rebuild the allowlist on restart without a separate partition→profile map.
|
|
const partition = getOrcaProfileBrowserSessionPartition(this.activeOrcaProfileId, id)
|
|
const profile: BrowserSessionProfile = {
|
|
id,
|
|
scope,
|
|
partition,
|
|
label,
|
|
source: null,
|
|
...(options.userAgentMode ? { userAgentMode: options.userAgentMode } : {})
|
|
}
|
|
this.profiles.set(id, profile)
|
|
installBrowserSessionPartitionPolicies(profile)
|
|
this.persistProfiles()
|
|
return profile
|
|
}
|
|
|
|
updateProfileSource(
|
|
profileId: string,
|
|
source: BrowserSessionProfile['source']
|
|
): BrowserSessionProfile | null {
|
|
const profile = this.profiles.get(profileId)
|
|
if (!profile) {
|
|
return null
|
|
}
|
|
const updated = { ...profile, source }
|
|
this.profiles.set(profileId, updated)
|
|
if (profileId === 'default') {
|
|
this.persistSource(source)
|
|
} else {
|
|
this.persistProfiles()
|
|
}
|
|
return updated
|
|
}
|
|
|
|
async deleteProfile(profileId: string): Promise<boolean> {
|
|
const profile = this.profiles.get(profileId)
|
|
if (!profile || profile.scope === 'default') {
|
|
return false
|
|
}
|
|
this.profiles.delete(profileId)
|
|
this.persistProfiles()
|
|
const meta = this.loadPersistedMeta()
|
|
const pendingCookieImports = { ...meta.pendingCookieImports }
|
|
delete pendingCookieImports[profile.partition]
|
|
const defaultPendingImport = pendingCookieImports[this.defaultPartition]
|
|
this.persistMeta({
|
|
pendingCookieImports,
|
|
pendingCookieDbPath: typeof defaultPendingImport === 'string' ? defaultPendingImport : null
|
|
})
|
|
|
|
// 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)
|
|
clearBrowserSessionPartitionPolicies(profile.partition, sess)
|
|
await sess.clearStorageData()
|
|
await sess.clearCache()
|
|
} catch {
|
|
// Why: cleanup is best-effort — the profile is already out of the registry, so will-attach-webview blocks it regardless.
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Why: lets users undo a cookie import without deleting the default profile itself.
|
|
async clearDefaultSessionCookies(): Promise<boolean> {
|
|
try {
|
|
// Why: persist metadata before clearing storage so a mid-clear quit doesn't leave a stale "imported from X" badge.
|
|
const defaultProfile = this.profiles.get('default')
|
|
if (defaultProfile) {
|
|
this.profiles.set('default', { ...defaultProfile, source: null })
|
|
}
|
|
const meta = this.loadPersistedMeta()
|
|
const pendingCookieImports = { ...meta.pendingCookieImports }
|
|
delete pendingCookieImports[this.defaultPartition]
|
|
this.persistMeta({
|
|
defaultSource: null,
|
|
pendingCookieDbPath: null,
|
|
pendingCookieImports
|
|
})
|
|
|
|
const sess = session.fromPartition(this.defaultPartition)
|
|
await sess.clearStorageData({ storages: ['cookies'] })
|
|
return true
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
hydrateFromPersisted(profiles: BrowserSessionProfile[]): void {
|
|
for (const profile of profiles) {
|
|
if (!isValidPersistedBrowserSessionProfile(profile, this.activeOrcaProfileId)) {
|
|
continue
|
|
}
|
|
this.profiles.set(profile.id, profile)
|
|
if (profile.partition !== this.defaultPartition) {
|
|
installBrowserSessionPartitionPolicies(profile)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
export const browserSessionRegistry = new BrowserSessionRegistry()
|