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

BrowserSession.test.ts

414 lines16.7 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Crypto from "effect/Crypto";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as PlatformError from "effect/PlatformError";
7import { beforeEach, vi } from "vite-plus/test";
8​
9const { fromPartition, sessions } = vi.hoisted(() => ({
10 fromPartition: vi.fn(),
11 sessions: new Map<
12 string,
13 {
14 readonly clearCache: ReturnType<typeof vi.fn>;
15 readonly clearStorageData: ReturnType<typeof vi.fn>;
16 readonly getUserAgent: ReturnType<typeof vi.fn<() => string>>;
17 readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
18 readonly setPermissionCheckHandler: ReturnType<typeof vi.fn>;
19 readonly setUserAgent: ReturnType<typeof vi.fn>;
20 }
21 >(),
22}));
23​
24const { fromWebContents } = vi.hoisted(() => ({
25 fromWebContents: vi.fn<(webContents: unknown) => unknown>(() => null),
26}));
27​
28vi.mock("electron", () => ({
29 BrowserWindow: { fromWebContents },
30 session: {
31 fromPartition,
32 },
33}));
34​
35import * as ElectronDialog from "../electron/ElectronDialog.ts";
36import * as BrowserSession from "./BrowserSession.ts";
37​
38const { showMessageBox } = vi.hoisted(() => ({
39 showMessageBox: vi.fn<
40 (options: Electron.MessageBoxOptions, owner?: Electron.BrowserWindow) => number
41 >(() => 1),
42}));
43const layerDialog = Layer.succeed(ElectronDialog.ElectronDialog, {
44 pickFolder: () => Effect.die("unused"),
45 pickFiles: () => Effect.die("unused"),
46 showMessageBox: (options, owner) =>
47 Effect.sync(() => ({ response: showMessageBox(options, owner), checkboxChecked: false })),
48 showErrorBox: () => Effect.void,
49});
50const layer = BrowserSession.layer.pipe(
51 Layer.provide(Layer.merge(NodeServices.layer, layerDialog)),
52);
53​
54describe("BrowserSession", () => {
55 beforeEach(() => {
56 sessions.clear();
57 fromPartition.mockReset();
58 fromPartition.mockImplementation((partition: string) => {
59 const browserSession = {
60 clearCache: vi.fn(() => Promise.resolve()),
61 clearStorageData: vi.fn(() => Promise.resolve()),
62 getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
63 setPermissionRequestHandler: vi.fn(),
64 setPermissionCheckHandler: vi.fn(),
65 setUserAgent: vi.fn(),
66 };
67 sessions.set(partition, browserSession);
68 return browserSession;
69 });
70 });
71​
72 it.effect("derives deterministic partitions and memoizes sessions", () =>
73 Effect.gen(function* () {
74 const browserSessions = yield* BrowserSession.BrowserSession;
75​
76 const partition = yield* browserSessions.getPartition("scope-a");
77 const first = yield* browserSessions.getSession("scope-a");
78 const second = yield* browserSessions.getSession("scope-a");
79​
80 assert.strictEqual(partition, "persist:t3code-preview-f051bb2c68cb7b2fe969");
81 assert.strictEqual(first, second);
82 assert.strictEqual(fromPartition.mock.calls.length, 1);
83 }).pipe(Effect.provide(layer)),
84 );
85​
86 it.effect("keeps scopes that differ only by a lone surrogate in separate partitions", () =>
87 Effect.gen(function* () {
88 const browserSessions = yield* BrowserSession.BrowserSession;
89​
90 // TextEncoder folds a lone surrogate to U+FFFD, so without escaping these
91 // two supported ids would hash to one partition and share every cookie.
92 const loneSurrogate = yield* browserSessions.getPartition("p\ud800");
93 const replacementChar = yield* browserSessions.getPartition("p\ufffd");
94 assert.notStrictEqual(loneSurrogate, replacementChar);
95​
96 const literal = yield* browserSessions.getPartition("p\\ud800");
97 assert.notStrictEqual(literal, loneSurrogate);
98​
99 assert.strictEqual(
100 yield* browserSessions.getPartition("scope-a"),
101 "persist:t3code-preview-f051bb2c68cb7b2fe969",
102 );
103 }).pipe(Effect.provide(layer)),
104 );
105​
106 it.effect("keeps legacy defaults disjoint from nondefault profile partitions", () =>
107 Effect.gen(function* () {
108 const browserSessions = yield* BrowserSession.BrowserSession;
109​
110 const legacyDefault = yield* browserSessions.getPartition("a::b");
111 const nondefaultProfile = yield* browserSessions.getPartition("a::b", true, "profile");
112​
113 assert.strictEqual(legacyDefault, "persist:t3code-preview-78f0be89237d77f7a70e");
114 assert.strictEqual(nondefaultProfile, "persist:t3code-preview-profile-78f0be89237d77f7a70e");
115 assert.notStrictEqual(nondefaultProfile, legacyDefault);
116 assert.isTrue(browserSessions.isPartition(legacyDefault));
117 assert.isTrue(browserSessions.isPartition(nondefaultProfile));
118 }).pipe(Effect.provide(layer)),
119 );
120​
121 // A rewritten session UA — any variant, even ones that keep the Electron
122 // token — makes Cloudflare Turnstile loop with error 600010 (#5002), so the
123 // guest must end up with Electron's native User-Agent.
124 it.effect("keeps the guest's effective User-Agent equal to Electron's native one", () =>
125 Effect.gen(function* () {
126 // Electron's real UA shape: app token, then Chrome, then Electron, then
127 // Safari — the token order and casing matter to any strip regex.
128 const nativeUserAgent =
129 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) T3Code(Alpha)/0.0.33 Chrome/146.0.7680.216 Electron/41.5.0 Safari/537.36";
130 fromPartition.mockReset();
131 fromPartition.mockImplementation((partition: string) => {
132 let userAgent = nativeUserAgent;
133 const browserSession = {
134 clearCache: vi.fn(() => Promise.resolve()),
135 clearStorageData: vi.fn(() => Promise.resolve()),
136 getUserAgent: vi.fn(() => userAgent),
137 setPermissionRequestHandler: vi.fn(),
138 setPermissionCheckHandler: vi.fn(),
139 setUserAgent: vi.fn((next: string) => {
140 userAgent = next;
141 }),
142 };
143 sessions.set(partition, browserSession);
144 return browserSession;
145 });
146​
147 const browserSessions = yield* BrowserSession.BrowserSession;
148 const partition = yield* browserSessions.getPartition("scope-a");
149 yield* browserSessions.getSession("scope-a");
150​
151 const browserSession = sessions.get(partition);
152 assert.isDefined(browserSession);
153 assert.strictEqual(browserSession.getUserAgent(), nativeUserAgent);
154 }).pipe(Effect.provide(layer)),
155 );
156​
157 it.effect("grants clipboard-sanitized-write through both the request and check handlers", () =>
158 Effect.gen(function* () {
159 const browserSessions = yield* BrowserSession.BrowserSession;
160 const partition = yield* browserSessions.getPartition("scope-a");
161 yield* browserSessions.getSession("scope-a");
162​
163 const browserSession = sessions.get(partition);
164 assert.isDefined(browserSession);
165​
166 const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
167 const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
168 assert.isFunction(requestHandler);
169 assert.isFunction(checkHandler);
170​
171 const requestAllows = (permission: string): boolean => {
172 let granted: boolean | undefined;
173 requestHandler(null, permission, (value: boolean) => {
174 granted = value;
175 });
176 assert.isDefined(granted);
177 return granted;
178 };
179​
180 for (const permission of [
181 "clipboard-read",
182 "clipboard-sanitized-write",
183 "geolocation",
184 "fullscreen",
185 ]) {
186 assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
187 assert.isTrue(
188 checkHandler(null, permission) as boolean,
189 `check handler should allow ${permission}`,
190 );
191 }
192​
193 // `clipboard-write` is not a real Electron permission — the async write API
194 // uses `clipboard-sanitized-write` — so the stale name must not be granted,
195 // and unrelated permissions stay denied.
196 for (const permission of ["clipboard-write", "notifications", "midi"]) {
197 assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
198 assert.isFalse(
199 checkHandler(null, permission) as boolean,
200 `check handler should deny ${permission}`,
201 );
202 }
203 }).pipe(Effect.provide(layer)),
204 );
205​
206 it.effect("opens custom-scheme links externally only after the user confirms", () =>
207 Effect.gen(function* () {
208 const browserSessions = yield* BrowserSession.BrowserSession;
209 const partition = yield* browserSessions.getPartition("scope-a");
210 yield* browserSessions.getSession("scope-a");
211 const requestHandler =
212 sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0];
213 assert.isFunction(requestHandler);
214​
215 const request = (externalURL: string) =>
216 Effect.callback<boolean>((resume) => {
217 requestHandler(
218 null,
219 "openExternal",
220 (granted: boolean) => resume(Effect.succeed(granted)),
221 { externalURL },
222 );
223 });
224​
225 showMessageBox.mockReset();
226 showMessageBox.mockReturnValueOnce(0).mockReturnValueOnce(1);
227 assert.isTrue(yield* request("slack://open?team=T1"));
228 assert.isFalse(yield* request("zoommtg://zoom.us/join"));
229 assert.strictEqual(showMessageBox.mock.calls.length, 2);
230​
231 for (const url of ["file:///etc/passwd", "javascript:alert(1)", "data:text/html,x"]) {
232 assert.isFalse(yield* request(url), `${url} must never open externally`);
233 }
234 assert.strictEqual(showMessageBox.mock.calls.length, 2);
235 }).pipe(Effect.provide(layer)),
236 );
237​
238 it.effect("attaches the open-externally prompt to the window hosting the preview", () =>
239 Effect.gen(function* () {
240 const browserSessions = yield* BrowserSession.BrowserSession;
241 const partition = yield* browserSessions.getPartition("scope-a");
242 yield* browserSessions.getSession("scope-a");
243 const requestHandler =
244 sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0];
245 assert.isFunction(requestHandler);
246​
247 const hostWindow = { id: 7 } as unknown as Electron.BrowserWindow;
248 const host = { isDestroyed: () => false };
249 const guest = { isDestroyed: () => false, hostWebContents: host };
250 fromWebContents.mockImplementation((webContents) =>
251 webContents === host ? hostWindow : null,
252 );
253 showMessageBox.mockReset();
254 showMessageBox.mockReturnValueOnce(1);
255​
256 yield* Effect.callback<boolean>((resume) => {
257 requestHandler(
258 guest,
259 "openExternal",
260 (granted: boolean) => resume(Effect.succeed(granted)),
261 {
262 externalURL: "slack://open?team=T1",
263 },
264 );
265 });
266​
267 assert.strictEqual(showMessageBox.mock.calls[0]?.[1], hostWindow);
268 }).pipe(Effect.provide(layer)),
269 );
270​
271 it.effect("preserves partition scope and the platform failure chain", () => {
272 const nativeCause = new Error("native digest failed");
273 const platformCause = PlatformError.systemError({
274 _tag: "Unknown",
275 module: "Crypto",
276 method: "digest",
277 cause: nativeCause,
278 });
279 const layerFailingCrypto = Layer.succeed(
280 Crypto.Crypto,
281 Crypto.make({
282 randomBytes: (size) => new Uint8Array(size),
283 digest: () => Effect.fail(platformCause),
284 }),
285 );
286​
287 return Effect.gen(function* () {
288 const browserSessions = yield* BrowserSession.BrowserSession;
289 const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
290​
291 assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
292 assert.equal(error.scope, "environment-a");
293 assert.strictEqual(error.cause, platformCause);
294 assert.strictEqual(error.cause.reason.cause, nativeCause);
295 assert.equal(
296 error.message,
297 "Failed to derive a desktop preview browser partition for scope environment-a.",
298 );
299 assert.notInclude(error.message, nativeCause.message);
300 }).pipe(
301 Effect.provide(
302 BrowserSession.layer.pipe(Layer.provide(Layer.merge(layerFailingCrypto, layerDialog))),
303 ),
304 );
305 });
306​
307 it.effect("preserves session scope, partition, and the Electron failure", () =>
308 Effect.gen(function* () {
309 const cause = new Error("Electron session failed");
310 fromPartition.mockImplementationOnce(() => {
311 throw cause;
312 });
313 const browserSessions = yield* BrowserSession.BrowserSession;
314 const partition = yield* browserSessions.getPartition("environment-b");
315 const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
316​
317 assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
318 assert.equal(error.scope, "environment-b");
319 assert.equal(error.partition, partition);
320 assert.strictEqual(error.cause, cause);
321 assert.equal(
322 error.message,
323 `Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
324 );
325 assert.notInclude(error.message, cause.message);
326 }).pipe(Effect.provide(layer)),
327 );
328​
329 it.effect("clears storage and cache for every created session", () =>
330 Effect.gen(function* () {
331 const browserSessions = yield* BrowserSession.BrowserSession;
332 yield* browserSessions.getSession("scope-a");
333 yield* browserSessions.getSession("scope-b");
334​
335 yield* browserSessions.clearCookies();
336 yield* browserSessions.clearCache();
337​
338 assert.strictEqual(sessions.size, 2);
339 for (const browserSession of sessions.values()) {
340 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
341 assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
342 {
343 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
344 },
345 ]);
346 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
347 }
348 }).pipe(Effect.provide(layer)),
349 );
350​
351 it.effect("clears a partition whose session has not been opened yet", () =>
352 Effect.gen(function* () {
353 const browserSessions = yield* BrowserSession.BrowserSession;
354 const partition = yield* browserSessions.getPartition("scope-untouched");
355​
356 assert.isUndefined(sessions.get(partition));
357 yield* browserSessions.clearCookies([partition]);
358 assert.isUndefined(sessions.get(partition));
359​
360 yield* browserSessions.getSession("scope-untouched");
361 yield* browserSessions.clearCookies([partition]);
362​
363 const created = sessions.get(partition);
364 assert.isDefined(created);
365 assert.strictEqual(created.clearStorageData.mock.calls.length, 1);
366 }).pipe(Effect.provide(layer)),
367 );
368​
369 it.effect("correlates clear failures while still attempting every session", () =>
370 Effect.gen(function* () {
371 const browserSessions = yield* BrowserSession.BrowserSession;
372 yield* browserSessions.getSession("scope-a");
373 yield* browserSessions.getSession("scope-b");
374 const firstPartition = yield* browserSessions.getPartition("scope-a");
375 const secondPartition = yield* browserSessions.getPartition("scope-b");
376 const firstSession = sessions.get(firstPartition);
377 const secondSession = sessions.get(secondPartition);
378 assert.isDefined(firstSession);
379 assert.isDefined(secondSession);
380​
381 const storageCause = new Error("storage clear failed");
382 secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
383 const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
384​
385 assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
386 assert.equal(storageError.partition, secondPartition);
387 assert.strictEqual(storageError.cause, storageCause);
388 assert.equal(
389 storageError.message,
390 `Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
391 );
392 assert.notInclude(storageError.message, storageCause.message);
393 for (const browserSession of sessions.values()) {
394 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
395 }
396​
397 const cacheCause = new Error("cache clear failed");
398 firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
399 const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
400​
401 assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
402 assert.equal(cacheError.partition, firstPartition);
403 assert.strictEqual(cacheError.cause, cacheCause);
404 assert.equal(
405 cacheError.message,
406 `Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
407 );
408 assert.notInclude(cacheError.message, cacheCause.message);
409 for (const browserSession of sessions.values()) {
410 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
411 }
412 }).pipe(Effect.provide(layer)),
413 );
414});