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

Sources.test.ts

739 lines30.1 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 Scope from "effect/Scope";
11import { ChildProcessSpawner } from "effect/process";
12import * as NodeSqlite from "node:sqlite";
13​
14import type { BrowserImportPathContext } from "./Sources.ts";
15import {
16 BROWSER_IMPORT_SOURCES,
17 chromiumProcessIsAlive,
18 chromiumSingletonLockIsHeld,
19 firefoxSymlinkLockIsHeld,
20 resolveCookieDatabase,
21 isSourceInstalled,
22 isSourceRunning,
23 listSourceProfiles,
24 sourcePathContext,
25 windowsChromiumCookiesAreHeld,
26} from "./Sources.ts";
27import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
28​
29const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!;
30​
31const withSourceHome = Effect.fnUntraced(function* () {
32 const fileSystem = yield* FileSystem.FileSystem;
33 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-sources-" });
34 const context = yield* sourcePathContext.pipe(
35 Effect.provideService(HostProcess.Environment, { HOME: home }),
36 Effect.provideService(HostProcess.Platform, "darwin"),
37 );
38 yield* fileSystem.makeDirectory(userDataDirectory(context), { recursive: true });
39 return context;
40});
41​
42const userDataDirectory = (context: BrowserImportPathContext) => {
43 const root = helium.userDataDirectory(context);
44 if (root === undefined) throw new Error("Helium has no macOS user-data directory");
45 return root;
46};
47​
48const run = <A, E>(
49 effect: Effect.Effect<
50 A,
51 E,
52 FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
53 >,
54) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
55​
56const writeCookieDatabase = (file: string, count: number) =>
57 Effect.sync(() => {
58 const database = new NodeSqlite.DatabaseSync(file);
59 database.exec("create table cookies (host_key text, name text)");
60 const insert = database.prepare("insert into cookies (host_key, name) values (?, ?)");
61 for (let index = 0; index < count; index += 1) insert.run("example.test", `c${index}`);
62 database.close();
63 });
64​
65const writeFirefoxCookieDatabase = (
66 file: string,
67 defaultContainerCount: number,
68 containerCount: number,
69) =>
70 Effect.sync(() => {
71 const database = new NodeSqlite.DatabaseSync(file);
72 database.exec("create table moz_cookies (originAttributes text not null)");
73 const insert = database.prepare("insert into moz_cookies (originAttributes) values (?)");
74 for (let index = 0; index < defaultContainerCount; index += 1) insert.run("");
75 for (let index = 0; index < containerCount; index += 1) insert.run("^userContextId=2");
76 database.close();
77 });
78​
79describe("isSourceRunning", () => {
80 it.effect("uses the held cookie database as Chromium's Windows running signal", () =>
81 run(
82 Effect.gen(function* () {
83 const fileSystem = yield* FileSystem.FileSystem;
84 const home = yield* fileSystem.makeTempDirectoryScoped({
85 prefix: "t3code-helium-windows-lock-",
86 });
87 const context = yield* sourcePathContext.pipe(
88 Effect.provideService(HostProcess.Environment, {
89 HOME: home,
90 LOCALAPPDATA: home,
91 }),
92 Effect.provideService(HostProcess.Platform, "win32"),
93 );
94 const profile = context.path.join(helium.userDataDirectory(context)!, "Default");
95 const database = context.path.join(profile, "Network", "Cookies");
96 yield* fileSystem.makeDirectory(context.path.join(profile, "Network"), { recursive: true });
97 yield* writeCookieDatabase(database, 1);
98​
99 const probed: string[] = [];
100 assert.isTrue(
101 yield* windowsChromiumCookiesAreHeld(helium, context, (path) =>
102 Effect.sync(() => {
103 probed.push(path);
104 return true;
105 }),
106 ),
107 );
108 assert.deepEqual(probed, [database]);
109 }),
110 ),
111 );
112​
113 it.effect.skipIf(!symlinksSupported)(
114 "reads Chromium's dangling SingletonLock symlink as a running browser",
115 () =>
116 run(
117 Effect.gen(function* () {
118 const fileSystem = yield* FileSystem.FileSystem;
119 const context = yield* withSourceHome();
120 assert.isFalse(yield* isSourceRunning(helium, context));
121​
122 // Chromium points the lock at `<host>-<pid>`, a target that never
123 // exists on disk. A check that follows the link reports a running
124 // browser as closed, letting an import read a live, mid-write database.
125 yield* fileSystem.symlink(
126 "host-that-does-not-exist-1234",
127 `${userDataDirectory(context)}/SingletonLock`,
128 );
129​
130 assert.isTrue(yield* isSourceRunning(helium, context));
131 }),
132 ),
133 );
134});
135​
136describe("chromiumSingletonLockIsHeld", () => {
137 it.effect("ignores a positively dead PID on the current host", () =>
138 Effect.gen(function* () {
139 const checked: number[] = [];
140 const held = yield* chromiumSingletonLockIsHeld("current-host-4321", "current-host", (pid) =>
141 Effect.sync(() => {
142 checked.push(pid);
143 return false;
144 }),
145 );
146 assert.isFalse(held);
147 assert.deepEqual(checked, [4321]);
148 }),
149 );
150​
151 it.effect("keeps foreign-host and malformed targets without probing a PID", () =>
152 Effect.gen(function* () {
153 let probes = 0;
154 const probe = (_pid: number) =>
155 Effect.sync(() => {
156 probes += 1;
157 return false;
158 });
159 assert.isTrue(yield* chromiumSingletonLockIsHeld("another-host-4321", "current-host", probe));
160 assert.isTrue(
161 yield* chromiumSingletonLockIsHeld("current-host-no-pid", "current-host", probe),
162 );
163 assert.isTrue(yield* chromiumSingletonLockIsHeld("current-host-0", "current-host", probe));
164 assert.strictEqual(probes, 0);
165 }),
166 );
167});
168​
169describe("chromiumProcessIsAlive", () => {
170 it.effect("returns false only when signal 0 reports a missing process", () =>
171 Effect.gen(function* () {
172 const missing = Object.assign(new Error("missing"), { code: "ESRCH" });
173 const denied = Object.assign(new Error("denied"), { code: "EPERM" });
174 assert.isFalse(
175 yield* chromiumProcessIsAlive(4321, () => {
176 throw missing;
177 }),
178 );
179 assert.isTrue(
180 yield* chromiumProcessIsAlive(4321, () => {
181 throw denied;
182 }),
183 );
184 assert.isTrue(
185 yield* chromiumProcessIsAlive(4321, () => {
186 throw undefined;
187 }),
188 );
189 assert.isTrue(
190 yield* chromiumProcessIsAlive(4321, () => {
191 throw "unknown failure";
192 }),
193 );
194 assert.isTrue(
195 yield* chromiumProcessIsAlive(4321, () => {
196 throw null;
197 }),
198 );
199 assert.isTrue(yield* chromiumProcessIsAlive(4321, () => true));
200 }),
201 );
202});
203​
204describe("isSourceInstalled", () => {
205 it.effect("ignores a user-data directory that holds no cookie database", () =>
206 run(
207 Effect.gen(function* () {
208 const fileSystem = yield* FileSystem.FileSystem;
209 const context = yield* withSourceHome();
210 const root = userDataDirectory(context);
211​
212 // Installers for native messaging hosts create an empty user-data
213 // directory for every Chromium fork they know about, so treating the
214 // directory as evidence lists browsers the user does not have.
215 yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true });
216 assert.isFalse(yield* isSourceInstalled(helium, context));
217​
218 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
219 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
220 assert.isTrue(yield* isSourceInstalled(helium, context));
221​
222 yield* fileSystem.remove(`${root}/Default`, { recursive: true });
223 yield* fileSystem.makeDirectory(`${root}/Profile 1`, { recursive: true });
224 yield* fileSystem.writeFileString(`${root}/Profile 1/Cookies`, "db");
225 assert.isTrue(yield* isSourceInstalled(helium, context));
226​
227 yield* fileSystem.remove(root, { recursive: true });
228 assert.isFalse(yield* isSourceInstalled(helium, context));
229 }),
230 ),
231 );
232});
233​
234describe("listSourceProfiles", () => {
235 it.effect("reads the profile names the browser shows", () =>
236 run(
237 Effect.gen(function* () {
238 const fileSystem = yield* FileSystem.FileSystem;
239 const context = yield* withSourceHome();
240 yield* fileSystem.writeFileString(
241 `${userDataDirectory(context)}/Local State`,
242 `{"profile":{"info_cache":{"Default":{"name":"You"},"Profile 2":{"name":" "}}}}`,
243 );
244​
245 assert.deepEqual(yield* listSourceProfiles(helium, context), [
246 { directory: "Default", name: "You" },
247 { directory: "Profile 2", name: "Profile 2" },
248 ]);
249 }),
250 ),
251 );
252​
253 it.effect("scans for profiles when Local State is malformed", () =>
254 run(
255 Effect.gen(function* () {
256 const fileSystem = yield* FileSystem.FileSystem;
257 const context = yield* withSourceHome();
258 const root = userDataDirectory(context);
259 yield* fileSystem.writeFileString(`${root}/Local State`, "{not-json");
260 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
261 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
262​
263 assert.deepEqual(yield* listSourceProfiles(helium, context), [
264 { directory: "Default", name: "Default" },
265 ]);
266 }),
267 ),
268 );
269​
270 it.effect("discovers profiles with cookies under Network/ (Chromium 127+)", () =>
271 run(
272 Effect.gen(function* () {
273 const fileSystem = yield* FileSystem.FileSystem;
274 const context = yield* withSourceHome();
275 const root = userDataDirectory(context);
276 yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
277 yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "db");
278​
279 assert.deepEqual(yield* listSourceProfiles(helium, context), [
280 { directory: "Default", name: "Default" },
281 ]);
282 }),
283 ),
284 );
285​
286 it.effect("falls through to the legacy database when Network/Cookies is a directory", () =>
287 run(
288 Effect.gen(function* () {
289 const fileSystem = yield* FileSystem.FileSystem;
290 const paths = yield* withSourceHome();
291 const root = helium.userDataDirectory(paths);
292 yield* fileSystem.makeDirectory(`${root}/Default/Network/Cookies`, { recursive: true });
293 yield* writeCookieDatabase(`${root}/Default/Cookies`, 2);
294​
295 const [profile] = yield* listSourceProfiles(helium, paths);
296 assert.equal(profile?.directory, "Default");
297 assert.equal(profile?.cookieCount, 2);
298 }),
299 ),
300 );
301});
302​
303describe("cookieDatabaseCandidatePaths", () => {
304 it.effect("resolves the live Network/ jar over a leftover root Cookies", () =>
305 run(
306 Effect.gen(function* () {
307 const fileSystem = yield* FileSystem.FileSystem;
308 const context = yield* withSourceHome();
309 const root = userDataDirectory(context);
310 // Chromium 96+ keeps sessions in Network/; a root Cookies left behind
311 // by the move is stale and must not be the one imported.
312 yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true });
313 yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "live");
314 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "stale");
315​
316 assert.equal(
317 yield* resolveCookieDatabase(helium, context, "Default"),
318 context.path.join(root, "Default", "Network", "Cookies"),
319 );
320 yield* fileSystem.remove(`${root}/Default/Cookies`);
321 assert.isTrue(yield* isSourceInstalled(helium, context));
322 }),
323 ),
324 );
325});
326​
327const firefox = BROWSER_IMPORT_SOURCES.find((source) => source.id === "firefox")!;
328​
329describe("Firefox Snap profiles", () => {
330 it.effect.skipIf(!symlinksSupported)(
331 "finds Snap profiles with or without profiles.ini and checks their locks",
332 () =>
333 run(
334 Effect.gen(function* () {
335 const fileSystem = yield* FileSystem.FileSystem;
336 const home = yield* fileSystem.makeTempDirectoryScoped({
337 prefix: "t3code-firefox-snap-",
338 });
339 const context = yield* sourcePathContext.pipe(
340 Effect.provideService(HostProcess.Environment, { HOME: home }),
341 Effect.provideService(HostProcess.Platform, "linux"),
342 );
343 const root = context.path.join(home, "snap", "firefox", "common", ".mozilla", "firefox");
344 const directory = context.path.join(root, "abcd.default");
345 yield* fileSystem.makeDirectory(directory, { recursive: true });
346 yield* writeFirefoxCookieDatabase(`${directory}/cookies.sqlite`, 2, 1);
347 yield* fileSystem.writeFileString(
348 `${root}/profiles.ini`,
349 "[Profile0]\nName=Personal\nIsRelative=1\nPath=abcd.default\n",
350 );
351​
352 assert.isTrue(yield* isSourceInstalled(firefox, context));
353 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
354 { directory, name: "Personal", cookieCount: 2 },
355 ]);
356 assert.equal(
357 yield* resolveCookieDatabase(firefox, context, directory),
358 context.path.join(directory, "cookies.sqlite"),
359 );
360 assert.isFalse(yield* isSourceRunning(firefox, context));
361 yield* fileSystem.symlink("foreign-host:+4242", `${directory}/lock`);
362 assert.isTrue(yield* isSourceRunning(firefox, context));
363 yield* fileSystem.remove(`${directory}/lock`);
364 assert.isFalse(yield* isSourceRunning(firefox, context));
365​
366 yield* fileSystem.remove(`${root}/profiles.ini`);
367 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
368 { directory, name: "abcd.default", cookieCount: 2 },
369 ]);
370 }),
371 ),
372 );
373​
374 it.effect("keeps matching profile names in native and Snap installs distinct", () =>
375 run(
376 Effect.gen(function* () {
377 const fileSystem = yield* FileSystem.FileSystem;
378 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-snap-" });
379 const context = yield* sourcePathContext.pipe(
380 Effect.provideService(HostProcess.Environment, { HOME: home }),
381 Effect.provideService(HostProcess.Platform, "linux"),
382 );
383 const native = context.path.join(home, ".mozilla", "firefox");
384 const snap = context.path.join(home, "snap", "firefox", "common", ".mozilla", "firefox");
385 for (const root of [native, snap]) {
386 yield* fileSystem.makeDirectory(`${root}/abcd.default`, { recursive: true });
387 yield* writeFirefoxCookieDatabase(`${root}/abcd.default/cookies.sqlite`, 1, 0);
388 yield* fileSystem.writeFileString(
389 `${root}/profiles.ini`,
390 "[Profile0]\nName=Personal\nIsRelative=1\nPath=abcd.default\n" +
391 `[Profile1]\nName=Shared\nIsRelative=0\nPath=${snap}/abcd.default\n`,
392 );
393 }
394​
395 const profiles = yield* listSourceProfiles(firefox, context);
396 assert.deepEqual(
397 profiles.map((profile) => profile.directory),
398 ["abcd.default", context.path.join(snap, "abcd.default")],
399 );
400 const databases = yield* Effect.forEach(profiles, (profile) =>
401 resolveCookieDatabase(firefox, context, profile.directory),
402 );
403 assert.deepEqual(databases, [
404 context.path.join(native, "abcd.default", "cookies.sqlite"),
405 context.path.join(snap, "abcd.default", "cookies.sqlite"),
406 ]);
407 }),
408 ),
409 );
410});
411​
412describe("listSourceProfiles Firefox fallback", () => {
413 const cases = [
414 { platform: "linux" as const, profileDirectory: "linux.default" },
415 { platform: "darwin" as const, profileDirectory: NodePath.join("Profiles", "macos.default") },
416 { platform: "win32" as const, profileDirectory: NodePath.join("Profiles", "windows.default") },
417 ];
418​
419 it.effect.each(cases)(
420 "scans the $platform profile location and excludes stale entries",
421 ({ platform, profileDirectory }) =>
422 run(
423 Effect.gen(function* () {
424 const fileSystem = yield* FileSystem.FileSystem;
425 const path = yield* Path.Path;
426 const home = yield* fileSystem.makeTempDirectoryScoped({
427 prefix: `t3code-firefox-${platform}-`,
428 });
429 const appData = path.join(home, "AppData", "Roaming");
430 const context = yield* sourcePathContext.pipe(
431 Effect.provideService(HostProcess.Environment, {
432 HOME: home,
433 APPDATA: appData,
434 }),
435 Effect.provideService(HostProcess.Platform, platform),
436 );
437 const root = firefox.userDataDirectory(context)!;
438 const scanRoot = platform === "linux" ? root : path.join(root, "Profiles");
439 yield* fileSystem.makeDirectory(path.join(root, profileDirectory), { recursive: true });
440 yield* fileSystem.writeFileString(
441 path.join(root, profileDirectory, "cookies.sqlite"),
442 "db",
443 );
444 yield* fileSystem.makeDirectory(path.join(scanRoot, "stale.default"), {
445 recursive: true,
446 });
447 yield* fileSystem.writeFileString(path.join(scanRoot, "stale-file.default"), "not-dir");
448​
449 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
450 {
451 directory: profileDirectory,
452 name: path.basename(profileDirectory),
453 },
454 ]);
455 }),
456 ),
457 );
458​
459 it.effect("scans for profiles when profiles.ini declares only ones without cookies", () =>
460 run(
461 Effect.gen(function* () {
462 const fileSystem = yield* FileSystem.FileSystem;
463 const path = yield* Path.Path;
464 const home = yield* fileSystem.makeTempDirectoryScoped({
465 prefix: "t3code-firefox-stale-ini-",
466 });
467 const context = yield* sourcePathContext.pipe(
468 Effect.provideService(HostProcess.Environment, { HOME: home }),
469 Effect.provideService(HostProcess.Platform, "darwin"),
470 );
471 const root = firefox.userDataDirectory(context)!;
472 yield* fileSystem.makeDirectory(path.join(root, "Profiles", "stale.default"), {
473 recursive: true,
474 });
475 const realDirectory = path.join(root, "Profiles", "real.default");
476 yield* fileSystem.makeDirectory(realDirectory, { recursive: true });
477 yield* writeFirefoxCookieDatabase(path.join(realDirectory, "cookies.sqlite"), 3, 0);
478 yield* fileSystem.writeFileString(
479 path.join(root, "profiles.ini"),
480 ["[Profile0]", "Name=Stale", "IsRelative=1", "Path=Profiles/stale.default"].join("\n"),
481 );
482​
483 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
484 {
485 directory: path.join("Profiles", "real.default"),
486 name: "real.default",
487 cookieCount: 3,
488 },
489 ]);
490 assert.isTrue(yield* isSourceInstalled(firefox, context));
491 }),
492 ),
493 );
494​
495 it.effect("counts only importable cookies for declared and fallback profiles", () =>
496 run(
497 Effect.gen(function* () {
498 const fileSystem = yield* FileSystem.FileSystem;
499 const path = yield* Path.Path;
500 const home = yield* fileSystem.makeTempDirectoryScoped({
501 prefix: "t3code-firefox-counts-",
502 });
503 const context = yield* sourcePathContext.pipe(
504 Effect.provideService(HostProcess.Environment, { HOME: home }),
505 Effect.provideService(HostProcess.Platform, "darwin"),
506 );
507 const root = firefox.userDataDirectory(context)!;
508 const declaredDirectory = path.join(root, "Profiles", "declared.default");
509 yield* fileSystem.makeDirectory(declaredDirectory, { recursive: true });
510 yield* writeFirefoxCookieDatabase(path.join(declaredDirectory, "cookies.sqlite"), 2, 3);
511 yield* fileSystem.writeFileString(
512 path.join(root, "profiles.ini"),
513 ["[Profile0]", "Name=Declared", "IsRelative=1", "Path=Profiles/declared.default"].join(
514 "\n",
515 ),
516 );
517​
518 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
519 {
520 directory: path.join("Profiles", "declared.default"),
521 name: "Declared",
522 cookieCount: 2,
523 },
524 ]);
525​
526 yield* fileSystem.remove(path.join(root, "profiles.ini"));
527 const fallbackDirectory = path.join(root, "Profiles", "fallback.default");
528 yield* fileSystem.makeDirectory(fallbackDirectory, { recursive: true });
529 yield* writeFirefoxCookieDatabase(path.join(fallbackDirectory, "cookies.sqlite"), 1, 4);
530​
531 assert.deepEqual(yield* listSourceProfiles(firefox, context), [
532 {
533 directory: path.join("Profiles", "declared.default"),
534 name: "declared.default",
535 cookieCount: 2,
536 },
537 {
538 directory: path.join("Profiles", "fallback.default"),
539 name: "fallback.default",
540 cookieCount: 1,
541 },
542 ]);
543 }),
544 ),
545 );
546});
547​
548describe("isSourceRunning for Firefox", () => {
549 it.effect.skipIf(!symlinksSupported)("finds the lock inside the profile, not at the root", () =>
550 run(
551 Effect.gen(function* () {
552 const fileSystem = yield* FileSystem.FileSystem;
553 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" });
554 const context = yield* sourcePathContext.pipe(
555 Effect.provideService(HostProcess.Environment, { HOME: home }),
556 Effect.provideService(HostProcess.Platform, "darwin"),
557 );
558 const root = firefox.userDataDirectory(context)!;
559 const profile = `${root}/Profiles/abcd.default-release`;
560 yield* fileSystem.makeDirectory(profile, { recursive: true });
561 yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db");
562​
563 assert.isFalse(yield* isSourceRunning(firefox, context));
564​
565 yield* fileSystem.writeFileString(`${root}/lock`, "");
566 assert.isFalse(yield* isSourceRunning(firefox, context));
567​
568 // `.parentlock` is deliberately left on disk after a clean exit as a
569 // last-used marker, so an unlocked one is not evidence of a running
570 // browser — treating it as one blocked every import after first use.
571 yield* fileSystem.writeFileString(`${profile}/.parentlock`, "");
572 assert.isFalse(yield* isSourceRunning(firefox, context));
573​
574 // The `lock` symlink is what Firefox removes on exit; a live pid in
575 // its target means the profile is held.
576 yield* fileSystem.symlink(`127.0.0.1:+${process.pid}`, `${profile}/lock`);
577 assert.isTrue(yield* isSourceRunning(firefox, context));
578 }),
579 ),
580 );
581​
582 it.effect("reads a Firefox lock symlink's pid to tell live from crashed", () =>
583 Effect.gen(function* () {
584 const alive = (pid: number) => Effect.succeed(pid === 4242);
585 // The resolver may hand Firefox any of the machine's addresses, not
586 // just 127.0.0.1 — 127.0.1.1 on Debian-style hosts, a LAN address
587 // elsewhere — so every local address counts as ours.
588 const local = new Set(["127.0.0.1", "127.0.1.1", "192.168.1.20"]);
589 // Both the plain and the fcntl-marked (`+`) forms carry the pid.
590 assert.isTrue(yield* firefoxSymlinkLockIsHeld("127.0.0.1:4242", local, alive));
591 assert.isTrue(yield* firefoxSymlinkLockIsHeld("127.0.1.1:+4242", local, alive));
592 assert.isTrue(yield* firefoxSymlinkLockIsHeld("192.168.1.20:+4242", local, alive));
593 assert.isFalse(yield* firefoxSymlinkLockIsHeld("127.0.0.1:+9999", local, alive));
594 assert.isFalse(yield* firefoxSymlinkLockIsHeld("192.168.1.20:+9999", local, alive));
595 assert.isTrue(yield* firefoxSymlinkLockIsHeld("garbage", local, alive));
596 assert.isTrue(yield* firefoxSymlinkLockIsHeld("10.0.0.7:+9999", local, alive));
597 }),
598 );
599​
600 it.effect("does not treat a stale parent.lock file as a running browser", () =>
601 run(
602 Effect.gen(function* () {
603 const fileSystem = yield* FileSystem.FileSystem;
604 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" });
605 const context = yield* sourcePathContext.pipe(
606 // Firefox's win32 root hangs off %APPDATA%; without it the root is
607 // undefined and the fixture would escape the sandbox into the repo.
608 Effect.provideService(HostProcess.Environment, {
609 HOME: home,
610 APPDATA: `${home}/AppData/Roaming`,
611 }),
612 Effect.provideService(HostProcess.Platform, "win32"),
613 );
614 const root = firefox.userDataDirectory(context)!;
615 const profile = `${root}/Profiles/gx7x7fqx.default-release`;
616 yield* fileSystem.makeDirectory(profile, { recursive: true });
617 yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db");
618​
619 // On Windows, Firefox creates parent.lock as a regular file that
620 // persists after the process exits.
621 yield* fileSystem.writeFileString(`${profile}/parent.lock`, "");
622 assert.isFalse(yield* isSourceRunning(firefox, context));
623 }),
624 ),
625 );
626});
627​
628describe("listSourceProfiles hardening", () => {
629 it.effect("drops profile directories that are not a single plain segment", () =>
630 run(
631 Effect.gen(function* () {
632 const fileSystem = yield* FileSystem.FileSystem;
633 const context = yield* withSourceHome();
634 yield* fileSystem.writeFileString(
635 `${userDataDirectory(context)}/Local State`,
636 `{"profile":{"info_cache":{"Default":{"name":"You"},"../../../../secrets":{"name":"Escape"},"a/b":{"name":"Nested"},"..":{"name":"Parent"}}}}`,
637 );
638​
639 const profiles = yield* listSourceProfiles(helium, context);
640​
641 assert.deepEqual(
642 profiles.map((profile) => profile.directory),
643 ["Default"],
644 );
645 }),
646 ),
647 );
648});
649​
650describe("Safari profiles", () => {
651 const safari = BROWSER_IMPORT_SOURCES.find((source) => source.id === "safari")!;
652 const workUuid = "C561D071-67AD-4537-866F-54F65FB8E8DD";
653 const otherUuid = "2875EB19-B938-4E38-BE92-5AE97C256BDD";
654​
655 const fixture = Effect.fnUntraced(function* () {
656 const context = yield* withSourceHome();
657 const fileSystem = yield* FileSystem.FileSystem;
658 const root = safari.userDataDirectory(context)!;
659 const library = context.path.dirname(root);
660 yield* fileSystem.makeDirectory(root, { recursive: true });
661 yield* fileSystem.writeFileString(context.path.join(root, "Cookies.binarycookies"), "default");
662 const store = (uuid: string) =>
663 context.path.join(library, "WebKit", "WebsiteDataStore", uuid.toLowerCase(), "Cookies");
664 for (const uuid of [workUuid, otherUuid]) {
665 yield* fileSystem.makeDirectory(store(uuid), { recursive: true });
666 yield* fileSystem.writeFileString(
667 context.path.join(store(uuid), "Cookies.binarycookies"),
668 uuid,
669 );
670 }
671 yield* fileSystem.makeDirectory(context.path.join(library, "Safari"), { recursive: true });
672 const metadata = context.path.join(library, "Safari", "SafariTabs.db");
673 return { context, root, store, metadata };
674 });
675​
676 it.effect("discovers named profiles and resolves only the selected profile's cookies", () =>
677 run(
678 Effect.gen(function* () {
679 const { context, root, store, metadata } = yield* fixture();
680 yield* Effect.sync(() => {
681 const database = new NodeSqlite.DatabaseSync(metadata);
682 try {
683 database.exec(`CREATE TABLE bookmarks (
684 title TEXT, external_uuid TEXT, parent INTEGER DEFAULT 0,
685 type INTEGER DEFAULT 1, subtype INTEGER DEFAULT 2,
686 deleted INTEGER DEFAULT 0, order_index INTEGER DEFAULT 0
687 )`);
688 const insert = database.prepare(
689 "INSERT INTO bookmarks (title, external_uuid, deleted) VALUES (?, ?, ?)",
690 );
691 insert.run("", "DefaultProfile", 0);
692 insert.run("Ping", workUuid, 0);
693 insert.run("Deleted", otherUuid, 1);
694 insert.run("Unsafe", "../../outside", 0);
695 database.exec(
696 "INSERT INTO bookmarks (title, external_uuid, subtype) VALUES ('Tab group', 'group', 1)",
697 );
698 } finally {
699 database.close();
700 }
701 });
702 const profiles = yield* listSourceProfiles(safari, context);
703 assert.deepEqual(profiles, [
704 { directory: ".", name: "Personal" },
705 { directory: store(workUuid), name: "Ping" },
706 ]);
707 assert.strictEqual(
708 yield* resolveCookieDatabase(safari, context, "."),
709 context.path.join(root, "Cookies.binarycookies"),
710 );
711 const selected = yield* resolveCookieDatabase(safari, context, profiles[1]!.directory);
712 assert.strictEqual(selected, context.path.join(store(workUuid), "Cookies.binarycookies"));
713 const fileSystem = yield* FileSystem.FileSystem;
714 assert.strictEqual(yield* fileSystem.readFileString(selected!), workUuid);
715 yield* fileSystem.remove(selected!);
716 assert.isUndefined(yield* resolveCookieDatabase(safari, context, profiles[1]!.directory));
717 assert.deepEqual(yield* listSourceProfiles(safari, context), profiles);
718 }),
719 ),
720 );
721​
722 it.effect.each(["missing", "corrupt"] as const)(
723 "recovers separate cookie stores when metadata is %s",
724 (metadataState) =>
725 run(
726 Effect.gen(function* () {
727 const { context, store, metadata } = yield* fixture();
728 const fileSystem = yield* FileSystem.FileSystem;
729 if (metadataState === "corrupt") yield* fileSystem.writeFileString(metadata, "invalid");
730 yield* fileSystem.remove(context.path.join(store(otherUuid), "Cookies.binarycookies"));
731 assert.deepEqual(yield* listSourceProfiles(safari, context), [
732 { directory: ".", name: "Safari" },
733 { directory: store(workUuid), name: workUuid.toLowerCase() },
734 ]);
735 assert.isTrue(yield* isSourceInstalled(safari, context));
736 }),
737 ),
738 );
739});