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

BrowserSession.test.ts

415 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 "notifications",
184 "geolocation",
185 "fullscreen",
186 ]) {
187 assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
188 assert.isTrue(
189 checkHandler(null, permission) as boolean,
190 `check handler should allow ${permission}`,
191 );
192 }
193​
194 // `clipboard-write` is not a real Electron permission — the async write API
195 // uses `clipboard-sanitized-write` — so the stale name must not be granted,
196 // and unrelated permissions stay denied.
197 for (const permission of ["clipboard-write", "midi"]) {
198 assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
199 assert.isFalse(
200 checkHandler(null, permission) as boolean,
201 `check handler should deny ${permission}`,
202 );
203 }
204 }).pipe(Effect.provide(layer)),
205 );
206​
207 it.effect("opens custom-scheme links externally only after the user confirms", () =>
208 Effect.gen(function* () {
209 const browserSessions = yield* BrowserSession.BrowserSession;
210 const partition = yield* browserSessions.getPartition("scope-a");
211 yield* browserSessions.getSession("scope-a");
212 const requestHandler =
213 sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0];
214 assert.isFunction(requestHandler);
215​
216 const request = (externalURL: string) =>
217 Effect.callback<boolean>((resume) => {
218 requestHandler(
219 null,
220 "openExternal",
221 (granted: boolean) => resume(Effect.succeed(granted)),
222 { externalURL },
223 );
224 });
225​
226 showMessageBox.mockReset();
227 showMessageBox.mockReturnValueOnce(0).mockReturnValueOnce(1);
228 assert.isTrue(yield* request("slack://open?team=T1"));
229 assert.isFalse(yield* request("zoommtg://zoom.us/join"));
230 assert.strictEqual(showMessageBox.mock.calls.length, 2);
231​
232 for (const url of ["file:///etc/passwd", "javascript:alert(1)", "data:text/html,x"]) {
233 assert.isFalse(yield* request(url), `${url} must never open externally`);
234 }
235 assert.strictEqual(showMessageBox.mock.calls.length, 2);
236 }).pipe(Effect.provide(layer)),
237 );
238​
239 it.effect("attaches the open-externally prompt to the window hosting the preview", () =>
240 Effect.gen(function* () {
241 const browserSessions = yield* BrowserSession.BrowserSession;
242 const partition = yield* browserSessions.getPartition("scope-a");
243 yield* browserSessions.getSession("scope-a");
244 const requestHandler =
245 sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0];
246 assert.isFunction(requestHandler);
247​
248 const hostWindow = { id: 7 } as unknown as Electron.BrowserWindow;
249 const host = { isDestroyed: () => false };
250 const guest = { isDestroyed: () => false, hostWebContents: host };
251 fromWebContents.mockImplementation((webContents) =>
252 webContents === host ? hostWindow : null,
253 );
254 showMessageBox.mockReset();
255 showMessageBox.mockReturnValueOnce(1);
256​
257 yield* Effect.callback<boolean>((resume) => {
258 requestHandler(
259 guest,
260 "openExternal",
261 (granted: boolean) => resume(Effect.succeed(granted)),
262 {
263 externalURL: "slack://open?team=T1",
264 },
265 );
266 });
267​
268 assert.strictEqual(showMessageBox.mock.calls[0]?.[1], hostWindow);
269 }).pipe(Effect.provide(layer)),
270 );
271​
272 it.effect("preserves partition scope and the platform failure chain", () => {
273 const nativeCause = new Error("native digest failed");
274 const platformCause = PlatformError.systemError({
275 _tag: "Unknown",
276 module: "Crypto",
277 method: "digest",
278 cause: nativeCause,
279 });
280 const layerFailingCrypto = Layer.succeed(
281 Crypto.Crypto,
282 Crypto.make({
283 randomBytes: (size) => new Uint8Array(size),
284 digest: () => Effect.fail(platformCause),
285 }),
286 );
287​
288 return Effect.gen(function* () {
289 const browserSessions = yield* BrowserSession.BrowserSession;
290 const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
291​
292 assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
293 assert.equal(error.scope, "environment-a");
294 assert.strictEqual(error.cause, platformCause);
295 assert.strictEqual(error.cause.reason.cause, nativeCause);
296 assert.equal(
297 error.message,
298 "Failed to derive a desktop preview browser partition for scope environment-a.",
299 );
300 assert.notInclude(error.message, nativeCause.message);
301 }).pipe(
302 Effect.provide(
303 BrowserSession.layer.pipe(Layer.provide(Layer.merge(layerFailingCrypto, layerDialog))),
304 ),
305 );
306 });
307​
308 it.effect("preserves session scope, partition, and the Electron failure", () =>
309 Effect.gen(function* () {
310 const cause = new Error("Electron session failed");
311 fromPartition.mockImplementationOnce(() => {
312 throw cause;
313 });
314 const browserSessions = yield* BrowserSession.BrowserSession;
315 const partition = yield* browserSessions.getPartition("environment-b");
316 const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
317​
318 assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
319 assert.equal(error.scope, "environment-b");
320 assert.equal(error.partition, partition);
321 assert.strictEqual(error.cause, cause);
322 assert.equal(
323 error.message,
324 `Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
325 );
326 assert.notInclude(error.message, cause.message);
327 }).pipe(Effect.provide(layer)),
328 );
329​
330 it.effect("clears storage and cache for every created session", () =>
331 Effect.gen(function* () {
332 const browserSessions = yield* BrowserSession.BrowserSession;
333 yield* browserSessions.getSession("scope-a");
334 yield* browserSessions.getSession("scope-b");
335​
336 yield* browserSessions.clearCookies();
337 yield* browserSessions.clearCache();
338​
339 assert.strictEqual(sessions.size, 2);
340 for (const browserSession of sessions.values()) {
341 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
342 assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
343 {
344 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
345 },
346 ]);
347 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
348 }
349 }).pipe(Effect.provide(layer)),
350 );
351​
352 it.effect("clears a partition whose session has not been opened yet", () =>
353 Effect.gen(function* () {
354 const browserSessions = yield* BrowserSession.BrowserSession;
355 const partition = yield* browserSessions.getPartition("scope-untouched");
356​
357 assert.isUndefined(sessions.get(partition));
358 yield* browserSessions.clearCookies([partition]);
359 assert.isUndefined(sessions.get(partition));
360​
361 yield* browserSessions.getSession("scope-untouched");
362 yield* browserSessions.clearCookies([partition]);
363​
364 const created = sessions.get(partition);
365 assert.isDefined(created);
366 assert.strictEqual(created.clearStorageData.mock.calls.length, 1);
367 }).pipe(Effect.provide(layer)),
368 );
369​
370 it.effect("correlates clear failures while still attempting every session", () =>
371 Effect.gen(function* () {
372 const browserSessions = yield* BrowserSession.BrowserSession;
373 yield* browserSessions.getSession("scope-a");
374 yield* browserSessions.getSession("scope-b");
375 const firstPartition = yield* browserSessions.getPartition("scope-a");
376 const secondPartition = yield* browserSessions.getPartition("scope-b");
377 const firstSession = sessions.get(firstPartition);
378 const secondSession = sessions.get(secondPartition);
379 assert.isDefined(firstSession);
380 assert.isDefined(secondSession);
381​
382 const storageCause = new Error("storage clear failed");
383 secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
384 const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
385​
386 assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
387 assert.equal(storageError.partition, secondPartition);
388 assert.strictEqual(storageError.cause, storageCause);
389 assert.equal(
390 storageError.message,
391 `Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
392 );
393 assert.notInclude(storageError.message, storageCause.message);
394 for (const browserSession of sessions.values()) {
395 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
396 }
397​
398 const cacheCause = new Error("cache clear failed");
399 firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
400 const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
401​
402 assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
403 assert.equal(cacheError.partition, firstPartition);
404 assert.strictEqual(cacheError.cause, cacheCause);
405 assert.equal(
406 cacheError.message,
407 `Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
408 );
409 assert.notInclude(cacheError.message, cacheCause.message);
410 for (const browserSession of sessions.values()) {
411 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
412 }
413 }).pipe(Effect.provide(layer)),
414 );
415});