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