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