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

Sources.test.ts

1,154 lines44.9 KB

1// @effect-diagnostics nodeBuiltinImport:off - Builds a Chromium-shaped cookie
2// table with the same native bindings the source reads.
3import * as NodePath from "node:path";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { assert, describe, it } from "@effect/vitest";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13import { ChildProcess, ChildProcessSpawner } from "effect/process";
14import * as NodeSqlite from "node:sqlite";
15​
16import type { BrowserImportPathContext } from "./Sources.ts";
17import {
18 BROWSER_IMPORT_SOURCES,
19 chromiumProcessIsAlive,
20 chromiumSingletonLockIsHeld,
21 cookieDatabaseCandidatePaths,
22 firefoxSymlinkLockIsHeld,
23 resolveCookieDatabase,
24 isSourceInstalled,
25 isSourceRunning,
26 isWindowsLockHeldError,
27 posixLockIsHeld,
28 listSourceProfiles,
29 sourcePathContext,
30 windowsChromiumCookiesAreHeld,
31} from "./Sources.ts";
32import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
33​
34const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!;
35​
36describe("Linux Chromium secret applications", () => {
37 it("pins the libsecret application attribute for each supported fork", () => {
38 assert.deepEqual(
39 Object.fromEntries(
40 BROWSER_IMPORT_SOURCES.filter((source) => source.platforms.includes("linux")).map(
41 (source) => [source.id, source.linuxSecretApplication],
42 ),
43 ),
44 {
45 chrome: "chrome",
46 edge: "msedge",
47 brave: "brave",
48 vivaldi: "vivaldi",
49 opera: "opera",
50 helium: "chromium",
51 firefox: undefined,
52 },
53 );
54 });
55});
56​
57const platformError = (reasonTag: string): PlatformError.PlatformError =>
58 ({ _tag: "PlatformError", reason: { _tag: reasonTag } }) as never;
59​
60describe("Windows browser lock errors", () => {
61 it("treats sharing and lock violations reported as Busy as held", () => {
62 assert.isTrue(isWindowsLockHeldError(platformError("Busy")));
63 });
64​
65 it("does not treat access denied as proof of an active lock", () => {
66 assert.isFalse(isWindowsLockHeldError(platformError("PermissionDenied")));
67 });
68​
69 it("does not treat a missing lock file as held", () => {
70 assert.isFalse(isWindowsLockHeldError(platformError("NotFound")));
71 });
72});
73​
74const withSourceHome = Effect.fnUntraced(function* () {
75 const fileSystem = yield* FileSystem.FileSystem;
76 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-sources-" });
77 const context = yield* sourcePathContext.pipe(
78 Effect.provideService(HostProcess.Environment, { HOME: home }),
79 Effect.provideService(HostProcess.Platform, "darwin"),
80 );
81 yield* fileSystem.makeDirectory(userDataDirectory(context), { recursive: true });
82 return context;
83});
84​
85const userDataDirectory = (context: BrowserImportPathContext) => {
86 const root = helium.userDataDirectory(context);
87 if (root === undefined) throw new Error("Helium has no macOS user-data directory");
88 return root;
89};
90​
91const run = <A, E>(
92 effect: Effect.Effect<
93 A,
94 E,
95 FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
96 >,
97) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
98​
99const writeCookieDatabase = (file: string, count: number) =>
100 Effect.sync(() => {
101 const database = new NodeSqlite.DatabaseSync(file);
102 database.exec("create table cookies (host_key text, name text)");
103 const insert = database.prepare("insert into cookies (host_key, name) values (?, ?)");
104 for (let index = 0; index < count; index += 1) insert.run("example.test", `c${index}`);
105 database.close();
106 });
107​
108const writeFirefoxCookieDatabase = (
109 file: string,
110 defaultContainerCount: number,
111 containerCount: number,
112) =>
113 Effect.sync(() => {
114 const database = new NodeSqlite.DatabaseSync(file);
115 database.exec("create table moz_cookies (originAttributes text not null)");
116 const insert = database.prepare("insert into moz_cookies (originAttributes) values (?)");
117 for (let index = 0; index < defaultContainerCount; index += 1) insert.run("");
118 for (let index = 0; index < containerCount; index += 1) insert.run("^userContextId=2");
119 database.close();
120 });
121​
122describe("Helium on Linux", () => {
123 it.effect.skipIf(!symlinksSupported)("discovers its profiles and checks the user-data lock", () =>
124 run(
125 Effect.gen(function* () {
126 const fileSystem = yield* FileSystem.FileSystem;
127 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-helium-linux-" });
128 const context = yield* sourcePathContext.pipe(
129 Effect.provideService(HostProcess.Environment, { HOME: home }),
130 Effect.provideService(HostProcess.Platform, "linux"),
131 );
132 const root = `${home}/.config/net.imput.helium`;
133 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
134 yield* writeCookieDatabase(`${root}/Default/Cookies`, 3);
135 yield* fileSystem.writeFileString(
136 `${root}/Local State`,
137 '{"profile":{"info_cache":{"Default":{"name":"Personal"}}}}',
138 );
139​
140 assert.include(helium.platforms, "linux");
141 assert.isTrue(yield* isSourceInstalled(helium, context));
142 assert.deepEqual(yield* listSourceProfiles(helium, context), [
143 { directory: "Default", name: "Personal", cookieCount: 3 },
144 ]);
145 assert.isFalse(yield* isSourceRunning(helium, context));
146 yield* fileSystem.symlink("foreign-host-4242", `${root}/SingletonLock`);
147 assert.isTrue(yield* isSourceRunning(helium, context));
148 }),
149 ),
150 );
151});
152​
153describe("Helium on Windows", () => {
154 it.effect("uses Helium's local app-data profile while other Chromium forks stay disabled", () =>
155 run(
156 Effect.gen(function* () {
157 const context = yield* sourcePathContext.pipe(
158 Effect.provideService(HostProcess.Environment, {
159 USERPROFILE: "C:\\Users\\browser-user",
160 LOCALAPPDATA: "C:\\Users\\browser-user\\AppData\\Local",
161 }),
162 Effect.provideService(HostProcess.Platform, "win32"),
163 );
164​
165 assert.include(helium.platforms, "win32");
166 assert.equal(
167 helium.userDataDirectory(context),
168 context.path.join(
169 "C:\\Users\\browser-user\\AppData\\Local",
170 "imput",
171 "Helium",
172 "User Data",
173 ),
174 );
175 for (const source of BROWSER_IMPORT_SOURCES) {
176 if (source.engine === "chromium" && source.id !== "helium") {
177 assert.notInclude(source.platforms, "win32");
178 }
179 }
180 }),
181 ),
182 );
183});
184​
185describe("isSourceRunning", () => {
186 it.effect("uses the held cookie database as Chromium's Windows running signal", () =>
187 run(
188 Effect.gen(function* () {
189 const fileSystem = yield* FileSystem.FileSystem;
190 const home = yield* fileSystem.makeTempDirectoryScoped({
191 prefix: "t3code-helium-windows-lock-",
192 });
193 const context = yield* sourcePathContext.pipe(
194 Effect.provideService(HostProcess.Environment, {
195 HOME: home,
196 LOCALAPPDATA: home,
197 }),
198 Effect.provideService(HostProcess.Platform, "win32"),
199 );
200 const profile = context.path.join(helium.userDataDirectory(context)!, "Default");
201 const database = context.path.join(profile, "Network", "Cookies");
202 yield* fileSystem.makeDirectory(context.path.join(profile, "Network"), { recursive: true });
203 yield* writeCookieDatabase(database, 1);
204​
205 const probed: string[] = [];
206 assert.isTrue(
207 yield* windowsChromiumCookiesAreHeld(helium, context, (path) =>
208 Effect.sync(() => {
209 probed.push(path);
210 return true;
211 }),
212 ),
213 );
214 assert.deepEqual(probed, [database]);
215 }),
216 ),
217 );
218​
219 it.effect.skipIf(!symlinksSupported)(
220 "reads Chromium's dangling SingletonLock symlink as a running browser",
221 () =>
222 run(
223 Effect.gen(function* () {
224 const fileSystem = yield* FileSystem.FileSystem;
225 const context = yield* withSourceHome();
226 assert.isFalse(yield* isSourceRunning(helium, context));
227​
228 // Chromium points the lock at `<host>-<pid>`, a target that never
229 // exists on disk. A check that follows the link reports a running
230 // browser as closed, letting an import read a live, mid-write database.
231 yield* fileSystem.symlink(
232 "host-that-does-not-exist-1234",
233 `${userDataDirectory(context)}/SingletonLock`,
234 );
235​
236 assert.isTrue(yield* isSourceRunning(helium, context));
237 }),
238 ),
239 );
240​
241 it.effect.skipIf(!symlinksSupported)(
242 "uses the provided hostname to classify Chromium locks",
243 () =>
244 run(
245 Effect.gen(function* () {
246 const fileSystem = yield* FileSystem.FileSystem;
247 const paths = yield* withSourceHome();
248 yield* fileSystem.symlink(
249 "lock-owner-99999999",
250 `${helium.userDataDirectory(paths)}/SingletonLock`,
251 );
252​
253 assert.isTrue(
254 yield* isSourceRunning(helium, paths).pipe(
255 Effect.provideService(HostProcess.Hostname, "another-host"),
256 ),
257 );
258 assert.isFalse(
259 yield* isSourceRunning(helium, paths).pipe(
260 Effect.provideService(HostProcess.Hostname, "lock-owner"),
261 ),
262 );
263 }),
264 ),
265 );
266});
267​
268describe("chromiumSingletonLockIsHeld", () => {
269 it.effect("ignores a positively dead PID on the current host", () =>
270 Effect.gen(function* () {
271 const checked: number[] = [];
272 const held = yield* chromiumSingletonLockIsHeld("current-host-4321", "current-host", (pid) =>
273 Effect.sync(() => {
274 checked.push(pid);
275 return false;
276 }),
277 );
278 assert.isFalse(held);
279 assert.deepEqual(checked, [4321]);
280 }),
281 );
282​
283 it.effect("keeps a live PID on the current host", () =>
284 chromiumSingletonLockIsHeld("current-host-4321", "current-host", () =>
285 Effect.succeed(true),
286 ).pipe(Effect.tap((held) => Effect.sync(() => assert.isTrue(held)))),
287 );
288​
289 it.effect("keeps foreign-host and malformed targets without probing a PID", () =>
290 Effect.gen(function* () {
291 let probes = 0;
292 const probe = (_pid: number) =>
293 Effect.sync(() => {
294 probes += 1;
295 return false;
296 });
297 assert.isTrue(yield* chromiumSingletonLockIsHeld("another-host-4321", "current-host", probe));
298 assert.isTrue(
299 yield* chromiumSingletonLockIsHeld("current-host-no-pid", "current-host", probe),
300 );
301 assert.isTrue(yield* chromiumSingletonLockIsHeld("current-host-0", "current-host", probe));
302 assert.strictEqual(probes, 0);
303 }),
304 );
305});
306​
307describe("chromiumProcessIsAlive", () => {
308 it.effect("returns false only when signal 0 reports a missing process", () =>
309 Effect.gen(function* () {
310 const missing = Object.assign(new Error("missing"), { code: "ESRCH" });
311 const denied = Object.assign(new Error("denied"), { code: "EPERM" });
312 assert.isFalse(
313 yield* chromiumProcessIsAlive(4321, () => {
314 throw missing;
315 }),
316 );
317 assert.isTrue(
318 yield* chromiumProcessIsAlive(4321, () => {
319 throw denied;
320 }),
321 );
322 assert.isTrue(
323 yield* chromiumProcessIsAlive(4321, () => {
324 throw undefined;
325 }),
326 );
327 assert.isTrue(
328 yield* chromiumProcessIsAlive(4321, () => {
329 throw "unknown failure";
330 }),
331 );
332 assert.isTrue(
333 yield* chromiumProcessIsAlive(4321, () => {
334 throw null;
335 }),
336 );
337 assert.isTrue(yield* chromiumProcessIsAlive(4321, () => true));
338 }),
339 );
340});
341​
342describe("isSourceInstalled", () => {
343 it.effect("ignores a user-data directory that holds no cookie database", () =>
344 run(
345 Effect.gen(function* () {
346 const fileSystem = yield* FileSystem.FileSystem;
347 const context = yield* withSourceHome();
348 const root = userDataDirectory(context);
349​
350 // Installers for native messaging hosts create an empty user-data
351 // directory for every Chromium fork they know about, so treating the
352 // directory as evidence lists browsers the user does not have.
353 yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true });
354 assert.isFalse(yield* isSourceInstalled(helium, context));
355​
356 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
357 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
358 assert.isTrue(yield* isSourceInstalled(helium, context));
359​
360 yield* fileSystem.remove(`${root}/Default`, { recursive: true });
361 yield* fileSystem.makeDirectory(`${root}/Profile 1`, { recursive: true });
362 yield* fileSystem.writeFileString(`${root}/Profile 1/Cookies`, "db");
363 assert.isTrue(yield* isSourceInstalled(helium, context));
364​
365 yield* fileSystem.remove(root, { recursive: true });
366 assert.isFalse(yield* isSourceInstalled(helium, context));
367 }),
368 ),
369 );
370​
371 it.effect("detects a Chromium 127+ install with cookies under Network/", () =>
372 run(
373 Effect.gen(function* () {
374 const fileSystem = yield* FileSystem.FileSystem;
375 const context = yield* withSourceHome();
376 const root = userDataDirectory(context);
377​
378 yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
379 yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "db");
380 assert.isTrue(yield* isSourceInstalled(helium, context));
381 }),
382 ),
383 );
384​
385 it.effect.skipIf(!symlinksSupported)(
386 "follows cookie database symlinks when detecting profiles",
387 () =>
388 run(
389 Effect.gen(function* () {
390 const fileSystem = yield* FileSystem.FileSystem;
391 const context = yield* withSourceHome();
392 const root = userDataDirectory(context);
393 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
394 yield* fileSystem.symlink("missing-cookies", `${root}/Default/Cookies`);
395​
396 assert.deepEqual(yield* listSourceProfiles(helium, context), []);
397 assert.isFalse(yield* isSourceInstalled(helium, context));
398​
399 yield* fileSystem.writeFileString(`${root}/Default/missing-cookies`, "db");
400 assert.deepEqual(yield* listSourceProfiles(helium, context), [
401 { directory: "Default", name: "Default" },
402 ]);
403 assert.isTrue(yield* isSourceInstalled(helium, context));
404 }),
405 ),
406 );
407});
408​
409describe("listSourceProfiles", () => {
410 it.effect("ignores a profile whose Cookies entry is not a file", () =>
411 run(
412 Effect.gen(function* () {
413 const fileSystem = yield* FileSystem.FileSystem;
414 const paths = yield* withSourceHome();
415 const root = helium.userDataDirectory(paths);
416 yield* fileSystem.makeDirectory(`${root}/Broken/Cookies`, { recursive: true });
417 yield* fileSystem.makeDirectory(`${root}/Real`, { recursive: true });
418 yield* fileSystem.writeFileString(`${root}/Real/Cookies`, "db");
419​
420 assert.deepEqual(yield* listSourceProfiles(helium, paths), [
421 { directory: "Real", name: "Real" },
422 ]);
423 assert.isTrue(yield* isSourceInstalled(helium, paths));
424 }),
425 ),
426 );
427​
428 it.effect("discovers profiles by their cookie database when Local State is absent", () =>
429 run(
430 Effect.gen(function* () {
431 const fileSystem = yield* FileSystem.FileSystem;
432 const context = yield* withSourceHome();
433 const root = userDataDirectory(context);
434 yield* fileSystem.makeDirectory(`${root}/Profile 1`, { recursive: true });
435 yield* fileSystem.writeFileString(`${root}/Profile 1/Cookies`, "db");
436 yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true });
437​
438 assert.deepEqual(yield* listSourceProfiles(helium, context), [
439 { directory: "Profile 1", name: "Profile 1" },
440 ]);
441 }),
442 ),
443 );
444​
445 it.effect("reads the profile names the browser shows", () =>
446 run(
447 Effect.gen(function* () {
448 const fileSystem = yield* FileSystem.FileSystem;
449 const context = yield* withSourceHome();
450 yield* fileSystem.writeFileString(
451 `${userDataDirectory(context)}/Local State`,
452 `{"profile":{"info_cache":{"Default":{"name":"You"},"Profile 2":{"name":" "}}}}`,
453 );
454​
455 assert.deepEqual(yield* listSourceProfiles(helium, context), [
456 { directory: "Default", name: "You" },
457 { directory: "Profile 2", name: "Profile 2" },
458 ]);
459 }),
460 ),
461 );
462​
463 it.effect("scans for profiles when Local State is malformed", () =>
464 run(
465 Effect.gen(function* () {
466 const fileSystem = yield* FileSystem.FileSystem;
467 const context = yield* withSourceHome();
468 const root = userDataDirectory(context);
469 yield* fileSystem.writeFileString(`${root}/Local State`, "{not-json");
470 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
471 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
472​
473 assert.deepEqual(yield* listSourceProfiles(helium, context), [
474 { directory: "Default", name: "Default" },
475 ]);
476 }),
477 ),
478 );
479​
480 it.effect("reports nothing when no directory holds a cookie database", () =>
481 run(
482 Effect.gen(function* () {
483 const context = yield* withSourceHome();
484 assert.deepEqual(yield* listSourceProfiles(helium, context), []);
485 }),
486 ),
487 );
488​
489 it.effect("drops Firefox profiles that hold no cookie database", () =>
490 run(
491 Effect.gen(function* () {
492 const fileSystem = yield* FileSystem.FileSystem;
493 const context = yield* withSourceHome();
494 const root = firefox.userDataDirectory(context)!;
495 yield* fileSystem.makeDirectory(root, { recursive: true });
496 yield* fileSystem.writeFileString(
497 `${root}/profiles.ini`,
498 `[Profile0]
499Name=original
500IsRelative=1
501Path=Profiles/abcd.default-release
502Default=1
503​
504[Profile1]
505Name=empty
506IsRelative=1
507Path=Profiles/wxyz.empty
508`,
509 );
510 yield* fileSystem.makeDirectory(`${root}/Profiles/abcd.default-release`, {
511 recursive: true,
512 });
513 yield* fileSystem.writeFileString(
514 `${root}/Profiles/abcd.default-release/cookies.sqlite`,
515 "db",
516 );
517 yield* fileSystem.makeDirectory(`${root}/Profiles/wxyz.empty`, { recursive: true });
518​
519 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
520 { directory: context.path.join("Profiles", "abcd.default-release"), name: "original" },
521 ]);
522 }),
523 ),
524 );
525​
526 it.effect("drops empty profiles when falling back to the Profiles/ scan", () =>
527 run(
528 Effect.gen(function* () {
529 const fileSystem = yield* FileSystem.FileSystem;
530 const context = yield* withSourceHome();
531 const root = firefox.userDataDirectory(context)!;
532 yield* fileSystem.makeDirectory(`${root}/Profiles/filled.default`, { recursive: true });
533 yield* fileSystem.writeFileString(`${root}/Profiles/filled.default/cookies.sqlite`, "db");
534 yield* fileSystem.makeDirectory(`${root}/Profiles/empty.default`, { recursive: true });
535​
536 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
537 {
538 directory: context.path.join("Profiles", "filled.default"),
539 name: "filled.default",
540 },
541 ]);
542 }),
543 ),
544 );
545​
546 it.effect("discovers profiles with cookies under Network/ (Chromium 127+)", () =>
547 run(
548 Effect.gen(function* () {
549 const fileSystem = yield* FileSystem.FileSystem;
550 const context = yield* withSourceHome();
551 const root = userDataDirectory(context);
552 yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
553 yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "db");
554​
555 assert.deepEqual(yield* listSourceProfiles(helium, context), [
556 { directory: "Default", name: "Default" },
557 ]);
558 }),
559 ),
560 );
561​
562 it.effect("counts a profile's cookies without decrypting them", () =>
563 run(
564 Effect.gen(function* () {
565 const fileSystem = yield* FileSystem.FileSystem;
566 const paths = yield* withSourceHome();
567 const root = helium.userDataDirectory(paths);
568 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
569 yield* writeCookieDatabase(`${root}/Default/Cookies`, 3);
570​
571 const [profile] = yield* listSourceProfiles(helium, paths);
572 assert.equal(profile?.cookieCount, 3);
573 }),
574 ),
575 );
576​
577 it.effect("falls through to the legacy database when Network/Cookies is a directory", () =>
578 run(
579 Effect.gen(function* () {
580 const fileSystem = yield* FileSystem.FileSystem;
581 const paths = yield* withSourceHome();
582 const root = helium.userDataDirectory(paths);
583 yield* fileSystem.makeDirectory(`${root}/Default/Network/Cookies`, { recursive: true });
584 yield* writeCookieDatabase(`${root}/Default/Cookies`, 2);
585​
586 const [profile] = yield* listSourceProfiles(helium, paths);
587 assert.equal(profile?.directory, "Default");
588 assert.equal(profile?.cookieCount, 2);
589 }),
590 ),
591 );
592});
593​
594describe("cookieDatabaseCandidatePaths", () => {
595 it.effect("prefers Network/Cookies and falls back to the legacy Cookies", () =>
596 run(
597 Effect.gen(function* () {
598 const context = yield* withSourceHome();
599 const profile = context.path.join(
600 context.home,
601 "Library",
602 "Application Support",
603 "net.imput.helium",
604 "Profile 1",
605 );
606 assert.deepEqual(cookieDatabaseCandidatePaths(helium, context, "Profile 1"), [
607 context.path.join(profile, "Network", "Cookies"),
608 context.path.join(profile, "Cookies"),
609 ]);
610 }),
611 ),
612 );
613​
614 it.effect("resolves the live Network/ jar over a leftover root Cookies", () =>
615 run(
616 Effect.gen(function* () {
617 const fileSystem = yield* FileSystem.FileSystem;
618 const context = yield* withSourceHome();
619 const root = userDataDirectory(context);
620 // Chromium 96+ keeps sessions in Network/; a root Cookies left behind
621 // by the move is stale and must not be the one imported.
622 yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
623 yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "live");
624 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "stale");
625​
626 assert.equal(
627 yield* resolveCookieDatabase(helium, context, "Default"),
628 context.path.join(root, "Default", "Network", "Cookies"),
629 );
630 yield* fileSystem.remove(`${root}/Default/Cookies`);
631 assert.isTrue(yield* isSourceInstalled(helium, context));
632 }),
633 ),
634 );
635​
636 it.effect("returns only cookies.sqlite for Firefox", () =>
637 run(
638 Effect.gen(function* () {
639 const path = yield* Path.Path;
640 const context = yield* sourcePathContext.pipe(
641 Effect.provideService(HostProcess.Environment, { HOME: "/tmp/test" }),
642 Effect.provideService(HostProcess.Platform, "darwin"),
643 );
644 const candidates = cookieDatabaseCandidatePaths(firefox, context, "Profiles/abc.default");
645 assert.deepEqual(candidates, [
646 path.join(
647 "/tmp/test",
648 "Library/Application Support/Firefox/Profiles/abc.default/cookies.sqlite",
649 ),
650 ]);
651 }),
652 ),
653 );
654});
655​
656const firefox = BROWSER_IMPORT_SOURCES.find((source) => source.id === "firefox")!;
657​
658describe("Firefox Snap profiles", () => {
659 it.effect.skipIf(!symlinksSupported)(
660 "finds Snap profiles with or without profiles.ini and checks their locks",
661 () =>
662 run(
663 Effect.gen(function* () {
664 const fileSystem = yield* FileSystem.FileSystem;
665 const home = yield* fileSystem.makeTempDirectoryScoped({
666 prefix: "t3code-firefox-snap-",
667 });
668 const context = yield* sourcePathContext.pipe(
669 Effect.provideService(HostProcess.Environment, { HOME: home }),
670 Effect.provideService(HostProcess.Platform, "linux"),
671 );
672 const root = context.path.join(home, "snap", "firefox", "common", ".mozilla", "firefox");
673 const directory = context.path.join(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 context.path.join(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(HostProcess.Environment, { HOME: home }),
710 Effect.provideService(HostProcess.Platform, "linux"),
711 );
712 const native = context.path.join(home, ".mozilla", "firefox");
713 const snap = context.path.join(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", context.path.join(snap, "abcd.default")],
728 );
729 const databases = yield* Effect.forEach(profiles, (profile) =>
730 resolveCookieDatabase(firefox, context, profile.directory),
731 );
732 assert.deepEqual(databases, [
733 context.path.join(native, "abcd.default", "cookies.sqlite"),
734 context.path.join(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: NodePath.join("Profiles", "macos.default") },
745 { platform: "win32" as const, profileDirectory: NodePath.join("Profiles", "windows.default") },
746 ];
747​
748 it.effect.each(cases)(
749 "scans the $platform profile location and excludes stale entries",
750 ({ platform, profileDirectory }) =>
751 run(
752 Effect.gen(function* () {
753 const fileSystem = yield* FileSystem.FileSystem;
754 const path = yield* Path.Path;
755 const home = yield* fileSystem.makeTempDirectoryScoped({
756 prefix: `t3code-firefox-${platform}-`,
757 });
758 const appData = path.join(home, "AppData", "Roaming");
759 const context = yield* sourcePathContext.pipe(
760 Effect.provideService(HostProcess.Environment, {
761 HOME: home,
762 APPDATA: appData,
763 }),
764 Effect.provideService(HostProcess.Platform, platform),
765 );
766 const root = firefox.userDataDirectory(context)!;
767 const scanRoot = platform === "linux" ? root : path.join(root, "Profiles");
768 yield* fileSystem.makeDirectory(path.join(root, profileDirectory), { recursive: true });
769 yield* fileSystem.writeFileString(
770 path.join(root, profileDirectory, "cookies.sqlite"),
771 "db",
772 );
773 yield* fileSystem.makeDirectory(path.join(scanRoot, "stale.default"), {
774 recursive: true,
775 });
776 yield* fileSystem.writeFileString(path.join(scanRoot, "stale-file.default"), "not-dir");
777​
778 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
779 {
780 directory: profileDirectory,
781 name: path.basename(profileDirectory),
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(HostProcess.Environment, { HOME: home }),
798 Effect.provideService(HostProcess.Platform, "darwin"),
799 );
800 const root = firefox.userDataDirectory(context)!;
801 yield* fileSystem.makeDirectory(path.join(root, "Profiles", "stale.default"), {
802 recursive: true,
803 });
804 const realDirectory = path.join(root, "Profiles", "real.default");
805 yield* fileSystem.makeDirectory(realDirectory, { recursive: true });
806 yield* writeFirefoxCookieDatabase(path.join(realDirectory, "cookies.sqlite"), 3, 0);
807 yield* fileSystem.writeFileString(
808 path.join(root, "profiles.ini"),
809 ["[Profile0]", "Name=Stale", "IsRelative=1", "Path=Profiles/stale.default"].join("\n"),
810 );
811​
812 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
813 {
814 directory: path.join("Profiles", "real.default"),
815 name: "real.default",
816 cookieCount: 3,
817 },
818 ]);
819 assert.isTrue(yield* isSourceInstalled(firefox, context));
820 }),
821 ),
822 );
823​
824 it.effect("counts only importable cookies for declared and fallback profiles", () =>
825 run(
826 Effect.gen(function* () {
827 const fileSystem = yield* FileSystem.FileSystem;
828 const path = yield* Path.Path;
829 const home = yield* fileSystem.makeTempDirectoryScoped({
830 prefix: "t3code-firefox-counts-",
831 });
832 const context = yield* sourcePathContext.pipe(
833 Effect.provideService(HostProcess.Environment, { HOME: home }),
834 Effect.provideService(HostProcess.Platform, "darwin"),
835 );
836 const root = firefox.userDataDirectory(context)!;
837 const declaredDirectory = path.join(root, "Profiles", "declared.default");
838 yield* fileSystem.makeDirectory(declaredDirectory, { recursive: true });
839 yield* writeFirefoxCookieDatabase(path.join(declaredDirectory, "cookies.sqlite"), 2, 3);
840 yield* fileSystem.writeFileString(
841 path.join(root, "profiles.ini"),
842 ["[Profile0]", "Name=Declared", "IsRelative=1", "Path=Profiles/declared.default"].join(
843 "\n",
844 ),
845 );
846​
847 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
848 {
849 directory: path.join("Profiles", "declared.default"),
850 name: "Declared",
851 cookieCount: 2,
852 },
853 ]);
854​
855 yield* fileSystem.remove(path.join(root, "profiles.ini"));
856 const fallbackDirectory = path.join(root, "Profiles", "fallback.default");
857 yield* fileSystem.makeDirectory(fallbackDirectory, { recursive: true });
858 yield* writeFirefoxCookieDatabase(path.join(fallbackDirectory, "cookies.sqlite"), 1, 4);
859​
860 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
861 {
862 directory: path.join("Profiles", "declared.default"),
863 name: "declared.default",
864 cookieCount: 2,
865 },
866 {
867 directory: path.join("Profiles", "fallback.default"),
868 name: "fallback.default",
869 cookieCount: 1,
870 },
871 ]);
872 }),
873 ),
874 );
875});
876​
877describe("isSourceRunning for Firefox", () => {
878 it.effect.skipIf(!symlinksSupported)("finds the lock inside the profile, not at the root", () =>
879 run(
880 Effect.gen(function* () {
881 const fileSystem = yield* FileSystem.FileSystem;
882 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" });
883 const context = yield* sourcePathContext.pipe(
884 Effect.provideService(HostProcess.Environment, { HOME: home }),
885 Effect.provideService(HostProcess.Platform, "darwin"),
886 );
887 const root = firefox.userDataDirectory(context)!;
888 const profile = `${root}/Profiles/abcd.default-release`;
889 yield* fileSystem.makeDirectory(profile, { recursive: true });
890 yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db");
891​
892 assert.isFalse(yield* isSourceRunning(firefox, context));
893​
894 yield* fileSystem.writeFileString(`${root}/lock`, "");
895 assert.isFalse(yield* isSourceRunning(firefox, context));
896​
897 // `.parentlock` is deliberately left on disk after a clean exit as a
898 // last-used marker, so an unlocked one is not evidence of a running
899 // browser — treating it as one blocked every import after first use.
900 yield* fileSystem.writeFileString(`${profile}/.parentlock`, "");
901 assert.isFalse(yield* isSourceRunning(firefox, context));
902​
903 // The `lock` symlink is what Firefox removes on exit; a live pid in
904 // its target means the profile is held.
905 yield* fileSystem.symlink(`127.0.0.1:+${process.pid}`, `${profile}/lock`);
906 assert.isTrue(yield* isSourceRunning(firefox, context));
907 }),
908 ),
909 );
910​
911 it.effect("reports not-held when no interpreter can run the fcntl probe", () =>
912 run(
913 Effect.gen(function* () {
914 const fileSystem = yield* FileSystem.FileSystem;
915 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-lock-" });
916 const lock = `${directory}/.parentlock`;
917 yield* fileSystem.writeFileString(lock, "");
918 assert.isFalse(yield* posixLockIsHeld(lock, ["/nonexistent/python3"]));
919 assert.isFalse(yield* posixLockIsHeld(lock, ["/usr/bin/false"]));
920 }),
921 ),
922 );
923​
924 // Holds the lock with python3's fcntl, which does not exist on Windows.
925 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
926 "detects a live fcntl lock on .parentlock, as macOS Firefox leaves it",
927 () =>
928 run(
929 Effect.gen(function* () {
930 const fileSystem = yield* FileSystem.FileSystem;
931 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
932 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" });
933 const context = yield* sourcePathContext.pipe(
934 Effect.provideService(HostProcess.Environment, { HOME: home }),
935 Effect.provideService(HostProcess.Platform, "darwin"),
936 );
937 const root = firefox.userDataDirectory(context)!;
938 const profile = `${root}/Profiles/abcd.default-release`;
939 yield* fileSystem.makeDirectory(profile, { recursive: true });
940 yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db");
941 const parentLock = `${profile}/.parentlock`;
942 yield* fileSystem.writeFileString(parentLock, "");
943​
944 const holder = yield* spawner.spawn(
945 ChildProcess.make(
946 "python3",
947 [
948 "-c",
949 "import fcntl,os,sys,time\n" +
950 "fd=os.open(sys.argv[1],os.O_WRONLY)\n" +
951 "fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)\n" +
952 "print('locked',flush=True)\n" +
953 "time.sleep(30)",
954 parentLock,
955 ],
956 { stdin: "ignore" },
957 ),
958 );
959 yield* holder.stdout.pipe(
960 Stream.decodeText(),
961 Stream.splitLines,
962 Stream.filter((line) => line.trim() === "locked"),
963 Stream.take(1),
964 Stream.runDrain,
965 );
966​
967 assert.isTrue(yield* isSourceRunning(firefox, context));
968 yield* holder.kill();
969 }),
970 ),
971 );
972​
973 it.effect("reads a Firefox lock symlink's pid to tell live from crashed", () =>
974 Effect.gen(function* () {
975 const alive = (pid: number) => Effect.succeed(pid === 4242);
976 // The resolver may hand Firefox any of the machine's addresses, not
977 // just 127.0.0.1 — 127.0.1.1 on Debian-style hosts, a LAN address
978 // elsewhere — so every local address counts as ours.
979 const local = new Set(["127.0.0.1", "127.0.1.1", "192.168.1.20"]);
980 // Both the plain and the fcntl-marked (`+`) forms carry the pid.
981 assert.isTrue(yield* firefoxSymlinkLockIsHeld("127.0.0.1:4242", local, alive));
982 assert.isTrue(yield* firefoxSymlinkLockIsHeld("127.0.1.1:+4242", local, alive));
983 assert.isTrue(yield* firefoxSymlinkLockIsHeld("192.168.1.20:+4242", local, alive));
984 assert.isFalse(yield* firefoxSymlinkLockIsHeld("127.0.0.1:+9999", local, alive));
985 assert.isFalse(yield* firefoxSymlinkLockIsHeld("192.168.1.20:+9999", local, alive));
986 assert.isTrue(yield* firefoxSymlinkLockIsHeld("garbage", local, alive));
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(HostProcess.Environment, {
1000 HOME: home,
1001 APPDATA: `${home}/AppData/Roaming`,
1002 }),
1003 Effect.provideService(HostProcess.Platform, "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.
1012 yield* fileSystem.writeFileString(`${profile}/parent.lock`, "");
1013 assert.isFalse(yield* isSourceRunning(firefox, context));
1014 }),
1015 ),
1016 );
1017});
1018​
1019describe("Windows user-data directories", () => {
1020 it.effect("keeps app-bound Chromium forks unsupported on win32", () =>
1021 Effect.sync(() => {
1022 for (const source of BROWSER_IMPORT_SOURCES) {
1023 if (source.engine === "chromium" && source.id !== "helium") {
1024 assert.notInclude(source.platforms, "win32");
1027 }),
1028 );
1029});
1030​
1031describe("listSourceProfiles hardening", () => {
1032 it.effect("drops profile directories that are not a single plain segment", () =>
1033 run(
1034 Effect.gen(function* () {
1035 const fileSystem = yield* FileSystem.FileSystem;
1036 const context = yield* withSourceHome();
1037 yield* fileSystem.writeFileString(
1038 `${userDataDirectory(context)}/Local State`,
1039 `{"profile":{"info_cache":{"Default":{"name":"You"},"../../../../secrets":{"name":"Escape"},"a/b":{"name":"Nested"},"..":{"name":"Parent"}}}}`,
1040 );
1041​
1042 const profiles = yield* listSourceProfiles(helium, context);
1043​
1044 assert.deepEqual(
1045 profiles.map((profile) => profile.directory),
1046 ["Default"],
1047 );
1048 }),
1049 ),
1050 );
1051});
1052​
1053describe("Safari profiles", () => {
1054 const safari = BROWSER_IMPORT_SOURCES.find((source) => source.id === "safari")!;
1055 const workUuid = "C561D071-67AD-4537-866F-54F65FB8E8DD";
1056 const otherUuid = "2875EB19-B938-4E38-BE92-5AE97C256BDD";
1057​
1058 const fixture = Effect.fnUntraced(function* () {
1059 const context = yield* withSourceHome();
1060 const fileSystem = yield* FileSystem.FileSystem;
1061 const root = safari.userDataDirectory(context)!;
1062 const library = context.path.dirname(root);
1063 yield* fileSystem.makeDirectory(root, { recursive: true });
1064 yield* fileSystem.writeFileString(context.path.join(root, "Cookies.binarycookies"), "default");
1065 const store = (uuid: string) =>
1066 context.path.join(library, "WebKit", "WebsiteDataStore", uuid.toLowerCase(), "Cookies");
1067 for (const uuid of [workUuid, otherUuid]) {
1068 yield* fileSystem.makeDirectory(store(uuid), { recursive: true });
1069 yield* fileSystem.writeFileString(
1070 context.path.join(store(uuid), "Cookies.binarycookies"),
1071 uuid,
1072 );
1074 yield* fileSystem.makeDirectory(context.path.join(library, "Safari"), { recursive: true });
1075 const metadata = context.path.join(library, "Safari", "SafariTabs.db");
1076 return { context, root, store, metadata };
1077 });
1078​
1079 it.effect("discovers named profiles and resolves only the selected profile's cookies", () =>
1080 run(
1081 Effect.gen(function* () {
1082 const { context, root, store, metadata } = yield* fixture();
1083 yield* Effect.sync(() => {
1084 const database = new NodeSqlite.DatabaseSync(metadata);
1085 try {
1086 database.exec(`CREATE TABLE bookmarks (
1087 title TEXT, external_uuid TEXT, parent INTEGER DEFAULT 0,
1088 type INTEGER DEFAULT 1, subtype INTEGER DEFAULT 2,
1089 deleted INTEGER DEFAULT 0, order_index INTEGER DEFAULT 0
1090 )`);
1091 const insert = database.prepare(
1092 "INSERT INTO bookmarks (title, external_uuid, deleted) VALUES (?, ?, ?)",
1093 );
1094 insert.run("", "DefaultProfile", 0);
1095 insert.run("Ping", workUuid, 0);
1096 insert.run("Deleted", otherUuid, 1);
1097 insert.run("Unsafe", "../../outside", 0);
1098 database.exec(
1099 "INSERT INTO bookmarks (title, external_uuid, subtype) VALUES ('Tab group', 'group', 1)",
1100 );
1101 } finally {
1102 database.close();
1104 });
1105 const profiles = yield* listSourceProfiles(safari, context);
1106 assert.deepEqual(profiles, [
1107 { directory: ".", name: "Personal" },
1108 { directory: store(workUuid), name: "Ping" },
1109 ]);
1110 assert.strictEqual(
1111 yield* resolveCookieDatabase(safari, context, "."),
1112 context.path.join(root, "Cookies.binarycookies"),
1113 );
1114 const selected = yield* resolveCookieDatabase(safari, context, profiles[1]!.directory);
1115 assert.strictEqual(selected, context.path.join(store(workUuid), "Cookies.binarycookies"));
1116 const fileSystem = yield* FileSystem.FileSystem;
1117 assert.strictEqual(yield* fileSystem.readFileString(selected!), workUuid);
1118 yield* fileSystem.remove(selected!);
1119 assert.isUndefined(yield* resolveCookieDatabase(safari, context, profiles[1]!.directory));
1120 assert.deepEqual(yield* listSourceProfiles(safari, context), profiles);
1121 }),
1122 ),
1123 );
1124​
1125 it.effect.each(["missing", "corrupt"] as const)(
1126 "recovers separate cookie stores when metadata is %s",
1127 (metadataState) =>
1128 run(
1129 Effect.gen(function* () {
1130 const { context, store, metadata } = yield* fixture();
1131 const fileSystem = yield* FileSystem.FileSystem;
1132 if (metadataState === "corrupt") yield* fileSystem.writeFileString(metadata, "invalid");
1133 yield* fileSystem.remove(context.path.join(store(otherUuid), "Cookies.binarycookies"));
1134 assert.deepEqual(yield* listSourceProfiles(safari, context), [
1135 { directory: ".", name: "Safari" },
1136 { directory: store(workUuid), name: workUuid.toLowerCase() },
1137 ]);
1138 assert.isTrue(yield* isSourceInstalled(safari, context));
1139 }),
1140 ),
1141 );
1142​
1143 it.effect("keeps Safari without profiles available", () =>
1144 run(
1145 Effect.gen(function* () {
1146 const context = yield* withSourceHome();
1147 assert.deepEqual(yield* listSourceProfiles(safari, context), [
1148 { directory: ".", name: "Safari" },
1149 ]);
1150 assert.isFalse(yield* isSourceInstalled(safari, context));
1151 }),
1152 ),
1153 );
1154});