Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sources.ts

922 lines36.4 KB

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