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