Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import type { Certificate, Session, WebContents } from "electron";
3import { app, BrowserWindow, session, systemPreferences } from "electron";
4import { msg } from "gt-i18n";
5import * as Context from "effect/Context";
6import * as DateTime from "effect/DateTime";
7import * as Digest from "effect/crypto/Digest";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as PlatformError from "effect/PlatformError";
14import * as Result from "effect/Result";
15import * as Schema from "effect/Schema";
16import * as Semaphore from "effect/Semaphore";
17import * as SynchronizedRef from "effect/SynchronizedRef";
18
19import * as ElectronApp from "../electron/ElectronApp.ts";
20import * as ElectronDialog from "../electron/ElectronDialog.ts";
21import { m } from "../i18n/messages.ts";
22import { resolveSpellCheckerLanguages } from "../window/SpellCheckerLanguages.ts";
23
24const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
25/** Ephemeral partitions omit persist: but retain a product prefix so the webview gate recognizes them. */
26const PREVIEW_EPHEMERAL_PARTITION_PREFIX = "t3code-preview-ephemeral-";
27const PROFILE_PARTITION_MARKER = "profile-";
28
29export type BrowserSessionPartitionNamespace = "profile";
30
31// Electron's clipboard API uses clipboard-sanitized-write and checks both permission handlers.
32const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
33 "clipboard-sanitized-write",
34 // DesktopWindow confines HTML fullscreen to the guest's webview.
35 "fullscreen",
36 "pointerLock",
37 // Loopback requests already succeed in Electron 44; permission-aware sign-in widgets query first.
38 "loopback-network",
39 // Deny local-fonts to untrusted previews: it exposes installed-font fingerprints and file bytes.
40 // Deny notifications: pages could impersonate T3 Code; app notifications use the default session.
41]);
42
43const NEVER_EXTERNAL_PROTOCOLS: ReadonlySet<string> = new Set([
44 "about:",
45 "blob:",
46 "chrome:",
47 "data:",
48 "devtools:",
49 "file:",
50 "filesystem:",
51 "http:",
52 "https:",
53 "javascript:",
54 "view-source:",
55]);
56
57const externalProtocolPromptUrl = (rawUrl: string | undefined): string | null => {
58 if (!rawUrl) return null;
59 try {
60 const url = new URL(rawUrl);
61 return NEVER_EXTERNAL_PROTOCOLS.has(url.protocol) ? null : url.href;
62 } catch {
63 return null;
64 }
65};
66
67const GREASE_CHARS = [" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"];
68const GREASE_VERSIONS = ["8", "99", "24"];
69
70/**
71 * The low-entropy User-Agent client hints the renderer sends on fetches. Mirrors Chromium's
72 * GenerateBrandVersionList with no embedder brand, as Electron builds it.
73 */
74export const lowEntropyClientHints = (
75 chromeVersion: string,
76 platform: NodeJS.Platform,
77): Record<string, string> => {
78 const major = Number.parseInt(chromeVersion, 10);
79 const grease = `"Not${GREASE_CHARS[major % 11]}A${GREASE_CHARS[(major + 1) % 11]}Brand";v="${GREASE_VERSIONS[major % 3]}"`;
80 const chromium = `"Chromium";v="${major}"`;
81 return {
82 "sec-ch-ua": major % 2 === 0 ? `${grease}, ${chromium}` : `${chromium}, ${grease}`,
83 "sec-ch-ua-mobile": "?0",
84 "sec-ch-ua-platform": `"${platform === "darwin" ? "macOS" : platform === "win32" ? "Windows" : "Linux"}"`,
85 };
86};
87
88/** Chrome's reduced User-Agent on this engine: Electron's own without its app and `Electron/` tokens. */
89export const chromeUserAgent = (nativeUserAgent: string, chromeVersion: string): string =>
90 nativeUserAgent.replace(
91 /\(KHTML, like Gecko\) .* Safari\/537\.36$/,
92 `(KHTML, like Gecko) Chrome/${Number.parseInt(chromeVersion, 10)}.0.0.0 Safari/537.36`,
93 );
94
95const isPotentiallyTrustworthy = (rawUrl: string): boolean => {
96 try {
97 const { protocol, hostname } = new URL(rawUrl);
98 if (protocol === "https:") return true;
99 return (
100 protocol === "http:" &&
101 (hostname === "localhost" ||
102 hostname.endsWith(".localhost") ||
103 hostname === "[::1]" ||
104 /^127\.\d+\.\d+\.\d+$/.test(hostname))
105 );
106 } catch {
107 return false;
108 }
109};
110
111const MAX_PROMPT_URL_LENGTH = 300;
112
113const truncateForPrompt = (text: string): string =>
114 text.length > MAX_PROMPT_URL_LENGTH ? `${text.slice(0, MAX_PROMPT_URL_LENGTH)}…` : text;
115
116const permissionOrigin = (rawUrl: string | undefined): string | null => {
117 if (!rawUrl) return null;
118 try {
119 const { origin } = new URL(rawUrl);
120 return origin === "null" ? null : origin;
121 } catch {
122 return null;
123 }
124};
125
126/**
127 * Certificate errors a user may accept for a preview page, with the reason the
128 * prompt shows. Every other error keeps Electron's denial.
129 */
130const OVERRIDABLE_CERTIFICATE_ERRORS: ReadonlyMap<string, string> = new Map([
131 ["net::ERR_CERT_AUTHORITY_INVALID", msg("No trusted authority issued this certificate.")],
132 ["net::ERR_CERT_COMMON_NAME_INVALID", msg("This certificate is not for this address.")],
133 ["net::ERR_CERT_DATE_INVALID", msg("This certificate has expired or is not valid yet.")],
134]);
135
136/**
137 * A `wss:` socket reaches the same TLS endpoint as the page, so it shares the
138 * `https:` origin. It must: a socket is never a main frame, so it could not be
139 * approved on its own, and a page's dev-server socket would stay blocked.
140 */
141const certificateOrigin = (rawUrl: string): string | null => {
142 try {
143 const url = new URL(rawUrl);
144 return url.protocol === "https:" || url.protocol === "wss:" ? `https://${url.host}` : null;
145 } catch {
146 return null;
147 }
148};
149
150const CertificateApproval = Schema.Struct({
151 origin: Schema.String,
152 fingerprint: Schema.String,
153 error: Schema.String,
154});
155type CertificateApproval = typeof CertificateApproval.Type;
156const CertificateApprovalsJson = Schema.fromJsonString(Schema.Array(CertificateApproval));
157const decodeCertificateApprovals = Schema.decodeEffect(CertificateApprovalsJson);
158const encodeCertificateApprovals = Schema.encodeEffect(CertificateApprovalsJson);
159
160const certificateApprovalKey = ({ origin, fingerprint, error }: CertificateApproval): string =>
161 JSON.stringify([origin, fingerprint, error]);
162
163/** Kept beside the profile's cookies, so it lives and dies with them. */
164const CERTIFICATE_APPROVALS_FILE = "t3code-certificate-approvals.json";
165
166/** Server-chosen certificate names must not add lines or flood the prompt. */
167const promptCertificateName = (name: string): string => {
168 const flat = name.replace(/\s+/g, " ").trim();
169 return flat.length > 120 ? `${flat.slice(0, 120).replace(/\p{Surrogate}$/u, "")}…` : flat;
170};
171
172const promptCertificateDate = (seconds: number): string =>
173 DateTime.formatIsoDateUtc(DateTime.makeUnsafe(seconds * 1000));
174
175/** The certificates a user accepted in one preview Session. */
176interface CertificateTrust {
177 /** `null` for an incognito Session, whose approvals end with the process. */
178 readonly file: string | null;
179 readonly approvals: Map<string, CertificateApproval>;
180 /** Bumped by each revocation, so an answer to an older prompt cannot restore trust. */
181 revocations: number;
182}
183
184type MediaDevice = "camera" | "microphone";
185
186const mediaDeviceFor = (mediaType: string | undefined): MediaDevice | null =>
187 mediaType === "video" ? "camera" : mediaType === "audio" ? "microphone" : null;
188
189// Whole sentences per device set, so each language can phrase them its own way.
190const mediaRequestMessage = (devices: ReadonlyArray<MediaDevice>, origin: string): string =>
191 devices.length === 2
192 ? m(msg`${{ origin }} wants to use your camera and microphone`)
193 : devices[0] === "microphone"
194 ? m(msg`${{ origin }} wants to use your microphone`)
195 : m(msg`${{ origin }} wants to use your camera`);
196
197const mediaBlockedMessage = (devices: ReadonlyArray<MediaDevice>): string =>
198 devices.length === 2
199 ? m(msg("macOS blocked T3 Code from using your camera and microphone"))
200 : devices[0] === "microphone"
201 ? m(msg("macOS blocked T3 Code from using your microphone"))
202 : m(msg("macOS blocked T3 Code from using your camera"));
203
204/**
205 * macOS gates capture devices per app and lists an app under Privacy & Security
206 * only after it asks, so ask the OS once the user allowed the page.
207 */
208/** Returns the devices macOS blocks, so the recovery message names only those; empty means allowed. */
209const ensureSystemMediaAccess = async (
210 platform: NodeJS.Platform,
211 devices: ReadonlyArray<MediaDevice>,
212): Promise<ReadonlyArray<MediaDevice>> => {
213 if (platform !== "darwin") return [];
214 const statuses = devices.map((device) => systemPreferences.getMediaAccessStatus(device));
215 const refused = devices.filter(
216 (_device, index) => statuses[index] !== "granted" && statuses[index] !== "not-determined",
217 );
218 if (refused.length > 0) return refused;
219 const results = await Promise.all(
220 devices.map((device, index) =>
221 statuses[index] === "granted"
222 ? true
223 : systemPreferences.askForMediaAccess(device).catch(() => false),
224 ),
225 );
226 return devices.filter((_device, index) => !results[index]);
227};
228
229/** The camera and microphone answers given in one preview Session. */
230interface MediaConsent {
231 readonly decisions: Map<string, boolean>;
232 /** Bumped by each reset, so an answer to an older prompt cannot restore a decision. */
233 resets: number;
234}
235
236export class BrowserSessionPartitionDerivationError extends Schema.TaggedError<BrowserSessionPartitionDerivationError>()(
237 "BrowserSessionPartitionDerivationError",
238 {
239 scope: Schema.String,
240 cause: Schema.instanceOf(PlatformError.PlatformError),
241 },
242) {
243 override get message(): string {
244 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
245 }
246}
247
248export class BrowserSessionCreationError extends Schema.TaggedError<BrowserSessionCreationError>()(
249 "BrowserSessionCreationError",
250 {
251 scope: Schema.String,
252 partition: Schema.String,
253 cause: Schema.Defect(),
254 },
255) {
256 override get message(): string {
257 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
258 }
259}
260
261export class BrowserSessionStorageClearError extends Schema.TaggedError<BrowserSessionStorageClearError>()(
262 "BrowserSessionStorageClearError",
263 {
264 partition: Schema.String,
265 cause: Schema.Defect(),
266 },
267) {
268 override get message(): string {
269 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
270 }
271}
272
273export class BrowserSessionCacheClearError extends Schema.TaggedError<BrowserSessionCacheClearError>()(
274 "BrowserSessionCacheClearError",
275 {
276 partition: Schema.String,
277 cause: Schema.Defect(),
278 },
279) {
280 override get message(): string {
281 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
282 }
283}
284
285export const BrowserSessionGetSessionError = Schema.Union([
286 BrowserSessionPartitionDerivationError,
287 BrowserSessionCreationError,
288]);
289export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
290
291export const BrowserSessionError = Schema.Union([
292 BrowserSessionPartitionDerivationError,
293 BrowserSessionCreationError,
294 BrowserSessionStorageClearError,
295 BrowserSessionCacheClearError,
296]);
297export type BrowserSessionError = typeof BrowserSessionError.Type;
298
299export class BrowserSession extends Context.Service<
300 BrowserSession,
301 {
302 readonly getPartition: (
303 scope?: string,
304 persistent?: boolean,
305 namespace?: BrowserSessionPartitionNamespace,
306 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
307 readonly isPartition: (partition: string) => boolean;
308 readonly getSession: (
309 scope?: string,
310 persistent?: boolean,
311 namespace?: BrowserSessionPartitionNamespace,
312 ) => Effect.Effect<Session, BrowserSessionGetSessionError>;
313 /** Omit `partitions` to clear every known partition. */
314 readonly clearCookies: (
315 partitions?: ReadonlyArray<string>,
316 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
317 /** For cookies cleared outside `clearCookies`, such as over a tab's CDP session. */
318 readonly cookiesCleared: (
319 browserSession: Session,
320 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
321 readonly clearCache: (
322 partitions?: ReadonlyArray<string>,
323 ) => Effect.Effect<void, BrowserSessionCacheClearError>;
324 }
325>()("@t3tools/desktop/preview/BrowserSession") {}
326
327const selectSessions = (
328 sessions: ReadonlyMap<string, Session>,
329 partitions: ReadonlyArray<string> | undefined,
330): ReadonlyArray<readonly [string, Session]> =>
331 [...sessions.entries()].filter(
332 ([partition]) => partitions === undefined || partitions.includes(partition),
333 );
334
335/** Escape lone surrogates before UTF-8 hashing, which otherwise merges them with U+FFFD; escape backslashes too. */
336const encodeScopeForDigest = (scope: string): Uint8Array =>
337 new TextEncoder().encode(
338 scope
339 .replace(/\\/g, "\\\\")
340 .replace(
341 /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
342 (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
343 ),
344 );
345
346// Webview guests have no window; use their embedding page.
347const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined => {
348 if (guest === null || guest.isDestroyed()) return undefined;
349 const host = guest.hostWebContents ?? guest;
350 if (host.isDestroyed()) return undefined;
351 return BrowserWindow.fromWebContents(host) ?? undefined;
352};
353
354/** @public */
355export const make = Effect.gen(function* BrowserSessionMake() {
356 const crypto = yield* Digest.Digest;
357 const electronApp = yield* ElectronApp.ElectronApp;
358 const electronDialog = yield* ElectronDialog.ElectronDialog;
359 const fileSystem = yield* FileSystem.FileSystem;
360 const path = yield* Path.Path;
361 const platform = yield* HostProcess.Platform;
362 const runFork = Effect.runForkWith(yield* Effect.context<never>());
363 // One prompt at a time, so a page cannot stack dialogs by looping a deep link.
364 let permissionPromptOpen = false;
365 let mediaRecoveryOpen = false;
366 /** Settles with `undefined` when the user gave no answer: another prompt was open or the dialog failed. */
367 const promptPermission = (
368 requester: WebContents | null,
369 prompt: {
370 readonly buttons: readonly [allow: string, deny: string];
371 readonly message: string;
372 readonly detail?: string;
373 },
374 callback: (answer: boolean | undefined) => void,
375 ): void => {
376 if (permissionPromptOpen || requester?.isDestroyed()) {
377 callback(undefined);
378 return;
379 }
380 permissionPromptOpen = true;
381 const dismiss = new AbortController();
382 const abandon = () => dismiss.abort();
383 requester?.once("destroyed", abandon);
384 const settle = (answer: boolean | undefined) =>
385 Effect.sync(() => {
386 permissionPromptOpen = false;
387 requester?.off("destroyed", abandon);
388 callback(dismiss.signal.aborted || requester?.isDestroyed() ? undefined : answer);
389 });
390 runFork(
391 electronDialog
392 .showMessageBox(
393 {
394 type: "question",
395 signal: dismiss.signal,
396 buttons: [...prompt.buttons],
397 // Default to deny so an Enter typed into the page cannot accept a prompt it raised.
398 defaultId: 1,
399 cancelId: 1,
400 message: prompt.message,
401 ...(prompt.detail === undefined ? {} : { detail: prompt.detail }),
402 },
403 platform === "win32" ? undefined : previewHostWindow(requester),
404 )
405 .pipe(
406 Effect.map(({ response }): boolean | undefined => response === 0),
407 Effect.orElseSucceed(() => undefined),
408 Effect.flatMap(settle),
409 Effect.onInterrupt(() => settle(undefined)),
410 ),
411 );
412 };
413 /** Electron launches external protocols after granting openExternal; untrusted pages require confirmation. */
414 const confirmOpenExternal = (
415 requester: WebContents | null,
416 rawUrl: string | undefined,
417 callback: (granted: boolean) => void,
418 ): void => {
419 const url = externalProtocolPromptUrl(rawUrl);
420 if (url === null) {
421 callback(false);
422 return;
423 }
424 promptPermission(
425 requester,
426 {
427 buttons: [
428 m(msg({ context: "button, opens a link in another app" })`Open`),
429 m(msg("Cancel")),
430 ],
431 message: m(msg`Open this ${{ protocol: new URL(url).protocol.slice(0, -1) }} link?`),
432 detail: m(msg`A page in the browser wants to open another application:
433
434${{ url: truncateForPrompt(url) }}`),
435 },
436 (answer) => callback(answer === true),
437 );
438 };
439
440 const certificateTrust = new WeakMap<Session, CertificateTrust>();
441 const writeCertificateApprovals = yield* Semaphore.make(1);
442 const loadCertificateTrust = Effect.fn("BrowserSession.loadCertificateTrust")(function* (
443 browserSession: Session,
444 ) {
445 const file =
446 browserSession.storagePath == null
447 ? null
448 : path.join(browserSession.storagePath, CERTIFICATE_APPROVALS_FILE);
449 const approvals: ReadonlyArray<CertificateApproval> =
450 file === null
451 ? []
452 : yield* fileSystem.readFileString(file).pipe(
453 Effect.flatMap(decodeCertificateApprovals),
454 Effect.catchTags({
455 PlatformError: (error) =>
456 error.reason._tag === "NotFound" ? Effect.succeed([]) : Effect.fail(error),
457 }),
458 Effect.catch((cause) =>
459 Effect.logWarning("Ignored saved certificate approvals.", { file, cause }).pipe(
460 Effect.as([]),
461 ),
462 ),
463 );
464 const trust: CertificateTrust = {
465 file,
466 approvals: new Map(approvals.map((approval) => [certificateApprovalKey(approval), approval])),
467 revocations: 0,
468 };
469 return trust;
470 });
471 const writeApprovalsFile = Effect.fn("BrowserSession.writeApprovalsFile")(function* (
472 file: string,
473 approvals: ReadonlyMap<string, CertificateApproval>,
474 ) {
475 if (approvals.size === 0) return yield* fileSystem.remove(file, { force: true });
476 yield* fileSystem.makeDirectory(path.dirname(file), { recursive: true });
477 yield* fileSystem.writeFileString(
478 file,
479 yield* encodeCertificateApprovals([...approvals.values()]),
480 );
481 });
482 /**
483 * Saved before it is trusted, so a failed write cannot leave an approval that
484 * silently ends at restart. Writes share one lock, so a slower write cannot
485 * restore stale data.
486 */
487 const rememberCertificate = Effect.fn("BrowserSession.rememberCertificate")(function* (
488 trust: CertificateTrust,
489 key: string,
490 approval: CertificateApproval,
491 revocations: number,
492 ) {
493 if (trust.revocations !== revocations) return false;
494 if (trust.file !== null) {
495 yield* writeApprovalsFile(trust.file, new Map(trust.approvals).set(key, approval));
496 // A revocation during the write queues its own rewrite behind this one.
497 if (trust.revocations !== revocations) return false;
498 }
499 trust.approvals.set(key, approval);
500 return true;
501 }, writeCertificateApprovals.withPermits(1));
502 /**
503 * Rewrites the file from memory. Clearing cookies runs this even when memory
504 * is already empty, so retrying after a failed removal still deletes the file.
505 */
506 const saveCertificateApprovals = Effect.fn("BrowserSession.saveCertificateApprovals")(function* (
507 trust: CertificateTrust,
508 ) {
509 if (trust.file !== null) yield* writeApprovalsFile(trust.file, trust.approvals);
510 }, writeCertificateApprovals.withPermits(1));
511
512 // One prompt at a time; tabs that hit the same certificate wait on it.
513 let certificatePrompt: {
514 readonly trust: CertificateTrust;
515 readonly key: string;
516 readonly callbacks: Array<(trusted: boolean) => void>;
517 } | null = null;
518 const confirmCertificate = (
519 contents: WebContents,
520 trust: CertificateTrust,
521 approval: CertificateApproval,
522 certificate: Certificate,
523 reason: string,
524 callback: (trusted: boolean) => void,
525 ): void => {
526 const key = certificateApprovalKey(approval);
527 if (certificatePrompt !== null) {
528 if (certificatePrompt.trust === trust && certificatePrompt.key === key) {
529 certificatePrompt.callbacks.push(callback);
530 } else {
531 callback(false);
532 }
533 return;
534 }
535 const prompt = { trust, key, callbacks: [callback] };
536 certificatePrompt = prompt;
537 // A prompt for a tab that closed or moved on would approve a page nobody is waiting for.
538 const dismiss = new AbortController();
539 const abandon = () => dismiss.abort();
540 const navigated = (
541 event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
542 ) => {
543 if (event.isMainFrame && !event.isSameDocument) abandon();
544 };
545 contents.once("destroyed", abandon);
546 contents.on("did-start-navigation", navigated);
547 const settle = (trusted: boolean) =>
548 Effect.sync(() => {
549 certificatePrompt = null;
550 if (!contents.isDestroyed()) {
551 contents.off("destroyed", abandon);
552 contents.off("did-start-navigation", navigated);
553 }
554 for (const waiter of prompt.callbacks) waiter(trusted);
555 });
556 const host = new URL(approval.origin).host;
557 const revocations = trust.revocations;
558 runFork(
559 electronDialog
560 .showMessageBox(
561 {
562 type: "warning",
563 buttons: [m(msg("Trust and Remember")), m(msg("Cancel"))],
564 defaultId: 1,
565 cancelId: 1,
566 signal: dismiss.signal,
567 message: m(msg`${{ host }} has an untrusted certificate`),
568 detail: [
569 m(reason),
570 "",
571 m(msg`Issued to: ${{ name: promptCertificateName(certificate.subjectName) }}`),
572 m(msg`Issued by: ${{ name: promptCertificateName(certificate.issuerName) }}`),
573 m(
574 msg`Valid: ${{ start: promptCertificateDate(certificate.validStart) }} – ${{ end: promptCertificateDate(certificate.validExpiry) }}`,
575 ),
576 m(msg`Fingerprint: ${{ fingerprint: approval.fingerprint }}`),
577 "",
578 m(
579 msg(
580 "Trust it only if you know this certificate belongs to the site. Clearing this browser profile's cookies forgets it.",
581 ),
582 ),
583 ].join("\n"),
584 },
585 // In the reporter's Windows test, a box owned by the host window
586 // blocked all mouse input, its own buttons included, until it closed.
587 platform === "win32" ? undefined : previewHostWindow(contents),
588 )
589 .pipe(
590 Effect.flatMap(({ response }) =>
591 response === 0 && !dismiss.signal.aborted
592 ? rememberCertificate(trust, key, approval, revocations).pipe(
593 Effect.catch((cause) =>
594 Effect.logWarning("Failed to save a certificate approval.", { cause }).pipe(
595 Effect.andThen(
596 electronDialog.showErrorBox(
597 m(msg`Could not trust the certificate for ${{ host }}`),
598 m(
599 msg(
600 "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.",
601 ),
602 ),
603 ),
604 ),
605 Effect.as(false),
606 ),
607 ),
608 )
609 : Effect.succeed(false),
610 ),
611 Effect.orElseSucceed(() => false),
612 Effect.flatMap(settle),
613 Effect.onInterrupt(() => settle(false)),
614 ),
615 );
616 };
617 yield* electronApp.on(
618 "certificate-error",
619 (
620 event: Electron.Event,
621 contents: WebContents,
622 url: string,
623 error: string,
624 certificate: Certificate,
625 callback: (trusted: boolean) => void,
626 isMainFrame: boolean,
627 ) => {
628 if (contents.isDestroyed()) return;
629 // Sessions this service did not create keep Electron's denial.
630 const trust = certificateTrust.get(contents.session);
631 const origin = certificateOrigin(url);
632 const reason = OVERRIDABLE_CERTIFICATE_ERRORS.get(error);
633 if (trust === undefined || origin === null || reason === undefined) return;
634 const approval = { origin, fingerprint: certificate.fingerprint, error };
635 event.preventDefault();
636 if (trust.approvals.has(certificateApprovalKey(approval))) {
637 callback(true);
638 return;
639 }
640 // Only a page navigation asks; a subresource the user has not accepted stays blocked.
641 if (!isMainFrame) {
642 callback(false);
643 return;
644 }
645 confirmCertificate(contents, trust, approval, certificate, reason, callback);
646 },
647 );
648
649 /** Clearing a profile's cookies also forgets the certificates its user trusted. */
650 const revokeCertificates = Effect.fn("BrowserSession.revokeCertificates")(function* (
651 partition: string,
652 browserSession: Session,
653 ) {
654 const trust = certificateTrust.get(browserSession);
655 if (trust === undefined) return;
656 const hadApprovals = trust.approvals.size > 0;
657 trust.revocations += 1;
658 trust.approvals.clear();
659 const saved = yield* saveCertificateApprovals(trust).pipe(Effect.result);
660 // An open connection already passed its certificate check.
661 if (hadApprovals) {
662 yield* Effect.tryPromise({
663 try: () => browserSession.closeAllConnections(),
664 catch: (cause) => new BrowserSessionStorageClearError({ partition, cause }),
665 });
666 }
667 if (Result.isFailure(saved)) {
668 return yield* new BrowserSessionStorageClearError({ partition, cause: saved.failure });
669 }
670 });
671
672 /** Camera and microphone answers by Session; clearing a profile's cookies forgets them too. */
673 const mediaConsentBySession = new WeakMap<Session, MediaConsent>();
674 const forgetMediaDecisions = (browserSession: Session): void => {
675 const consent = mediaConsentBySession.get(browserSession);
676 if (consent === undefined) return;
677 consent.resets += 1;
678 consent.decisions.clear();
679 };
680
681 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
682
683 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
684 scope = "shared",
685 persistent = true,
686 namespace?: BrowserSessionPartitionNamespace,
687 ) {
688 const digest = yield* crypto.digest(Digest.sha256, encodeScopeForDigest(scope)).pipe(
689 Effect.mapError(
690 (cause) =>
691 new BrowserSessionPartitionDerivationError({
692 scope,
693 cause,
694 }),
695 ),
696 );
697 const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
698 return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Hex.encode(digest).slice(0, 20)}`;
699 });
700
701 const getSession = Effect.fn("BrowserSession.getSession")(function* (
702 scope = "shared",
703 persistent = true,
704 namespace?: BrowserSessionPartitionNamespace,
705 ) {
706 const partition = yield* getPartition(scope, persistent, namespace);
707 const preferredSystemLanguages = yield* electronApp.preferredSystemLanguages;
708 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
709 const existing = sessions.get(partition);
710 if (existing) return Effect.succeed([existing, sessions] as const);
711 return Effect.try({
712 try: () => {
713 // Sites refuse the app and Electron tokens. Workers read only the app-wide fallback, and a
714 // page whose workers disagree with it fails Turnstile (600010), so a session override can't
715 // do this. The app window's session follows the fallback too, so it is pinned first.
716 const nativeUserAgent = app.userAgentFallback;
717 const previewUserAgent = chromeUserAgent(nativeUserAgent, process.versions.chrome);
718 if (previewUserAgent !== nativeUserAgent) {
719 session.defaultSession.setUserAgent(nativeUserAgent);
720 app.userAgentFallback = previewUserAgent;
721 }
722 const browserSession = session.fromPartition(partition);
723 // Each session has its own dictionaries; the app window's follow the OS the same way.
724 if (platform !== "darwin") {
725 const spellCheckerLanguages = resolveSpellCheckerLanguages(
726 browserSession.getSpellCheckerLanguages(),
727 preferredSystemLanguages,
728 browserSession.availableSpellCheckerLanguages,
729 );
730 if (spellCheckerLanguages)
731 browserSession.setSpellCheckerLanguages(spellCheckerLanguages);
732 }
733 // Location and clipboard decisions are remembered separately for each origin.
734 const permissionDecisions = {
735 "clipboard-read": new Map<string, boolean>(),
736 geolocation: new Map<string, boolean>(),
737 };
738 const confirmOriginPermission = (
739 requester: WebContents,
740 permission: keyof typeof permissionDecisions,
741 rawUrl: string | undefined,
742 callback: (granted: boolean) => void,
743 ): void => {
744 const origin = permissionOrigin(rawUrl);
745 if (origin === null) {
746 // A frame URL such as about:srcdoc cannot establish whether its origin is inherited or opaque.
747 callback(false);
748 return;
749 }
750 const decisions = permissionDecisions[permission];
751 const remembered = decisions.get(origin);
752 if (remembered !== undefined) {
753 callback(remembered);
754 return;
755 }
756 promptPermission(
757 requester,
758 {
759 buttons: [
760 m(msg({ context: "button, grants a site permission" })`Allow`),
761 m(msg({ context: "button, denies a site permission" })`Block`),
762 ],
763 message:
764 permission === "geolocation"
765 ? m(msg`${{ origin: truncateForPrompt(origin) }} wants to know your location`)
766 : m(
767 msg`${{ origin: truncateForPrompt(origin) }} wants to see text and images copied to the clipboard`,
768 ),
769 },
770 (answer) => {
771 if (answer !== undefined) decisions.set(origin, answer);
772 callback(answer === true);
773 },
774 );
775 };
776 // Camera and microphone ask once per origin and device, like clipboard reads.
777 const mediaConsent: MediaConsent = { decisions: new Map(), resets: 0 };
778 mediaConsentBySession.set(browserSession, mediaConsent);
779 const mediaDecisions = mediaConsent.decisions;
780 const mediaKey = (origin: string, device: MediaDevice) => `${device} ${origin}`;
781 const confirmMedia = (
782 requester: WebContents,
783 rawUrl: string | undefined,
784 mediaTypes: ReadonlyArray<string> | undefined,
785 callback: (granted: boolean) => void,
786 ): void => {
787 const origin = permissionOrigin(rawUrl);
788 const devices = [
789 ...new Set((mediaTypes ?? []).map(mediaDeviceFor).filter((d) => d !== null)),
790 ];
791 if (origin === null || devices.length === 0) {
792 callback(false);
793 return;
794 }
795 // A reset while a prompt or the macOS check is pending must not grant or remember.
796 const resets = mediaConsent.resets;
797 const isStale = () =>
798 mediaConsent.resets !== resets || requester?.isDestroyed() === true;
799 const finish = (granted: boolean) => {
800 if (!granted || isStale()) {
801 callback(false);
802 return;
803 }
804 void ensureSystemMediaAccess(platform, devices).then(
805 (blocked) => {
806 const systemGranted = blocked.length === 0;
807 if (isStale()) {
808 callback(false);
809 return;
810 }
811 if (!systemGranted && !mediaRecoveryOpen) {
812 mediaRecoveryOpen = true;
813 runFork(
814 electronDialog
815 .showMessageBox(
816 {
817 type: "info",
818 buttons: [m(msg("OK"))],
819 message: mediaBlockedMessage(blocked),
820 detail: m(
821 msg(
822 "Allow T3 Code in System Settings › Privacy & Security, then restart T3 Code.",
823 ),
824 ),
825 },
826 previewHostWindow(requester),
827 )
828 .pipe(
829 Effect.ignore,
830 Effect.ensuring(
831 Effect.sync(() => {
832 mediaRecoveryOpen = false;
833 }),
834 ),
835 ),
836 );
837 }
838 callback(systemGranted);
839 },
840 () => callback(false),
841 );
842 };
843 const remembered = devices.map((device) =>
844 mediaDecisions.get(mediaKey(origin, device)),
845 );
846 if (remembered.some((answer) => answer === false)) {
847 callback(false);
848 return;
849 }
850 if (remembered.every((answer) => answer === true)) {
851 finish(true);
852 return;
853 }
854 const undecided = devices.filter(
855 (device) => !mediaDecisions.has(mediaKey(origin, device)),
856 );
857 promptPermission(
858 requester,
859 {
860 buttons: [
861 m(msg({ context: "button, grants a site permission" })`Allow`),
862 m(msg({ context: "button, denies a site permission" })`Block`),
863 ],
864 message: mediaRequestMessage(undecided, truncateForPrompt(origin)),
865 },
866 (answer) => {
867 if (answer !== undefined && !isStale()) {
868 for (const device of undecided)
869 mediaDecisions.set(mediaKey(origin, device), answer);
870 }
871 finish(answer === true);
872 },
873 );
874 };
875 browserSession.setPermissionRequestHandler(
876 (webContents, permission, callback, details) => {
877 if (permission === "openExternal") {
878 confirmOpenExternal(
879 webContents,
880 "externalURL" in details ? details.externalURL : undefined,
881 callback,
882 );
883 return;
884 }
885 if (permission === "clipboard-read" || permission === "geolocation") {
886 confirmOriginPermission(
887 webContents,
888 permission,
889 "requestingUrl" in details ? details.requestingUrl : undefined,
890 callback,
891 );
892 return;
893 }
894 if (permission === "media") {
895 confirmMedia(
896 webContents,
897 ("securityOrigin" in details ? details.securityOrigin : undefined) ??
898 details.requestingUrl,
899 "mediaTypes" in details ? details.mediaTypes : undefined,
900 callback,
901 );
902 return;
903 }
904 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
905 },
906 );
907 browserSession.setPermissionCheckHandler(
908 (_webContents, permission, requestingOrigin, details) => {
909 if (permission === "clipboard-read" || permission === "geolocation") {
910 return (
911 permissionDecisions[permission].get(permissionOrigin(requestingOrigin) ?? "") ===
912 true
913 );
914 }
915 if (permission === "media") {
916 const origin = permissionOrigin(requestingOrigin);
917 const device = mediaDeviceFor(details?.mediaType);
918 return (
919 origin !== null &&
920 device !== null &&
921 mediaDecisions.get(mediaKey(origin, device)) === true &&
922 (platform !== "darwin" ||
923 systemPreferences.getMediaAccessStatus(device) === "granted")
924 );
925 }
926 return ALLOWED_PREVIEW_PERMISSIONS.has(permission);
927 },
928 );
929 const clientHints = lowEntropyClientHints(process.versions.chrome, platform);
930 // Electron adds client hints to subresources only; sites that compare them across a session reject navigations without them.
931 browserSession.webRequest.onBeforeSendHeaders(
932 { urls: ["http://*/*", "https://*/*"] },
933 ({ url, resourceType, requestHeaders }, callback) => {
934 callback(
935 (resourceType === "mainFrame" || resourceType === "subFrame") &&
936 !Object.keys(requestHeaders).some((name) => name.toLowerCase() === "sec-ch-ua") &&
937 isPotentiallyTrustworthy(url)
938 ? { requestHeaders: { ...requestHeaders, ...clientHints } }
939 : {},
940 );
941 },
942 );
943 return browserSession;
944 },
945 catch: (cause) =>
946 new BrowserSessionCreationError({
947 scope,
948 partition,
949 cause,
950 }),
951 }).pipe(
952 Effect.flatMap((browserSession) =>
953 loadCertificateTrust(browserSession).pipe(
954 Effect.map((trust) => {
955 certificateTrust.set(browserSession, trust);
956 const next = new Map(sessions);
957 next.set(partition, browserSession);
958 return [browserSession, next] as const;
959 }),
960 ),
961 ),
962 );
963 });
964 });
965
966 return BrowserSession.of({
967 getPartition,
968 isPartition: (partition) =>
969 partition.startsWith(PREVIEW_PARTITION_PREFIX) ||
970 partition.startsWith(PREVIEW_EPHEMERAL_PARTITION_PREFIX),
971 getSession,
972 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) {
973 const sessions = yield* SynchronizedRef.get(sessionsRef);
974 const selected = selectSessions(sessions, partitions);
975 for (const [, browserSession] of selected) forgetMediaDecisions(browserSession);
976 yield* Effect.forEach(
977 selected,
978 ([partition, browserSession]) =>
979 Effect.gen(function* () {
980 const cleared = yield* Effect.tryPromise({
981 try: () =>
982 browserSession.clearStorageData({
983 storages: [
984 "cookies",
985 "localstorage",
986 "indexdb",
987 "serviceworkers",
988 "cachestorage",
989 ],
990 }),
991 catch: (cause) =>
992 new BrowserSessionStorageClearError({
993 partition,
994 cause,
995 }),
996 }).pipe(Effect.result);
997 // Approvals go even when the storage clear fails, since the user asked to forget them.
998 yield* revokeCertificates(partition, browserSession);
999 if (Result.isFailure(cleared)) return yield* cleared.failure;
1000 }),
1001 { concurrency: "unbounded", discard: true },
1002 );
1003 }),
1004 cookiesCleared: Effect.fn("BrowserSession.cookiesCleared")(function* (browserSession) {
1005 const sessions = yield* SynchronizedRef.get(sessionsRef);
1006 for (const [partition, candidate] of sessions) {
1007 if (candidate !== browserSession) continue;
1008 forgetMediaDecisions(browserSession);
1009 yield* revokeCertificates(partition, browserSession);
1010 }
1011 }),
1012 clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
1013 const sessions = yield* SynchronizedRef.get(sessionsRef);
1014 yield* Effect.forEach(
1015 selectSessions(sessions, partitions),
1016 ([partition, browserSession]) =>
1017 Effect.tryPromise({
1018 try: () => browserSession.clearCache(),
1019 catch: (cause) =>
1020 new BrowserSessionCacheClearError({
1021 partition,
1022 cause,
1023 }),
1024 }),
1025 { concurrency: "unbounded", discard: true },
1026 );
1027 }),
1028 });
1029}).pipe(Effect.withSpan("BrowserSession.make"));
1030
1031export const layer = Layer.effect(BrowserSession, make);