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

BrowserSession.test.ts

303 lines12.6 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.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
176 assert.isTrue(BrowserSession.isBrowserSessionError(error));
177 assert.equal(error.scope, "environment-a");
178 assert.strictEqual(error.cause, platformCause);
179 assert.strictEqual(error.cause.reason.cause, nativeCause);
180 assert.equal(
181 error.message,
182 "Failed to derive a desktop preview browser partition for scope environment-a.",
183 );
184 assert.notInclude(error.message, nativeCause.message);
185 }).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
186 });
187​
188 it.effect("preserves session scope, partition, and the Electron failure", () =>
189 Effect.gen(function* () {
190 const cause = new Error("Electron session failed");
191 fromPartition.mockImplementationOnce(() => {
192 throw cause;
193 });
194 const browserSessions = yield* BrowserSession.BrowserSession;
195 const partition = yield* browserSessions.getPartition("environment-b");
196 const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
197​
198 assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
199 assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
200 assert.isTrue(BrowserSession.isBrowserSessionError(error));
201 assert.equal(error.scope, "environment-b");
202 assert.equal(error.partition, partition);
203 assert.strictEqual(error.cause, cause);
204 assert.equal(
205 error.message,
206 `Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
207 );
208 assert.notInclude(error.message, cause.message);
209 }).pipe(Effect.provide(layer)),
210 );
211​
212 it.effect("clears storage and cache for every created session", () =>
213 Effect.gen(function* () {
214 const browserSessions = yield* BrowserSession.BrowserSession;
215 yield* browserSessions.getSession("scope-a");
216 yield* browserSessions.getSession("scope-b");
217​
218 yield* browserSessions.clearCookies();
219 yield* browserSessions.clearCache();
220​
221 assert.strictEqual(sessions.size, 2);
222 for (const browserSession of sessions.values()) {
223 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
224 assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
225 {
226 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
227 },
228 ]);
229 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
230 }
231 }).pipe(Effect.provide(layer)),
232 );
233​
234 it.effect("clears a partition whose session has not been opened yet", () =>
235 Effect.gen(function* () {
236 const browserSessions = yield* BrowserSession.BrowserSession;
237 const partition = yield* browserSessions.getPartition("scope-untouched");
238​
239 // Deriving the partition string does not create the session, and the
240 // clear only walks sessions it already holds. Without loading it first
241 // this reports success and deletes nothing — which is what a user
242 // clearing a profile after a restart would get.
243 assert.isUndefined(sessions.get(partition));
244 yield* browserSessions.clearCookies([partition]);
245 assert.isUndefined(sessions.get(partition));
246​
247 yield* browserSessions.getSession("scope-untouched");
248 yield* browserSessions.clearCookies([partition]);
249​
250 const created = sessions.get(partition);
251 assert.isDefined(created);
252 assert.strictEqual(created.clearStorageData.mock.calls.length, 1);
253 }).pipe(Effect.provide(layer)),
254 );
255​
256 it.effect("correlates clear failures while still attempting every session", () =>
257 Effect.gen(function* () {
258 const browserSessions = yield* BrowserSession.BrowserSession;
259 yield* browserSessions.getSession("scope-a");
260 yield* browserSessions.getSession("scope-b");
261 const firstPartition = yield* browserSessions.getPartition("scope-a");
262 const secondPartition = yield* browserSessions.getPartition("scope-b");
263 const firstSession = sessions.get(firstPartition);
264 const secondSession = sessions.get(secondPartition);
265 assert.isDefined(firstSession);
266 assert.isDefined(secondSession);
267​
268 const storageCause = new Error("storage clear failed");
269 secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
270 const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
271​
272 assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
273 assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
274 assert.equal(storageError.partition, secondPartition);
275 assert.strictEqual(storageError.cause, storageCause);
276 assert.equal(
277 storageError.message,
278 `Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
279 );
280 assert.notInclude(storageError.message, storageCause.message);
281 for (const browserSession of sessions.values()) {
282 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
283 }
284​
285 const cacheCause = new Error("cache clear failed");
286 firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
287 const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
288​
289 assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
290 assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
291 assert.equal(cacheError.partition, firstPartition);
292 assert.strictEqual(cacheError.cause, cacheCause);
293 assert.equal(
294 cacheError.message,
295 `Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
296 );
297 assert.notInclude(cacheError.message, cacheCause.message);
298 for (const browserSession of sessions.values()) {
299 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
300 }
301 }).pipe(Effect.provide(layer)),
302 );
303});