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

Sources.ts

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