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

Sources.ts

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