@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 659 lines 27.8 KB
Raw
1 import { assert, describe, it } from "@effect/vitest";
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as Deferred from "effect/Deferred";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Layer from "effect/Layer";
8 import * as NodeEvents from "node:events";
9 import { beforeEach, vi } from "vite-plus/test";
10
11 const { fromPartition, sessions } = vi.hoisted(() => ({
12 fromPartition: vi.fn(),
13 sessions: new Map<
14 string,
15 {
16 readonly clearCache: ReturnType<typeof vi.fn>;
17 readonly clearStorageData: ReturnType<typeof vi.fn>;
18 readonly closeAllConnections: ReturnType<typeof vi.fn>;
19 readonly storagePath: string | null;
20 readonly getUserAgent: ReturnType<typeof vi.fn<() => string>>;
21 readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
22 readonly setPermissionCheckHandler: ReturnType<typeof vi.fn>;
23 readonly setUserAgent: ReturnType<typeof vi.fn>;
24 readonly webRequest: { readonly onBeforeSendHeaders: ReturnType<typeof vi.fn> };
25 }
26 >(),
27 }));
28
29 const storage = vi.hoisted(() => ({ root: "" }));
30
31 const { fromWebContents } = vi.hoisted(() => ({
32 fromWebContents: vi.fn<(webContents: unknown) => unknown>(() => null),
33 }));
34
35 const { appListeners } = vi.hoisted(() => ({
36 appListeners: new Map<string, (...args: unknown[]) => void>(),
37 }));
38
39 vi.mock("electron", () => ({
40 app: {
41 on: (eventName: string, listener: (...args: unknown[]) => void) => {
42 appListeners.set(eventName, listener);
43 },
44 removeListener: (eventName: string) => {
45 appListeners.delete(eventName);
46 },
47 },
48 BrowserWindow: { fromWebContents },
49 session: {
50 fromPartition,
51 },
52 }));
53
54 import * as ElectronApp from "../electron/ElectronApp.ts";
55 import * as ElectronDialog from "../electron/ElectronDialog.ts";
56 import * as BrowserSession from "./BrowserSession.ts";
57
58 const { showMessageBox, showErrorBox } = vi.hoisted(() => ({
59 showMessageBox: vi.fn<
60 (
61 options: Electron.MessageBoxOptions,
62 owner?: Electron.BrowserWindow,
63 ) => number | Promise<number>
64 >(() => 1),
65 showErrorBox: vi.fn<(title: string, content: string) => void>(),
66 }));
67 const layerDialog = Layer.succeed(ElectronDialog.ElectronDialog, {
68 pickFolder: () => Effect.die("unused"),
69 pickFiles: () => Effect.die("unused"),
70 showMessageBox: (options, owner) =>
71 Effect.promise(async () => ({
72 response: await showMessageBox(options, owner),
73 checkboxChecked: false,
74 })),
75 showErrorBox: (title, content) => Effect.sync(() => showErrorBox(title, content)),
76 });
77 const layer = BrowserSession.layer.pipe(
78 Layer.provide(
79 Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, layerDialog, ElectronApp.layer),
80 ),
81 );
82
83 const selfSignedCertificate = {
84 fingerprint: "sha256/self-signed",
85 subjectName: "localhost",
86 issuerName: "localhost",
87 validStart: 1_735_776_000,
88 validExpiry: 1_807_056_000,
89 } as Electron.Certificate;
90
91 /** Raises Electron's `certificate-error` for a preview guest in `browserSession`. */
92 const certificateError = (
93 browserSession: unknown,
94 input: {
95 readonly url: string;
96 readonly certificate?: Electron.Certificate;
97 readonly isMainFrame?: boolean;
98 },
99 ) => {
100 const listener = appListeners.get("certificate-error");
101 assert.isDefined(listener, "preview sessions should handle certificate errors");
102 const guest = Object.assign(new NodeEvents.EventEmitter(), {
103 session: browserSession,
104 hostWebContents: null,
105 isDestroyed: () => false,
106 });
107 const event = { preventDefault: vi.fn() };
108 const decision = Deferred.makeUnsafe<boolean>();
109 const callback = vi.fn((trusted: boolean) => {
110 Deferred.doneUnsafe(decision, Effect.succeed(trusted));
111 });
112 listener(
113 event,
114 guest,
115 input.url,
116 "net::ERR_CERT_AUTHORITY_INVALID",
117 input.certificate ?? selfSignedCertificate,
118 callback,
119 input.isMainFrame ?? true,
120 );
121 return { guest, event, callback, trusted: Deferred.await(decision) };
122 };
123
124 /** Answers the certificate prompt with its "Trust…" button. */
125 const trustCertificateButton = (options: Electron.MessageBoxOptions): number => {
126 const index = (options.buttons ?? []).findIndex((label) => label.startsWith("Trust"));
127 assert.notStrictEqual(index, -1, "the certificate prompt should offer to trust");
128 return index;
129 };
130
131 describe("BrowserSession", () => {
132 beforeEach(() => {
133 sessions.clear();
134 appListeners.clear();
135 storage.root = "";
136 showErrorBox.mockReset();
137 fromPartition.mockReset();
138 fromPartition.mockImplementation((partition: string) => {
139 const browserSession = {
140 clearCache: vi.fn(() => Promise.resolve()),
141 clearStorageData: vi.fn(() => Promise.resolve()),
142 closeAllConnections: vi.fn(() => Promise.resolve()),
143 // Like Electron, only a `persist:` partition has storage on disk.
144 storagePath:
145 storage.root !== "" && partition.startsWith("persist:")
146 ? `${storage.root}/Partitions/${partition}`
147 : null,
148 getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
149 setPermissionRequestHandler: vi.fn(),
150 setPermissionCheckHandler: vi.fn(),
151 setUserAgent: vi.fn(),
152 webRequest: { onBeforeSendHeaders: vi.fn() },
153 };
154 sessions.set(partition, browserSession);
155 return browserSession;
156 });
157 });
158
159 it.effect("derives deterministic partitions and memoizes sessions", () =>
160 Effect.gen(function* () {
161 const browserSessions = yield* BrowserSession.BrowserSession;
162
163 const partition = yield* browserSessions.getPartition("scope-a");
164 const first = yield* browserSessions.getSession("scope-a");
165 const second = yield* browserSessions.getSession("scope-a");
166
167 assert.strictEqual(partition, "persist:t3code-preview-f051bb2c68cb7b2fe969");
168 assert.strictEqual(first, second);
169 assert.strictEqual(fromPartition.mock.calls.length, 1);
170 }).pipe(Effect.provide(layer)),
171 );
172
173 it.effect("keeps scopes that differ only by a lone surrogate in separate partitions", () =>
174 Effect.gen(function* () {
175 const browserSessions = yield* BrowserSession.BrowserSession;
176
177 const loneSurrogate = yield* browserSessions.getPartition("p\ud800");
178 const replacementChar = yield* browserSessions.getPartition("p\ufffd");
179 assert.notStrictEqual(loneSurrogate, replacementChar);
180
181 const literal = yield* browserSessions.getPartition("p\\ud800");
182 assert.notStrictEqual(literal, loneSurrogate);
183
184 assert.strictEqual(
185 yield* browserSessions.getPartition("scope-a"),
186 "persist:t3code-preview-f051bb2c68cb7b2fe969",
187 );
188 }).pipe(Effect.provide(layer)),
189 );
190
191 it.effect("keeps legacy defaults disjoint from nondefault profile partitions", () =>
192 Effect.gen(function* () {
193 const browserSessions = yield* BrowserSession.BrowserSession;
194
195 const legacyDefault = yield* browserSessions.getPartition("a::b");
196 const nondefaultProfile = yield* browserSessions.getPartition("a::b", true, "profile");
197
198 assert.strictEqual(legacyDefault, "persist:t3code-preview-78f0be89237d77f7a70e");
199 assert.strictEqual(nondefaultProfile, "persist:t3code-preview-profile-78f0be89237d77f7a70e");
200 assert.notStrictEqual(nondefaultProfile, legacyDefault);
201 assert.isTrue(browserSessions.isPartition(legacyDefault));
202 assert.isTrue(browserSessions.isPartition(nondefaultProfile));
203 }).pipe(Effect.provide(layer)),
204 );
205
206 it.effect("keeps the native User-Agent except for the Electron token sent to Teams", () =>
207 Effect.gen(function* () {
208 const nativeUserAgent =
209 "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";
210 const teamsUserAgent =
211 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) T3Code(Alpha)/0.0.33 Chrome/146.0.7680.216 Safari/537.36";
212 fromPartition.mockReset();
213 fromPartition.mockImplementation((partition: string) => {
214 let userAgent = nativeUserAgent;
215 const browserSession = {
216 clearCache: vi.fn(() => Promise.resolve()),
217 clearStorageData: vi.fn(() => Promise.resolve()),
218 closeAllConnections: vi.fn(() => Promise.resolve()),
219 storagePath: null,
220 getUserAgent: vi.fn(() => userAgent),
221 setPermissionRequestHandler: vi.fn(),
222 setPermissionCheckHandler: vi.fn(),
223 setUserAgent: vi.fn((next: string) => {
224 userAgent = next;
225 }),
226 webRequest: { onBeforeSendHeaders: vi.fn() },
227 };
228 sessions.set(partition, browserSession);
229 return browserSession;
230 });
231
232 const browserSessions = yield* BrowserSession.BrowserSession;
233 const partition = yield* browserSessions.getPartition("scope-a");
234 yield* browserSessions.getSession("scope-a");
235
236 const browserSession = sessions.get(partition);
237 assert.isDefined(browserSession);
238 assert.strictEqual(browserSession.getUserAgent(), nativeUserAgent);
239
240 // Teams redirects Electron to an error page before sign-in; every other host sees the native one.
241 const calls = browserSession.webRequest.onBeforeSendHeaders.mock.calls;
242 assert.strictEqual(calls.length, 1);
243 const [filter, listener] = calls[0] ?? [];
244 assert.deepStrictEqual(filter, {
245 urls: ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"],
246 });
247 const send = (requestHeaders: Record<string, string>) => {
248 let response: { requestHeaders?: Record<string, string> } | undefined;
249 listener({ requestHeaders }, (next: typeof response) => {
250 response = next;
251 });
252 return response;
253 };
254 for (const key of ["User-Agent", "user-agent"]) {
255 const requestHeaders = { [key]: nativeUserAgent, Accept: "*/*" };
256 assert.deepStrictEqual(send(requestHeaders), {
257 requestHeaders: { [key]: teamsUserAgent, Accept: "*/*" },
258 });
259 assert.strictEqual(requestHeaders[key], nativeUserAgent);
260 }
261 assert.deepStrictEqual(send({ Accept: "*/*" }), {});
262 }).pipe(Effect.provide(layer)),
263 );
264
265 it.effect("grants preview permissions through both the request and check handlers", () =>
266 Effect.gen(function* () {
267 const browserSessions = yield* BrowserSession.BrowserSession;
268 const partition = yield* browserSessions.getPartition("scope-a");
269 yield* browserSessions.getSession("scope-a");
270
271 const browserSession = sessions.get(partition);
272 assert.isDefined(browserSession);
273
274 const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
275 const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
276 assert.isFunction(requestHandler);
277 assert.isFunction(checkHandler);
278
279 const requestAllows = (permission: string): boolean => {
280 let granted: boolean | undefined;
281 requestHandler(null, permission, (value: boolean) => {
282 granted = value;
283 });
284 assert.isDefined(granted);
285 return granted;
286 };
287
288 for (const permission of [
289 "clipboard-sanitized-write",
290 "fullscreen",
291 "pointerLock",
292 "loopback-network",
293 ]) {
294 assert.isTrue(requestAllows(permission), `request handler should allow ${permission}`);
295 assert.isTrue(
296 checkHandler(null, permission) as boolean,
297 `check handler should allow ${permission}`,
298 );
299 }
300
301 // `clipboard-write` is not a real Electron permission — the async write API
302 // uses `clipboard-sanitized-write` — so the stale name must not be granted,
303 // and unrelated permissions stay denied.
304 for (const permission of [
305 "clipboard-write",
306 "notifications",
307 "midi",
308 "local-network",
309 "local-network-access",
310 ]) {
311 assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`);
312 assert.isFalse(
313 checkHandler(null, permission) as boolean,
314 `check handler should deny ${permission}`,
315 );
316 }
317 }).pipe(Effect.provide(layer)),
318 );
319
320 it.effect("opens custom-scheme links externally only after the user confirms", () =>
321 Effect.gen(function* () {
322 const browserSessions = yield* BrowserSession.BrowserSession;
323 const partition = yield* browserSessions.getPartition("scope-a");
324 yield* browserSessions.getSession("scope-a");
325 const requestHandler =
326 sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0];
327 assert.isFunction(requestHandler);
328
329 const request = (externalURL: string) =>
330 Effect.callback<boolean>((resume) => {
331 requestHandler(
332 null,
333 "openExternal",
334 (granted: boolean) => resume(Effect.succeed(granted)),
335 { externalURL },
336 );
337 });
338
339 showMessageBox.mockReset();
340 showMessageBox.mockReturnValueOnce(0).mockReturnValueOnce(1);
341 assert.isTrue(yield* request("slack://open?team=T1"));
342 assert.isFalse(yield* request("zoommtg://zoom.us/join"));
343 assert.strictEqual(showMessageBox.mock.calls.length, 2);
344
345 for (const url of ["file:///etc/passwd", "javascript:alert(1)", "data:text/html,x"]) {
346 assert.isFalse(yield* request(url), `${url} must never open externally`);
347 }
348 assert.strictEqual(showMessageBox.mock.calls.length, 2);
349 }).pipe(Effect.provide(layer)),
350 );
351
352 it.effect.each([
353 {
354 permission: "clipboard-read",
355 description: "see text and images copied to the clipboard",
356 },
357 { permission: "geolocation", description: "know your location" },
358 ])("asks once per origin before granting $permission", ({ permission, description }) =>
359 Effect.gen(function* () {
360 const browserSessions = yield* BrowserSession.BrowserSession;
361 const partition = yield* browserSessions.getPartition("scope-a");
362 yield* browserSessions.getSession("scope-a");
363 const browserSession = sessions.get(partition);
364 assert.isDefined(browserSession);
365 const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0];
366 const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0];
367 assert.isFunction(requestHandler);
368 assert.isFunction(checkHandler);
369
370 const requestPermission = (requestingUrl: string) =>
371 Effect.callback<boolean>((resume) => {
372 requestHandler(null, permission, (granted: boolean) => resume(Effect.succeed(granted)), {
373 requestingUrl,
374 isMainFrame: true,
375 });
376 });
377 const checkPermission = (origin: string): boolean =>
378 checkHandler(null, permission, origin, {}) as boolean;
379
380 showMessageBox.mockReset();
381 showMessageBox.mockReturnValueOnce(0).mockReturnValueOnce(1);
382
383 assert.isFalse(checkPermission("https://allowed.test"));
384 assert.isTrue(yield* requestPermission("https://allowed.test/page"));
385 assert.strictEqual(showMessageBox.mock.calls.length, 1);
386 assert.strictEqual(
387 showMessageBox.mock.calls[0]?.[0].message,
388 `https://allowed.test wants to ${description}`,
389 );
390 assert.deepStrictEqual(showMessageBox.mock.calls[0]?.[0].buttons, ["Allow", "Block"]);
391 // Enter must not accept a prompt the page raised while the user was typing.
392 assert.strictEqual(showMessageBox.mock.calls[0]?.[0].defaultId, 1);
393
394 assert.isTrue(yield* requestPermission("https://allowed.test/other"));
395 assert.isTrue(checkPermission("https://allowed.test"));
396
397 assert.isFalse(yield* requestPermission("https://blocked.test/"));
398 assert.isFalse(yield* requestPermission("https://blocked.test/again"));
399 assert.isFalse(checkPermission("https://blocked.test"));
400 assert.isTrue(checkPermission("https://allowed.test"));
401 assert.strictEqual(showMessageBox.mock.calls.length, 2);
402 }).pipe(Effect.provide(layer)),
403 );
404
405 it.effect("clears a partition whose session has not been opened yet", () =>
406 Effect.gen(function* () {
407 const browserSessions = yield* BrowserSession.BrowserSession;
408 const partition = yield* browserSessions.getPartition("scope-untouched");
409
410 assert.isUndefined(sessions.get(partition));
411 yield* browserSessions.clearCookies([partition]);
412 assert.isUndefined(sessions.get(partition));
413
414 yield* browserSessions.getSession("scope-untouched");
415 const other = yield* browserSessions.getSession("scope-other");
416 yield* browserSessions.clearCookies([partition]);
417
418 const created = sessions.get(partition);
419 assert.isDefined(created);
420 assert.strictEqual(created.clearStorageData.mock.calls.length, 1);
421 assert.deepStrictEqual(created.clearStorageData.mock.calls[0]?.[0], {
422 storages: ["cookies", "localstorage", "indexdb", "serviceworkers", "cachestorage"],
423 });
424 assert.strictEqual(vi.mocked(other.clearStorageData).mock.calls.length, 0);
425 }).pipe(Effect.provide(layer)),
426 );
427
428 it.effect("asks before trusting an untrusted certificate and remembers the approval", () =>
429 Effect.gen(function* () {
430 const browserSessions = yield* BrowserSession.BrowserSession;
431 const partition = yield* browserSessions.getPartition("scope-a");
432 yield* browserSessions.getSession("scope-a");
433 const browserSession = sessions.get(partition);
434
435 showMessageBox.mockReset();
436 showMessageBox.mockImplementation(trustCertificateButton);
437 const first = certificateError(browserSession, { url: "https://localhost:18443/" });
438 assert.strictEqual(first.event.preventDefault.mock.calls.length, 1);
439 assert.isTrue(yield* first.trusted);
440 assert.strictEqual(showMessageBox.mock.calls.length, 1);
441
442 // The approval covers this origin, port, and certificate in this profile.
443 const again = certificateError(browserSession, { url: "https://localhost:18443/other" });
444 assert.isTrue(yield* again.trusted);
445 assert.strictEqual(showMessageBox.mock.calls.length, 1);
446 // Its sockets reach the same TLS endpoint, and cannot ask on their own.
447 const socket = certificateError(browserSession, {
448 url: "wss://localhost:18443/hmr",
449 isMainFrame: false,
450 });
451 assert.isTrue(yield* socket.trusted);
452 const otherSocket = certificateError(browserSession, {
453 url: "wss://localhost:18444/hmr",
454 isMainFrame: false,
455 });
456 assert.isFalse(yield* otherSocket.trusted);
457 assert.strictEqual(showMessageBox.mock.calls.length, 1);
458
459 showMessageBox.mockReset();
460 showMessageBox.mockReturnValue(1);
461 const otherPort = certificateError(browserSession, { url: "https://localhost:18444/" });
462 assert.isFalse(yield* otherPort.trusted);
463 const renewed = certificateError(browserSession, {
464 url: "https://localhost:18443/",
465 certificate: { ...selfSignedCertificate, fingerprint: "sha256/renewed" },
466 });
467 assert.isFalse(yield* renewed.trusted);
468 assert.strictEqual(showMessageBox.mock.calls.length, 2);
469
470 // A Session that is not a preview profile keeps Electron's denial.
471 const appSession = certificateError({}, { url: "https://localhost:18443/" });
472 assert.strictEqual(appSession.event.preventDefault.mock.calls.length, 0);
473 assert.strictEqual(appSession.callback.mock.calls.length, 0);
474 }).pipe(Effect.provide(layer)),
475 );
476
477 it.effect("revokes certificate approvals when cookies are cleared, not the cache", () =>
478 Effect.gen(function* () {
479 const browserSessions = yield* BrowserSession.BrowserSession;
480 const partition = yield* browserSessions.getPartition("scope-a");
481 yield* browserSessions.getSession("scope-a");
482 const browserSession = sessions.get(partition);
483 const url = "https://localhost:18443/";
484
485 showMessageBox.mockReset();
486 showMessageBox.mockImplementation(trustCertificateButton);
487 assert.isTrue(yield* certificateError(browserSession, { url }).trusted);
488
489 yield* browserSessions.clearCache([partition]);
490 assert.isTrue(yield* certificateError(browserSession, { url }).trusted);
491 assert.strictEqual(showMessageBox.mock.calls.length, 1);
492
493 // A failed storage clear still forgets the approvals the user asked to clear.
494 browserSession!.clearStorageData.mockRejectedValueOnce(new Error("disk busy"));
495 const failure = yield* browserSessions.clearCookies([partition]).pipe(Effect.flip);
496 assert.strictEqual(failure._tag, "BrowserSessionStorageClearError");
497 showMessageBox.mockReset();
498 showMessageBox.mockReturnValue(1);
499 assert.isFalse(yield* certificateError(browserSession, { url }).trusted);
500 assert.strictEqual(showMessageBox.mock.calls.length, 1);
501 }).pipe(Effect.provide(layer)),
502 );
503
504 it.effect("remembers approvals across restarts, but not incognito ones", () =>
505 Effect.gen(function* () {
506 storage.root = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
507 const url = "https://localhost:18443/";
508 const approve = Effect.gen(function* () {
509 const browserSessions = yield* BrowserSession.BrowserSession;
510 const persistent = yield* browserSessions.getPartition("scope-a");
511 const incognito = yield* browserSessions.getPartition("scope-a", false);
512 yield* browserSessions.getSession("scope-a");
513 yield* browserSessions.getSession("scope-a", false);
514 showMessageBox.mockReset();
515 showMessageBox.mockImplementation(trustCertificateButton);
516 assert.isTrue(yield* certificateError(sessions.get(persistent), { url }).trusted);
517 assert.isTrue(yield* certificateError(sessions.get(incognito), { url }).trusted);
518 return { persistent, incognito };
519 });
520 const { persistent, incognito } = yield* approve.pipe(Effect.provide(layer));
521
522 // A restarted app gets fresh Session objects and reads approvals from disk.
523 sessions.clear();
524 appListeners.clear();
525 yield* Effect.gen(function* () {
526 const browserSessions = yield* BrowserSession.BrowserSession;
527 yield* browserSessions.getSession("scope-a");
528 yield* browserSessions.getSession("scope-a", false);
529 showMessageBox.mockReset();
530 showMessageBox.mockReturnValue(1);
531 assert.isTrue(yield* certificateError(sessions.get(persistent), { url }).trusted);
532 assert.strictEqual(showMessageBox.mock.calls.length, 0);
533 assert.isFalse(yield* certificateError(sessions.get(incognito), { url }).trusted);
534 assert.strictEqual(showMessageBox.mock.calls.length, 1);
535 }).pipe(Effect.provide(layer));
536 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
537 );
538
539 it.effect("an answer to a prompt opened before cookies were cleared does not trust", () =>
540 Effect.gen(function* () {
541 storage.root = yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
542 const browserSessions = yield* BrowserSession.BrowserSession;
543 const partition = yield* browserSessions.getPartition("scope-a");
544 yield* browserSessions.getSession("scope-a");
545 const browserSession = sessions.get(partition);
546 const url = "https://localhost:18443/";
547
548 const asked = yield* Deferred.make<void>();
549 let answer = () => {};
550 const answered = new Promise<void>((resolve) => {
551 answer = resolve;
552 });
553 showMessageBox.mockReset();
554 showMessageBox.mockImplementation((options) => {
555 Deferred.doneUnsafe(asked, Effect.void);
556 return answered.then(() => trustCertificateButton(options));
557 });
558 const pending = certificateError(browserSession, { url });
559 yield* Deferred.await(asked);
560 yield* browserSessions.clearCookies([partition]);
561 answer();
562 assert.isFalse(yield* pending.trusted);
563
564 showMessageBox.mockReset();
565 showMessageBox.mockReturnValue(1);
566 assert.isFalse(yield* certificateError(browserSession, { url }).trusted);
567 assert.strictEqual(showMessageBox.mock.calls.length, 1);
568 assert.isFalse(
569 yield* (yield* FileSystem.FileSystem).exists(
570 `${browserSession!.storagePath}/t3code-certificate-approvals.json`,
571 ),
572 );
573 }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))),
574 );
575
576 it.effect("a tab that closes or navigates away dismisses its certificate prompt", () =>
577 Effect.gen(function* () {
578 const browserSessions = yield* BrowserSession.BrowserSession;
579 const partition = yield* browserSessions.getPartition("scope-a");
580 yield* browserSessions.getSession("scope-a");
581 const browserSession = sessions.get(partition);
582 const url = "https://localhost:18443/";
583
584 for (const leave of [
585 (guest: NodeEvents.EventEmitter) =>
586 guest.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }),
587 (guest: NodeEvents.EventEmitter) => guest.emit("destroyed"),
588 ]) {
589 showMessageBox.mockReset();
590 // Answering "Trust" as the tab leaves must not approve the certificate.
591 showMessageBox.mockImplementation(
592 (options) =>
593 new Promise((resolve) =>
594 options.signal?.addEventListener("abort", () =>
595 resolve(trustCertificateButton(options)),
596 ),
597 ),
598 );
599 const pending = certificateError(browserSession, { url });
600 pending.guest.emit("did-start-navigation", { isMainFrame: true, isSameDocument: true });
601 leave(pending.guest);
602 assert.isFalse(yield* pending.trusted);
603 assert.strictEqual(showMessageBox.mock.calls.length, 1);
604 }
605 }).pipe(Effect.provide(layer)),
606 );
607
608 it.effect("does not trust a certificate whose approval cannot be saved", () =>
609 Effect.gen(function* () {
610 const fileSystem = yield* FileSystem.FileSystem;
611 // A file where the profile directory should be makes every write fail.
612 const root = yield* fileSystem.makeTempDirectoryScoped();
613 yield* fileSystem.writeFileString(`${root}/Partitions`, "");
614 storage.root = root;
615 const browserSessions = yield* BrowserSession.BrowserSession;
616 const partition = yield* browserSessions.getPartition("scope-a");
617 yield* browserSessions.getSession("scope-a");
618 const browserSession = sessions.get(partition);
619 const url = "https://localhost:18443/";
620
621 showMessageBox.mockReset();
622 showMessageBox.mockImplementation(trustCertificateButton);
623 assert.isFalse(yield* certificateError(browserSession, { url }).trusted);
624 assert.strictEqual(showErrorBox.mock.calls.length, 1);
625 // Nothing was trusted for this run either, so the next visit asks again.
626 showMessageBox.mockReset();
627 showMessageBox.mockReturnValue(1);
628 assert.isFalse(yield* certificateError(browserSession, { url }).trusted);
629 assert.strictEqual(showMessageBox.mock.calls.length, 1);
630 }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))),
631 );
632
633 it.effect("clearing cookies deletes a saved approval even when none are loaded", () =>
634 Effect.gen(function* () {
635 const fileSystem = yield* FileSystem.FileSystem;
636 storage.root = yield* fileSystem.makeTempDirectoryScoped();
637 const browserSessions = yield* BrowserSession.BrowserSession;
638 const partition = yield* browserSessions.getPartition("scope-a");
639 yield* browserSessions.getSession("scope-a");
640 const browserSession = sessions.get(partition);
641 // What a clear whose removal failed leaves behind: memory forgot, the file did not.
642 const file = `${browserSession!.storagePath}/t3code-certificate-approvals.json`;
643 yield* fileSystem.makeDirectory(browserSession!.storagePath!, { recursive: true });
644 yield* fileSystem.writeFileString(
645 file,
646 JSON.stringify([
647 {
648 origin: "https://localhost:18443",
649 fingerprint: selfSignedCertificate.fingerprint,
650 error: "net::ERR_CERT_AUTHORITY_INVALID",
651 },
652 ]),
653 );
654
655 yield* browserSessions.clearCookies([partition]);
656 assert.isFalse(yield* fileSystem.exists(file));
657 }).pipe(Effect.scoped, Effect.provide(Layer.merge(layer, NodeServices.layer))),
658 );
659 });