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

BrowserSession.test.ts

297 lines12.2 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>;
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 it.effect("grants clipboard-sanitized-write through both the request and check handlers", () =>
106 Effect.gen(function* () {
107 const browserSessions = yield* BrowserSession.BrowserSession;
108 const partition = yield* browserSessions.getPartition("scope-a");
109 yield* browserSessions.getSession("scope-a");
110​
111 const browserSession = sessions.get(partition);
112 assert.isDefined(browserSession);
113​
114 const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
115 const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
116 assert.isFunction(requestHandler);
117 assert.isFunction(checkHandler);
118​
119 const requestAllows = (permission: string): boolean => {
120 let granted: boolean | undefined;
121 requestHandler(null, permission, (value: boolean) => {
122 granted = value;
123 });
124 assert.isDefined(granted);
125 return granted;
126 };
127​
128 for (const permission of [
129 "clipboard-read",
130 "clipboard-sanitized-write",
131 "notifications",
132 "geolocation",
133 ]) {
134 assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
135 assert.isTrue(
136 checkHandler(null, permission) as boolean,
137 `check handler should allow ${permission}`,
138 );
139 }
140​
141 // `clipboard-write` is not a real Electron permission — the async write API
142 // uses `clipboard-sanitized-write` — so the stale name must not be granted,
143 // and unrelated permissions stay denied.
144 for (const permission of ["clipboard-write", "midi"]) {
145 assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
146 assert.isFalse(
147 checkHandler(null, permission) as boolean,
148 `check handler should deny ${permission}`,
149 );
150 }
151 }).pipe(Effect.provide(layer)),
152 );
153​
154 it.effect("preserves partition scope and the platform failure chain", () => {
155 const nativeCause = new Error("native digest failed");
156 const platformCause = PlatformError.systemError({
157 _tag: "Unknown",
158 module: "Crypto",
159 method: "digest",
160 cause: nativeCause,
161 });
162 const failingCryptoLayer = Layer.succeed(
163 Crypto.Crypto,
164 Crypto.make({
165 randomBytes: (size) => new Uint8Array(size),
166 digest: () => Effect.fail(platformCause),
167 }),
168 );
169​
170 return Effect.gen(function* () {
171 const browserSessions = yield* BrowserSession.BrowserSession;
172 const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
173​
174 assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
175 assert.equal(error.scope, "environment-a");
176 assert.strictEqual(error.cause, platformCause);
177 assert.strictEqual(error.cause.reason.cause, nativeCause);
178 assert.equal(
179 error.message,
180 "Failed to derive a desktop preview browser partition for scope environment-a.",
181 );
182 assert.notInclude(error.message, nativeCause.message);
183 }).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
184 });
185​
186 it.effect("preserves session scope, partition, and the Electron failure", () =>
187 Effect.gen(function* () {
188 const cause = new Error("Electron session failed");
189 fromPartition.mockImplementationOnce(() => {
190 throw cause;
191 });
192 const browserSessions = yield* BrowserSession.BrowserSession;
193 const partition = yield* browserSessions.getPartition("environment-b");
194 const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
195​
196 assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
197 assert.equal(error.scope, "environment-b");
198 assert.equal(error.partition, partition);
199 assert.strictEqual(error.cause, cause);
200 assert.equal(
201 error.message,
202 `Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
203 );
204 assert.notInclude(error.message, cause.message);
205 }).pipe(Effect.provide(layer)),
206 );
207​
208 it.effect("clears storage and cache for every created session", () =>
209 Effect.gen(function* () {
210 const browserSessions = yield* BrowserSession.BrowserSession;
211 yield* browserSessions.getSession("scope-a");
212 yield* browserSessions.getSession("scope-b");
213​
214 yield* browserSessions.clearCookies();
215 yield* browserSessions.clearCache();
216​
217 assert.strictEqual(sessions.size, 2);
218 for (const browserSession of sessions.values()) {
219 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
220 assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
221 {
222 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
223 },
224 ]);
225 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
226 }
227 }).pipe(Effect.provide(layer)),
228 );
229​
230 it.effect("clears a partition whose session has not been opened yet", () =>
231 Effect.gen(function* () {
232 const browserSessions = yield* BrowserSession.BrowserSession;
233 const partition = yield* browserSessions.getPartition("scope-untouched");
234​
235 // Deriving the partition string does not create the session, and the
236 // clear only walks sessions it already holds. Without loading it first
237 // this reports success and deletes nothing — which is what a user
238 // clearing a profile after a restart would get.
239 assert.isUndefined(sessions.get(partition));
240 yield* browserSessions.clearCookies([partition]);
241 assert.isUndefined(sessions.get(partition));
242​
243 yield* browserSessions.getSession("scope-untouched");
244 yield* browserSessions.clearCookies([partition]);
245​
246 const created = sessions.get(partition);
247 assert.isDefined(created);
248 assert.strictEqual(created.clearStorageData.mock.calls.length, 1);
249 }).pipe(Effect.provide(layer)),
250 );
251​
252 it.effect("correlates clear failures while still attempting every session", () =>
253 Effect.gen(function* () {
254 const browserSessions = yield* BrowserSession.BrowserSession;
255 yield* browserSessions.getSession("scope-a");
256 yield* browserSessions.getSession("scope-b");
257 const firstPartition = yield* browserSessions.getPartition("scope-a");
258 const secondPartition = yield* browserSessions.getPartition("scope-b");
259 const firstSession = sessions.get(firstPartition);
260 const secondSession = sessions.get(secondPartition);
261 assert.isDefined(firstSession);
262 assert.isDefined(secondSession);
263​
264 const storageCause = new Error("storage clear failed");
265 secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
266 const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
267​
268 assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
269 assert.equal(storageError.partition, secondPartition);
270 assert.strictEqual(storageError.cause, storageCause);
271 assert.equal(
272 storageError.message,
273 `Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
274 );
275 assert.notInclude(storageError.message, storageCause.message);
276 for (const browserSession of sessions.values()) {
277 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
278 }
279​
280 const cacheCause = new Error("cache clear failed");
281 firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
282 const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
283​
284 assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
285 assert.equal(cacheError.partition, firstPartition);
286 assert.strictEqual(cacheError.cause, cacheCause);
287 assert.equal(
288 cacheError.message,
289 `Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
290 );
291 assert.notInclude(cacheError.message, cacheCause.message);
292 for (const browserSession of sessions.values()) {
293 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
294 }
295 }).pipe(Effect.provide(layer)),
296 );
297});