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

main
ts 783 lines 29.4 KB
Raw
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 import type { Certificate, Session, WebContents } from "electron";
3 import { BrowserWindow, session } from "electron";
4 import { msg } from "gt-i18n";
5 import * as Context from "effect/Context";
6 import * as DateTime from "effect/DateTime";
7 import * as Digest from "effect/crypto/Digest";
8 import * as Effect from "effect/Effect";
9 import * as Hex from "effect/encoding/Hex";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Layer from "effect/Layer";
12 import * as Path from "effect/Path";
13 import * as PlatformError from "effect/PlatformError";
14 import * as Result from "effect/Result";
15 import * as Schema from "effect/Schema";
16 import * as Semaphore from "effect/Semaphore";
17 import * as SynchronizedRef from "effect/SynchronizedRef";
18
19 import * as ElectronApp from "../electron/ElectronApp.ts";
20 import * as ElectronDialog from "../electron/ElectronDialog.ts";
21 import { m } from "../i18n/messages.ts";
22
23 const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
24 /** Ephemeral partitions omit persist: but retain a product prefix so the webview gate recognizes them. */
25 const PREVIEW_EPHEMERAL_PARTITION_PREFIX = "t3code-preview-ephemeral-";
26 const PROFILE_PARTITION_MARKER = "profile-";
27
28 export type BrowserSessionPartitionNamespace = "profile";
29
30 // Electron's clipboard API uses clipboard-sanitized-write and checks both permission handlers.
31 const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
32 "clipboard-sanitized-write",
33 // DesktopWindow confines HTML fullscreen to the guest's webview.
34 "fullscreen",
35 "pointerLock",
36 // Loopback requests already succeed in Electron 44; permission-aware sign-in widgets query first.
37 "loopback-network",
38 // Deny local-fonts to untrusted previews: it exposes installed-font fingerprints and file bytes.
39 // Deny notifications: pages could impersonate T3 Code; app notifications use the default session.
40 ]);
41
42 const NEVER_EXTERNAL_PROTOCOLS: ReadonlySet<string> = new Set([
43 "about:",
44 "blob:",
45 "chrome:",
46 "data:",
47 "devtools:",
48 "file:",
49 "filesystem:",
50 "http:",
51 "https:",
52 "javascript:",
53 "view-source:",
54 ]);
55
56 const externalProtocolPromptUrl = (rawUrl: string | undefined): string | null => {
57 if (!rawUrl) return null;
58 try {
59 const url = new URL(rawUrl);
60 return NEVER_EXTERNAL_PROTOCOLS.has(url.protocol) ? null : url.href;
61 } catch {
62 return null;
63 }
64 };
65
66 // Teams sends Electron User-Agents to an error page before sign-in. Electron allows one listener per session.
67 const TEAMS_URL_PATTERNS = ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"];
68
69 const MAX_PROMPT_URL_LENGTH = 300;
70
71 const truncateForPrompt = (text: string): string =>
72 text.length > MAX_PROMPT_URL_LENGTH ? `${text.slice(0, MAX_PROMPT_URL_LENGTH)}…` : text;
73
74 const permissionOrigin = (rawUrl: string | undefined): string | null => {
75 if (!rawUrl) return null;
76 try {
77 const { origin } = new URL(rawUrl);
78 return origin === "null" ? null : origin;
79 } catch {
80 return null;
81 }
82 };
83
84 /**
85 * Certificate errors a user may accept for a preview page, with the reason the
86 * prompt shows. Every other error keeps Electron's denial.
87 */
88 const OVERRIDABLE_CERTIFICATE_ERRORS: ReadonlyMap<string, string> = new Map([
89 ["net::ERR_CERT_AUTHORITY_INVALID", msg("No trusted authority issued this certificate.")],
90 ["net::ERR_CERT_COMMON_NAME_INVALID", msg("This certificate is not for this address.")],
91 ["net::ERR_CERT_DATE_INVALID", msg("This certificate has expired or is not valid yet.")],
92 ]);
93
94 /**
95 * A `wss:` socket reaches the same TLS endpoint as the page, so it shares the
96 * `https:` origin. It must: a socket is never a main frame, so it could not be
97 * approved on its own, and a page's dev-server socket would stay blocked.
98 */
99 const certificateOrigin = (rawUrl: string): string | null => {
100 try {
101 const url = new URL(rawUrl);
102 return url.protocol === "https:" || url.protocol === "wss:" ? `https://${url.host}` : null;
103 } catch {
104 return null;
105 }
106 };
107
108 const CertificateApproval = Schema.Struct({
109 origin: Schema.String,
110 fingerprint: Schema.String,
111 error: Schema.String,
112 });
113 type CertificateApproval = typeof CertificateApproval.Type;
114 const CertificateApprovalsJson = Schema.fromJsonString(Schema.Array(CertificateApproval));
115 const decodeCertificateApprovals = Schema.decodeEffect(CertificateApprovalsJson);
116 const encodeCertificateApprovals = Schema.encodeEffect(CertificateApprovalsJson);
117
118 const certificateApprovalKey = ({ origin, fingerprint, error }: CertificateApproval): string =>
119 JSON.stringify([origin, fingerprint, error]);
120
121 /** Kept beside the profile's cookies, so it lives and dies with them. */
122 const CERTIFICATE_APPROVALS_FILE = "t3code-certificate-approvals.json";
123
124 /** Server-chosen certificate names must not add lines or flood the prompt. */
125 const promptCertificateName = (name: string): string => {
126 const flat = name.replace(/\s+/g, " ").trim();
127 return flat.length > 120 ? `${flat.slice(0, 120)}…` : flat;
128 };
129
130 const promptCertificateDate = (seconds: number): string =>
131 DateTime.formatIsoDateUtc(DateTime.makeUnsafe(seconds * 1000));
132
133 /** The certificates a user accepted in one preview Session. */
134 interface CertificateTrust {
135 /** `null` for an incognito Session, whose approvals end with the process. */
136 readonly file: string | null;
137 readonly approvals: Map<string, CertificateApproval>;
138 /** Bumped by each revocation, so an answer to an older prompt cannot restore trust. */
139 revocations: number;
140 }
141
142 export class BrowserSessionPartitionDerivationError extends Schema.TaggedError<BrowserSessionPartitionDerivationError>()(
143 "BrowserSessionPartitionDerivationError",
144 {
145 scope: Schema.String,
146 cause: Schema.instanceOf(PlatformError.PlatformError),
147 },
148 ) {
149 override get message(): string {
150 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
151 }
152 }
153
154 export class BrowserSessionCreationError extends Schema.TaggedError<BrowserSessionCreationError>()(
155 "BrowserSessionCreationError",
156 {
157 scope: Schema.String,
158 partition: Schema.String,
159 cause: Schema.Defect(),
160 },
161 ) {
162 override get message(): string {
163 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
164 }
165 }
166
167 export class BrowserSessionStorageClearError extends Schema.TaggedError<BrowserSessionStorageClearError>()(
168 "BrowserSessionStorageClearError",
169 {
170 partition: Schema.String,
171 cause: Schema.Defect(),
172 },
173 ) {
174 override get message(): string {
175 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
176 }
177 }
178
179 export class BrowserSessionCacheClearError extends Schema.TaggedError<BrowserSessionCacheClearError>()(
180 "BrowserSessionCacheClearError",
181 {
182 partition: Schema.String,
183 cause: Schema.Defect(),
184 },
185 ) {
186 override get message(): string {
187 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
188 }
189 }
190
191 export const BrowserSessionGetSessionError = Schema.Union([
192 BrowserSessionPartitionDerivationError,
193 BrowserSessionCreationError,
194 ]);
195 export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
196
197 export const BrowserSessionError = Schema.Union([
198 BrowserSessionPartitionDerivationError,
199 BrowserSessionCreationError,
200 BrowserSessionStorageClearError,
201 BrowserSessionCacheClearError,
202 ]);
203 export type BrowserSessionError = typeof BrowserSessionError.Type;
204
205 export class BrowserSession extends Context.Service<
206 BrowserSession,
207 {
208 readonly getPartition: (
209 scope?: string,
210 persistent?: boolean,
211 namespace?: BrowserSessionPartitionNamespace,
212 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
213 readonly isPartition: (partition: string) => boolean;
214 readonly getSession: (
215 scope?: string,
216 persistent?: boolean,
217 namespace?: BrowserSessionPartitionNamespace,
218 ) => Effect.Effect<Session, BrowserSessionGetSessionError>;
219 /** Omit `partitions` to clear every known partition. */
220 readonly clearCookies: (
221 partitions?: ReadonlyArray<string>,
222 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
223 /** For cookies cleared outside `clearCookies`, such as over a tab's CDP session. */
224 readonly cookiesCleared: (
225 browserSession: Session,
226 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
227 readonly clearCache: (
228 partitions?: ReadonlyArray<string>,
229 ) => Effect.Effect<void, BrowserSessionCacheClearError>;
230 }
231 >()("@t3tools/desktop/preview/BrowserSession") {}
232
233 const selectSessions = (
234 sessions: ReadonlyMap<string, Session>,
235 partitions: ReadonlyArray<string> | undefined,
236 ): ReadonlyArray<readonly [string, Session]> =>
237 [...sessions.entries()].filter(
238 ([partition]) => partitions === undefined || partitions.includes(partition),
239 );
240
241 /** Escape lone surrogates before UTF-8 hashing, which otherwise merges them with U+FFFD; escape backslashes too. */
242 const encodeScopeForDigest = (scope: string): Uint8Array =>
243 new TextEncoder().encode(
244 scope
245 .replace(/\\/g, "\\\\")
246 .replace(
247 /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
248 (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
249 ),
250 );
251
252 // Webview guests have no window; use their embedding page.
253 const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined => {
254 if (guest === null || guest.isDestroyed()) return undefined;
255 const host = guest.hostWebContents ?? guest;
256 if (host.isDestroyed()) return undefined;
257 return BrowserWindow.fromWebContents(host) ?? undefined;
258 };
259
260 /** @public */
261 export const make = Effect.gen(function* BrowserSessionMake() {
262 const crypto = yield* Digest.Digest;
263 const electronApp = yield* ElectronApp.ElectronApp;
264 const electronDialog = yield* ElectronDialog.ElectronDialog;
265 const fileSystem = yield* FileSystem.FileSystem;
266 const path = yield* Path.Path;
267 const platform = yield* HostProcess.Platform;
268 const runFork = Effect.runForkWith(yield* Effect.context<never>());
269 // One prompt at a time, so a page cannot stack dialogs by looping a deep link.
270 let permissionPromptOpen = false;
271 /** Settles with `undefined` when the user gave no answer: another prompt was open or the dialog failed. */
272 const promptPermission = (
273 requester: WebContents | null,
274 prompt: {
275 readonly buttons: readonly [allow: string, deny: string];
276 readonly message: string;
277 readonly detail?: string;
278 },
279 callback: (answer: boolean | undefined) => void,
280 ): void => {
281 if (permissionPromptOpen) {
282 callback(undefined);
283 return;
284 }
285 permissionPromptOpen = true;
286 const settle = (answer: boolean | undefined) =>
287 Effect.sync(() => {
288 permissionPromptOpen = false;
289 callback(answer);
290 });
291 runFork(
292 electronDialog
293 .showMessageBox(
294 {
295 type: "question",
296 buttons: [...prompt.buttons],
297 // Default to deny so an Enter typed into the page cannot accept a prompt it raised.
298 defaultId: 1,
299 cancelId: 1,
300 message: prompt.message,
301 ...(prompt.detail === undefined ? {} : { detail: prompt.detail }),
302 },
303 platform === "win32" ? undefined : previewHostWindow(requester),
304 )
305 .pipe(
306 Effect.map(({ response }): boolean | undefined => response === 0),
307 Effect.orElseSucceed(() => undefined),
308 Effect.flatMap(settle),
309 Effect.onInterrupt(() => settle(undefined)),
310 ),
311 );
312 };
313 /** Electron launches external protocols after granting openExternal; untrusted pages require confirmation. */
314 const confirmOpenExternal = (
315 requester: WebContents | null,
316 rawUrl: string | undefined,
317 callback: (granted: boolean) => void,
318 ): void => {
319 const url = externalProtocolPromptUrl(rawUrl);
320 if (url === null) {
321 callback(false);
322 return;
323 }
324 promptPermission(
325 requester,
326 {
327 buttons: [
328 m(msg("Open", { $context: "button, opens a link in another app" })),
329 m(msg("Cancel")),
330 ],
331 message: m(msg("Open this {protocol} link?"), {
332 protocol: new URL(url).protocol.slice(0, -1),
333 }),
334 detail: m(msg("A page in the browser wants to open another application:\n\n{url}"), {
335 url: truncateForPrompt(url),
336 }),
337 },
338 (answer) => callback(answer === true),
339 );
340 };
341
342 const certificateTrust = new WeakMap<Session, CertificateTrust>();
343 const writeCertificateApprovals = yield* Semaphore.make(1);
344 const loadCertificateTrust = Effect.fn("BrowserSession.loadCertificateTrust")(function* (
345 browserSession: Session,
346 ) {
347 const file =
348 browserSession.storagePath == null
349 ? null
350 : path.join(browserSession.storagePath, CERTIFICATE_APPROVALS_FILE);
351 const approvals: ReadonlyArray<CertificateApproval> =
352 file === null
353 ? []
354 : yield* fileSystem.readFileString(file).pipe(
355 Effect.flatMap(decodeCertificateApprovals),
356 Effect.catchTags({
357 PlatformError: (error) =>
358 error.reason._tag === "NotFound" ? Effect.succeed([]) : Effect.fail(error),
359 }),
360 Effect.catch((cause) =>
361 Effect.logWarning("Ignored saved certificate approvals.", { file, cause }).pipe(
362 Effect.as([]),
363 ),
364 ),
365 );
366 const trust: CertificateTrust = {
367 file,
368 approvals: new Map(approvals.map((approval) => [certificateApprovalKey(approval), approval])),
369 revocations: 0,
370 };
371 return trust;
372 });
373 const writeApprovalsFile = Effect.fn("BrowserSession.writeApprovalsFile")(function* (
374 file: string,
375 approvals: ReadonlyMap<string, CertificateApproval>,
376 ) {
377 if (approvals.size === 0) return yield* fileSystem.remove(file, { force: true });
378 yield* fileSystem.makeDirectory(path.dirname(file), { recursive: true });
379 yield* fileSystem.writeFileString(
380 file,
381 yield* encodeCertificateApprovals([...approvals.values()]),
382 );
383 });
384 /**
385 * Saved before it is trusted, so a failed write cannot leave an approval that
386 * silently ends at restart. Writes share one lock, so a slower write cannot
387 * restore stale data.
388 */
389 const rememberCertificate = Effect.fn("BrowserSession.rememberCertificate")(function* (
390 trust: CertificateTrust,
391 key: string,
392 approval: CertificateApproval,
393 revocations: number,
394 ) {
395 if (trust.revocations !== revocations) return false;
396 if (trust.file !== null) {
397 yield* writeApprovalsFile(trust.file, new Map(trust.approvals).set(key, approval));
398 // A revocation during the write queues its own rewrite behind this one.
399 if (trust.revocations !== revocations) return false;
400 }
401 trust.approvals.set(key, approval);
402 return true;
403 }, writeCertificateApprovals.withPermits(1));
404 /**
405 * Rewrites the file from memory. Clearing cookies runs this even when memory
406 * is already empty, so retrying after a failed removal still deletes the file.
407 */
408 const saveCertificateApprovals = Effect.fn("BrowserSession.saveCertificateApprovals")(function* (
409 trust: CertificateTrust,
410 ) {
411 if (trust.file !== null) yield* writeApprovalsFile(trust.file, trust.approvals);
412 }, writeCertificateApprovals.withPermits(1));
413
414 // One prompt at a time; tabs that hit the same certificate wait on it.
415 let certificatePrompt: {
416 readonly trust: CertificateTrust;
417 readonly key: string;
418 readonly callbacks: Array<(trusted: boolean) => void>;
419 } | null = null;
420 const confirmCertificate = (
421 contents: WebContents,
422 trust: CertificateTrust,
423 approval: CertificateApproval,
424 certificate: Certificate,
425 reason: string,
426 callback: (trusted: boolean) => void,
427 ): void => {
428 const key = certificateApprovalKey(approval);
429 if (certificatePrompt !== null) {
430 if (certificatePrompt.trust === trust && certificatePrompt.key === key) {
431 certificatePrompt.callbacks.push(callback);
432 } else {
433 callback(false);
434 }
435 return;
436 }
437 const prompt = { trust, key, callbacks: [callback] };
438 certificatePrompt = prompt;
439 // A prompt for a tab that closed or moved on would approve a page nobody is waiting for.
440 const dismiss = new AbortController();
441 const abandon = () => dismiss.abort();
442 const navigated = (
443 event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
444 ) => {
445 if (event.isMainFrame && !event.isSameDocument) abandon();
446 };
447 contents.once("destroyed", abandon);
448 contents.on("did-start-navigation", navigated);
449 const settle = (trusted: boolean) =>
450 Effect.sync(() => {
451 certificatePrompt = null;
452 if (!contents.isDestroyed()) {
453 contents.off("destroyed", abandon);
454 contents.off("did-start-navigation", navigated);
455 }
456 for (const waiter of prompt.callbacks) waiter(trusted);
457 });
458 const host = new URL(approval.origin).host;
459 const revocations = trust.revocations;
460 runFork(
461 electronDialog
462 .showMessageBox(
463 {
464 type: "warning",
465 buttons: [m(msg("Trust and Remember")), m(msg("Cancel"))],
466 defaultId: 1,
467 cancelId: 1,
468 signal: dismiss.signal,
469 message: m(msg("{host} has an untrusted certificate"), { host }),
470 detail: [
471 m(reason),
472 "",
473 m(msg("Issued to: {name}"), {
474 name: promptCertificateName(certificate.subjectName),
475 }),
476 m(msg("Issued by: {name}"), { name: promptCertificateName(certificate.issuerName) }),
477 m(msg("Valid: {start} – {end}"), {
478 start: promptCertificateDate(certificate.validStart),
479 end: promptCertificateDate(certificate.validExpiry),
480 }),
481 m(msg("Fingerprint: {fingerprint}"), { fingerprint: approval.fingerprint }),
482 "",
483 m(
484 msg(
485 "Trust it only if you know this certificate belongs to the site. Clearing this browser profile's cookies forgets it.",
486 ),
487 ),
488 ].join("\n"),
489 },
490 // In the reporter's Windows test, a box owned by the host window
491 // blocked all mouse input, its own buttons included, until it closed.
492 platform === "win32" ? undefined : previewHostWindow(contents),
493 )
494 .pipe(
495 Effect.flatMap(({ response }) =>
496 response === 0 && !dismiss.signal.aborted
497 ? rememberCertificate(trust, key, approval, revocations).pipe(
498 Effect.catch((cause) =>
499 Effect.logWarning("Failed to save a certificate approval.", { cause }).pipe(
500 Effect.andThen(
501 electronDialog.showErrorBox(
502 m(msg("Could not trust the certificate for {host}"), { host }),
503 m(
504 msg(
505 "T3 Code could not save this approval, so the page stays blocked. Check that the disk is not full and its data folder is writable, then try again.",
506 ),
507 ),
508 ),
509 ),
510 Effect.as(false),
511 ),
512 ),
513 )
514 : Effect.succeed(false),
515 ),
516 Effect.orElseSucceed(() => false),
517 Effect.flatMap(settle),
518 Effect.onInterrupt(() => settle(false)),
519 ),
520 );
521 };
522 yield* electronApp.on(
523 "certificate-error",
524 (
525 event: Electron.Event,
526 contents: WebContents,
527 url: string,
528 error: string,
529 certificate: Certificate,
530 callback: (trusted: boolean) => void,
531 isMainFrame: boolean,
532 ) => {
533 if (contents.isDestroyed()) return;
534 // Sessions this service did not create keep Electron's denial.
535 const trust = certificateTrust.get(contents.session);
536 const origin = certificateOrigin(url);
537 const reason = OVERRIDABLE_CERTIFICATE_ERRORS.get(error);
538 if (trust === undefined || origin === null || reason === undefined) return;
539 const approval = { origin, fingerprint: certificate.fingerprint, error };
540 event.preventDefault();
541 if (trust.approvals.has(certificateApprovalKey(approval))) {
542 callback(true);
543 return;
544 }
545 // Only a page navigation asks; a subresource the user has not accepted stays blocked.
546 if (!isMainFrame) {
547 callback(false);
548 return;
549 }
550 confirmCertificate(contents, trust, approval, certificate, reason, callback);
551 },
552 );
553
554 /** Clearing a profile's cookies also forgets the certificates its user trusted. */
555 const revokeCertificates = Effect.fn("BrowserSession.revokeCertificates")(function* (
556 partition: string,
557 browserSession: Session,
558 ) {
559 const trust = certificateTrust.get(browserSession);
560 if (trust === undefined) return;
561 const hadApprovals = trust.approvals.size > 0;
562 trust.revocations += 1;
563 trust.approvals.clear();
564 const saved = yield* saveCertificateApprovals(trust).pipe(Effect.result);
565 // An open connection already passed its certificate check.
566 if (hadApprovals) {
567 yield* Effect.tryPromise({
568 try: () => browserSession.closeAllConnections(),
569 catch: (cause) => new BrowserSessionStorageClearError({ partition, cause }),
570 });
571 }
572 if (Result.isFailure(saved)) {
573 return yield* new BrowserSessionStorageClearError({ partition, cause: saved.failure });
574 }
575 });
576
577 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
578
579 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
580 scope = "shared",
581 persistent = true,
582 namespace?: BrowserSessionPartitionNamespace,
583 ) {
584 const digest = yield* crypto.digest(Digest.sha256, encodeScopeForDigest(scope)).pipe(
585 Effect.mapError(
586 (cause) =>
587 new BrowserSessionPartitionDerivationError({
588 scope,
589 cause,
590 }),
591 ),
592 );
593 const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
594 return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Hex.encode(digest).slice(0, 20)}`;
595 });
596
597 const getSession = Effect.fn("BrowserSession.getSession")(function* (
598 scope = "shared",
599 persistent = true,
600 namespace?: BrowserSessionPartitionNamespace,
601 ) {
602 const partition = yield* getPartition(scope, persistent, namespace);
603 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
604 const existing = sessions.get(partition);
605 if (existing) return Effect.succeed([existing, sessions] as const);
606 return Effect.try({
607 try: () => {
608 const browserSession = session.fromPartition(partition);
609 // Location and clipboard decisions are remembered separately for each origin.
610 const permissionDecisions = {
611 "clipboard-read": new Map<string, boolean>(),
612 geolocation: new Map<string, boolean>(),
613 };
614 const confirmOriginPermission = (
615 requester: WebContents,
616 permission: keyof typeof permissionDecisions,
617 rawUrl: string | undefined,
618 callback: (granted: boolean) => void,
619 ): void => {
620 const origin = permissionOrigin(rawUrl);
621 if (origin === null) {
622 // A frame URL such as about:srcdoc cannot establish whether its origin is inherited or opaque.
623 callback(false);
624 return;
625 }
626 const decisions = permissionDecisions[permission];
627 const remembered = decisions.get(origin);
628 if (remembered !== undefined) {
629 callback(remembered);
630 return;
631 }
632 promptPermission(
633 requester,
634 {
635 buttons: [
636 m(msg("Allow", { $context: "button, grants a site permission" })),
637 m(msg("Block", { $context: "button, denies a site permission" })),
638 ],
639 message:
640 permission === "geolocation"
641 ? m(msg("{origin} wants to know your location"), {
642 origin: truncateForPrompt(origin),
643 })
644 : m(msg("{origin} wants to see text and images copied to the clipboard"), {
645 origin: truncateForPrompt(origin),
646 }),
647 },
648 (answer) => {
649 if (answer !== undefined) decisions.set(origin, answer);
650 callback(answer === true);
651 },
652 );
653 };
654 // Rewriting Electron's native User-Agent makes Turnstile fail integrity checks with error 600010.
655 browserSession.setPermissionRequestHandler(
656 (webContents, permission, callback, details) => {
657 if (permission === "openExternal") {
658 confirmOpenExternal(
659 webContents,
660 "externalURL" in details ? details.externalURL : undefined,
661 callback,
662 );
663 return;
664 }
665 if (permission === "clipboard-read" || permission === "geolocation") {
666 confirmOriginPermission(
667 webContents,
668 permission,
669 "requestingUrl" in details ? details.requestingUrl : undefined,
670 callback,
671 );
672 return;
673 }
674 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
675 },
676 );
677 browserSession.setPermissionCheckHandler((_webContents, permission, requestingOrigin) =>
678 permission === "clipboard-read" || permission === "geolocation"
679 ? permissionDecisions[permission].get(permissionOrigin(requestingOrigin) ?? "") ===
680 true
681 : ALLOWED_PREVIEW_PERMISSIONS.has(permission),
682 );
683 browserSession.webRequest.onBeforeSendHeaders(
684 { urls: TEAMS_URL_PATTERNS },
685 ({ requestHeaders }, callback) => {
686 const userAgent = Object.entries(requestHeaders).find(
687 ([name]) => name.toLowerCase() === "user-agent",
688 );
689 if (userAgent === undefined) {
690 callback({});
691 return;
692 }
693 const [name, value] = userAgent;
694 callback({
695 requestHeaders: { ...requestHeaders, [name]: value.replace(/ Electron\/\S+/, "") },
696 });
697 },
698 );
699 return browserSession;
700 },
701 catch: (cause) =>
702 new BrowserSessionCreationError({
703 scope,
704 partition,
705 cause,
706 }),
707 }).pipe(
708 Effect.flatMap((browserSession) =>
709 loadCertificateTrust(browserSession).pipe(
710 Effect.map((trust) => {
711 certificateTrust.set(browserSession, trust);
712 const next = new Map(sessions);
713 next.set(partition, browserSession);
714 return [browserSession, next] as const;
715 }),
716 ),
717 ),
718 );
719 });
720 });
721
722 return BrowserSession.of({
723 getPartition,
724 isPartition: (partition) =>
725 partition.startsWith(PREVIEW_PARTITION_PREFIX) ||
726 partition.startsWith(PREVIEW_EPHEMERAL_PARTITION_PREFIX),
727 getSession,
728 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) {
729 const sessions = yield* SynchronizedRef.get(sessionsRef);
730 yield* Effect.forEach(
731 selectSessions(sessions, partitions),
732 ([partition, browserSession]) =>
733 Effect.gen(function* () {
734 const cleared = yield* Effect.tryPromise({
735 try: () =>
736 browserSession.clearStorageData({
737 storages: [
738 "cookies",
739 "localstorage",
740 "indexdb",
741 "serviceworkers",
742 "cachestorage",
743 ],
744 }),
745 catch: (cause) =>
746 new BrowserSessionStorageClearError({
747 partition,
748 cause,
749 }),
750 }).pipe(Effect.result);
751 // Approvals go even when the storage clear fails, since the user asked to forget them.
752 yield* revokeCertificates(partition, browserSession);
753 if (Result.isFailure(cleared)) return yield* cleared.failure;
754 }),
755 { concurrency: "unbounded", discard: true },
756 );
757 }),
758 cookiesCleared: Effect.fn("BrowserSession.cookiesCleared")(function* (browserSession) {
759 const sessions = yield* SynchronizedRef.get(sessionsRef);
760 for (const [partition, candidate] of sessions) {
761 if (candidate === browserSession) yield* revokeCertificates(partition, browserSession);
762 }
763 }),
764 clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
765 const sessions = yield* SynchronizedRef.get(sessionsRef);
766 yield* Effect.forEach(
767 selectSessions(sessions, partitions),
768 ([partition, browserSession]) =>
769 Effect.tryPromise({
770 try: () => browserSession.clearCache(),
771 catch: (cause) =>
772 new BrowserSessionCacheClearError({
773 partition,
774 cause,
775 }),
776 }),
777 { concurrency: "unbounded", discard: true },
778 );
779 }),
780 });
781 }).pipe(Effect.withSpan("BrowserSession.make"));
782
783 export const layer = Layer.effect(BrowserSession, make);