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