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

BrowserImport.test.ts

212 lines7.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import {
4 HostProcessEnvironment,
5 HostProcessExecutablePath,
6 HostProcessPlatform,
7} from "@t3tools/shared/hostProcess";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Fiber from "effect/Fiber";
11import * as Layer from "effect/Layer";
12import * as Ref from "effect/Ref";
13​
14import * as BrowserSession from "../BrowserSession.ts";
15import * as BrowserImport from "./BrowserImport.ts";
16import { BROWSER_IMPORT_SOURCES, sourcePathContext } from "./Sources.ts";
17import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
18​
19const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!;
20​
21const cookie = {
22 url: "https://rejected.example/path",
23 name: "session",
24 value: "value",
25 domain: undefined,
26 path: "/",
27 secure: true,
28 httpOnly: true,
29 expirationDate: undefined,
30 sameSite: "lax" as const,
31};
32​
33/**
34 * Dies if the import reaches session work: every case here covers a request
35 * that must be rejected before a cookie is read or written.
36 */
37const rejectedBeforeSession = Layer.succeed(
38 BrowserSession.BrowserSession,
39 BrowserSession.BrowserSession.of({
40 getPartition: () => Effect.die("getPartition must not be reached"),
41 isPartition: () => false,
42 getSession: () => Effect.die("getSession must not be reached"),
43 clearCookies: () => Effect.die("clearCookies must not be reached"),
44 clearCache: () => Effect.die("clearCache must not be reached"),
45 }),
46);
47​
48/**
49 * Builds the service against a scratch home containing an installed, closed
50 * copy of the source browser.
51 */
52const withImporter = Effect.fnUntraced(function* () {
53 const fileSystem = yield* FileSystem.FileSystem;
54 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-import-" });
55 const environment = Layer.succeed(HostProcessEnvironment, { HOME: home });
56 const context = yield* sourcePathContext.pipe(
57 Effect.provideService(HostProcessEnvironment, { HOME: home }),
58 Effect.provideService(HostProcessPlatform, "darwin"),
59 );
60 const root = helium.userDataDirectory(context);
61 if (root === undefined) throw new Error("Helium has no macOS user-data directory");
62 yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true });
63 // The cookie database is what marks a source as installed, so a fixture
64 // without one is reported as absent before any other check runs.
65 yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db");
66​
67 const importer = yield* BrowserImport.BrowserImport.pipe(
68 Effect.provide(
69 BrowserImport.layer.pipe(
70 Layer.provide(rejectedBeforeSession),
71 Layer.provide(environment),
72 Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
73 Layer.provide(Layer.succeed(HostProcessExecutablePath, "/Applications/T3 Code.app")),
74 Layer.provide(NodeServices.layer),
75 ),
76 ),
77 );
78 return { importer, home, root };
79});
80​
81describe("BrowserImport.importCookies", () => {
82 it.effect("rejects a source profile the browser never reported", () =>
83 Effect.gen(function* () {
84 const fileSystem = yield* FileSystem.FileSystem;
85 const { importer, home } = yield* withImporter();
86​
87 // A cookie database reachable on disk but outside the browser's
88 // user-data directory — the payoff a traversal would be after.
89 yield* fileSystem.makeDirectory(`${home}/secrets`, { recursive: true });
90 yield* fileSystem.writeFileString(`${home}/secrets/Cookies`, "not-a-db");
91​
92 const error = yield* importer
93 .importCookies({
94 input: {
95 sourceId: "helium",
96 sourceProfileDirectory: "../../../../secrets",
97 targetProfileId: "default",
98 },
99 scope: "persist:t3code-preview-test",
100 persistent: true,
101 })
102 .pipe(Effect.flip);
103​
104 assert.instanceOf(error, BrowserImport.BrowserImportFailedError);
105 assert.equal(error.reason, "unknownSourceProfile");
106 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
107 );
108​
109 it.effect.skipIf(!symlinksSupported)(
110 "refuses to import while the source browser holds its profile",
111 () =>
112 Effect.gen(function* () {
113 const fileSystem = yield* FileSystem.FileSystem;
114 const { importer, root } = yield* withImporter();
115 // The lock Chromium leaves while it is running, dangling target and
116 // all. This must stop the import before it ever asks the keychain.
117 yield* fileSystem.symlink("host-that-does-not-exist-1234", `${root}/SingletonLock`);
118​
119 const error = yield* importer
120 .importCookies({
121 input: {
122 sourceId: "helium",
123 sourceProfileDirectory: "Default",
124 targetProfileId: "default",
125 },
126 scope: "persist:t3code-preview-test",
127 persistent: true,
128 })
129 .pipe(Effect.flip);
130​
131 assert.equal(error.reason, "browserRunning");
132 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
133 );
134});
135​
136describe("BrowserImport.writeCookies", () => {
137 it.effect("counts a rejected cookie and its domain as skipped", () =>
138 Effect.gen(function* () {
139 let flushes = 0;
140 const result = yield* BrowserImport.writeCookies(
141 {
142 cookies: {
143 set: () => Promise.reject(new Error("fixture rejection")),
144 flushStore: () => {
145 flushes += 1;
146 return Promise.resolve();
147 },
148 },
149 },
150 { cookies: [cookie], undecryptable: 0, undecryptableHosts: [] },
151 );
152​
153 assert.deepEqual(result, {
154 imported: 0,
155 skipped: 1,
156 skippedDomains: ["rejected.example"],
157 });
158 // Nothing landed, so there is nothing to persist.
159 assert.equal(flushes, 0);
160 }),
161 );
162​
163 it.effect("flushes the store after writing, and reports success if the flush fails", () =>
164 Effect.gen(function* () {
165 const events: Array<string> = [];
166 const result = yield* BrowserImport.writeCookies(
167 {
168 cookies: {
169 set: () => {
170 events.push("set");
171 return Promise.resolve();
172 },
173 flushStore: () => {
174 events.push("flush");
175 return Promise.reject(new Error("fixture flush failure"));
176 },
177 },
178 },
179 { cookies: [cookie, cookie], undecryptable: 0, undecryptableHosts: [] },
180 );
181​
182 // One flush after every write, not one per cookie; the cookies are in
183 // the session either way, so a failed flush is not a failed import.
184 assert.deepEqual(events, ["set", "set", "flush"]);
185 assert.deepEqual(result, { imported: 2, skipped: 0, skippedDomains: [] });
186 }),
187 );
188​
189 it.effect("propagates interruption while writing a cookie", () =>
190 Effect.gen(function* () {
191 const write = BrowserImport.writeCookies(
192 {
193 cookies: {
194 set: () => new Promise<void>(() => {}),
195 flushStore: () => Promise.resolve(),
196 },
197 },
198 { cookies: [cookie], undecryptable: 0, undecryptableHosts: [] },
199 );
200​
201 const interrupted = yield* Ref.make(false);
202 const fiber = yield* write.pipe(
203 Effect.onInterrupt(() => Ref.set(interrupted, true)),
204 Effect.forkChild,
205 );
206 yield* Effect.yieldNow;
207 yield* Fiber.interrupt(fiber);
208​
209 assert.isTrue(yield* Ref.get(interrupted));
210 }),
211 );
212});