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

BrowserSession.test.ts

242 lines9.8 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("grants clipboard-sanitized-write through both the request and check handlers", () =>
67 Effect.gen(function* () {
68 const browserSessions = yield* BrowserSession.BrowserSession;
69 const partition = yield* browserSessions.getPartition("scope-a");
70 yield* browserSessions.getSession("scope-a");
71​
72 const browserSession = sessions.get(partition);
73 assert.isDefined(browserSession);
74​
75 const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
76 const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
77 assert.isFunction(requestHandler);
78 assert.isFunction(checkHandler);
79​
80 const requestAllows = (permission: string): boolean => {
81 let granted: boolean | undefined;
82 requestHandler(null, permission, (value: boolean) => {
83 granted = value;
84 });
85 assert.isDefined(granted);
86 return granted;
87 };
88​
89 for (const permission of [
90 "clipboard-read",
91 "clipboard-sanitized-write",
92 "notifications",
93 "geolocation",
94 ]) {
95 assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
96 assert.isTrue(
97 checkHandler(null, permission) as boolean,
98 `check handler should allow ${permission}`,
99 );
100 }
101​
102 // `clipboard-write` is not a real Electron permission — the async write API
103 // uses `clipboard-sanitized-write` — so the stale name must not be granted,
104 // and unrelated permissions stay denied.
105 for (const permission of ["clipboard-write", "midi"]) {
106 assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
107 assert.isFalse(
108 checkHandler(null, permission) as boolean,
109 `check handler should deny ${permission}`,
110 );
111 }
112 }).pipe(Effect.provide(layer)),
113 );
114​
115 it.effect("preserves partition scope and the platform failure chain", () => {
116 const nativeCause = new Error("native digest failed");
117 const platformCause = PlatformError.systemError({
118 _tag: "Unknown",
119 module: "Crypto",
120 method: "digest",
121 cause: nativeCause,
122 });
123 const failingCryptoLayer = Layer.succeed(
124 Crypto.Crypto,
125 Crypto.make({
126 randomBytes: (size) => new Uint8Array(size),
127 digest: () => Effect.fail(platformCause),
128 }),
129 );
130​
131 return Effect.gen(function* () {
132 const browserSessions = yield* BrowserSession.BrowserSession;
133 const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
134​
135 assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
136 assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
137 assert.isTrue(BrowserSession.isBrowserSessionError(error));
138 assert.equal(error.scope, "environment-a");
139 assert.strictEqual(error.cause, platformCause);
140 assert.strictEqual(error.cause.reason.cause, nativeCause);
141 assert.equal(
142 error.message,
143 "Failed to derive a desktop preview browser partition for scope environment-a.",
144 );
145 assert.notInclude(error.message, nativeCause.message);
146 }).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
147 });
148​
149 it.effect("preserves session scope, partition, and the Electron failure", () =>
150 Effect.gen(function* () {
151 const cause = new Error("Electron session failed");
152 fromPartition.mockImplementationOnce(() => {
153 throw cause;
154 });
155 const browserSessions = yield* BrowserSession.BrowserSession;
156 const partition = yield* browserSessions.getPartition("environment-b");
157 const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
158​
159 assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
160 assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
161 assert.isTrue(BrowserSession.isBrowserSessionError(error));
162 assert.equal(error.scope, "environment-b");
163 assert.equal(error.partition, partition);
164 assert.strictEqual(error.cause, cause);
165 assert.equal(
166 error.message,
167 `Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
168 );
169 assert.notInclude(error.message, cause.message);
170 }).pipe(Effect.provide(layer)),
171 );
172​
173 it.effect("clears storage and cache for every created session", () =>
174 Effect.gen(function* () {
175 const browserSessions = yield* BrowserSession.BrowserSession;
176 yield* browserSessions.getSession("scope-a");
177 yield* browserSessions.getSession("scope-b");
178​
179 yield* browserSessions.clearCookies();
180 yield* browserSessions.clearCache();
181​
182 assert.strictEqual(sessions.size, 2);
183 for (const browserSession of sessions.values()) {
184 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
185 assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
186 {
187 storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
188 },
189 ]);
190 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
191 }
192 }).pipe(Effect.provide(layer)),
193 );
194​
195 it.effect("correlates clear failures while still attempting every session", () =>
196 Effect.gen(function* () {
197 const browserSessions = yield* BrowserSession.BrowserSession;
198 yield* browserSessions.getSession("scope-a");
199 yield* browserSessions.getSession("scope-b");
200 const firstPartition = yield* browserSessions.getPartition("scope-a");
201 const secondPartition = yield* browserSessions.getPartition("scope-b");
202 const firstSession = sessions.get(firstPartition);
203 const secondSession = sessions.get(secondPartition);
204 assert.isDefined(firstSession);
205 assert.isDefined(secondSession);
206​
207 const storageCause = new Error("storage clear failed");
208 secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
209 const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
210​
211 assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
212 assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
213 assert.equal(storageError.partition, secondPartition);
214 assert.strictEqual(storageError.cause, storageCause);
215 assert.equal(
216 storageError.message,
217 `Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
218 );
219 assert.notInclude(storageError.message, storageCause.message);
220 for (const browserSession of sessions.values()) {
221 assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
222 }
223​
224 const cacheCause = new Error("cache clear failed");
225 firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
226 const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
227​
228 assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
229 assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
230 assert.equal(cacheError.partition, firstPartition);
231 assert.strictEqual(cacheError.cause, cacheCause);
232 assert.equal(
233 cacheError.message,
234 `Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
235 );
236 assert.notInclude(cacheError.message, cacheCause.message);
237 for (const browserSession of sessions.values()) {
238 assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
239 }
240 }).pipe(Effect.provide(layer)),
241 );
242});