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