The best way to control Claude Code, Codex and more from any computer or phone

main
ts 763 lines 28.5 KB
Raw
1 import type { BrowserImportSourceId, BrowserImportSourceProfile } from "@t3tools/contracts";
2 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Path from "effect/Path";
7 import * as PlatformError from "effect/PlatformError";
8 import * as Schema from "effect/Schema";
9 import * as Stream from "effect/Stream";
10 import { ChildProcess, ChildProcessSpawner } from "effect/process";
11 import * as SqlClient from "effect/sql/SqlClient";
12
13 export type BrowserImportEngine = "chromium" | "firefox" | "safari";
14
15 export interface BrowserImportPathContext {
16 readonly path: Path.Path;
17 readonly platform: NodeJS.Platform;
18 readonly home: string;
19 readonly linuxConfigHome: string;
20 readonly linuxChromeConfigHome: string;
21 readonly appData: string | undefined;
22 readonly localAppData: string | undefined;
23 }
24
25 export interface BrowserImportSourceDefinition {
26 readonly id: BrowserImportSourceId;
27 readonly name: string;
28 readonly engine: BrowserImportEngine;
29 readonly platforms: ReadonlyArray<NodeJS.Platform>;
30 readonly userDataDirectory: (context: BrowserImportPathContext) => string | undefined;
31 readonly alternateLinuxRoots?: (context: BrowserImportPathContext) => ReadonlyArray<string>;
32 readonly keychainService?: string;
33 readonly keychainAccount?: string;
34 readonly linuxSecretApplication?: string;
35 }
36
37 const macApplicationSupport = (
38 context: BrowserImportPathContext,
39 ...segments: ReadonlyArray<string>
40 ) => context.path.join(context.home, "Library", "Application Support", ...segments);
41
42 const 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
81 export 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
202 const 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
225 export 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. */
237 export 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;
294 }
295
296 export 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
317 const 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 });
326 const decodeLocalState = Schema.decodeUnknownEffect(Schema.fromJsonString(LocalState));
327
328 const isSafeProfileDirectory = (directory: string): boolean =>
329 directory.length > 0 &&
330 directory !== "." &&
331 directory !== ".." &&
332 !/[\\/]/.test(directory) &&
333 !directory.includes("\u0000");
334
335 const CookieCountRow = Schema.Struct({ count: Schema.Number });
336 const decodeCookieCount = Schema.decodeUnknownEffect(Schema.Array(CookieCountRow));
337
338 // Count only default-container cookies because Electron cannot represent Firefox containers.
339 const 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 // readChromiumCookieDatabase imports a razed jar as empty; Firefox has no such reader guard.
349 if (definition.engine !== "firefox") {
350 const tables =
351 yield* sql`select 1 from sqlite_master where type = 'table' and name = 'cookies'`;
352 if (tables.length === 0) return 0;
353 }
354 const rows =
355 definition.engine === "firefox"
356 ? yield* sql`select count(*) as count from moz_cookies where originAttributes = ''`
357 : yield* sql`select count(*) as count from cookies`;
358 const [row] = yield* decodeCookieCount(rows);
359 return row?.count;
360 }).pipe(
361 Effect.provide(NodeSqliteClient.layer({ filename: database, readonly: true })),
362 Effect.orElseSucceed(() => undefined),
363 );
364 });
365
366 const withCookieCounts = (
367 definition: BrowserImportSourceDefinition,
368 context: BrowserImportPathContext,
369 profiles: ReadonlyArray<BrowserImportSourceProfile>,
370 ) =>
371 Effect.forEach(profiles, (profile) =>
372 countProfileCookies(definition, context, profile.directory).pipe(
373 Effect.map((cookieCount) =>
374 cookieCount === undefined ? profile : { ...profile, cookieCount },
375 ),
376 ),
377 );
378
379 const SafariProfileRows = Schema.Array(
380 Schema.Struct({ title: Schema.NullOr(Schema.String), external_uuid: Schema.String }),
381 );
382 const decodeSafariProfiles = Schema.decodeUnknownEffect(SafariProfileRows);
383 const isSafariProfileUuid = (value: string) =>
384 /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
385
386 const listSafariProfiles = Effect.fnUntraced(function* (
387 context: BrowserImportPathContext,
388 root: string,
389 ) {
390 const fileSystem = yield* FileSystem.FileSystem;
391 const library = context.path.dirname(root);
392 const metadata = context.path.join(library, "Safari", "SafariTabs.db");
393 const declared = yield* Effect.gen(function* () {
394 const sql = yield* SqlClient.SqlClient;
395 return yield* decodeSafariProfiles(
396 yield* sql`
397 select title, external_uuid from bookmarks
398 where parent = 0 and type = 1 and subtype = 2 and deleted = 0
399 order by order_index
400 `,
401 );
402 }).pipe(
403 Effect.provide(NodeSqliteClient.layer({ filename: metadata, readonly: true })),
404 Effect.orElseSucceed(() => []),
405 );
406 const defaultProfile = declared.find((profile) => profile.external_uuid === "DefaultProfile");
407 const profiles: Array<BrowserImportSourceProfile> = [
408 {
409 directory: ".",
410 name: defaultProfile ? defaultProfile.title?.trim() || "Personal" : "Safari",
411 },
412 ];
413 const stores = context.path.join(library, "WebKit", "WebsiteDataStore");
414 const profileDirectory = (uuid: string) =>
415 context.path.join(stores, uuid.toLowerCase(), "Cookies");
416 for (const profile of declared) {
417 if (!isSafariProfileUuid(profile.external_uuid)) continue;
418 profiles.push({
419 directory: profileDirectory(profile.external_uuid),
420 name: profile.title?.trim() || profile.external_uuid,
421 });
422 }
423 // With readable metadata, avoid resurrecting deleted profiles left on disk.
424 if (declared.length === 0) {
425 const entries = yield* fileSystem.readDirectory(stores).pipe(Effect.orElseSucceed(() => []));
426 for (const entry of entries.filter(isSafariProfileUuid).sort()) {
427 const directory = context.path.join(stores, entry, "Cookies");
428 if (yield* databaseFileExists(context.path.join(directory, "Cookies.binarycookies"))) {
429 profiles.push({ directory, name: entry });
430 }
431 }
432 }
433 return profiles;
434 });
435
436 const listSourceProfilesInDirectory = Effect.fnUntraced(function* (
437 definition: BrowserImportSourceDefinition,
438 context: BrowserImportPathContext,
439 ): Effect.fn.Return<ReadonlyArray<BrowserImportSourceProfile>, never, FileSystem.FileSystem> {
440 const fileSystem = yield* FileSystem.FileSystem;
441 const root = definition.userDataDirectory(context);
442 if (root === undefined) return [];
443
444 if (definition.engine === "safari") {
445 return yield* listSafariProfiles(context, root);
446 }
447
448 if (definition.engine === "firefox") {
449 const declared = yield* fileSystem.readFileString(context.path.join(root, "profiles.ini")).pipe(
450 Effect.map((ini) => parseFirefoxProfiles(ini, context.path, root)),
451 Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
452 );
453 // Declared profiles may be stale or never launched; scan for unlisted stores if none has a cookie database.
454 if (declared.length > 0) {
455 const found = yield* Effect.forEach(declared, (profile) =>
456 Effect.forEach(
457 cookieDatabaseCandidatePaths(definition, context, profile.directory),
458 (candidate) => databaseFileExists(candidate),
459 ).pipe(Effect.map((results) => (results.some(Boolean) ? profile : undefined))),
460 );
461 const withDatabase = found.filter((profile) => profile !== undefined);
462 if (withDatabase.length > 0) {
463 return yield* withCookieCounts(definition, context, withDatabase);
464 }
465 }
466
467 const fallbackDirectory =
468 context.platform === "linux" ? root : context.path.join(root, "Profiles");
469 const scanned = yield* fileSystem
470 .readDirectory(fallbackDirectory)
471 .pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
472 const found = yield* Effect.forEach(scanned, (entry) => {
473 const directory = context.platform === "linux" ? entry : context.path.join("Profiles", entry);
474 return resolveCookieDatabase(definition, context, directory).pipe(
475 Effect.map((database) => (database === undefined ? undefined : { directory, name: entry })),
476 );
477 });
478 return yield* withCookieCounts(
479 definition,
480 context,
481 found.filter((profile) => profile !== undefined),
482 );
483 }
484
485 const declared = yield* fileSystem.readFileString(context.path.join(root, "Local State")).pipe(
486 Effect.flatMap(decodeLocalState),
487 Effect.map((state) => Object.entries(state.profile?.info_cache ?? {})),
488 // Browser metadata is user-writable; reject traversal segments before resolving cookie database paths.
489 Effect.map((entries) => entries.filter(([directory]) => isSafeProfileDirectory(directory))),
490 Effect.map((entries) =>
491 entries.map(([directory, info]) => ({ directory, name: info.name?.trim() || directory })),
492 ),
493 Effect.orElseSucceed(() => [] as ReadonlyArray<BrowserImportSourceProfile>),
494 );
495 if (declared.length > 0) return yield* withCookieCounts(definition, context, declared);
496
497 const entries = yield* fileSystem
498 .readDirectory(root)
499 .pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<string>));
500 const found = yield* Effect.forEach(entries.filter(isSafeProfileDirectory), (directory) =>
501 resolveCookieDatabase(definition, context, directory).pipe(
502 Effect.map((database) =>
503 database === undefined ? undefined : { directory, name: directory },
504 ),
505 ),
506 );
507 return yield* withCookieCounts(
508 definition,
509 context,
510 found.filter((profile) => profile !== undefined),
511 );
512 });
513
514 /** Keep alternate-root profile paths absolute so cookie reads and locks use the correct installation. */
515 export const listSourceProfiles = Effect.fn("BrowserImportSources.listSourceProfiles")(function* (
516 definition: BrowserImportSourceDefinition,
517 context: BrowserImportPathContext,
518 ): Effect.fn.Return<ReadonlyArray<BrowserImportSourceProfile>, never, FileSystem.FileSystem> {
519 if (definition.engine !== "firefox" || context.platform !== "linux") {
520 return yield* listSourceProfilesInDirectory(definition, context);
521 }
522
523 const root = definition.userDataDirectory(context);
524 if (root === undefined) return [];
525 const roots = [root, ...(definition.alternateLinuxRoots?.(context) ?? [])];
526 const profiles = new Map<string, BrowserImportSourceProfile>();
527 for (const directory of roots) {
528 const found = yield* listSourceProfilesInDirectory(
529 { ...definition, userDataDirectory: () => directory },
530 context,
531 );
532 for (const profile of found) {
533 const absolute = context.path.resolve(directory, profile.directory);
534 if (!profiles.has(absolute)) {
535 profiles.set(absolute, directory === root ? profile : { ...profile, directory: absolute });
536 }
537 }
538 }
539 return [...profiles.values()];
540 });
541
542 const databaseFileExists = Effect.fnUntraced(function* (path: string) {
543 const fileSystem = yield* FileSystem.FileSystem;
544 return yield* fileSystem.stat(path).pipe(
545 Effect.map((info) => info.type === "File"),
546 Effect.orElseSucceed(() => false),
547 );
548 });
549
550 type ProcessLivenessProbe = (pid: number) => Effect.Effect<boolean>;
551
552 export const chromiumProcessIsAlive = (
553 pid: number,
554 signalProcess: (pid: number, signal: 0) => unknown = process.kill.bind(process),
555 ) =>
556 Effect.sync(() => {
557 try {
558 signalProcess(pid, 0);
559 return true;
560 } catch (cause) {
561 // Only ESRCH proves a stale lock; permission and unknown failures may still hide an active browser.
562 return !(
563 typeof cause === "object" &&
564 cause !== null &&
565 "code" in cause &&
566 cause.code === "ESRCH"
567 );
568 }
569 });
570
571 const processIsAlive: ProcessLivenessProbe = (pid) => chromiumProcessIsAlive(pid);
572
573 export const chromiumSingletonLockIsHeld = Effect.fnUntraced(function* (
574 target: string,
575 currentHost: string,
576 isProcessAlive: ProcessLivenessProbe,
577 ) {
578 const separator = target.lastIndexOf("-");
579 if (separator <= 0) return true;
580 const host = target.slice(0, separator);
581 const pidText = target.slice(separator + 1);
582 if (!/^\d+$/.test(pidText)) return true;
583 const pid = Number(pidText);
584 if (!Number.isSafeInteger(pid) || pid <= 0) return true;
585 // Foreign-host PIDs may come from a shared home; never declare them stale here.
586 if (host !== currentHost) return true;
587 return yield* isProcessAlive(pid);
588 });
589
590 /** Windows sharing and lock violations are translated by libuv to `Busy`. */
591 const isWindowsLockHeldError = (error: PlatformError.PlatformError): boolean =>
592 error.reason._tag === "Busy";
593
594 /** Windows leaves parent.lock after exit; only opening it for write reveals a live holder as Busy. */
595 const windowsLockIsHeld = Effect.fnUntraced(function* (lockPath: string) {
596 // Permission failures do not prove a running browser owns the lock.
597 const fileSystem = yield* FileSystem.FileSystem;
598 return yield* fileSystem.open(lockPath, { flag: "r+" }).pipe(
599 Effect.as(false),
600 Effect.catchIf(isWindowsLockHeldError, () => Effect.succeed(true)),
601 Effect.orElseSucceed(() => false),
602 Effect.scoped,
603 );
604 });
605
606 type WindowsLockProbe = (path: string) => Effect.Effect<boolean, never, FileSystem.FileSystem>;
607
608 /** Windows Chromium locks cookie databases without sharing instead of creating POSIX SingletonLock symlinks. */
609 export const windowsChromiumCookiesAreHeld = Effect.fnUntraced(function* (
610 definition: BrowserImportSourceDefinition,
611 context: BrowserImportPathContext,
612 lockIsHeld: WindowsLockProbe = windowsLockIsHeld,
613 ) {
614 const profiles = yield* listSourceProfiles(definition, context);
615 const held = yield* Effect.forEach(profiles, (profile) =>
616 resolveCookieDatabase(definition, context, profile.directory).pipe(
617 Effect.flatMap((database) =>
618 database === undefined ? Effect.succeed(false) : lockIsHeld(database),
619 ),
620 ),
621 );
622 return held.some(Boolean);
623 });
624
625 export const firefoxSymlinkLockIsHeld = Effect.fnUntraced(function* (
626 target: string,
627 localAddresses: ReadonlySet<string>,
628 isProcessAlive: ProcessLivenessProbe,
629 ) {
630 const separator = target.lastIndexOf(":");
631 if (separator < 0) return true;
632 // Firefox resolves the hostname to loopback or LAN addresses; only local owners' PIDs are meaningful.
633 const owner = target.slice(0, separator);
634 if (!localAddresses.has(owner)) return true;
635 // A `+` marks an fcntl-holding owner; the pid follows either way.
636 const pidText = target.slice(separator + 1).replace(/^\+/, "");
637 if (!/^\d+$/.test(pidText)) return true;
638 const pid = Number(pidText);
639 if (!Number.isSafeInteger(pid) || pid <= 0) return true;
640 return yield* isProcessAlive(pid);
641 });
642
643 /** Dock launches have a bare PATH; try the absolute interpreter before relying on shell discovery. */
644 const FCNTL_PROBE_INTERPRETERS = ["/usr/bin/python3", "python3"] as const;
645
646 /** Apple's python3 shim can fail with an install prompt before the probe script runs. */
647 const FCNTL_PROBE_SCRIPT =
648 "import fcntl,os,sys\n" +
649 "fd=os.open(sys.argv[1],os.O_WRONLY)\n" +
650 "try:\n" +
651 " fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)\n" +
652 "except BlockingIOError:\n" +
653 " print('held')\n" +
654 "else:\n" +
655 " print('free')";
656
657 /**
658 * A missing or refusing interpreter (Apple's shim without developer tools) means
659 * the probe is unavailable, so report "not held": "held" would block Firefox import
660 * forever, and the SQLite snapshot already copes with a live WAL.
661 */
662 const posixLockIsHeld = Effect.fnUntraced(function* (
663 path: string,
664 interpreters: ReadonlyArray<string> = FCNTL_PROBE_INTERPRETERS,
665 ) {
666 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
667 const environment = yield* HostProcess.Environment;
668 for (const interpreter of interpreters) {
669 const verdict = yield* Effect.scoped(
670 Effect.gen(function* () {
671 const handle = yield* spawner.spawn(
672 ChildProcess.make(interpreter, ["-c", FCNTL_PROBE_SCRIPT, path], {
673 stdin: "ignore",
674 env: environment,
675 }),
676 );
677 const [stdout] = yield* Effect.all(
678 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
679 { concurrency: "unbounded" },
680 );
681 return stdout.trim();
682 }),
683 ).pipe(Effect.orElseSucceed(() => ""));
684 if (verdict === "held") return true;
685 if (verdict === "free") return false;
686 }
687 return false;
688 });
689
690 /** Firefox leaves regular lock files after exit; test the lock, not file existence. */
691 const firefoxProfileIsHeld = Effect.fnUntraced(function* (
692 directory: string,
693 context: BrowserImportPathContext,
694 localAddresses: ReadonlySet<string>,
695 ) {
696 const fileSystem = yield* FileSystem.FileSystem;
697 if (context.platform === "win32") {
698 return yield* windowsLockIsHeld(context.path.join(directory, "parent.lock"));
699 }
700 const symlinkHeld = yield* fileSystem.readLink(context.path.join(directory, "lock")).pipe(
701 Effect.flatMap((target) => firefoxSymlinkLockIsHeld(target, localAddresses, processIsAlive)),
702 Effect.orElseSucceed(() => false),
703 );
704 if (symlinkHeld) return true;
705 const parentLock = context.path.join(directory, ".parentlock");
706 const present = yield* fileSystem.stat(parentLock).pipe(
707 Effect.map((info) => info.type === "File"),
708 Effect.orElseSucceed(() => false),
709 );
710 if (!present) return false;
711 return yield* posixLockIsHeld(parentLock);
712 });
713
714 export const isSourceRunning = Effect.fn("BrowserImportSources.isSourceRunning")(function* (
715 definition: BrowserImportSourceDefinition,
716 context: BrowserImportPathContext,
717 ): Effect.fn.Return<
718 boolean,
719 never,
720 FileSystem.FileSystem | ChildProcessSpawner.ChildProcessSpawner
721 > {
722 const fileSystem = yield* FileSystem.FileSystem;
723 const root = definition.userDataDirectory(context);
724 if (root === undefined) return false;
725 // Safari writes its jar atomically and needs no lock, even while running.
726 if (definition.engine === "safari") return false;
727 if (definition.engine !== "firefox") {
728 if (context.platform === "win32") {
729 return yield* windowsChromiumCookiesAreHeld(definition, context);
730 }
731 const currentHost = yield* HostProcess.Hostname;
732 const lock = context.path.join(root, "SingletonLock");
733 return yield* fileSystem.readLink(lock).pipe(
734 Effect.flatMap((target) => chromiumSingletonLockIsHeld(target, currentHost, processIsAlive)),
735 Effect.catch((error) => Effect.succeed(error.reason._tag !== "NotFound")),
736 );
737 }
738
739 const profiles = yield* listSourceProfiles(definition, context);
740 const localAddresses: ReadonlySet<string> =
741 context.platform === "win32" ? new Set() : yield* yield* HostProcess.Addresses;
742 const found = yield* Effect.forEach(profiles, (profile) => {
743 const directory = context.path.isAbsolute(profile.directory)
744 ? profile.directory
745 : context.path.join(root, profile.directory);
746 return firefoxProfileIsHeld(directory, context, localAddresses);
747 });
748 return found.some(Boolean);
749 });
750
751 /** Require a cookie database; installers create empty directories. Safari stat needs no Full Disk Access. */
752 export const isSourceInstalled = Effect.fn("BrowserImportSources.isSourceInstalled")(function* (
753 definition: BrowserImportSourceDefinition,
754 context: BrowserImportPathContext,
755 ): Effect.fn.Return<boolean, never, FileSystem.FileSystem> {
756 const profiles = yield* listSourceProfiles(definition, context);
757 const found = yield* Effect.forEach(profiles, (profile) =>
758 resolveCookieDatabase(definition, context, profile.directory).pipe(
759 Effect.map((database) => database !== undefined),
760 ),
761 );
762 return found.some(Boolean);
763 });