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

BrowserSession.test.ts

335 lines14.1 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​
24vi.mock("electron", () => ({
25 session: {
26 fromPartition,
27 },
28}));
29​
30import * as BrowserSession from "./BrowserSession.ts";
31​
32const layer = BrowserSession.layer.pipe(Layer.provide(NodeServices.layer));
33​
34describe("BrowserSession", () => {
35 beforeEach(() => {
36 sessions.clear();
37 fromPartition.mockReset();
38 fromPartition.mockImplementation((partition: string) => {
39 const browserSession = {
40 clearCache: vi.fn(() => Promise.resolve()),
41 clearStorageData: vi.fn(() => Promise.resolve()),
42 getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
43 setPermissionRequestHandler: vi.fn(),
44 setPermissionCheckHandler: vi.fn(),
45 setUserAgent: vi.fn(),
46 };
47 sessions.set(partition, browserSession);
48 return browserSession;
49 });
50 });
51​
52 it.effect("derives deterministic partitions and memoizes sessions", () =>
53 Effect.gen(function* () {
54 const browserSessions = yield* BrowserSession.BrowserSession;
55​
56 const partition = yield* browserSessions.getPartition("scope-a");
57 const first = yield* browserSessions.getSession("scope-a");
58 const second = yield* browserSessions.getSession("scope-a");
59​
60 assert.strictEqual(partition, "persist:t3code-preview-f051bb2c68cb7b2fe969");
61 assert.strictEqual(first, second);
62 assert.strictEqual(fromPartition.mock.calls.length, 1);
63 }).pipe(Effect.provide(layer)),
64 );
65​
66 it.effect("keeps scopes that differ only by a lone surrogate in separate partitions", () =>
67 Effect.gen(function* () {
68 const browserSessions = yield* BrowserSession.BrowserSession;
69​
70 // TextEncoder folds a lone surrogate to U+FFFD, so without escaping these
71 // two supported ids would hash to one partition and share every cookie.
72 const loneSurrogate = yield* browserSessions.getPartition("p\ud800");
73 const replacementChar = yield* browserSessions.getPartition("p\ufffd");
74 assert.notStrictEqual(loneSurrogate, replacementChar);
75​
76 // The escape can't be forged with a literal backslash either.
77 const literal = yield* browserSessions.getPartition("p\\ud800");
78 assert.notStrictEqual(literal, loneSurrogate);
79​
80 // And a well-formed scope still lands on its historical partition.
81 assert.strictEqual(
82 yield* browserSessions.getPartition("scope-a"),
83 "persist:t3code-preview-f051bb2c68cb7b2fe969",
84 );
85 }).pipe(Effect.provide(layer)),
86 );
87​
88 it.effect("keeps legacy defaults disjoint from nondefault profile partitions", () =>
89 Effect.gen(function* () {
90 const browserSessions = yield* BrowserSession.BrowserSession;
91​
92 // These share the same scope string: default environment `a::b`, and
93 // environment `a` with nondefault profile `b`.
94 const legacyDefault = yield* browserSessions.getPartition("a::b");
95 const nondefaultProfile = yield* browserSessions.getPartition("a::b", true, "profile");
96​
97 assert.strictEqual(legacyDefault, "persist:t3code-preview-78f0be89237d77f7a70e");
98 assert.strictEqual(nondefaultProfile, "persist:t3code-preview-profile-78f0be89237d77f7a70e");
99 assert.notStrictEqual(nondefaultProfile, legacyDefault);
100 assert.isTrue(browserSessions.isPartition(legacyDefault));
101 assert.isTrue(browserSessions.isPartition(nondefaultProfile));
102 }).pipe(Effect.provide(layer)),
103 );
104​
105 // A rewritten session UA — any variant, even ones that keep the Electron
106 // token — makes Cloudflare Turnstile loop with error 600010 (#5002), so
107 // the guest must end up with Electron's native User-Agent. The mock applies
108 // setUserAgent calls, so this fails on any reintroduced rewrite while still
109 // permitting a harmless re-set of the unchanged native string.
110 it.effect("keeps the guest's effective User-Agent equal to Electron's native one", () =>
111 Effect.gen(function* () {
112 // Electron's real UA shape: app token, then Chrome, then Electron, then
113 // Safari — the token order and casing matter to any strip regex.
114 const nativeUserAgent =
115 "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";
116 fromPartition.mockReset();
117 fromPartition.mockImplementation((partition: string) => {
118 let userAgent = nativeUserAgent;
119 const browserSession = {
120 clearCache: vi.fn(() => Promise.resolve()),
121 clearStorageData: vi.fn(() => Promise.resolve()),
122 getUserAgent: vi.fn(() => userAgent),
123 setPermissionRequestHandler: vi.fn(),
124 setPermissionCheckHandler: vi.fn(),
125 setUserAgent: vi.fn((next: string) => {
126 userAgent = next;
127 }),
128 };
129 sessions.set(partition, browserSession);
130 return browserSession;
131 });
132​
133 const browserSessions = yield* BrowserSession.BrowserSession;
134 const partition = yield* browserSessions.getPartition("scope-a");
135 yield* browserSessions.getSession("scope-a");
136​
137 const browserSession = sessions.get(partition);
138 assert.isDefined(browserSession);
139 assert.strictEqual(browserSession.getUserAgent(), nativeUserAgent);
140 }).pipe(Effect.provide(layer)),
141 );
142​
143 it.effect("grants clipboard-sanitized-write through both the request and check handlers", () =>
144 Effect.gen(function* () {
145 const browserSessions = yield* BrowserSession.BrowserSession;
146 const partition = yield* browserSessions.getPartition("scope-a");
147 yield* browserSessions.getSession("scope-a");
148​
149 const browserSession = sessions.get(partition);
150 assert.isDefined(browserSession);
151​
152 const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
153 const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
154 assert.isFunction(requestHandler);
155 assert.isFunction(checkHandler);
156​
157 const requestAllows = (permission: string): boolean => {
158 let granted: boolean | undefined;
159 requestHandler(null, permission, (value: boolean) => {
160 granted = value;
161 });
162 assert.isDefined(granted);
163 return granted;
164 };
165​
166 for (const permission of [
167 "clipboard-read",
168 "clipboard-sanitized-write",
169 "notifications",
170 "geolocation",
171 ]) {
172 assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
173 assert.isTrue(
174 checkHandler(null, permission) as boolean,
175 `check handler should allow ${permission}`,
176 );
177 }
178​
179 // `clipboard-write` is not a real Electron permission — the async write API
180 // uses `clipboard-sanitized-write` — so the stale name must not be granted,
181 // and unrelated permissions stay denied.
182 for (const permission of ["clipboard-write", "midi"]) {
183 assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
184 assert.isFalse(
185 checkHandler(null, permission) as boolean,
186 `check handler should deny ${permission}`,
187 );
188 }
189 }).pipe(Effect.provide(layer)),
190 );
191​
192 it.effect("preserves partition scope and the platform failure chain", () => {
193 const nativeCause = new Error("native digest failed");
194 const platformCause = PlatformError.systemError({
195 _tag: "Unknown",
196 module: "Crypto",
197 method: "digest",
198 cause: nativeCause,
199 });
200 const failingCryptoLayer = Layer.succeed(
201 Crypto.Crypto,
202 Crypto.make({
203 randomBytes: (size) => new Uint8Array(size),
204 digest: () => Effect.fail(platformCause),
205 }),
206 );
207​
208 return Effect.gen(function* () {
209 const browserSessions = yield* BrowserSession.BrowserSession;
210 const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
211​
212 assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
213 assert.equal(error.scope, "environment-a");
214 assert.strictEqual(error.cause, platformCause);
215 assert.strictEqual(error.cause.reason.cause, nativeCause);
216 assert.equal(
217 error.message,
218 "Failed to derive a desktop preview browser partition for scope environment-a.",
219 );
220 assert.notInclude(error.message, nativeCause.message);
221 }).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
222 });
223​
224 it.effect("preserves session scope, partition, and the Electron failure", () =>
225 Effect.gen(function* () {
226 const cause = new Error("Electron session failed");
227 fromPartition.mockImplementationOnce(() => {
228 throw cause;
229 });
230 const browserSessions = yield* BrowserSession.BrowserSession;
231 const partition = yield* browserSessions.getPartition("environment-b");
232 const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
233​
234 assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
235 assert.equal(error.scope, "environment-b");
236 assert.equal(error.partition, partition);
237 assert.strictEqual(error.cause, cause);
238 assert.equal(
239 error.message,
240 `Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
241 );
242 assert.notInclude(error.message, cause.message);
243 }).pipe(Effect.provide(layer)),
244 );
245​
246 it.effect("clears storage and cache for every created session", () =>
247 Effect.gen(function* () {
248 const browserSessions = yield* BrowserSession.BrowserSession;
249 yield* browserSessions.getSession("scope-a");
250 yield* browserSessions.getSession("scope-b");
251​
252 yield* browserSessions.clearCookies();
253 yield* browserSessions.clearCache();
254​
255 assert.strictEqual(sessions.size, 2);
256 for (const browserSession of sessions.values()) {
257 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
258 assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
259 {
260 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
261 },
262 ]);
263 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
264 }
265 }).pipe(Effect.provide(layer)),
266 );
267​
268 it.effect("clears a partition whose session has not been opened yet", () =>
269 Effect.gen(function* () {
270 const browserSessions = yield* BrowserSession.BrowserSession;
271 const partition = yield* browserSessions.getPartition("scope-untouched");
272​
273 // Deriving the partition string does not create the session, and the
274 // clear only walks sessions it already holds. Without loading it first
275 // this reports success and deletes nothing — which is what a user
276 // clearing a profile after a restart would get.
277 assert.isUndefined(sessions.get(partition));
278 yield* browserSessions.clearCookies([partition]);
279 assert.isUndefined(sessions.get(partition));
280​
281 yield* browserSessions.getSession("scope-untouched");
282 yield* browserSessions.clearCookies([partition]);
283​
284 const created = sessions.get(partition);
285 assert.isDefined(created);
286 assert.strictEqual(created.clearStorageData.mock.calls.length, 1);
287 }).pipe(Effect.provide(layer)),
288 );
289​
290 it.effect("correlates clear failures while still attempting every session", () =>
291 Effect.gen(function* () {
292 const browserSessions = yield* BrowserSession.BrowserSession;
293 yield* browserSessions.getSession("scope-a");
294 yield* browserSessions.getSession("scope-b");
295 const firstPartition = yield* browserSessions.getPartition("scope-a");
296 const secondPartition = yield* browserSessions.getPartition("scope-b");
297 const firstSession = sessions.get(firstPartition);
298 const secondSession = sessions.get(secondPartition);
299 assert.isDefined(firstSession);
300 assert.isDefined(secondSession);
301​
302 const storageCause = new Error("storage clear failed");
303 secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
304 const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
305​
306 assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
307 assert.equal(storageError.partition, secondPartition);
308 assert.strictEqual(storageError.cause, storageCause);
309 assert.equal(
310 storageError.message,
311 `Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
312 );
313 assert.notInclude(storageError.message, storageCause.message);
314 for (const browserSession of sessions.values()) {
315 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
316 }
317​
318 const cacheCause = new Error("cache clear failed");
319 firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
320 const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
321​
322 assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
323 assert.equal(cacheError.partition, firstPartition);
324 assert.strictEqual(cacheError.cause, cacheCause);
325 assert.equal(
326 cacheError.message,
327 `Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
328 );
329 assert.notInclude(cacheError.message, cacheCause.message);
330 for (const browserSession of sessions.values()) {
331 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
332 }
333 }).pipe(Effect.provide(layer)),
334 );
335});