Open History to see the last commit
1import type { Session, WebContents } from "electron";
2import { BrowserWindow, session } from "electron";
3import * as Context from "effect/Context";
4import * as Digest from "effect/crypto/Digest";
5import * as Effect from "effect/Effect";
6import * as Hex from "effect/encoding/Hex";
7import * as Layer from "effect/Layer";
8import * as PlatformError from "effect/PlatformError";
9import * as Schema from "effect/Schema";
10import * as SynchronizedRef from "effect/SynchronizedRef";
11
12import * as ElectronDialog from "../electron/ElectronDialog.ts";
13
14const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
15/** Ephemeral partitions omit persist: but retain a product prefix so the webview gate recognizes them. */
16const PREVIEW_EPHEMERAL_PARTITION_PREFIX = "t3code-preview-ephemeral-";
17const PROFILE_PARTITION_MARKER = "profile-";
18
19export type BrowserSessionPartitionNamespace = "profile";
20
21// Electron's clipboard API uses clipboard-sanitized-write and checks both permission handlers.
22const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
23 "clipboard-sanitized-write",
24 "geolocation",
25 // DesktopWindow confines HTML fullscreen to the guest's webview.
26 "fullscreen",
27 "pointerLock",
28 // Loopback requests already succeed in Electron 44; permission-aware sign-in widgets query first.
29 "loopback-network",
30 // Deny local-fonts to untrusted previews: it exposes installed-font fingerprints and file bytes.
31 // Deny notifications: pages could impersonate T3 Code; app notifications use the default session.
32]);
33
34const NEVER_EXTERNAL_PROTOCOLS: ReadonlySet<string> = new Set([
35 "about:",
36 "blob:",
37 "chrome:",
38 "data:",
39 "devtools:",
40 "file:",
41 "filesystem:",
42 "http:",
43 "https:",
44 "javascript:",
45 "view-source:",
46]);
47
48const externalProtocolPromptUrl = (rawUrl: string | undefined): string | null => {
49 if (!rawUrl) return null;
50 try {
51 const url = new URL(rawUrl);
52 return NEVER_EXTERNAL_PROTOCOLS.has(url.protocol) ? null : url.href;
53 } catch {
54 return null;
55 }
56};
57
58// Teams sends Electron User-Agents to an error page before sign-in. Electron allows one listener per session.
59const TEAMS_URL_PATTERNS = ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"];
60
61const MAX_PROMPT_URL_LENGTH = 300;
62
63const truncateForPrompt = (text: string): string =>
64 text.length > MAX_PROMPT_URL_LENGTH ? `${text.slice(0, MAX_PROMPT_URL_LENGTH)}…` : text;
65
66const permissionOrigin = (rawUrl: string | undefined): string | null => {
67 if (!rawUrl) return null;
68 try {
69 const { origin } = new URL(rawUrl);
70 return origin === "null" ? null : origin;
71 } catch {
72 return null;
73 }
74};
75
76export class BrowserSessionPartitionDerivationError extends Schema.TaggedError<BrowserSessionPartitionDerivationError>()(
77 "BrowserSessionPartitionDerivationError",
78 {
79 scope: Schema.String,
80 cause: Schema.instanceOf(PlatformError.PlatformError),
81 },
82) {
83 override get message(): string {
84 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
85 }
86}
87
88export class BrowserSessionCreationError extends Schema.TaggedError<BrowserSessionCreationError>()(
89 "BrowserSessionCreationError",
90 {
91 scope: Schema.String,
92 partition: Schema.String,
93 cause: Schema.Defect(),
94 },
95) {
96 override get message(): string {
97 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
98 }
99}
100
101export class BrowserSessionStorageClearError extends Schema.TaggedError<BrowserSessionStorageClearError>()(
102 "BrowserSessionStorageClearError",
103 {
104 partition: Schema.String,
105 cause: Schema.Defect(),
106 },
107) {
108 override get message(): string {
109 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
110 }
111}
112
113export class BrowserSessionCacheClearError extends Schema.TaggedError<BrowserSessionCacheClearError>()(
114 "BrowserSessionCacheClearError",
115 {
116 partition: Schema.String,
117 cause: Schema.Defect(),
118 },
119) {
120 override get message(): string {
121 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
122 }
123}
124
125export const BrowserSessionGetSessionError = Schema.Union([
126 BrowserSessionPartitionDerivationError,
127 BrowserSessionCreationError,
128]);
129export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
130
131export const BrowserSessionError = Schema.Union([
132 BrowserSessionPartitionDerivationError,
133 BrowserSessionCreationError,
134 BrowserSessionStorageClearError,
135 BrowserSessionCacheClearError,
136]);
137export type BrowserSessionError = typeof BrowserSessionError.Type;
138
139export class BrowserSession extends Context.Service<
140 BrowserSession,
141 {
142 readonly getPartition: (
143 scope?: string,
144 persistent?: boolean,
145 namespace?: BrowserSessionPartitionNamespace,
146 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
147 readonly isPartition: (partition: string) => boolean;
148 readonly getSession: (
149 scope?: string,
150 persistent?: boolean,
151 namespace?: BrowserSessionPartitionNamespace,
152 ) => Effect.Effect<Session, BrowserSessionGetSessionError>;
153 /** Omit `partitions` to clear every known partition. */
154 readonly clearCookies: (
155 partitions?: ReadonlyArray<string>,
156 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
157 readonly clearCache: (
158 partitions?: ReadonlyArray<string>,
159 ) => Effect.Effect<void, BrowserSessionCacheClearError>;
160 }
161>()("@t3tools/desktop/preview/BrowserSession") {}
162
163const selectSessions = (
164 sessions: ReadonlyMap<string, Session>,
165 partitions: ReadonlyArray<string> | undefined,
166): ReadonlyArray<readonly [string, Session]> =>
167 [...sessions.entries()].filter(
168 ([partition]) => partitions === undefined || partitions.includes(partition),
169 );
170
171/** Escape lone surrogates before UTF-8 hashing, which otherwise merges them with U+FFFD; escape backslashes too. */
172const encodeScopeForDigest = (scope: string): Uint8Array =>
173 new TextEncoder().encode(
174 scope
175 .replace(/\\/g, "\\\\")
176 .replace(
177 /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
178 (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
179 ),
180 );
181
182// Webview guests have no window; use their embedding page.
183const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined => {
184 if (guest === null || guest.isDestroyed()) return undefined;
185 const host = guest.hostWebContents ?? guest;
186 if (host.isDestroyed()) return undefined;
187 return BrowserWindow.fromWebContents(host) ?? undefined;
188};
189
190/** @public */
191export const make = Effect.gen(function* BrowserSessionMake() {
192 const crypto = yield* Digest.Digest;
193 const electronDialog = yield* ElectronDialog.ElectronDialog;
194 const runFork = Effect.runForkWith(yield* Effect.context<never>());
195 // One prompt at a time, so a page cannot stack dialogs by looping a deep link.
196 let permissionPromptOpen = false;
197 /** Settles with `undefined` when the user gave no answer: another prompt was open or the dialog failed. */
198 const promptPermission = (
199 requester: WebContents | null,
200 prompt: {
201 readonly buttons: readonly [allow: string, deny: string];
202 readonly message: string;
203 readonly detail?: string;
204 },
205 callback: (answer: boolean | undefined) => void,
206 ): void => {
207 if (permissionPromptOpen) {
208 callback(undefined);
209 return;
210 }
211 permissionPromptOpen = true;
212 const settle = (answer: boolean | undefined) =>
213 Effect.sync(() => {
214 permissionPromptOpen = false;
215 callback(answer);
216 });
217 runFork(
218 electronDialog
219 .showMessageBox(
220 {
221 type: "question",
222 buttons: [...prompt.buttons],
223 // Default to deny so an Enter typed into the page cannot accept a prompt it raised.
224 defaultId: 1,
225 cancelId: 1,
226 message: prompt.message,
227 ...(prompt.detail === undefined ? {} : { detail: prompt.detail }),
228 },
229 previewHostWindow(requester),
230 )
231 .pipe(
232 Effect.map(({ response }): boolean | undefined => response === 0),
233 Effect.orElseSucceed(() => undefined),
234 Effect.flatMap(settle),
235 Effect.onInterrupt(() => settle(undefined)),
236 ),
237 );
238 };
239 /** Electron launches external protocols after granting openExternal; untrusted pages require confirmation. */
240 const confirmOpenExternal = (
241 requester: WebContents | null,
242 rawUrl: string | undefined,
243 callback: (granted: boolean) => void,
244 ): void => {
245 const url = externalProtocolPromptUrl(rawUrl);
246 if (url === null) {
247 callback(false);
248 return;
249 }
250 promptPermission(
251 requester,
252 {
253 buttons: ["Open", "Cancel"],
254 message: `Open this ${new URL(url).protocol.slice(0, -1)} link?`,
255 detail: `A page in the browser wants to open another application:\n\n${truncateForPrompt(url)}`,
256 },
257 (answer) => callback(answer === true),
258 );
259 };
260 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
261
262 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
263 scope = "shared",
264 persistent = true,
265 namespace?: BrowserSessionPartitionNamespace,
266 ) {
267 const digest = yield* crypto.digest(Digest.sha256, encodeScopeForDigest(scope)).pipe(
268 Effect.mapError(
269 (cause) =>
270 new BrowserSessionPartitionDerivationError({
271 scope,
272 cause,
273 }),
274 ),
275 );
276 const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
277 return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Hex.encode(digest).slice(0, 20)}`;
278 });
279
280 const getSession = Effect.fn("BrowserSession.getSession")(function* (
281 scope = "shared",
282 persistent = true,
283 namespace?: BrowserSessionPartitionNamespace,
284 ) {
285 const partition = yield* getPartition(scope, persistent, namespace);
286 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
287 const existing = sessions.get(partition);
288 if (existing) return Effect.succeed([existing, sessions] as const);
289 return Effect.try({
290 try: () => {
291 const browserSession = session.fromPartition(partition);
292 // Like Chrome, clipboard reads ask once per origin; both answers last for the session.
293 const clipboardReadDecisions = new Map<string, boolean>();
294 const confirmClipboardRead = (
295 requester: WebContents,
296 rawUrl: string | undefined,
297 callback: (granted: boolean) => void,
298 ): void => {
299 const origin = permissionOrigin(rawUrl);
300 if (origin === null) {
301 callback(false);
302 return;
303 }
304 const remembered = clipboardReadDecisions.get(origin);
305 if (remembered !== undefined) {
306 callback(remembered);
307 return;
308 }
309 promptPermission(
310 requester,
311 {
312 buttons: ["Allow", "Block"],
313 message: `${truncateForPrompt(origin)} wants to see text and images copied to the clipboard`,
314 },
315 (answer) => {
316 if (answer !== undefined) clipboardReadDecisions.set(origin, answer);
317 callback(answer === true);
318 },
319 );
320 };
321 // Rewriting Electron's native User-Agent makes Turnstile fail integrity checks with error 600010.
322 browserSession.setPermissionRequestHandler(
323 (webContents, permission, callback, details) => {
324 if (permission === "openExternal") {
325 confirmOpenExternal(
326 webContents,
327 "externalURL" in details ? details.externalURL : undefined,
328 callback,
329 );
330 return;
331 }
332 if (permission === "clipboard-read") {
333 confirmClipboardRead(
334 webContents,
335 "requestingUrl" in details ? details.requestingUrl : undefined,
336 callback,
337 );
338 return;
339 }
340 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
341 },
342 );
343 browserSession.setPermissionCheckHandler((_webContents, permission, requestingOrigin) =>
344 permission === "clipboard-read"
345 ? clipboardReadDecisions.get(permissionOrigin(requestingOrigin) ?? "") === true
346 : ALLOWED_PREVIEW_PERMISSIONS.has(permission),
347 );
348 browserSession.webRequest.onBeforeSendHeaders(
349 { urls: TEAMS_URL_PATTERNS },
350 ({ requestHeaders }, callback) => {
351 const userAgent = Object.entries(requestHeaders).find(
352 ([name]) => name.toLowerCase() === "user-agent",
353 );
354 if (userAgent === undefined) {
355 callback({});
356 return;
357 }
358 const [name, value] = userAgent;
359 callback({
360 requestHeaders: { ...requestHeaders, [name]: value.replace(/ Electron\/\S+/, "") },
361 });
362 },
363 );
364 const next = new Map(sessions);
365 next.set(partition, browserSession);
366 return [browserSession, next] as const;
367 },
368 catch: (cause) =>
369 new BrowserSessionCreationError({
370 scope,
371 partition,
372 cause,
373 }),
374 });
375 });
376 });
377
378 return BrowserSession.of({
379 getPartition,
380 isPartition: (partition) =>
381 partition.startsWith(PREVIEW_PARTITION_PREFIX) ||
382 partition.startsWith(PREVIEW_EPHEMERAL_PARTITION_PREFIX),
383 getSession,
384 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) {
385 const sessions = yield* SynchronizedRef.get(sessionsRef);
386 yield* Effect.forEach(
387 selectSessions(sessions, partitions),
388 ([partition, browserSession]) =>
389 Effect.tryPromise({
390 try: () =>
391 browserSession.clearStorageData({
392 storages: ["cookies", "localstorage", "indexdb", "serviceworkers", "cachestorage"],
393 }),
394 catch: (cause) =>
395 new BrowserSessionStorageClearError({
396 partition,
397 cause,
398 }),
399 }),
400 { concurrency: "unbounded", discard: true },
401 );
402 }),
403 clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
404 const sessions = yield* SynchronizedRef.get(sessionsRef);
405 yield* Effect.forEach(
406 selectSessions(sessions, partitions),
407 ([partition, browserSession]) =>
408 Effect.tryPromise({
409 try: () => browserSession.clearCache(),
410 catch: (cause) =>
411 new BrowserSessionCacheClearError({
412 partition,
413 cause,
414 }),
415 }),
416 { concurrency: "unbounded", discard: true },
417 );
418 }),
419 });
420}).pipe(Effect.withSpan("BrowserSession.make"));
421
422export const layer = Layer.effect(BrowserSession, make);