Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Builds a Chromium-shaped cookie
2// table with the same native bindings the source reads.
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, describe, it } from "@effect/vitest";
5import {
6 HostProcessEnvironment,
7 HostProcessHostname,
8 HostProcessPlatform,
9} from "@t3tools/shared/hostProcess";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Path from "effect/Path";
13import * as PlatformError from "effect/PlatformError";
14import * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
17import * as NodeSqlite from "node:sqlite";
18
19import type { BrowserImportPathContext } from "./Sources.ts";
20import {
21 BROWSER_IMPORT_SOURCES,
22 chromiumProcessIsAlive,
23 chromiumSingletonLockIsHeld,
24 cookieDatabaseCandidatePaths,
25 firefoxSymlinkLockIsHeld,
26 resolveCookieDatabase,
27 isSourceInstalled,
28 isSourceRunning,
29 isWindowsLockHeldError,
30 posixLockIsHeld,
31 listSourceProfiles,
32 sourcePathContext,
33 windowsChromiumCookiesAreHeld,
34} from "./Sources.ts";
35
36const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!;
37
38describe("Linux Chromium secret applications", () => {
39 it("pins the libsecret application attribute for each supported fork", () => {
40 assert.deepEqual(
41 Object.fromEntries(
42 BROWSER_IMPORT_SOURCES.filter((source) => source.platforms.includes("linux")).map(
43 (source) => [source.id, source.linuxSecretApplication],
44 ),
45 ),
46 {
47 chrome: "chrome",
48 edge: "msedge",
49 brave: "brave",
50 vivaldi: "vivaldi",
51 opera: "opera",
52 helium: "chromium",
53 firefox: undefined,
54 },
55 );
56 });
57});
58
59const platformError = (reasonTag: string): PlatformError.PlatformError =>
60 ({ _tag: "PlatformError", reason: { _tag: reasonTag } }) as never;
61
62describe("Windows browser lock errors", () => {
63 it("treats sharing and lock violations reported as Busy as held", () => {
64 assert.isTrue(isWindowsLockHeldError(platformError("Busy")));
65 });
66
67 it("does not treat access denied as proof of an active lock", () => {
68 assert.isFalse(isWindowsLockHeldError(platformError("PermissionDenied")));
69 });
70
71 it("does not treat a missing lock file as held", () => {
72 assert.isFalse(isWindowsLockHeldError(platformError("NotFound")));
73 });
74});
75
76/** A scratch home with the source's user-data directory already created. */
77const withSourceHome = Effect.fnUntraced(function* () {
78 const fileSystem = yield* FileSystem.FileSystem;
79 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-sources-" });
80 const context = yield* sourcePathContext.pipe(
81 Effect.provideService(HostProcessEnvironment, { HOME: home }),
82 Effect.provideService(HostProcessPlatform, "darwin"),
83 );
84 yield* fileSystem.makeDirectory(userDataDirectory(context), { recursive: true });
85 return context;
86});
87
88/** Every case here runs on darwin, where Helium always resolves a directory. */
89const userDataDirectory = (context: BrowserImportPathContext) => {
90 const root = helium.userDataDirectory(context);
91 if (root === undefined) throw new Error("Helium has no macOS user-data directory");
92 return root;
93};
94
95const run = <A, E>(
96 effect: Effect.Effect<
97 A,
98 E,
99 FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
100 >,
101) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
102
103/** Writes a Chromium-shaped cookie table with `count` rows. */
104const writeCookieDatabase = (file: string, count: number) =>
105 Effect.sync(() => {
106 const database = new NodeSqlite.DatabaseSync(file);
107 database.exec("create table cookies (host_key text, name text)");
108 const insert = database.prepare("insert into cookies (host_key, name) values (?, ?)");
109 for (let index = 0; index < count; index += 1) insert.run("example.test", `c${index}`);
110 database.close();
111 });
112
113const writeFirefoxCookieDatabase = (
114 file: string,
115 defaultContainerCount: number,
116 containerCount: number,
117) =>
118 Effect.sync(() => {
119 const database = new NodeSqlite.DatabaseSync(file);
120 database.exec("create table moz_cookies (originAttributes text not null)");
121 const insert = database.prepare("insert into moz_cookies (originAttributes) values (?)");
122 for (let index = 0; index < defaultContainerCount; index += 1) insert.run("");
123 for (let index = 0; index < containerCount; index += 1) insert.run("^userContextId=2");
124 database.close();
125 });
126
127describe("Helium on Linux", () => {
128 it.effect("discovers its profiles and checks the user-data lock", () =>
129 run(
130 Effect.gen(function* () {
131 const fileSystem = yield* FileSystem.FileSystem;
132 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-helium-linux-" });
133 const context = yield* sourcePathContext.pipe(
134 Effect.provideService(HostProcessEnvironment, { HOME: home }),
135 Effect.provideService(HostProcessPlatform, "linux"),
136 );
137 const root = `${home}/.config/net.imput.helium`;
138 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
139 yield* writeCookieDatabase(`${root}/Default/Cookies`, 3);
140 yield* fileSystem.writeFileString(
141 `${root}/Local State`,
142 '{"profile":{"info_cache":{"Default":{"name":"Personal"}}}}',
143 );
144
145 assert.include(helium.platforms, "linux");
146 assert.isTrue(yield* isSourceInstalled(helium, context));
147 assert.deepEqual(yield* listSourceProfiles(helium, context), [
148 { directory: "Default", name: "Personal", cookieCount: 3 },
149 ]);
150 assert.isFalse(yield* isSourceRunning(helium, context));
151 yield* fileSystem.symlink("foreign-host-4242", `${root}/SingletonLock`);
152 assert.isTrue(yield* isSourceRunning(helium, context));
153 }),
154 ),
155 );
156});
157
158describe("Helium on Windows", () => {
159 it.effect("uses Helium's local app-data profile while other Chromium forks stay disabled", () =>
160 run(
161 Effect.gen(function* () {
162 const context = yield* sourcePathContext.pipe(
163 Effect.provideService(HostProcessEnvironment, {
164 USERPROFILE: "C:\\Users\\browser-user",
165 LOCALAPPDATA: "C:\\Users\\browser-user\\AppData\\Local",
166 }),
167 Effect.provideService(HostProcessPlatform, "win32"),
168 );
169
170 assert.include(helium.platforms, "win32");
171 assert.equal(
172 helium.userDataDirectory(context),
173 context.path.join(
174 "C:\\Users\\browser-user\\AppData\\Local",
175 "imput",
176 "Helium",
177 "User Data",
178 ),
179 );
180 for (const source of BROWSER_IMPORT_SOURCES) {
181 if (source.engine === "chromium" && source.id !== "helium") {
182 assert.notInclude(source.platforms, "win32");
183 }
184 }
185 }),
186 ),
187 );
188});
189
190describe("isSourceRunning", () => {
191 it.effect("uses the held cookie database as Chromium's Windows running signal", () =>
192 run(
193 Effect.gen(function* () {
194 const fileSystem = yield* FileSystem.FileSystem;
195 const home = yield* fileSystem.makeTempDirectoryScoped({
196 prefix: "t3code-helium-windows-lock-",
197 });
198 const context = yield* sourcePathContext.pipe(
199 Effect.provideService(HostProcessEnvironment, {
200 HOME: home,
201 LOCALAPPDATA: home,
202 }),
203 Effect.provideService(HostProcessPlatform, "win32"),
204 );
205 const profile = context.path.join(helium.userDataDirectory(context)!, "Default");
206 const database = context.path.join(profile, "Network", "Cookies");
207 yield* fileSystem.makeDirectory(context.path.join(profile, "Network"), { recursive: true });
208 yield* writeCookieDatabase(database, 1);
209
210 const probed: string[] = [];
211 assert.isTrue(
212 yield* windowsChromiumCookiesAreHeld(helium, context, (path) =>
213 Effect.sync(() => {
214 probed.push(path);
215 return true;
216 }),
217 ),
218 );
219 assert.deepEqual(probed, [database]);
220 }),
221 ),
222 );
223
224 it.effect("reads Chromium's dangling SingletonLock symlink as a running browser", () =>
225 run(
226 Effect.gen(function* () {
227 const fileSystem = yield* FileSystem.FileSystem;
228 const context = yield* withSourceHome();
229 assert.isFalse(yield* isSourceRunning(helium, context));
230
231 // Chromium points the lock at `<host>-<pid>`, a target that never
232 // exists on disk. A check that follows the link reports a running
233 // browser as closed, letting an import read a live, mid-write database.
234 yield* fileSystem.symlink(
235 "host-that-does-not-exist-1234",
236 `${userDataDirectory(context)}/SingletonLock`,
237 );
238
239 assert.isTrue(yield* isSourceRunning(helium, context));
240 }),
241 ),
242 );
243
244 it.effect("uses the provided hostname to classify Chromium locks", () =>
245 run(
246 Effect.gen(function* () {
247 const fileSystem = yield* FileSystem.FileSystem;
248 const paths = yield* withSourceHome();
249 yield* fileSystem.symlink(
250 "lock-owner-99999999",
251 `${helium.userDataDirectory(paths)}/SingletonLock`,
252 );
253
254 assert.isTrue(
255 yield* isSourceRunning(helium, paths).pipe(
256 Effect.provideService(HostProcessHostname, "another-host"),
257 ),
258 );
259 assert.isFalse(
260 yield* isSourceRunning(helium, paths).pipe(
261 Effect.provideService(HostProcessHostname, "lock-owner"),
262 ),
263 );
264 }),
265 ),
266 );
267});
268
269describe("chromiumSingletonLockIsHeld", () => {
270 it.effect("ignores a positively dead PID on the current host", () =>
271 Effect.gen(function* () {
272 const checked: number[] = [];
273 const held = yield* chromiumSingletonLockIsHeld("current-host-4321", "current-host", (pid) =>
274 Effect.sync(() => {
275 checked.push(pid);
276 return false;
277 }),
278 );
279 assert.isFalse(held);
280 assert.deepEqual(checked, [4321]);
281 }),
282 );
283
284 it.effect("keeps a live PID on the current host", () =>
285 chromiumSingletonLockIsHeld("current-host-4321", "current-host", () =>
286 Effect.succeed(true),
287 ).pipe(Effect.tap((held) => Effect.sync(() => assert.isTrue(held)))),
288 );
289
290 it.effect("keeps foreign-host and malformed targets without probing a PID", () =>
291 Effect.gen(function* () {
292 let probes = 0;
293 const probe = (_pid: number) =>
294 Effect.sync(() => {
295 probes += 1;
296 return false;
297 });
298 assert.isTrue(yield* chromiumSingletonLockIsHeld("another-host-4321", "current-host", probe));
299 assert.isTrue(
300 yield* chromiumSingletonLockIsHeld("current-host-no-pid", "current-host", probe),
301 );
302 assert.isTrue(yield* chromiumSingletonLockIsHeld("current-host-0", "current-host", probe));
303 assert.strictEqual(probes, 0);
304 }),
305 );
306});
307
308describe("chromiumProcessIsAlive", () => {
309 it.effect("returns false only when signal 0 reports a missing process", () =>
310 Effect.gen(function* () {
311 const missing = Object.assign(new Error("missing"), { code: "ESRCH" });
312 const denied = Object.assign(new Error("denied"), { code: "EPERM" });
313 assert.isFalse(
314 yield* chromiumProcessIsAlive(4321, () => {
315 throw missing;
316 }),
317 );
318 assert.isTrue(
319 yield* chromiumProcessIsAlive(4321, () => {
320 throw denied;
321 }),
322 );
323 assert.isTrue(
324 yield* chromiumProcessIsAlive(4321, () => {
325 throw undefined;
326 }),
327 );
328 assert.isTrue(
329 yield* chromiumProcessIsAlive(4321, () => {
330 throw "unknown failure";
331 }),
332 );
333 assert.isTrue(
334 yield* chromiumProcessIsAlive(4321, () => {
335 throw null;
336 }),
337 );
338 assert.isTrue(yield* chromiumProcessIsAlive(4321, () => true));
339 }),
340 );
341});
342
343describe("isSourceInstalled", () => {
344 it.effect("ignores a user-data directory that holds no cookie database", () =>
345 run(
346 Effect.gen(function* () {
347 const fileSystem = yield* FileSystem.FileSystem;
348 const context = yield* withSourceHome();
349 const root = userDataDirectory(context);
350
351 // Installers for native messaging hosts create an empty user-data
352 // directory for every Chromium fork they know about, so treating the
353 // directory as evidence lists browsers the user does not have.
354 yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true });
355 assert.isFalse(yield* isSourceInstalled(helium, context));
356
357 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
358 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
359 assert.isTrue(yield* isSourceInstalled(helium, context));
360
361 // A real install whose cookies live outside `Default` still counts:
362 // reporting it as absent hides the source from the menu entirely.
363 yield* fileSystem.remove(`${root}/Default`, { recursive: true });
364 yield* fileSystem.makeDirectory(`${root}/Profile 1`, { recursive: true });
365 yield* fileSystem.writeFileString(`${root}/Profile 1/Cookies`, "db");
366 assert.isTrue(yield* isSourceInstalled(helium, context));
367
368 yield* fileSystem.remove(root, { recursive: true });
369 assert.isFalse(yield* isSourceInstalled(helium, context));
370 }),
371 ),
372 );
373
374 it.effect("detects a Chromium 127+ install with cookies under Network/", () =>
375 run(
376 Effect.gen(function* () {
377 const fileSystem = yield* FileSystem.FileSystem;
378 const context = yield* withSourceHome();
379 const root = userDataDirectory(context);
380
381 yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
382 yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "db");
383 assert.isTrue(yield* isSourceInstalled(helium, context));
384 }),
385 ),
386 );
387
388 it.effect("follows cookie database symlinks when detecting profiles", () =>
389 run(
390 Effect.gen(function* () {
391 const fileSystem = yield* FileSystem.FileSystem;
392 const context = yield* withSourceHome();
393 const root = userDataDirectory(context);
394 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
395 yield* fileSystem.symlink("missing-cookies", `${root}/Default/Cookies`);
396
397 assert.deepEqual(yield* listSourceProfiles(helium, context), []);
398 assert.isFalse(yield* isSourceInstalled(helium, context));
399
400 yield* fileSystem.writeFileString(`${root}/Default/missing-cookies`, "db");
401 assert.deepEqual(yield* listSourceProfiles(helium, context), [
402 { directory: "Default", name: "Default" },
403 ]);
404 assert.isTrue(yield* isSourceInstalled(helium, context));
405 }),
406 ),
407 );
408});
409
410describe("listSourceProfiles", () => {
411 it.effect("ignores a profile whose Cookies entry is not a file", () =>
412 run(
413 Effect.gen(function* () {
414 const fileSystem = yield* FileSystem.FileSystem;
415 const paths = yield* withSourceHome();
416 const root = helium.userDataDirectory(paths);
417 // A directory named `Cookies` would list as importable and then fail
418 // the SQLite open, so only a regular file counts as a database.
419 yield* fileSystem.makeDirectory(`${root}/Broken/Cookies`, { recursive: true });
420 yield* fileSystem.makeDirectory(`${root}/Real`, { recursive: true });
421 yield* fileSystem.writeFileString(`${root}/Real/Cookies`, "db");
422
423 assert.deepEqual(yield* listSourceProfiles(helium, paths), [
424 { directory: "Real", name: "Real" },
425 ]);
426 assert.isTrue(yield* isSourceInstalled(helium, paths));
427 }),
428 ),
429 );
430
431 it.effect("discovers profiles by their cookie database when Local State is absent", () =>
432 run(
433 Effect.gen(function* () {
434 const fileSystem = yield* FileSystem.FileSystem;
435 const context = yield* withSourceHome();
436 const root = userDataDirectory(context);
437 // Assuming `Default` would report a browser whose cookies live in
438 // `Profile 1` as having nothing to import, and it is then hidden.
439 yield* fileSystem.makeDirectory(`${root}/Profile 1`, { recursive: true });
440 yield* fileSystem.writeFileString(`${root}/Profile 1/Cookies`, "db");
441 yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true });
442
443 assert.deepEqual(yield* listSourceProfiles(helium, context), [
444 { directory: "Profile 1", name: "Profile 1" },
445 ]);
446 }),
447 ),
448 );
449
450 it.effect("reads the profile names the browser shows", () =>
451 run(
452 Effect.gen(function* () {
453 const fileSystem = yield* FileSystem.FileSystem;
454 const context = yield* withSourceHome();
455 yield* fileSystem.writeFileString(
456 `${userDataDirectory(context)}/Local State`,
457 `{"profile":{"info_cache":{"Default":{"name":"You"},"Profile 2":{"name":" "}}}}`,
458 );
459
460 assert.deepEqual(yield* listSourceProfiles(helium, context), [
461 { directory: "Default", name: "You" },
462 // Blank display name falls back to the directory rather than
463 // rendering an empty row.
464 { directory: "Profile 2", name: "Profile 2" },
465 ]);
466 }),
467 ),
468 );
469
470 it.effect("scans for profiles when Local State is malformed", () =>
471 run(
472 Effect.gen(function* () {
473 const fileSystem = yield* FileSystem.FileSystem;
474 const context = yield* withSourceHome();
475 const root = userDataDirectory(context);
476 yield* fileSystem.writeFileString(`${root}/Local State`, "{not-json");
477 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
478 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
479
480 assert.deepEqual(yield* listSourceProfiles(helium, context), [
481 { directory: "Default", name: "Default" },
482 ]);
483 }),
484 ),
485 );
486
487 it.effect("reports nothing when no directory holds a cookie database", () =>
488 run(
489 Effect.gen(function* () {
490 const context = yield* withSourceHome();
491 assert.deepEqual(yield* listSourceProfiles(helium, context), []);
492 }),
493 ),
494 );
495
496 it.effect("drops Firefox profiles that hold no cookie database", () =>
497 run(
498 Effect.gen(function* () {
499 const fileSystem = yield* FileSystem.FileSystem;
500 const context = yield* withSourceHome();
501 const root = firefox.userDataDirectory(context)!;
502 yield* fileSystem.makeDirectory(root, { recursive: true });
503 yield* fileSystem.writeFileString(
504 `${root}/profiles.ini`,
505 `[Profile0]
506Name=original
507IsRelative=1
508Path=Profiles/abcd.default-release
509Default=1
510
511[Profile1]
512Name=empty
513IsRelative=1
514Path=Profiles/wxyz.empty
515`,
516 );
517 yield* fileSystem.makeDirectory(`${root}/Profiles/abcd.default-release`, {
518 recursive: true,
519 });
520 yield* fileSystem.writeFileString(
521 `${root}/Profiles/abcd.default-release/cookies.sqlite`,
522 "db",
523 );
524 yield* fileSystem.makeDirectory(`${root}/Profiles/wxyz.empty`, { recursive: true });
525
526 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
527 { directory: "Profiles/abcd.default-release", name: "original" },
528 ]);
529 }),
530 ),
531 );
532
533 it.effect("drops empty profiles when falling back to the Profiles/ scan", () =>
534 run(
535 Effect.gen(function* () {
536 const fileSystem = yield* FileSystem.FileSystem;
537 const context = yield* withSourceHome();
538 const root = firefox.userDataDirectory(context)!;
539 yield* fileSystem.makeDirectory(`${root}/Profiles/filled.default`, { recursive: true });
540 yield* fileSystem.writeFileString(`${root}/Profiles/filled.default/cookies.sqlite`, "db");
541 yield* fileSystem.makeDirectory(`${root}/Profiles/empty.default`, { recursive: true });
542
543 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
544 {
545 directory: context.path.join("Profiles", "filled.default"),
546 name: "filled.default",
547 },
548 ]);
549 }),
550 ),
551 );
552
553 it.effect("discovers profiles with cookies under Network/ (Chromium 127+)", () =>
554 run(
555 Effect.gen(function* () {
556 const fileSystem = yield* FileSystem.FileSystem;
557 const context = yield* withSourceHome();
558 const root = userDataDirectory(context);
559 yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
560 yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "db");
561
562 assert.deepEqual(yield* listSourceProfiles(helium, context), [
563 { directory: "Default", name: "Default" },
564 ]);
565 }),
566 ),
567 );
568
569 it.effect("counts a profile's cookies without decrypting them", () =>
570 run(
571 Effect.gen(function* () {
572 const fileSystem = yield* FileSystem.FileSystem;
573 const paths = yield* withSourceHome();
574 const root = helium.userDataDirectory(paths);
575 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
576 yield* writeCookieDatabase(`${root}/Default/Cookies`, 3);
577
578 const [profile] = yield* listSourceProfiles(helium, paths);
579 assert.equal(profile?.cookieCount, 3);
580 }),
581 ),
582 );
583
584 it.effect("falls through to the legacy database when Network/Cookies is a directory", () =>
585 run(
586 Effect.gen(function* () {
587 const fileSystem = yield* FileSystem.FileSystem;
588 const paths = yield* withSourceHome();
589 const root = helium.userDataDirectory(paths);
590 // A folder squatting on the preferred candidate path must not shadow
591 // the real legacy database behind it.
592 yield* fileSystem.makeDirectory(`${root}/Default/Network/Cookies`, { recursive: true });
593 yield* writeCookieDatabase(`${root}/Default/Cookies`, 2);
594
595 const [profile] = yield* listSourceProfiles(helium, paths);
596 assert.equal(profile?.directory, "Default");
597 assert.equal(profile?.cookieCount, 2);
598 }),
599 ),
600 );
601});
602
603describe("cookieDatabaseCandidatePaths", () => {
604 it.effect("prefers Network/Cookies and falls back to the legacy Cookies", () =>
605 run(
606 Effect.gen(function* () {
607 const context = yield* withSourceHome();
608 const profile = `${context.home}/Library/Application Support/net.imput.helium/Profile 1`;
609 assert.deepEqual(cookieDatabaseCandidatePaths(helium, context, "Profile 1"), [
610 `${profile}/Network/Cookies`,
611 `${profile}/Cookies`,
612 ]);
613 }),
614 ),
615 );
616
617 it.effect("resolves the live Network/ jar over a leftover root Cookies", () =>
618 run(
619 Effect.gen(function* () {
620 const fileSystem = yield* FileSystem.FileSystem;
621 const context = yield* withSourceHome();
622 const root = helium.userDataDirectory(context);
623 // Chromium 96+ keeps sessions in Network/; a root Cookies left behind
624 // by the move is stale and must not be the one imported.
625 yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
626 yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "live");
627 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "stale");
628
629 assert.equal(
630 yield* resolveCookieDatabase(helium, context, "Default"),
631 `${root}/Default/Network/Cookies`,
632 );
633 // A fresh install with only the Network/ jar is installed, not hidden.
634 yield* fileSystem.remove(`${root}/Default/Cookies`);
635 assert.isTrue(yield* isSourceInstalled(helium, context));
636 }),
637 ),
638 );
639
640 it.effect("returns only cookies.sqlite for Firefox", () =>
641 run(
642 Effect.gen(function* () {
643 const path = yield* Path.Path;
644 const context = yield* sourcePathContext.pipe(
645 Effect.provideService(HostProcessEnvironment, { HOME: "/tmp/test" }),
646 Effect.provideService(HostProcessPlatform, "darwin"),
647 );
648 const candidates = cookieDatabaseCandidatePaths(firefox, context, "Profiles/abc.default");
649 assert.deepEqual(candidates, [
650 path.join(
651 "/tmp/test",
652 "Library/Application Support/Firefox/Profiles/abc.default/cookies.sqlite",
653 ),
654 ]);
655 }),
656 ),
657 );
658});
659
660const firefox = BROWSER_IMPORT_SOURCES.find((source) => source.id === "firefox")!;
661
662describe("Firefox Snap profiles", () => {
663 it.effect("finds Snap profiles with or without profiles.ini and checks their locks", () =>
664 run(
665 Effect.gen(function* () {
666 const fileSystem = yield* FileSystem.FileSystem;
667 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-snap-" });
668 const context = yield* sourcePathContext.pipe(
669 Effect.provideService(HostProcessEnvironment, { HOME: home }),
670 Effect.provideService(HostProcessPlatform, "linux"),
671 );
672 const root = `${home}/snap/firefox/common/.mozilla/firefox`;
673 const directory = `${root}/abcd.default`;
674 yield* fileSystem.makeDirectory(directory, { recursive: true });
675 yield* writeFirefoxCookieDatabase(`${directory}/cookies.sqlite`, 2, 1);
676 yield* fileSystem.writeFileString(
677 `${root}/profiles.ini`,
678 "[Profile0]\nName=Personal\nIsRelative=1\nPath=abcd.default\n",
679 );
680
681 assert.isTrue(yield* isSourceInstalled(firefox, context));
682 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
683 { directory, name: "Personal", cookieCount: 2 },
684 ]);
685 assert.equal(
686 yield* resolveCookieDatabase(firefox, context, directory),
687 `${directory}/cookies.sqlite`,
688 );
689 assert.isFalse(yield* isSourceRunning(firefox, context));
690 yield* fileSystem.symlink("foreign-host:+4242", `${directory}/lock`);
691 assert.isTrue(yield* isSourceRunning(firefox, context));
692 yield* fileSystem.remove(`${directory}/lock`);
693 assert.isFalse(yield* isSourceRunning(firefox, context));
694
695 yield* fileSystem.remove(`${root}/profiles.ini`);
696 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
697 { directory, name: "abcd.default", cookieCount: 2 },
698 ]);
699 }),
700 ),
701 );
702
703 it.effect("keeps matching profile names in native and Snap installs distinct", () =>
704 run(
705 Effect.gen(function* () {
706 const fileSystem = yield* FileSystem.FileSystem;
707 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-snap-" });
708 const context = yield* sourcePathContext.pipe(
709 Effect.provideService(HostProcessEnvironment, { HOME: home }),
710 Effect.provideService(HostProcessPlatform, "linux"),
711 );
712 const native = `${home}/.mozilla/firefox`;
713 const snap = `${home}/snap/firefox/common/.mozilla/firefox`;
714 for (const root of [native, snap]) {
715 yield* fileSystem.makeDirectory(`${root}/abcd.default`, { recursive: true });
716 yield* writeFirefoxCookieDatabase(`${root}/abcd.default/cookies.sqlite`, 1, 0);
717 yield* fileSystem.writeFileString(
718 `${root}/profiles.ini`,
719 "[Profile0]\nName=Personal\nIsRelative=1\nPath=abcd.default\n" +
720 `[Profile1]\nName=Shared\nIsRelative=0\nPath=${snap}/abcd.default\n`,
721 );
722 }
723
724 const profiles = yield* listSourceProfiles(firefox, context);
725 assert.deepEqual(
726 profiles.map((profile) => profile.directory),
727 ["abcd.default", `${snap}/abcd.default`],
728 );
729 const databases = yield* Effect.forEach(profiles, (profile) =>
730 resolveCookieDatabase(firefox, context, profile.directory),
731 );
732 assert.deepEqual(databases, [
733 `${native}/abcd.default/cookies.sqlite`,
734 `${snap}/abcd.default/cookies.sqlite`,
735 ]);
736 }),
737 ),
738 );
739});
740
741describe("listSourceProfiles Firefox fallback", () => {
742 const cases = [
743 { platform: "linux" as const, profileDirectory: "linux.default" },
744 { platform: "darwin" as const, profileDirectory: "Profiles/macos.default" },
745 { platform: "win32" as const, profileDirectory: "Profiles/windows.default" },
746 ];
747
748 for (const { platform, profileDirectory } of cases) {
749 it.effect(`scans the ${platform} profile location and excludes stale entries`, () =>
750 run(
751 Effect.gen(function* () {
752 const fileSystem = yield* FileSystem.FileSystem;
753 const path = yield* Path.Path;
754 const home = yield* fileSystem.makeTempDirectoryScoped({
755 prefix: `t3code-firefox-${platform}-`,
756 });
757 const appData = path.join(home, "AppData", "Roaming");
758 const context = yield* sourcePathContext.pipe(
759 Effect.provideService(HostProcessEnvironment, {
760 HOME: home,
761 APPDATA: appData,
762 }),
763 Effect.provideService(HostProcessPlatform, platform),
764 );
765 const root = firefox.userDataDirectory(context)!;
766 const scanRoot = platform === "linux" ? root : path.join(root, "Profiles");
767 yield* fileSystem.makeDirectory(path.join(root, profileDirectory), { recursive: true });
768 yield* fileSystem.writeFileString(
769 path.join(root, profileDirectory, "cookies.sqlite"),
770 "db",
771 );
772 yield* fileSystem.makeDirectory(path.join(scanRoot, "stale.default"), {
773 recursive: true,
774 });
775 yield* fileSystem.writeFileString(path.join(scanRoot, "stale-file.default"), "not-dir");
776
777 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
778 {
779 directory: profileDirectory,
780 name: path.basename(profileDirectory),
781 },
782 ]);
783 }),
784 ),
785 );
786 }
787
788 it.effect("scans for profiles when profiles.ini declares only ones without cookies", () =>
789 run(
790 Effect.gen(function* () {
791 const fileSystem = yield* FileSystem.FileSystem;
792 const path = yield* Path.Path;
793 const home = yield* fileSystem.makeTempDirectoryScoped({
794 prefix: "t3code-firefox-stale-ini-",
795 });
796 const context = yield* sourcePathContext.pipe(
797 Effect.provideService(HostProcessEnvironment, { HOME: home }),
798 Effect.provideService(HostProcessPlatform, "darwin"),
799 );
800 const root = firefox.userDataDirectory(context)!;
801 // `profiles.ini` names a profile that was never launched (no cookie
802 // database), while the real cookies sit in an undeclared one.
803 yield* fileSystem.makeDirectory(path.join(root, "Profiles", "stale.default"), {
804 recursive: true,
805 });
806 const realDirectory = path.join(root, "Profiles", "real.default");
807 yield* fileSystem.makeDirectory(realDirectory, { recursive: true });
808 yield* writeFirefoxCookieDatabase(path.join(realDirectory, "cookies.sqlite"), 3, 0);
809 yield* fileSystem.writeFileString(
810 path.join(root, "profiles.ini"),
811 ["[Profile0]", "Name=Stale", "IsRelative=1", "Path=Profiles/stale.default"].join("\n"),
812 );
813
814 // Returning the empty declared list would hide the browser entirely.
815 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
816 { directory: "Profiles/real.default", name: "real.default", cookieCount: 3 },
817 ]);
818 assert.isTrue(yield* isSourceInstalled(firefox, context));
819 }),
820 ),
821 );
822
823 it.effect("counts only importable cookies for declared and fallback profiles", () =>
824 run(
825 Effect.gen(function* () {
826 const fileSystem = yield* FileSystem.FileSystem;
827 const path = yield* Path.Path;
828 const home = yield* fileSystem.makeTempDirectoryScoped({
829 prefix: "t3code-firefox-counts-",
830 });
831 const context = yield* sourcePathContext.pipe(
832 Effect.provideService(HostProcessEnvironment, { HOME: home }),
833 Effect.provideService(HostProcessPlatform, "darwin"),
834 );
835 const root = firefox.userDataDirectory(context)!;
836 const declaredDirectory = path.join(root, "Profiles", "declared.default");
837 yield* fileSystem.makeDirectory(declaredDirectory, { recursive: true });
838 yield* writeFirefoxCookieDatabase(path.join(declaredDirectory, "cookies.sqlite"), 2, 3);
839 yield* fileSystem.writeFileString(
840 path.join(root, "profiles.ini"),
841 ["[Profile0]", "Name=Declared", "IsRelative=1", "Path=Profiles/declared.default"].join(
842 "\n",
843 ),
844 );
845
846 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
847 { directory: "Profiles/declared.default", name: "Declared", cookieCount: 2 },
848 ]);
849
850 yield* fileSystem.remove(path.join(root, "profiles.ini"));
851 const fallbackDirectory = path.join(root, "Profiles", "fallback.default");
852 yield* fileSystem.makeDirectory(fallbackDirectory, { recursive: true });
853 yield* writeFirefoxCookieDatabase(path.join(fallbackDirectory, "cookies.sqlite"), 1, 4);
854
855 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
856 { directory: "Profiles/declared.default", name: "declared.default", cookieCount: 2 },
857 { directory: "Profiles/fallback.default", name: "fallback.default", cookieCount: 1 },
858 ]);
859 }),
860 ),
861 );
862});
863
864describe("isSourceRunning for Firefox", () => {
865 it.effect("finds the lock inside the profile, not at the root", () =>
866 run(
867 Effect.gen(function* () {
868 const fileSystem = yield* FileSystem.FileSystem;
869 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" });
870 const context = yield* sourcePathContext.pipe(
871 Effect.provideService(HostProcessEnvironment, { HOME: home }),
872 Effect.provideService(HostProcessPlatform, "darwin"),
873 );
874 const root = firefox.userDataDirectory(context)!;
875 const profile = `${root}/Profiles/abcd.default-release`;
876 yield* fileSystem.makeDirectory(profile, { recursive: true });
877 yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db");
878
879 assert.isFalse(yield* isSourceRunning(firefox, context));
880
881 // Firefox keeps its locks per profile. A root-level lock is not one,
882 // and looking there was why a running Firefox read as importable.
883 yield* fileSystem.writeFileString(`${root}/lock`, "");
884 assert.isFalse(yield* isSourceRunning(firefox, context));
885
886 // `.parentlock` is deliberately left on disk after a clean exit as a
887 // last-used marker, so an unlocked one is not evidence of a running
888 // browser — treating it as one blocked every import after first use.
889 yield* fileSystem.writeFileString(`${profile}/.parentlock`, "");
890 assert.isFalse(yield* isSourceRunning(firefox, context));
891
892 // The `lock` symlink is what Firefox removes on exit; a live pid in
893 // its target means the profile is held.
894 yield* fileSystem.symlink(`127.0.0.1:+${process.pid}`, `${profile}/lock`);
895 assert.isTrue(yield* isSourceRunning(firefox, context));
896 }),
897 ),
898 );
899
900 it.effect("reports not-held when no interpreter can run the fcntl probe", () =>
901 run(
902 Effect.gen(function* () {
903 const fileSystem = yield* FileSystem.FileSystem;
904 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-lock-" });
905 const lock = `${directory}/.parentlock`;
906 yield* fileSystem.writeFileString(lock, "");
907 // A Mac without the developer tools has only Apple's shim, which
908 // refuses to run the script; a machine with no python at all has
909 // nothing. Either way the probe is unavailable, not the lock held —
910 // treating it as held would block Firefox import on that machine for
911 // good.
912 assert.isFalse(yield* posixLockIsHeld(lock, ["/nonexistent/python3"]));
913 // And a fake "interpreter" that exits non-zero without a verdict, as
914 // the shim does, is the same case.
915 assert.isFalse(yield* posixLockIsHeld(lock, ["/usr/bin/false"]));
916 }),
917 ),
918 );
919
920 it.effect("detects a live fcntl lock on .parentlock, as macOS Firefox leaves it", () =>
921 run(
922 Effect.gen(function* () {
923 const fileSystem = yield* FileSystem.FileSystem;
924 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
925 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" });
926 const context = yield* sourcePathContext.pipe(
927 Effect.provideService(HostProcessEnvironment, { HOME: home }),
928 Effect.provideService(HostProcessPlatform, "darwin"),
929 );
930 const root = firefox.userDataDirectory(context)!;
931 const profile = `${root}/Profiles/abcd.default-release`;
932 yield* fileSystem.makeDirectory(profile, { recursive: true });
933 yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db");
934 const parentLock = `${profile}/.parentlock`;
935 yield* fileSystem.writeFileString(parentLock, "");
936
937 // Hold the lock from a child the way Firefox does (F_SETLK, write),
938 // and keep it until the scope closes.
939 const holder = yield* spawner.spawn(
940 ChildProcess.make(
941 "python3",
942 [
943 "-c",
944 "import fcntl,os,sys,time\n" +
945 "fd=os.open(sys.argv[1],os.O_WRONLY)\n" +
946 "fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)\n" +
947 "print('locked',flush=True)\n" +
948 "time.sleep(30)",
949 parentLock,
950 ],
951 { stdin: "ignore" },
952 ),
953 );
954 // Wait for the child to confirm it holds the lock before probing.
955 yield* holder.stdout.pipe(
956 Stream.decodeText(),
957 Stream.splitLines,
958 Stream.filter((line) => line.trim() === "locked"),
959 Stream.take(1),
960 Stream.runDrain,
961 );
962
963 assert.isTrue(yield* isSourceRunning(firefox, context));
964 yield* holder.kill();
965 }),
966 ),
967 );
968
969 it.effect("reads a Firefox lock symlink's pid to tell live from crashed", () =>
970 Effect.gen(function* () {
971 const alive = (pid: number) => Effect.succeed(pid === 4242);
972 // The resolver may hand Firefox any of the machine's addresses, not
973 // just 127.0.0.1 — 127.0.1.1 on Debian-style hosts, a LAN address
974 // elsewhere — so every local address counts as ours.
975 const local = new Set(["127.0.0.1", "127.0.1.1", "192.168.1.20"]);
976 // Both the plain and the fcntl-marked (`+`) forms carry the pid.
977 assert.isTrue(yield* firefoxSymlinkLockIsHeld("127.0.0.1:4242", local, alive));
978 assert.isTrue(yield* firefoxSymlinkLockIsHeld("127.0.1.1:+4242", local, alive));
979 assert.isTrue(yield* firefoxSymlinkLockIsHeld("192.168.1.20:+4242", local, alive));
980 // A crash leaves the symlink behind with a dead pid, on any local address.
981 assert.isFalse(yield* firefoxSymlinkLockIsHeld("127.0.0.1:+9999", local, alive));
982 assert.isFalse(yield* firefoxSymlinkLockIsHeld("192.168.1.20:+9999", local, alive));
983 // Anything unparseable stays conservative.
984 assert.isTrue(yield* firefoxSymlinkLockIsHeld("garbage", local, alive));
985 // A foreign owner (a shared profile locked from another machine) names
986 // a pid we cannot probe, so it is held regardless of local liveness.
987 assert.isTrue(yield* firefoxSymlinkLockIsHeld("10.0.0.7:+9999", local, alive));
988 }),
989 );
990
991 it.effect("does not treat a stale parent.lock file as a running browser", () =>
992 run(
993 Effect.gen(function* () {
994 const fileSystem = yield* FileSystem.FileSystem;
995 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" });
996 const context = yield* sourcePathContext.pipe(
997 // Firefox's win32 root hangs off %APPDATA%; without it the root is
998 // undefined and the fixture would escape the sandbox into the repo.
999 Effect.provideService(HostProcessEnvironment, {
1000 HOME: home,
1001 APPDATA: `${home}/AppData/Roaming`,
1002 }),
1003 Effect.provideService(HostProcessPlatform, "win32"),
1004 );
1005 const root = firefox.userDataDirectory(context)!;
1006 const profile = `${root}/Profiles/gx7x7fqx.default-release`;
1007 yield* fileSystem.makeDirectory(profile, { recursive: true });
1008 yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db");
1009
1010 // On Windows, Firefox creates parent.lock as a regular file that
1011 // persists after the process exits. The file is only locked while
1012 // Firefox is running; the old stat-based check always found it.
1013 yield* fileSystem.writeFileString(`${profile}/parent.lock`, "");
1014 assert.isFalse(yield* isSourceRunning(firefox, context));
1015 }),
1016 ),
1017 );
1018});
1019
1020describe("Windows user-data directories", () => {
1021 it.effect("keeps app-bound Chromium forks unsupported on win32", () =>
1022 Effect.sync(() => {
1023 // Helium retains the older DPAPI-backed store. Other Chromium forks use
1024 // App-Bound Encryption, so omitting win32 makes `unavailableReason`
1025 // report `unsupportedPlatform` and keeps them out of the menu.
1026 for (const source of BROWSER_IMPORT_SOURCES) {
1027 if (source.engine === "chromium" && source.id !== "helium") {
1028 assert.notInclude(source.platforms, "win32");
1029 }
1030 }
1031 }),
1032 );
1033});
1034
1035describe("listSourceProfiles hardening", () => {
1036 it.effect("drops profile directories that are not a single plain segment", () =>
1037 run(
1038 Effect.gen(function* () {
1039 const fileSystem = yield* FileSystem.FileSystem;
1040 const context = yield* withSourceHome();
1041 // `Local State` is writable by anything running as the user, so a
1042 // crafted key must not reach `cookieDatabasePath` and read a database
1043 // outside the browser's user-data directory.
1044 yield* fileSystem.writeFileString(
1045 `${userDataDirectory(context)}/Local State`,
1046 `{"profile":{"info_cache":{"Default":{"name":"You"},"../../../../secrets":{"name":"Escape"},"a/b":{"name":"Nested"},"..":{"name":"Parent"}}}}`,
1047 );
1048
1049 const profiles = yield* listSourceProfiles(helium, context);
1050
1051 assert.deepEqual(
1052 profiles.map((profile) => profile.directory),
1053 ["Default"],
1054 );
1055 }),
1056 ),
1057 );
1058});