Open History to see the last commit
1/**
2 * Importable browser sources.
3 *
4 * Two engines are modelled. Chromium-family browsers keep cookies in an
5 * encrypted SQLite database whose key lives in an OS credential store; Firefox
6 * keeps them in plain SQLite with no key at all, so it needs no keychain and
7 * works the same on every platform.
8 *
9 * Each entry pins its own paths and credential-store coordinates rather than
10 * deriving them, because the forks do not agree. macOS uses service/account
11 * pairs, while Linux Chromium uses a custom libsecret schema keyed by an
12 * `application` attribute. The user-data directory also differs per fork and
13 * per platform.
14 *
15 * @module BrowserImportSources
16 */
17import type { BrowserImportSourceId, BrowserImportSourceProfile } from "@t3tools/contracts";
18import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
19import {
20 HostProcessEnvironment,
21 HostProcessAddresses,
22 HostProcessHostname,
23 HostProcessPlatform,
24} from "@t3tools/shared/hostProcess";
25import * as Effect from "effect/Effect";
26import * as FileSystem from "effect/FileSystem";
27import * as Path from "effect/Path";
28import * as PlatformError from "effect/PlatformError";
29import * as Schema from "effect/Schema";
30import * as Stream from "effect/Stream";
31import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
32import * as SqlClient from "effect/unstable/sql/SqlClient";
33
34export type BrowserImportEngine = "chromium" | "firefox";
35
36/**
37 * Directory roots a definition builds its paths from. Passed in rather than
38 * read from `process`, so source resolution stays testable for platforms the
39 * host is not currently running.
40 */
41export interface BrowserImportPathContext {
42 readonly path: Path.Path;
43 readonly platform: NodeJS.Platform;
44 readonly home: string;
45 /** `%APPDATA%` on Windows; unused elsewhere. */
46 readonly appData: string | undefined;
47 /** `%LOCALAPPDATA%` on Windows; unused elsewhere. */
48 readonly localAppData: string | undefined;
49}
50
51export interface BrowserImportSourceDefinition {
52 readonly id: BrowserImportSourceId;
53 readonly name: string;
54 readonly engine: BrowserImportEngine;
55 /** Platforms the definition has paths for. */
56 readonly platforms: ReadonlyArray<NodeJS.Platform>;
57 readonly userDataDirectory: (context: BrowserImportPathContext) => string | undefined;
58 /** Chromium on macOS only: where the OSCrypt key lives in the keychain. */
59 readonly keychainService?: string;
60 readonly keychainAccount?: string;
61 /** Chromium's `application` attribute in the Linux libsecret schema. */
62 readonly linuxSecretApplication?: string;
63}
64
65const macApplicationSupport = (
66 context: BrowserImportPathContext,
67 ...segments: ReadonlyArray<string>
68) => context.path.join(context.home, "Library", "Application Support", ...segments);
69
70/**
71 * One Chromium fork. The leaves differ per fork; omitting a platform's
72 * segments marks the fork as unavailable there. Most Windows Chromium builds
73 * use App-Bound Encryption, but forks can retain the older DPAPI-backed store.
74 */
75const chromiumSource = (input: {
76 readonly id: BrowserImportSourceId;
77 readonly name: string;
78 readonly keychainService: string;
79 readonly keychainAccount: string;
80 readonly macSegments: ReadonlyArray<string>;
81 readonly linuxSegments?: ReadonlyArray<string>;
82 readonly linuxSecretApplication?: string;
83 readonly windowsSegments?: ReadonlyArray<string>;
84}): BrowserImportSourceDefinition => ({
85 id: input.id,
86 name: input.name,
87 engine: "chromium",
88 platforms: [
89 "darwin" as NodeJS.Platform,
90 ...(input.linuxSegments ? ["linux" as NodeJS.Platform] : []),
91 ...(input.windowsSegments ? ["win32" as NodeJS.Platform] : []),
92 ],
93 keychainService: input.keychainService,
94 keychainAccount: input.keychainAccount,
95 ...(input.linuxSecretApplication === undefined
96 ? {}
97 : { linuxSecretApplication: input.linuxSecretApplication }),
98 userDataDirectory: (context) => {
99 if (context.platform === "darwin") return macApplicationSupport(context, ...input.macSegments);
100 if (context.platform === "win32") {
101 return input.windowsSegments && context.localAppData
102 ? context.path.join(context.localAppData, ...input.windowsSegments)
103 : undefined;
104 }
105 return input.linuxSegments
106 ? context.path.join(context.home, ".config", ...input.linuxSegments)
107 : undefined;
108 },
109});
110
111export const BROWSER_IMPORT_SOURCES: ReadonlyArray<BrowserImportSourceDefinition> = [
112 // No Chromium fork is importable on Windows: since Chrome 127 their cookies
113 // are encrypted to the browser's own identity (App-Bound Encryption), so no
114 // other process can read them. macOS and Linux keep working, so only the
115 // Windows segments are omitted.
116 chromiumSource({
117 id: "chrome",
118 name: "Chrome",
119 keychainService: "Chrome Safe Storage",
120 keychainAccount: "Chrome",
121 macSegments: ["Google", "Chrome"],
122 linuxSegments: ["google-chrome"],
123 linuxSecretApplication: "chrome",
124 }),
125 chromiumSource({
126 id: "edge",
127 name: "Microsoft Edge",
128 keychainService: "Microsoft Edge Safe Storage",
129 keychainAccount: "Microsoft Edge",
130 macSegments: ["Microsoft Edge"],
131 linuxSegments: ["microsoft-edge"],
132 linuxSecretApplication: "msedge",
133 }),
134 chromiumSource({
135 id: "brave",
136 name: "Brave",
137 keychainService: "Brave Safe Storage",
138 keychainAccount: "Brave",
139 macSegments: ["BraveSoftware", "Brave-Browser"],
140 linuxSegments: ["BraveSoftware", "Brave-Browser"],
141 linuxSecretApplication: "brave",
142 }),
143 chromiumSource({
144 id: "vivaldi",
145 name: "Vivaldi",
146 keychainService: "Vivaldi Safe Storage",
147 keychainAccount: "Vivaldi",
148 macSegments: ["Vivaldi"],
149 linuxSegments: ["vivaldi"],
150 linuxSecretApplication: "vivaldi",
151 }),
152 chromiumSource({
153 id: "opera",
154 name: "Opera",
155 keychainService: "Opera Safe Storage",
156 keychainAccount: "Opera",
157 macSegments: ["com.operasoftware.Opera"],
158 linuxSegments: ["opera"],
159 linuxSecretApplication: "opera",
160 }),
161 // Arc has no Linux build.
162 chromiumSource({
163 id: "arc",
164 name: "Arc",
165 keychainService: "Arc Safe Storage",
166 keychainAccount: "Arc",
167 macSegments: ["Arc", "User Data"],
168 }),
169 chromiumSource({
170 id: "helium",
171 name: "Helium",
172 keychainService: "Helium Storage Key",
173 keychainAccount: "Helium",
174 macSegments: ["net.imput.helium"],
175 linuxSegments: ["net.imput.helium"],
176 windowsSegments: ["imput", "Helium", "User Data"],
177 // Helium retains Chromium's libsecret application name on Linux.
178 linuxSecretApplication: "chromium",
179 }),
180 {
181 id: "firefox",
182 name: "Firefox",
183 engine: "firefox",
184 platforms: ["darwin", "win32", "linux"],
185 userDataDirectory: (context) => {
186 if (context.platform === "darwin") return macApplicationSupport(context, "Firefox");
187 if (context.platform === "win32") {
188 return context.appData
189 ? context.path.join(context.appData, "Mozilla", "Firefox")
190 : undefined;
191 }
192 return context.path.join(context.home, ".mozilla", "firefox");
193 },
194 },
195];
196
197/**
198 * Where a profile's cookie database may live, most current first. Chromium 96
199 * moved the live jar to `Network/Cookies`; a root-level `Cookies` is either a
200 * pre-96 install or a leftover from before the move. Importing the leftover
201 * while sessions live in `Network/` would snapshot a stale or empty database,
202 * and a fresh install with only `Network/Cookies` would read as not installed.
203 * Firefox uses `cookies.sqlite`, and its profile paths from `profiles.ini`
204 * may already be absolute.
205 *
206 * Chrome 96+ moved network-related files (including Cookies) into a `Network`
207 * subdirectory for sandboxing. The candidate list includes both locations so
208 * callers tolerate fresh and legacy installs alike.
209 */
210export const cookieDatabaseCandidatePaths = (
211 definition: BrowserImportSourceDefinition,
212 context: BrowserImportPathContext,
213 profileDirectory: string,
214): ReadonlyArray<string> => {
215 const root = definition.userDataDirectory(context);
216 if (root === undefined) return [];
217 const profilePath = context.path.isAbsolute(profileDirectory)
218 ? profileDirectory
219 : context.path.join(root, profileDirectory);
220 if (definition.engine === "firefox") {
221 return [context.path.join(profilePath, "cookies.sqlite")];
222 }
223 // Chromium: pre-96 uses `Cookies`, 96+ use `Network/Cookies`. An upgrade
224 // leaves the legacy file behind, so prefer the current one and fall back.
225 return [
226 context.path.join(profilePath, "Network", "Cookies"),
227 context.path.join(profilePath, "Cookies"),
228 ];
229};
230
231/** The first candidate that is a regular file, or undefined when none is. */
232export const resolveCookieDatabase = Effect.fnUntraced(function* (
233 definition: BrowserImportSourceDefinition,
234 context: BrowserImportPathContext,
235 profileDirectory: string,
236) {
237 for (const candidate of cookieDatabaseCandidatePaths(definition, context, profileDirectory)) {
238 if (yield* databaseFileExists(candidate)) return candidate;
239 }
240 return undefined;
241});
242
243/**
244 * Firefox records its profiles in `profiles.ini`. `Install*` sections point at
245 * a default profile but do not describe one, so only `[ProfileN]` blocks
246 * count.
247 */
248export function parseFirefoxProfiles(
249 ini: string,
250 path: Path.Path,
251 root: string,
252): ReadonlyArray<BrowserImportSourceProfile> {
253 const profiles: BrowserImportSourceProfile[] = [];
254 let current: { name?: string; path?: string; isRelative?: string } | null = null;
255
256 const flush = () => {
257 if (current?.path) {
258 const candidate = current.path;
259 const isRelative = current.isRelative === undefined || current.isRelative === "1";
260 const validIsRelative = current.isRelative === undefined || /^[01]$/.test(current.isRelative);
261 if (!validIsRelative || candidate.includes("\u0000")) {
262 current = null;
263 return;
264 }
265
266 let directory: string | undefined;
267 if (isRelative) {
268 if (!path.isAbsolute(candidate)) {
269 const resolved = path.resolve(root, candidate);
270 const relative = path.relative(root, resolved);
271 const escapesRoot =
272 relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
273 if (!escapesRoot) directory = path.normalize(candidate);
274 }
275 } else if (path.isAbsolute(candidate)) {
276 // Firefox supports profiles on arbitrary custom roots when
277 // IsRelative=0. Do not constrain them to the standard Firefox root.
278 directory = path.normalize(candidate);
279 }
280
281 if (directory !== undefined) {
282 profiles.push({ directory, name: current.name?.trim() || directory });
283 }
284 }
285 current = null;
286 };
287
288 for (const rawLine of ini.split(/\r?\n/)) {
289 const line = rawLine.trim();
290 if (line.startsWith("[")) {
291 flush();
292 current = /^\[Profile\d+\]$/i.test(line) ? {} : null;
293 continue;
294 }
295 if (!current) continue;
296 const separator = line.indexOf("=");
297 if (separator === -1) continue;
298 const key = line.slice(0, separator).trim().toLowerCase();
299 const value = line.slice(separator + 1).trim();
300 if (key === "name") current.name = value;
301 if (key === "path") current.path = value;
302 if (key === "isrelative") current.isRelative = value;
303 }
304 flush();
305 return profiles;
306}
307
308/**
309 * Resolves the roots the registry builds its paths from, from the ambient
310 * process. Tests build a context directly instead.
311 */
312export const sourcePathContext = Effect.gen(function* () {
313 const path = yield* Path.Path;
314 const platform = yield* HostProcessPlatform;
315 const environment = yield* HostProcessEnvironment;
316 return {
317 path,
318 platform,
319 home: environment.HOME ?? environment.USERPROFILE ?? "",
320 appData: environment.APPDATA,
321 localAppData: environment.LOCALAPPDATA,
322 } satisfies BrowserImportPathContext;
323});
324
325/** Shape of the slice of Chromium's `Local State` that names its profiles. */
326const LocalState = Schema.Struct({
327 profile: Schema.optional(
328 Schema.Struct({
329 info_cache: Schema.optional(
330 Schema.Record(Schema.String, Schema.Struct({ name: Schema.optional(Schema.String) })),
331 ),
332 }),
333 ),
334});
335const decodeLocalState = Schema.decodeUnknownEffect(Schema.fromJsonString(LocalState));
336
337/** A single plain path segment: no separators, no `.`/`..`, not empty. */
338const isSafeProfileDirectory = (directory: string): boolean =>
339 directory.length > 0 &&
340 directory !== "." &&
341 directory !== ".." &&
342 !/[\\/]/.test(directory) &&
343 !directory.includes("\u0000");
344
345const CookieCountRow = Schema.Struct({ count: Schema.Number });
346const decodeCookieCount = Schema.decodeUnknownEffect(Schema.Array(CookieCountRow));
347
348/**
349 * How many importable cookies a profile holds, counted without decrypting
350 * anything. Firefox containers use identities Electron cannot represent, so
351 * its count uses the same default-container predicate as the reader. Best
352 * effort: a locked, missing or unexpected database yields `undefined` rather
353 * than failing the listing.
354 */
355const countProfileCookies = Effect.fnUntraced(function* (
356 definition: BrowserImportSourceDefinition,
357 context: BrowserImportPathContext,
358 directory: string,
359): Effect.fn.Return<number | undefined, never, FileSystem.FileSystem> {
360 const database = yield* resolveCookieDatabase(definition, context, directory);
361 if (database === undefined) return undefined;
362 return yield* Effect.gen(function* () {
363 const sql = yield* SqlClient.SqlClient;
364 const rows =
365 definition.engine === "firefox"
366 ? yield* sql`select count(*) as count from moz_cookies where originAttributes = ''`
367 : yield* sql`select count(*) as count from cookies`;
368 const [row] = yield* decodeCookieCount(rows);
369 return row?.count;
370 }).pipe(
371 Effect.provide(NodeSqliteClient.layer({ filename: database, readonly: true })),
372 Effect.orElseSucceed(() => undefined),
373 );
374});
375
376const withCookieCounts = (
377 definition: BrowserImportSourceDefinition,
378 context: BrowserImportPathContext,
379 profiles: ReadonlyArray<BrowserImportSourceProfile>,
380) =>
381 Effect.forEach(profiles, (profile) =>
382 countProfileCookies(definition, context, profile.directory).pipe(
383 Effect.map((cookieCount) =>
384 cookieCount === undefined ? profile : { ...profile, cookieCount },
385 ),
386 ),
387 );
388
389/**
390 * Profiles the source browser knows about.
391 *
392 * Firefox declares them in `profiles.ini`; Chromium in `Local State`. When
393 * that metadata is missing, unreadable or malformed, the directories that
394 * actually hold a cookie database are scanned instead. Assuming a single
395 * `Default` would report a browser whose cookies live in `Profile 1` as having
396 * nothing to import — and it is then left out of the menu entirely.
397 */
398const listSourceProfilesInDirectory = Effect.fnUntraced(function* (
399 definition: BrowserImportSourceDefinition,
400 context: BrowserImportPathContext,
401): Effect.fn.Return<ReadonlyArray<BrowserImportSourceProfile>, never, FileSystem.FileSystem> {
402 const fileSystem = yield* FileSystem.FileSystem;
403 const root = definition.userDataDirectory(context);
404 if (root === undefined) return [];
405
406 if (definition.engine === "firefox") {
407 const declared = yield* fileSystem.readFileString(context.path.join(root, "profiles.ini")).pipe(
408 Effect.map((ini) => parseFirefoxProfiles(ini, context.path, root)),
409 Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
410 );
411 // `profiles.ini` also lists profiles the installer created but the user
412 // never launched, which hold no cookie database and nothing to import.
413 // Only keep the ones a database proves exist, like the directory scans
414 // below do. When none of the declared profiles has one, fall through to
415 // the scan rather than returning empty: `profiles.ini` can list stale or
416 // never-launched profiles while the cookies live in one it does not
417 // mention, and an empty answer here hides the browser entirely.
418 if (declared.length > 0) {
419 const found = yield* Effect.forEach(declared, (profile) =>
420 Effect.forEach(
421 cookieDatabaseCandidatePaths(definition, context, profile.directory),
422 (candidate) => databaseFileExists(candidate),
423 ).pipe(Effect.map((results) => (results.some(Boolean) ? profile : undefined))),
424 );
425 const withDatabase = found.filter((profile) => profile !== undefined);
426 if (withDatabase.length > 0) {
427 return yield* withCookieCounts(definition, context, withDatabase);
428 }
429 }
430
431 // No usable `profiles.ini`, so fall back to scanning the directory the
432 // profiles actually live in, keeping only the ones a cookie database
433 // proves were launched.
434 const fallbackDirectory =
435 context.platform === "linux" ? root : context.path.join(root, "Profiles");
436 const scanned = yield* fileSystem
437 .readDirectory(fallbackDirectory)
438 .pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
439 const found = yield* Effect.forEach(scanned, (entry) => {
440 const directory = context.platform === "linux" ? entry : context.path.join("Profiles", entry);
441 return resolveCookieDatabase(definition, context, directory).pipe(
442 Effect.map((database) => (database === undefined ? undefined : { directory, name: entry })),
443 );
444 });
445 return yield* withCookieCounts(
446 definition,
447 context,
448 found.filter((profile) => profile !== undefined),
449 );
450 }
451
452 const declared = yield* fileSystem.readFileString(context.path.join(root, "Local State")).pipe(
453 Effect.flatMap(decodeLocalState),
454 Effect.map((state) => Object.entries(state.profile?.info_cache ?? {})),
455 // The keys are directory names from the browser's own metadata file, which
456 // anything running as the user can write. Anything but a single plain
457 // segment is dropped: `..` or a path separator would otherwise be handed
458 // to `cookieDatabasePath` and read a database outside the user-data
459 // directory.
460 Effect.map((entries) => entries.filter(([directory]) => isSafeProfileDirectory(directory))),
461 Effect.map((entries) =>
462 entries.map(([directory, info]) => ({ directory, name: info.name?.trim() || directory })),
463 ),
464 Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
465 );
466 if (declared.length > 0) return yield* withCookieCounts(definition, context, declared);
467
468 // `Local State` is missing, unreadable or malformed. Scanning for directories
469 // that hold a cookie database finds the profiles anyway.
470 const entries = yield* fileSystem
471 .readDirectory(root)
472 .pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
473 const found = yield* Effect.forEach(entries.filter(isSafeProfileDirectory), (directory) =>
474 resolveCookieDatabase(definition, context, directory).pipe(
475 Effect.map((database) =>
476 database === undefined ? undefined : { directory, name: directory },
477 ),
478 ),
479 );
480 return yield* withCookieCounts(
481 definition,
482 context,
483 found.filter((profile) => profile !== undefined),
484 );
485});
486
487/**
488 * Include Firefox's Snap home alongside its native home. Snap profiles use
489 * absolute directories so cookie reads and lock checks keep pointing at the
490 * installation they came from, even when both installs use the same name.
491 */
492export const listSourceProfiles = Effect.fn("BrowserImportSources.listSourceProfiles")(function* (
493 definition: BrowserImportSourceDefinition,
494 context: BrowserImportPathContext,
495): Effect.fn.Return<ReadonlyArray<BrowserImportSourceProfile>, never, FileSystem.FileSystem> {
496 if (definition.engine !== "firefox" || context.platform !== "linux") {
497 return yield* listSourceProfilesInDirectory(definition, context);
498 }
499
500 const root = definition.userDataDirectory(context);
501 if (root === undefined) return [];
502 const roots = [
503 root,
504 context.path.join(context.home, "snap", "firefox", "common", ".mozilla", "firefox"),
505 ];
506 const profiles = new Map<string, BrowserImportSourceProfile>();
507 for (const directory of roots) {
508 const found = yield* listSourceProfilesInDirectory(
509 { ...definition, userDataDirectory: () => directory },
510 context,
511 );
512 for (const profile of found) {
513 const absolute = context.path.resolve(directory, profile.directory);
514 if (!profiles.has(absolute)) {
515 profiles.set(absolute, directory === root ? profile : { ...profile, directory: absolute });
516 }
517 }
518 }
519 return [...profiles.values()];
520});
521
522/**
523 * Whether a cookie database candidate is a regular file. Presence alone is
524 * not enough: a directory at the path would list as an importable profile and
525 * then fail the SQLite open, so anything but a file is treated as absent.
526 */
527const databaseFileExists = Effect.fnUntraced(function* (path: string) {
528 const fileSystem = yield* FileSystem.FileSystem;
529 return yield* fileSystem.stat(path).pipe(
530 Effect.map((info) => info.type === "File"),
531 Effect.orElseSucceed(() => false),
532 );
533});
534
535type ProcessLivenessProbe = (pid: number) => Effect.Effect<boolean>;
536
537export const chromiumProcessIsAlive = (
538 pid: number,
539 signalProcess: (pid: number, signal: 0) => unknown = process.kill.bind(process),
540) =>
541 Effect.sync(() => {
542 try {
543 // Signal 0 performs a read-only existence/permission check.
544 signalProcess(pid, 0);
545 return true;
546 } catch (cause) {
547 // Only ESRCH positively proves the process is gone. Permission errors
548 // and unknown failures stay conservative so an active browser is never
549 // mistaken for a stale lock.
550 return !(
551 typeof cause === "object" &&
552 cause !== null &&
553 "code" in cause &&
554 cause.code === "ESRCH"
555 );
556 }
557 });
558
559const processIsAlive: ProcessLivenessProbe = (pid) => chromiumProcessIsAlive(pid);
560
561/** Whether a Chromium `<host>-<pid>` lock target may still name its owner. */
562export const chromiumSingletonLockIsHeld = Effect.fnUntraced(function* (
563 target: string,
564 currentHost: string,
565 isProcessAlive: ProcessLivenessProbe,
566) {
567 const separator = target.lastIndexOf("-");
568 if (separator <= 0) return true;
569 const host = target.slice(0, separator);
570 const pidText = target.slice(separator + 1);
571 if (!/^\d+$/.test(pidText)) return true;
572 const pid = Number(pidText);
573 if (!Number.isSafeInteger(pid) || pid <= 0) return true;
574 // A PID is meaningful only on this host. A foreign hostname can come from a
575 // shared home directory, and cannot safely be declared stale from here.
576 if (host !== currentHost) return true;
577 return yield* isProcessAlive(pid);
578});
579
580/** Windows sharing and lock violations are translated by libuv to `Busy`. */
581export const isWindowsLockHeldError = (error: PlatformError.PlatformError): boolean =>
582 error.reason._tag === "Busy";
583
584/**
585 * Whether a Windows `parent.lock` is actually held by a running process. It
586 * is opened with no sharing, so it persists on disk after the process exits
587 * and `stat` always succeeds; only trying to open it for write reveals an
588 * active holder, which surfaces as `Busy`.
589 */
590const windowsLockIsHeld = Effect.fnUntraced(function* (lockPath: string) {
591 // Permission failures are distinct: they do not prove a browser owns the
592 // lock, so they must not hide the source as running.
593 const fileSystem = yield* FileSystem.FileSystem;
594 return yield* fileSystem.open(lockPath, { flag: "r+" }).pipe(
595 Effect.as(false),
596 Effect.catchIf(isWindowsLockHeldError, () => Effect.succeed(true)),
597 Effect.orElseSucceed(() => false),
598 Effect.scoped,
599 );
600});
601
602type WindowsLockProbe = (path: string) => Effect.Effect<boolean, never, FileSystem.FileSystem>;
603
604/**
605 * Chromium does not create its POSIX `SingletonLock` symlink on Windows. The
606 * live cookie database is opened without sharing instead, so probing each
607 * profile's current jar is the reliable running signal there.
608 */
609export const windowsChromiumCookiesAreHeld = Effect.fnUntraced(function* (
610 definition: BrowserImportSourceDefinition,
611 context: BrowserImportPathContext,
612 lockIsHeld: WindowsLockProbe = windowsLockIsHeld,
613) {
614 const profiles = yield* listSourceProfiles(definition, context);
615 const held = yield* Effect.forEach(profiles, (profile) =>
616 resolveCookieDatabase(definition, context, profile.directory).pipe(
617 Effect.flatMap((database) =>
618 database === undefined ? Effect.succeed(false) : lockIsHeld(database),
619 ),
620 ),
621 );
622 return held.some(Boolean);
623});
624
625/**
626 * Whether a Firefox `lock` symlink's `<ip>:[+]<pid>` target still names a
627 * live owner. Firefox writes this symlink beside the profile while it runs and
628 * unlinks it on a clean exit, so a dangling one is either live or a crash.
629 */
630export const firefoxSymlinkLockIsHeld = Effect.fnUntraced(function* (
631 target: string,
632 localAddresses: ReadonlySet<string>,
633 isProcessAlive: ProcessLivenessProbe,
634) {
635 const separator = target.lastIndexOf(":");
636 if (separator < 0) return true;
637 // The owner half is whatever Firefox's resolver returned for the machine's
638 // hostname — 127.0.0.1 when the lookup fails, but often 127.0.1.1 or a LAN
639 // address — so a pid is only meaningful when that address is one of ours.
640 // A shared (NFS) profile locked from another machine names a foreign
641 // address whose pid cannot be probed here, nor could a reused local pid
642 // vouch for it, so it stays conservatively held.
643 const owner = target.slice(0, separator);
644 if (!localAddresses.has(owner)) return true;
645 // A `+` marks an fcntl-holding owner; the pid follows either way.
646 const pidText = target.slice(separator + 1).replace(/^\+/, "");
647 if (!/^\d+$/.test(pidText)) return true;
648 const pid = Number(pidText);
649 if (!Number.isSafeInteger(pid) || pid <= 0) return true;
650 return yield* isProcessAlive(pid);
651});
652
653/**
654 * Interpreters that can run the fcntl probe, tried in order. `/usr/bin/python3`
655 * is named absolutely first so a Dock-launched app with launchd's bare `PATH`
656 * still finds it without depending on the login-shell PATH merge; Linux
657 * distributions carry python3 on the default path.
658 */
659const FCNTL_PROBE_INTERPRETERS = ["/usr/bin/python3", "python3"] as const;
660
661/**
662 * The probe prints exactly one of these. Anything else means the script never
663 * ran — most importantly Apple's `/usr/bin/python3` shim, which on a Mac
664 * without the Command Line Tools exits non-zero after printing an install
665 * prompt, without ever reaching our code.
666 */
667const FCNTL_PROBE_SCRIPT =
668 "import fcntl,os,sys\n" +
669 "fd=os.open(sys.argv[1],os.O_WRONLY)\n" +
670 "try:\n" +
671 " fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)\n" +
672 "except BlockingIOError:\n" +
673 " print('held')\n" +
674 "else:\n" +
675 " print('free')";
676
677/**
678 * Whether another process holds an fcntl write lock on `path`.
679 *
680 * Firefox's `.parentlock` is an empty file whose only signal is the kernel
681 * lock, and Node exposes no fcntl, so a throwaway interpreter tries a
682 * non-blocking `F_SETLK` and reports `EWOULDBLOCK`. The lock is never
683 * acquired for real: on success the child exits and the kernel drops it.
684 *
685 * The answer is trusted only when the script itself spoke. A verdict of
686 * `held` or `free` on stdout is the probe's own, and stands. Anything else —
687 * no interpreter on any candidate path, or one that refused to run the script
688 * (Apple's shim without the developer tools) — is the probe being unavailable,
689 * not evidence about the lock. That case falls back to "not held" rather than
690 * "held": reporting every profile as locked forever would block Firefox import
691 * outright on such machines, and the SQLite snapshot already copes with a
692 * live database's WAL, as it does for every other engine.
693 */
694export const posixLockIsHeld = Effect.fnUntraced(function* (
695 path: string,
696 interpreters: ReadonlyArray<string> = FCNTL_PROBE_INTERPRETERS,
697) {
698 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
699 const environment = yield* HostProcessEnvironment;
700 for (const interpreter of interpreters) {
701 const verdict = yield* Effect.scoped(
702 Effect.gen(function* () {
703 const handle = yield* spawner.spawn(
704 ChildProcess.make(interpreter, ["-c", FCNTL_PROBE_SCRIPT, path], {
705 stdin: "ignore",
706 env: environment,
707 }),
708 );
709 const [stdout] = yield* Effect.all(
710 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
711 { concurrency: "unbounded" },
712 );
713 return stdout.trim();
714 }),
715 ).pipe(Effect.orElseSucceed(() => ""));
716 if (verdict === "held") return true;
717 if (verdict === "free") return false;
718 }
719 return false;
720});
721
722/**
723 * Whether Firefox holds a profile.
724 *
725 * Firefox leaves two kinds of lock behind, and they mean different things.
726 * On Linux the `lock` symlink (target `<ip>:+<pid>`) is removed on a clean
727 * exit, so its presence is evidence — provided the pid it names is alive. But
728 * `.parentlock` (macOS/Linux) and `parent.lock` (Windows) are regular files
729 * held with fcntl or a Windows handle and are *deliberately left on disk*
730 * after exit, as a last-used marker; treating them as proof of a running
731 * browser blocks every import after Firefox has been used once. On POSIX the
732 * fcntl lock itself is the truth, and macOS in particular writes nothing else
733 * (no symlink, no pid), so `.parentlock` is probed for the kernel lock. On
734 * Windows the held handle denies our open, which `windowsLockIsHeld` reads as `Busy`.
735 */
736const firefoxProfileIsHeld = Effect.fnUntraced(function* (
737 directory: string,
738 context: BrowserImportPathContext,
739 // Resolved once by the caller: it involves a DNS lookup of the hostname and
740 // is the same for every profile.
741 localAddresses: ReadonlySet<string>,
742) {
743 const fileSystem = yield* FileSystem.FileSystem;
744 if (context.platform === "win32") {
745 return yield* windowsLockIsHeld(context.path.join(directory, "parent.lock"));
746 }
747 // Linux additionally writes the `lock` symlink; a live pid there settles it
748 // without spawning anything.
749 const symlinkHeld = yield* fileSystem.readLink(context.path.join(directory, "lock")).pipe(
750 Effect.flatMap((target) => firefoxSymlinkLockIsHeld(target, localAddresses, processIsAlive)),
751 Effect.orElseSucceed(() => false),
752 );
753 if (symlinkHeld) return true;
754 const parentLock = context.path.join(directory, ".parentlock");
755 const present = yield* fileSystem.stat(parentLock).pipe(
756 Effect.map((info) => info.type === "File"),
757 Effect.orElseSucceed(() => false),
758 );
759 if (!present) return false;
760 return yield* posixLockIsHeld(parentLock);
761});
762
763/** Whether the browser is running, which leaves its cookie DB mid-write. */
764export const isSourceRunning = Effect.fn("BrowserImportSources.isSourceRunning")(function* (
765 definition: BrowserImportSourceDefinition,
766 context: BrowserImportPathContext,
767): Effect.fn.Return<
768 boolean,
769 never,
770 FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
771> {
772 const fileSystem = yield* FileSystem.FileSystem;
773 const root = definition.userDataDirectory(context);
774 if (root === undefined) return false;
775 // Probe the source's own lock state rather than scanning the process table.
776 // Chromium exposes its lock through the cookie jar on Windows and through a
777 // user-data SingletonLock on POSIX. Firefox keeps its locks inside each
778 // profile under three names across platforms (`lock` on macOS and Linux,
779 // `.parentlock` beside it, `parent.lock` on Windows). Looking for Firefox's
780 // at the root finds nothing and reports a running browser as importable.
781 if (definition.engine !== "firefox") {
782 if (context.platform === "win32") {
783 return yield* windowsChromiumCookiesAreHeld(definition, context);
784 }
785 const currentHost = yield* HostProcessHostname;
786 const lock = context.path.join(root, "SingletonLock");
787 return yield* fileSystem.readLink(lock).pipe(
788 Effect.flatMap((target) => chromiumSingletonLockIsHeld(target, currentHost, processIsAlive)),
789 Effect.catch((error) => Effect.succeed(error.reason._tag !== "NotFound")),
790 );
791 }
792
793 const profiles = yield* listSourceProfiles(definition, context);
794 // Only the Linux `lock` symlink names an address, so Windows skips the lookup.
795 const localAddresses: ReadonlySet<string> =
796 context.platform === "win32" ? new Set() : yield* yield* HostProcessAddresses;
797 const found = yield* Effect.forEach(profiles, (profile) => {
798 const directory = context.path.isAbsolute(profile.directory)
799 ? profile.directory
800 : context.path.join(root, profile.directory);
801 return firefoxProfileIsHeld(directory, context, localAddresses);
802 });
803 return found.some(Boolean);
804});
805
806/**
807 * Whether the source has cookies to import.
808 *
809 * Keyed off the cookie database rather than the user-data directory, because
810 * that directory is not evidence the browser exists: installers for native
811 * messaging hosts create an empty one for every Chromium fork they know about,
812 * so a machine with only Chrome reports Edge, Brave, Vivaldi, Opera and Arc as
813 * present. The database is the thing an import actually needs, so its absence
814 * is the honest answer either way.
815 *
816 * Existence is checked without opening the file, which matters for Safari: TCC
817 * permits `stat` on the jar inside its container but refuses a read, so this
818 * still sees it and the user gets the Full Disk Access prompt rather than
819 * having Safari disappear.
820 */
821export const isSourceInstalled = Effect.fn("BrowserImportSources.isSourceInstalled")(function* (
822 definition: BrowserImportSourceDefinition,
823 context: BrowserImportPathContext,
824): Effect.fn.Return<boolean, never, FileSystem.FileSystem> {
825 const profiles = yield* listSourceProfiles(definition, context);
826 const found = yield* Effect.forEach(profiles, (profile) =>
827 resolveCookieDatabase(definition, context, profile.directory).pipe(
828 Effect.map((database) => database !== undefined),
829 ),
830 );
831 return found.some(Boolean);
832});