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 Crypto from "effect/Crypto";
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/**
16 * Incognito partitions deliberately omit the `persist:` prefix, which is what
17 * makes Chromium keep them in memory and discard them with the process. They
18 * still carry the product prefix so `isPartition` can admit them — the
19 * `will-attach-webview` gate rejects anything it does not recognise.
20 */
21const PREVIEW_EPHEMERAL_PARTITION_PREFIX = "t3code-preview-ephemeral-";
22const PROFILE_PARTITION_MARKER = "profile-";
23
24export type BrowserSessionPartitionNamespace = "profile";
25
26// `clipboard-sanitized-write` is the Electron permission behind
27// `navigator.clipboard.writeText()` — note it is NOT `clipboard-write`, which
28// is not a valid Electron permission name. Async clipboard writes are gated by
29// the permission *check* handler (not only the request handler), so both
30// handlers must allow it; otherwise built-in "Copy" buttons — e.g. the Next.js
31// / Vercel error overlay — fail with `Failed to execute 'writeText' on
32// 'Clipboard': Write permission denied`.
33const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
34 "clipboard-read",
35 "clipboard-sanitized-write",
36 "notifications",
37 "geolocation",
38 // `DesktopWindow` disables HTML fullscreen window resizing for the app window
39 // and every preview guest, so a page that goes fullscreen fills its own
40 // webview instead of taking over the whole T3 window.
41 "fullscreen",
42 // Deliberately NOT local-fonts: preview sessions run untrusted web content,
43 // and silently granting it would hand every page the user's installed-font
44 // fingerprint (and font file bytes via FontData.blob()).
45]);
46
47const NEVER_EXTERNAL_PROTOCOLS: ReadonlySet<string> = new Set([
48 "about:",
49 "blob:",
50 "chrome:",
51 "data:",
52 "devtools:",
53 "file:",
54 "filesystem:",
55 "http:",
56 "https:",
57 "javascript:",
58 "view-source:",
59]);
60
61const externalProtocolPromptUrl = (rawUrl: string | undefined): string | null => {
62 if (!rawUrl) return null;
63 try {
64 const url = new URL(rawUrl);
65 return NEVER_EXTERNAL_PROTOCOLS.has(url.protocol) ? null : url.href;
66 } catch {
67 return null;
68 }
69};
70
71const MAX_PROMPT_URL_LENGTH = 300;
72
73export class BrowserSessionPartitionDerivationError extends Schema.TaggedError<BrowserSessionPartitionDerivationError>()(
74 "BrowserSessionPartitionDerivationError",
75 {
76 scope: Schema.String,
77 cause: Schema.instanceOf(PlatformError.PlatformError),
78 },
79) {
80 override get message(): string {
81 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
82 }
83}
84
85export class BrowserSessionCreationError extends Schema.TaggedError<BrowserSessionCreationError>()(
86 "BrowserSessionCreationError",
87 {
88 scope: Schema.String,
89 partition: Schema.String,
90 cause: Schema.Defect(),
91 },
92) {
93 override get message(): string {
94 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
95 }
96}
97
98export class BrowserSessionStorageClearError extends Schema.TaggedError<BrowserSessionStorageClearError>()(
99 "BrowserSessionStorageClearError",
100 {
101 partition: Schema.String,
102 cause: Schema.Defect(),
103 },
104) {
105 override get message(): string {
106 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
107 }
108}
109
110export class BrowserSessionCacheClearError extends Schema.TaggedError<BrowserSessionCacheClearError>()(
111 "BrowserSessionCacheClearError",
112 {
113 partition: Schema.String,
114 cause: Schema.Defect(),
115 },
116) {
117 override get message(): string {
118 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
119 }
120}
121
122export const BrowserSessionGetSessionError = Schema.Union([
123 BrowserSessionPartitionDerivationError,
124 BrowserSessionCreationError,
125]);
126export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
127
128export const BrowserSessionError = Schema.Union([
129 BrowserSessionPartitionDerivationError,
130 BrowserSessionCreationError,
131 BrowserSessionStorageClearError,
132 BrowserSessionCacheClearError,
133]);
134export type BrowserSessionError = typeof BrowserSessionError.Type;
135
136export class BrowserSession extends Context.Service<
137 BrowserSession,
138 {
139 readonly getPartition: (
140 scope?: string,
141 persistent?: boolean,
142 namespace?: BrowserSessionPartitionNamespace,
143 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
144 readonly isPartition: (partition: string) => boolean;
145 readonly getSession: (
146 scope?: string,
147 persistent?: boolean,
148 namespace?: BrowserSessionPartitionNamespace,
149 ) => Effect.Effect<Session, BrowserSessionGetSessionError>;
150 /** Omit `partitions` to clear every known partition. */
151 readonly clearCookies: (
152 partitions?: ReadonlyArray<string>,
153 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
154 readonly clearCache: (
155 partitions?: ReadonlyArray<string>,
156 ) => Effect.Effect<void, BrowserSessionCacheClearError>;
157 }
158>()("@t3tools/desktop/preview/BrowserSession") {}
159
160const selectSessions = (
161 sessions: ReadonlyMap<string, Session>,
162 partitions: ReadonlyArray<string> | undefined,
163): ReadonlyArray<readonly [string, Session]> =>
164 [...sessions.entries()].filter(
165 ([partition]) => partitions === undefined || partitions.includes(partition),
166 );
167
168/**
169 * `TextEncoder` replaces a lone UTF-16 surrogate with U+FFFD, so `"p\ud800"`
170 * and `"p\ufffd"` would hash to the same partition and share cookies. Those
171 * are distinct, supported ids, so lone surrogates are escaped to `\uXXXX`
172 * first — and a literal backslash is doubled so the escape cannot be forged.
173 */
174const encodeScopeForDigest = (scope: string): Uint8Array =>
175 new TextEncoder().encode(
176 scope
177 .replace(/\\/g, "\\\\")
178 .replace(
179 /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
180 (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
181 ),
182 );
183
184/**
185 * A `<webview>` guest has no window of its own, so look it up through the page
186 * that embeds it.
187 */
188const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined => {
189 if (guest === null || guest.isDestroyed()) return undefined;
190 const host = guest.hostWebContents ?? guest;
191 if (host.isDestroyed()) return undefined;
192 return BrowserWindow.fromWebContents(host) ?? undefined;
193};
194
195/** @public Service construction is part of the canonical Effect module API. */
196export const make = Effect.gen(function* BrowserSessionMake() {
197 const crypto = yield* Crypto.Crypto;
198 const electronDialog = yield* ElectronDialog.ElectronDialog;
199 const runFork = Effect.runForkWith(yield* Effect.context<never>());
200 // One prompt at a time, so a page cannot stack dialogs by looping a deep link.
201 let externalPromptOpen = false;
202 /**
203 * Electron grants an external-protocol navigation through the `openExternal`
204 * permission and then launches the OS handler itself. Ask first: previews run
205 * untrusted pages, and a silent grant would let any of them launch apps.
206 */
207 const confirmOpenExternal = (
208 requester: WebContents | null,
209 rawUrl: string | undefined,
210 callback: (granted: boolean) => void,
211 ): void => {
212 const url = externalProtocolPromptUrl(rawUrl);
213 if (url === null || externalPromptOpen) {
214 callback(false);
215 return;
216 }
217 externalPromptOpen = true;
218 const settle = (granted: boolean) =>
219 Effect.sync(() => {
220 externalPromptOpen = false;
221 callback(granted);
222 });
223 const shownUrl =
224 url.length > MAX_PROMPT_URL_LENGTH ? `${url.slice(0, MAX_PROMPT_URL_LENGTH)}…` : url;
225 runFork(
226 electronDialog
227 .showMessageBox(
228 {
229 type: "question",
230 buttons: ["Open", "Cancel"],
231 defaultId: 0,
232 cancelId: 1,
233 message: `Open this ${new URL(url).protocol.slice(0, -1)} link?`,
234 detail: `A page in the browser wants to open another application:\n\n${shownUrl}`,
235 },
236 previewHostWindow(requester),
237 )
238 .pipe(
239 Effect.map(({ response }) => response === 0),
240 Effect.orElseSucceed(() => false),
241 Effect.flatMap(settle),
242 Effect.onInterrupt(() => settle(false)),
243 ),
244 );
245 };
246 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
247
248 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
249 scope = "shared",
250 persistent = true,
251 namespace?: BrowserSessionPartitionNamespace,
252 ) {
253 const digest = yield* crypto.digest("SHA-256", encodeScopeForDigest(scope)).pipe(
254 Effect.mapError(
255 (cause) =>
256 new BrowserSessionPartitionDerivationError({
257 scope,
258 cause,
259 }),
260 ),
261 );
262 const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
263 return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Hex.encode(digest).slice(0, 20)}`;
264 });
265
266 const getSession = Effect.fn("BrowserSession.getSession")(function* (
267 scope = "shared",
268 persistent = true,
269 namespace?: BrowserSessionPartitionNamespace,
270 ) {
271 const partition = yield* getPartition(scope, persistent, namespace);
272 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
273 const existing = sessions.get(partition);
274 if (existing) return Effect.succeed([existing, sessions] as const);
275 return Effect.try({
276 try: () => {
277 const browserSession = session.fromPartition(partition);
278 // The guest keeps Electron's native User-Agent. Rewriting it in any
279 // form — even variants that keep the Electron token — makes Cloudflare
280 // Turnstile fail its integrity check with error 600010 and recreate
281 // the challenge every few seconds, so logins behind it never complete
282 // (#5002).
283 browserSession.setPermissionRequestHandler(
284 (webContents, permission, callback, details) => {
285 if (permission === "openExternal") {
286 confirmOpenExternal(
287 webContents,
288 "externalURL" in details ? details.externalURL : undefined,
289 callback,
290 );
291 return;
292 }
293 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
294 },
295 );
296 browserSession.setPermissionCheckHandler((_webContents, permission) =>
297 ALLOWED_PREVIEW_PERMISSIONS.has(permission),
298 );
299 const next = new Map(sessions);
300 next.set(partition, browserSession);
301 return [browserSession, next] as const;
302 },
303 catch: (cause) =>
304 new BrowserSessionCreationError({
305 scope,
306 partition,
307 cause,
308 }),
309 });
310 });
311 });
312
313 return BrowserSession.of({
314 getPartition,
315 isPartition: (partition) =>
316 partition.startsWith(PREVIEW_PARTITION_PREFIX) ||
317 partition.startsWith(PREVIEW_EPHEMERAL_PARTITION_PREFIX),
318 getSession,
319 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) {
320 const sessions = yield* SynchronizedRef.get(sessionsRef);
321 yield* Effect.forEach(
322 selectSessions(sessions, partitions),
323 ([partition, browserSession]) =>
324 Effect.tryPromise({
325 try: () =>
326 browserSession.clearStorageData({
327 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
328 }),
329 catch: (cause) =>
330 new BrowserSessionStorageClearError({
331 partition,
332 cause,
333 }),
334 }),
335 { concurrency: "unbounded", discard: true },
336 );
337 }),
338 clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
339 const sessions = yield* SynchronizedRef.get(sessionsRef);
340 yield* Effect.forEach(
341 selectSessions(sessions, partitions),
342 ([partition, browserSession]) =>
343 Effect.tryPromise({
344 try: () => browserSession.clearCache(),
345 catch: (cause) =>
346 new BrowserSessionCacheClearError({
347 partition,
348 cause,
349 }),
350 }),
351 { concurrency: "unbounded", discard: true },
352 );
353 }),
354 });
355}).pipe(Effect.withSpan("BrowserSession.make"));
356
357export const layer = Layer.effect(BrowserSession, make);