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 linuxConfigHome: string;
20 readonly linuxChromeConfigHome: string;
21 readonly appData: string | undefined;
22 readonly localAppData: string | undefined;
23}
24
25export interface BrowserImportSourceDefinition {
26 readonly id: BrowserImportSourceId;
27 readonly name: string;
28 readonly engine: BrowserImportEngine;
29 readonly platforms: ReadonlyArray<NodeJS.Platform>;
30 readonly userDataDirectory: (context: BrowserImportPathContext) => string | undefined;
31 readonly alternateLinuxRoots?: (context: BrowserImportPathContext) => ReadonlyArray<string>;
32 readonly keychainService?: string;
33 readonly keychainAccount?: string;
34 readonly linuxSecretApplication?: string;
35}
36
37const macApplicationSupport = (
38 context: BrowserImportPathContext,
39 ...segments: ReadonlyArray<string>
40) => context.path.join(context.home, "Library", "Application Support", ...segments);
41
42const chromiumSource = (input: {
43 readonly id: BrowserImportSourceId;
44 readonly name: string;
45 readonly keychainService: string;
46 readonly keychainAccount: string;
47 readonly macSegments: ReadonlyArray<string>;
48 readonly linuxSegments?: ReadonlyArray<string>;
49 readonly linuxSecretApplication?: string;
50 readonly windowsSegments?: ReadonlyArray<string>;
51}): BrowserImportSourceDefinition => ({
52 id: input.id,
53 name: input.name,
54 engine: "chromium",
55 platforms: [
56 "darwin" as NodeJS.Platform,
57 ...(input.linuxSegments ? ["linux" as NodeJS.Platform] : []),
58 ...(input.windowsSegments ? ["win32" as NodeJS.Platform] : []),
59 ],
60 keychainService: input.keychainService,
61 keychainAccount: input.keychainAccount,
62 ...(input.linuxSecretApplication === undefined
63 ? {}
64 : { linuxSecretApplication: input.linuxSecretApplication }),
65 userDataDirectory: (context) => {
66 if (context.platform === "darwin") return macApplicationSupport(context, ...input.macSegments);
67 if (context.platform === "win32") {
68 return input.windowsSegments && context.localAppData
69 ? context.path.join(context.localAppData, ...input.windowsSegments)
70 : undefined;
71 }
72 return input.linuxSegments
73 ? context.path.join(
74 input.id === "chrome" || input.id === "chromium"
75 ? context.linuxChromeConfigHome
76 : context.linuxConfigHome,
77 ...input.linuxSegments,
78 )
79 : undefined;
80 },
81});
82
83export const BROWSER_IMPORT_SOURCES: ReadonlyArray<BrowserImportSourceDefinition> = [
84 // Chrome 127+ App-Bound Encryption prevents other processes from reading Windows Chromium cookies.
85 chromiumSource({
86 id: "chrome",
87 name: "Chrome",
88 keychainService: "Chrome Safe Storage",
89 keychainAccount: "Chrome",
90 macSegments: ["Google", "Chrome"],
91 linuxSegments: ["google-chrome"],
92 linuxSecretApplication: "chrome",
93 }),
94 chromiumSource({
95 id: "chromium",
96 name: "Chromium",
97 keychainService: "Chromium Safe Storage",
98 keychainAccount: "Chromium",
99 macSegments: ["Chromium"],
100 linuxSegments: ["chromium"],
101 linuxSecretApplication: "chromium",
102 }),
103 chromiumSource({
104 id: "edge",
105 name: "Microsoft Edge",
106 keychainService: "Microsoft Edge Safe Storage",
107 keychainAccount: "Microsoft Edge",
108 macSegments: ["Microsoft Edge"],
109 linuxSegments: ["microsoft-edge"],
110 linuxSecretApplication: "msedge",
111 }),
112 chromiumSource({
113 id: "brave",
114 name: "Brave",
115 keychainService: "Brave Safe Storage",
116 keychainAccount: "Brave",
117 macSegments: ["BraveSoftware", "Brave-Browser"],
118 linuxSegments: ["BraveSoftware", "Brave-Browser"],
119 linuxSecretApplication: "brave",
120 }),
121 chromiumSource({
122 id: "vivaldi",
123 name: "Vivaldi",
124 keychainService: "Vivaldi Safe Storage",
125 keychainAccount: "Vivaldi",
126 macSegments: ["Vivaldi"],
127 linuxSegments: ["vivaldi"],
128 // Vivaldi stores its Linux libsecret key under Chrome's application name.
129 linuxSecretApplication: "chrome",
130 }),
131 chromiumSource({
132 id: "opera",
133 name: "Opera",
134 keychainService: "Opera Safe Storage",
135 keychainAccount: "Opera",
136 macSegments: ["com.operasoftware.Opera"],
137 linuxSegments: ["opera"],
138 linuxSecretApplication: "opera",
139 }),
140 chromiumSource({
141 id: "arc",
142 name: "Arc",
143 keychainService: "Arc Safe Storage",
144 keychainAccount: "Arc",
145 macSegments: ["Arc", "User Data"],
146 }),
147 chromiumSource({
148 id: "helium",
149 name: "Helium",
150 keychainService: "Helium Storage Key",
151 keychainAccount: "Helium",
152 macSegments: ["net.imput.helium"],
153 linuxSegments: ["net.imput.helium"],
154 windowsSegments: ["imput", "Helium", "User Data"],
155 // Helium retains Chromium's libsecret application name on Linux.
156 linuxSecretApplication: "chromium",
157 }),
158 {
159 id: "safari",
160 name: "Safari",
161 engine: "safari",
162 platforms: ["darwin"],
163 userDataDirectory: (context) =>
164 context.platform === "darwin"
165 ? context.path.join(
166 context.home,
167 "Library",
168 "Containers",
169 "com.apple.Safari",
170 "Data",
171 "Library",
172 "Cookies",
173 )
174 : undefined,
175 },
176 {
177 id: "firefox",
178 name: "Firefox",
179 engine: "firefox",
180 platforms: ["darwin", "win32", "linux"],
181 userDataDirectory: (context) => {
182 if (context.platform === "darwin") return macApplicationSupport(context, "Firefox");
183 if (context.platform === "win32") {
184 return context.appData
185 ? context.path.join(context.appData, "Mozilla", "Firefox")
186 : undefined;
187 }
188 return context.path.join(context.home, ".mozilla", "firefox");
189 },
190 alternateLinuxRoots: (context) => [
191 context.path.join(context.home, "snap", "firefox", "common", ".mozilla", "firefox"),
192 ],
193 },
194 {
195 id: "zen",
196 name: "Zen",
197 engine: "firefox",
198 platforms: ["darwin", "win32", "linux"],
199 userDataDirectory: (context) => {
200 if (context.platform === "darwin") return macApplicationSupport(context, "zen");
201 if (context.platform === "win32") {
202 return context.appData ? context.path.join(context.appData, "zen") : undefined;
203 }
204 return context.path.join(context.linuxConfigHome, "zen");
205 },
206 alternateLinuxRoots: (context) => [
207 context.path.join(context.home, ".zen"),
208 context.path.join(context.home, ".var", "app", "app.zen_browser.zen", "zen"),
209 ],
210 },
211];
212
213const cookieDatabaseCandidatePaths = (
214 definition: BrowserImportSourceDefinition,
215 context: BrowserImportPathContext,
216 profileDirectory: string,
217): ReadonlyArray<string> => {
218 const root = definition.userDataDirectory(context);
219 if (root === undefined) return [];
220 const profilePath = context.path.isAbsolute(profileDirectory)
221 ? profileDirectory
222 : context.path.join(root, profileDirectory);
223 if (definition.engine === "firefox") {
224 return [context.path.join(profilePath, "cookies.sqlite")];
225 }
226 if (definition.engine === "safari") {
227 return [context.path.join(profilePath, "Cookies.binarycookies")];
228 }
229 // Prefer Chromium 96+'s Network/Cookies; upgrades leave the pre-96 Cookies file behind.
230 return [
231 context.path.join(profilePath, "Network", "Cookies"),
232 context.path.join(profilePath, "Cookies"),
233 ];
234};
235
236export const resolveCookieDatabase = Effect.fnUntraced(function* (
237 definition: BrowserImportSourceDefinition,
238 context: BrowserImportPathContext,
239 profileDirectory: string,
240) {
241 for (const candidate of cookieDatabaseCandidatePaths(definition, context, profileDirectory)) {
242 if (yield* databaseFileExists(candidate)) return candidate;
243 }
244 return undefined;
245});
246
247/** Install* sections select defaults, not profiles; only ProfileN blocks describe profiles. */
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 // IsRelative=0 permits custom roots outside Firefox's standard directory.
277 directory = path.normalize(candidate);
278 }
279
280 if (directory !== undefined) {
281 profiles.push({ directory, name: current.name?.trim() || directory });
282 }
283 }
284 current = null;
285 };
286
287 for (const rawLine of ini.split(/\r?\n/)) {
288 const line = rawLine.trim();
289 if (line.startsWith("[")) {
290 flush();
291 current = /^\[Profile\d+\]$/i.test(line) ? {} : null;
292 continue;
293 }
294 if (!current) continue;
295 const separator = line.indexOf("=");
296 if (separator === -1) continue;
297 const key = line.slice(0, separator).trim().toLowerCase();
298 const value = line.slice(separator + 1).trim();
299 if (key === "name") current.name = value;
300 if (key === "path") current.path = value;
301 if (key === "isrelative") current.isRelative = value;
302 }
303 flush();
304 return profiles;
305}
306
307export const sourcePathContext = Effect.gen(function* () {
308 const path = yield* Path.Path;
309 const platform = yield* HostProcess.Platform;
310 const environment = yield* HostProcess.Environment;
311 const home = environment.HOME ?? environment.USERPROFILE ?? "";
312 const xdgConfigHome = environment.XDG_CONFIG_HOME;
313 const linuxConfigHome =
314 xdgConfigHome && path.isAbsolute(xdgConfigHome) ? xdgConfigHome : path.join(home, ".config");
315 const chromeConfigHome = environment.CHROME_CONFIG_HOME;
316 return {
317 path,
318 platform,
319 home,
320 linuxConfigHome,
321 linuxChromeConfigHome:
322 chromeConfigHome && path.isAbsolute(chromeConfigHome) ? chromeConfigHome : linuxConfigHome,
323 appData: environment.APPDATA,
324 localAppData: environment.LOCALAPPDATA,
325 } satisfies BrowserImportPathContext;
326});
327
328const LocalState = Schema.Struct({
329 profile: Schema.optional(
330 Schema.Struct({
331 info_cache: Schema.optional(
332 Schema.Record(Schema.String, Schema.Struct({ name: Schema.optional(Schema.String) })),
333 ),
334 }),
335 ),
336});
337const decodeLocalState = Schema.decodeUnknownEffect(Schema.fromJsonString(LocalState));
338
339const isSafeProfileDirectory = (directory: string): boolean =>
340 directory.length > 0 &&
341 directory !== "." &&
342 directory !== ".." &&
343 !/[\\/]/.test(directory) &&
344 !directory.includes("\u0000");
345
346const CookieCountRow = Schema.Struct({ count: Schema.Number });
347const decodeCookieCount = Schema.decodeUnknownEffect(Schema.Array(CookieCountRow));
348
349// Count only default-container cookies because Electron cannot represent Firefox containers.
350const countProfileCookies = Effect.fnUntraced(function* (
351 definition: BrowserImportSourceDefinition,
352 context: BrowserImportPathContext,
353 directory: string,
354): Effect.fn.Return<number | undefined, never, FileSystem.FileSystem> {
355 const database = yield* resolveCookieDatabase(definition, context, directory);
356 if (database === undefined) return undefined;
357 return yield* Effect.gen(function* () {
358 const sql = yield* SqlClient.SqlClient;
359 // readChromiumCookieDatabase imports a razed jar as empty; Firefox has no such reader guard.
360 if (definition.engine !== "firefox") {
361 const tables =
362 yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`;
363 if (tables.length === 0) return 0;
364 }
365 const rows =
366 definition.engine === "firefox"
367 ? yield* sql`select count(*) as count from moz_cookies where originAttributes = ''`
368 : yield* sql`select count(*) as count from cookies`;
369 const [row] = yield* decodeCookieCount(rows);
370 return row?.count;
371 }).pipe(
372 Effect.provide(NodeSqliteClient.layer({ filename: database, readonly: true })),
373 Effect.orElseSucceed(() => undefined),
374 );
375});
376
377const withCookieCounts = (
378 definition: BrowserImportSourceDefinition,
379 context: BrowserImportPathContext,
380 profiles: ReadonlyArray<BrowserImportSourceProfile>,
381) =>
382 Effect.forEach(profiles, (profile) =>
383 countProfileCookies(definition, context, profile.directory).pipe(
384 Effect.map((cookieCount) =>
385 cookieCount === undefined ? profile : { ...profile, cookieCount },
386 ),
387 ),
388 );
389
390const SafariProfileRows = Schema.Array(
391 Schema.Struct({ title: Schema.NullOr(Schema.String), external_uuid: Schema.String }),
392);
393const decodeSafariProfiles = Schema.decodeUnknownEffect(SafariProfileRows);
394const isSafariProfileUuid = (value: string) =>
395 /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
396
397const listSafariProfiles = Effect.fnUntraced(function* (
398 context: BrowserImportPathContext,
399 root: string,
400) {
401 const fileSystem = yield* FileSystem.FileSystem;
402 const library = context.path.dirname(root);
403 const metadata = context.path.join(library, "Safari", "SafariTabs.db");
404 const declared = yield* Effect.gen(function* () {
405 const sql = yield* SqlClient.SqlClient;
406 return yield* decodeSafariProfiles(
407 yield* sql`
408 select title, external_uuid from bookmarks
409 where parent = 0 and type = 1 and subtype = 2 and deleted = 0
410 order by order_index
411 `,
412 );
413 }).pipe(
414 Effect.provide(NodeSqliteClient.layer({ filename: metadata, readonly: true })),
415 Effect.orElseSucceed(() => []),
416 );
417 const defaultProfile = declared.find((profile) => profile.external_uuid === "DefaultProfile");
418 const profiles: Array<BrowserImportSourceProfile> = [
419 {
420 directory: ".",
421 name: defaultProfile ? defaultProfile.title?.trim() || "Personal" : "Safari",
422 },
423 ];
424 const stores = context.path.join(library, "WebKit", "WebsiteDataStore");
425 const profileDirectory = (uuid: string) =>
426 context.path.join(stores, uuid.toLowerCase(), "Cookies");
427 for (const profile of declared) {
428 if (!isSafariProfileUuid(profile.external_uuid)) continue;
429 profiles.push({
430 directory: profileDirectory(profile.external_uuid),
431 name: profile.title?.trim() || profile.external_uuid,
432 });
433 }
434 // With readable metadata, avoid resurrecting deleted profiles left on disk.
435 if (declared.length === 0) {
436 const entries = yield* fileSystem.readDirectory(stores).pipe(Effect.orElseSucceed(() => []));
437 for (const entry of entries.filter(isSafariProfileUuid).sort()) {
438 const directory = context.path.join(stores, entry, "Cookies");
439 if (yield* databaseFileExists(context.path.join(directory, "Cookies.binarycookies"))) {
440 profiles.push({ directory, name: entry });
441 }
442 }
443 }
444 return profiles;
445});
446
447const listSourceProfilesInDirectory = Effect.fnUntraced(function* (
448 definition: BrowserImportSourceDefinition,
449 context: BrowserImportPathContext,
450): Effect.fn.Return<ReadonlyArray<BrowserImportSourceProfile>, never, FileSystem.FileSystem> {
451 const fileSystem = yield* FileSystem.FileSystem;
452 const root = definition.userDataDirectory(context);
453 if (root === undefined) return [];
454
455 if (definition.engine === "safari") {
456 return yield* listSafariProfiles(context, root);
457 }
458
459 if (definition.engine === "firefox") {
460 const declared = yield* fileSystem.readFileString(context.path.join(root, "profiles.ini")).pipe(
461 Effect.map((ini) => parseFirefoxProfiles(ini, context.path, root)),
462 Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
463 );
464 // Declared profiles may be stale or never launched; scan for unlisted stores if none has a cookie database.
465 if (declared.length > 0) {
466 const found = yield* Effect.forEach(declared, (profile) =>
467 Effect.forEach(
468 cookieDatabaseCandidatePaths(definition, context, profile.directory),
469 (candidate) => databaseFileExists(candidate),
470 ).pipe(Effect.map((results) => (results.some(Boolean) ? profile : undefined))),
471 );
472 const withDatabase = found.filter((profile) => profile !== undefined);
473 if (withDatabase.length > 0) {
474 return yield* withCookieCounts(definition, context, withDatabase);
475 }
476 }
477
478 const fallbackDirectory =
479 context.platform === "linux" ? root : context.path.join(root, "Profiles");
480 const scanned = yield* fileSystem
481 .readDirectory(fallbackDirectory)
482 .pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
483 const found = yield* Effect.forEach(scanned, (entry) => {
484 const directory = context.platform === "linux" ? entry : context.path.join("Profiles", entry);
485 return resolveCookieDatabase(definition, context, directory).pipe(
486 Effect.map((database) => (database === undefined ? undefined : { directory, name: entry })),
487 );
488 });
489 return yield* withCookieCounts(
490 definition,
491 context,
492 found.filter((profile) => profile !== undefined),
493 );
494 }
495
496 const declared = yield* fileSystem.readFileString(context.path.join(root, "Local State")).pipe(
497 Effect.flatMap(decodeLocalState),
498 Effect.map((state) => Object.entries(state.profile?.info_cache ?? {})),
499 // Browser metadata is user-writable; reject traversal segments before resolving cookie database paths.
500 Effect.map((entries) => entries.filter(([directory]) => isSafeProfileDirectory(directory))),
501 Effect.map((entries) =>
502 entries.map(([directory, info]) => ({ directory, name: info.name?.trim() || directory })),
503 ),
504 Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
505 );
506 if (declared.length > 0) return yield* withCookieCounts(definition, context, declared);
507
508 const entries = yield* fileSystem
509 .readDirectory(root)
510 .pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
511 const found = yield* Effect.forEach(entries.filter(isSafeProfileDirectory), (directory) =>
512 resolveCookieDatabase(definition, context, directory).pipe(
513 Effect.map((database) =>
514 database === undefined ? undefined : { directory, name: directory },
515 ),
516 ),
517 );
518 return yield* withCookieCounts(
519 definition,
520 context,
521 found.filter((profile) => profile !== undefined),
522 );
523});
524
525/** Keep alternate-root profile paths absolute so cookie reads and locks use the correct installation. */
526export const listSourceProfiles = Effect.fn("BrowserImportSources.listSourceProfiles")(function* (
527 definition: BrowserImportSourceDefinition,
528 context: BrowserImportPathContext,
529): Effect.fn.Return<ReadonlyArray<BrowserImportSourceProfile>, never, FileSystem.FileSystem> {
530 if (definition.engine !== "firefox" || context.platform !== "linux") {
531 return yield* listSourceProfilesInDirectory(definition, context);
532 }
533
534 const root = definition.userDataDirectory(context);
535 if (root === undefined) return [];
536 const roots = [root, ...(definition.alternateLinuxRoots?.(context) ?? [])];
537 const profiles = new Map<string, BrowserImportSourceProfile>();
538 for (const directory of roots) {
539 const found = yield* listSourceProfilesInDirectory(
540 { ...definition, userDataDirectory: () => directory },
541 context,
542 );
543 for (const profile of found) {
544 const absolute = context.path.resolve(directory, profile.directory);
545 if (!profiles.has(absolute)) {
546 profiles.set(absolute, directory === root ? profile : { ...profile, directory: absolute });
547 }
548 }
549 }
550 return [...profiles.values()];
551});
552
553const databaseFileExists = Effect.fnUntraced(function* (path: string) {
554 const fileSystem = yield* FileSystem.FileSystem;
555 return yield* fileSystem.stat(path).pipe(
556 Effect.map((info) => info.type === "File"),
557 Effect.orElseSucceed(() => false),
558 );
559});
560
561type ProcessLivenessProbe = (pid: number) => Effect.Effect<boolean>;
562
563export const chromiumProcessIsAlive = (
564 pid: number,
565 signalProcess: (pid: number, signal: 0) => unknown = process.kill.bind(process),
566) =>
567 Effect.sync(() => {
568 try {
569 signalProcess(pid, 0);
570 return true;
571 } catch (cause) {
572 // Only ESRCH proves a stale lock; permission and unknown failures may still hide an active browser.
573 return !(
574 typeof cause === "object" &&
575 cause !== null &&
576 "code" in cause &&
577 cause.code === "ESRCH"
578 );
579 }
580 });
581
582const processIsAlive: ProcessLivenessProbe = (pid) => chromiumProcessIsAlive(pid);
583
584export const chromiumSingletonLockIsHeld = Effect.fnUntraced(function* (
585 target: string,
586 currentHost: string,
587 isProcessAlive: ProcessLivenessProbe,
588) {
589 const separator = target.lastIndexOf("-");
590 if (separator <= 0) return true;
591 const host = target.slice(0, separator);
592 const pidText = target.slice(separator + 1);
593 if (!/^\d+$/.test(pidText)) return true;
594 const pid = Number(pidText);
595 if (!Number.isSafeInteger(pid) || pid <= 0) return true;
596 // Foreign-host PIDs may come from a shared home; never declare them stale here.
597 if (host !== currentHost) return true;
598 return yield* isProcessAlive(pid);
599});
600
601/** Windows sharing and lock violations are translated by libuv to `Busy`. */
602const isWindowsLockHeldError = (error: PlatformError.PlatformError): boolean =>
603 error.reason._tag === "Busy";
604
605/** Windows leaves parent.lock after exit; only opening it for write reveals a live holder as Busy. */
606const windowsLockIsHeld = Effect.fnUntraced(function* (lockPath: string) {
607 // Permission failures do not prove a running browser owns the lock.
608 const fileSystem = yield* FileSystem.FileSystem;
609 return yield* fileSystem.open(lockPath, { flag: "r+" }).pipe(
610 Effect.as(false),
611 Effect.catchIf(isWindowsLockHeldError, () => Effect.succeed(true)),
612 Effect.orElseSucceed(() => false),
613 Effect.scoped,
614 );
615});
616
617type WindowsLockProbe = (path: string) => Effect.Effect<boolean, never, FileSystem.FileSystem>;
618
619/** Windows Chromium locks cookie databases without sharing instead of creating POSIX SingletonLock symlinks. */
620export const windowsChromiumCookiesAreHeld = Effect.fnUntraced(function* (
621 definition: BrowserImportSourceDefinition,
622 context: BrowserImportPathContext,
623 lockIsHeld: WindowsLockProbe = windowsLockIsHeld,
624) {
625 const profiles = yield* listSourceProfiles(definition, context);
626 const held = yield* Effect.forEach(profiles, (profile) =>
627 resolveCookieDatabase(definition, context, profile.directory).pipe(
628 Effect.flatMap((database) =>
629 database === undefined ? Effect.succeed(false) : lockIsHeld(database),
630 ),
631 ),
632 );
633 return held.some(Boolean);
634});
635
636export const firefoxSymlinkLockIsHeld = Effect.fnUntraced(function* (
637 target: string,
638 localAddresses: ReadonlySet<string>,
639 isProcessAlive: ProcessLivenessProbe,
640) {
641 const separator = target.lastIndexOf(":");
642 if (separator < 0) return true;
643 // Firefox resolves the hostname to loopback or LAN addresses; only local owners' PIDs are meaningful.
644 const owner = target.slice(0, separator);
645 if (!localAddresses.has(owner)) return true;
646 // A `+` marks an fcntl-holding owner; the pid follows either way.
647 const pidText = target.slice(separator + 1).replace(/^\+/, "");
648 if (!/^\d+$/.test(pidText)) return true;
649 const pid = Number(pidText);
650 if (!Number.isSafeInteger(pid) || pid <= 0) return true;
651 return yield* isProcessAlive(pid);
652});
653
654/** Dock launches have a bare PATH; try the absolute interpreter before relying on shell discovery. */
655const FCNTL_PROBE_INTERPRETERS = ["/usr/bin/python3", "python3"] as const;
656
657/** Apple's python3 shim can fail with an install prompt before the probe script runs. */
658const FCNTL_PROBE_SCRIPT =
659 "import fcntl,os,sys\n" +
660 "fd=os.open(sys.argv[1],os.O_WRONLY)\n" +
661 "try:\n" +
662 " fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)\n" +
663 "except BlockingIOError:\n" +
664 " print('held')\n" +
665 "else:\n" +
666 " print('free')";
667
668/**
669 * A missing or refusing interpreter (Apple's shim without developer tools) means
670 * the probe is unavailable, so report "not held": "held" would block Firefox import
671 * forever, and the SQLite snapshot already copes with a live WAL.
672 */
673const posixLockIsHeld = Effect.fnUntraced(function* (
674 path: string,
675 interpreters: ReadonlyArray<string> = FCNTL_PROBE_INTERPRETERS,
676) {
677 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
678 const environment = yield* HostProcess.Environment;
679 for (const interpreter of interpreters) {
680 const verdict = yield* Effect.scoped(
681 Effect.gen(function* () {
682 const handle = yield* spawner.spawn(
683 ChildProcess.make(interpreter, ["-c", FCNTL_PROBE_SCRIPT, path], {
684 stdin: "ignore",
685 env: environment,
686 }),
687 );
688 const [stdout] = yield* Effect.all(
689 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
690 { concurrency: "unbounded" },
691 );
692 return stdout.trim();
693 }),
694 ).pipe(Effect.orElseSucceed(() => ""));
695 if (verdict === "held") return true;
696 if (verdict === "free") return false;
697 }
698 return false;
699});
700
701/** Firefox leaves regular lock files after exit; test the lock, not file existence. */
702const firefoxProfileIsHeld = Effect.fnUntraced(function* (
703 directory: string,
704 context: BrowserImportPathContext,
705 localAddresses: ReadonlySet<string>,
706) {
707 const fileSystem = yield* FileSystem.FileSystem;
708 if (context.platform === "win32") {
709 return yield* windowsLockIsHeld(context.path.join(directory, "parent.lock"));
710 }
711 const symlinkHeld = yield* fileSystem.readLink(context.path.join(directory, "lock")).pipe(
712 Effect.flatMap((target) => firefoxSymlinkLockIsHeld(target, localAddresses, processIsAlive)),
713 Effect.orElseSucceed(() => false),
714 );
715 if (symlinkHeld) return true;
716 const parentLock = context.path.join(directory, ".parentlock");
717 const present = yield* fileSystem.stat(parentLock).pipe(
718 Effect.map((info) => info.type === "File"),
719 Effect.orElseSucceed(() => false),
720 );
721 if (!present) return false;
722 return yield* posixLockIsHeld(parentLock);
723});
724
725export const isSourceRunning = Effect.fn("BrowserImportSources.isSourceRunning")(function* (
726 definition: BrowserImportSourceDefinition,
727 context: BrowserImportPathContext,
728): Effect.fn.Return<
729 boolean,
730 never,
731 FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
732> {
733 const fileSystem = yield* FileSystem.FileSystem;
734 const root = definition.userDataDirectory(context);
735 if (root === undefined) return false;
736 // Safari writes its jar atomically and needs no lock, even while running.
737 if (definition.engine === "safari") return false;
738 if (definition.engine !== "firefox") {
739 if (context.platform === "win32") {
740 return yield* windowsChromiumCookiesAreHeld(definition, context);
741 }
742 const currentHost = yield* HostProcess.Hostname;
743 const lock = context.path.join(root, "SingletonLock");
744 return yield* fileSystem.readLink(lock).pipe(
745 Effect.flatMap((target) => chromiumSingletonLockIsHeld(target, currentHost, processIsAlive)),
746 Effect.catch((error) => Effect.succeed(error.reason._tag !== "NotFound")),
747 );
748 }
749
750 const profiles = yield* listSourceProfiles(definition, context);
751 const localAddresses: ReadonlySet<string> =
752 context.platform === "win32" ? new Set() : yield* yield* HostProcess.Addresses;
753 const found = yield* Effect.forEach(profiles, (profile) => {
754 const directory = context.path.isAbsolute(profile.directory)
755 ? profile.directory
756 : context.path.join(root, profile.directory);
757 return firefoxProfileIsHeld(directory, context, localAddresses);
758 });
759 return found.some(Boolean);
760});
761
762/** Require a cookie database; installers create empty directories. Safari stat needs no Full Disk Access. */
763export const isSourceInstalled = Effect.fn("BrowserImportSources.isSourceInstalled")(function* (
764 definition: BrowserImportSourceDefinition,
765 context: BrowserImportPathContext,
766): Effect.fn.Return<boolean, never, FileSystem.FileSystem> {
767 const profiles = yield* listSourceProfiles(definition, context);
768 const found = yield* Effect.forEach(profiles, (profile) =>
769 resolveCookieDatabase(definition, context, profile.directory).pipe(
770 Effect.map((database) => database !== undefined),
771 ),
772 );
773 return found.some(Boolean);
774});