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