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

Sources.ts

725 lines26.8 KB

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