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/** 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-read",
24 "clipboard-sanitized-write",
25 "geolocation",
26 // DesktopWindow confines HTML fullscreen to the guest's webview.
27 "fullscreen",
28 // Deny local-fonts to untrusted previews: it exposes installed-font fingerprints and file bytes.
29 // Deny notifications: pages could impersonate T3 Code; app notifications use the default session.
30]);
31
32const NEVER_EXTERNAL_PROTOCOLS: ReadonlySet<string> = new Set([
33 "about:",
34 "blob:",
35 "chrome:",
36 "data:",
37 "devtools:",
38 "file:",
39 "filesystem:",
40 "http:",
41 "https:",
42 "javascript:",
43 "view-source:",
44]);
45
46const externalProtocolPromptUrl = (rawUrl: string | undefined): string | null => {
47 if (!rawUrl) return null;
48 try {
49 const url = new URL(rawUrl);
50 return NEVER_EXTERNAL_PROTOCOLS.has(url.protocol) ? null : url.href;
51 } catch {
52 return null;
53 }
54};
55
56const MAX_PROMPT_URL_LENGTH = 300;
57
58export class BrowserSessionPartitionDerivationError extends Schema.TaggedError<BrowserSessionPartitionDerivationError>()(
59 "BrowserSessionPartitionDerivationError",
60 {
61 scope: Schema.String,
62 cause: Schema.instanceOf(PlatformError.PlatformError),
63 },
64) {
65 override get message(): string {
66 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
67 }
68}
69
70export class BrowserSessionCreationError extends Schema.TaggedError<BrowserSessionCreationError>()(
71 "BrowserSessionCreationError",
72 {
73 scope: Schema.String,
74 partition: Schema.String,
75 cause: Schema.Defect(),
76 },
77) {
78 override get message(): string {
79 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
80 }
81}
82
83export class BrowserSessionStorageClearError extends Schema.TaggedError<BrowserSessionStorageClearError>()(
84 "BrowserSessionStorageClearError",
85 {
86 partition: Schema.String,
87 cause: Schema.Defect(),
88 },
89) {
90 override get message(): string {
91 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
92 }
93}
94
95export class BrowserSessionCacheClearError extends Schema.TaggedError<BrowserSessionCacheClearError>()(
96 "BrowserSessionCacheClearError",
97 {
98 partition: Schema.String,
99 cause: Schema.Defect(),
100 },
101) {
102 override get message(): string {
103 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
104 }
105}
106
107export const BrowserSessionGetSessionError = Schema.Union([
108 BrowserSessionPartitionDerivationError,
109 BrowserSessionCreationError,
110]);
111export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
112
113export const BrowserSessionError = Schema.Union([
114 BrowserSessionPartitionDerivationError,
115 BrowserSessionCreationError,
116 BrowserSessionStorageClearError,
117 BrowserSessionCacheClearError,
118]);
119export type BrowserSessionError = typeof BrowserSessionError.Type;
120
121export class BrowserSession extends Context.Service<
122 BrowserSession,
123 {
124 readonly getPartition: (
125 scope?: string,
126 persistent?: boolean,
127 namespace?: BrowserSessionPartitionNamespace,
128 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
129 readonly isPartition: (partition: string) => boolean;
130 readonly getSession: (
131 scope?: string,
132 persistent?: boolean,
133 namespace?: BrowserSessionPartitionNamespace,
134 ) => Effect.Effect<Session, BrowserSessionGetSessionError>;
135 /** Omit `partitions` to clear every known partition. */
136 readonly clearCookies: (
137 partitions?: ReadonlyArray<string>,
138 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
139 readonly clearCache: (
140 partitions?: ReadonlyArray<string>,
141 ) => Effect.Effect<void, BrowserSessionCacheClearError>;
142 }
143>()("@t3tools/desktop/preview/BrowserSession") {}
144
145const selectSessions = (
146 sessions: ReadonlyMap<string, Session>,
147 partitions: ReadonlyArray<string> | undefined,
148): ReadonlyArray<readonly [string, Session]> =>
149 [...sessions.entries()].filter(
150 ([partition]) => partitions === undefined || partitions.includes(partition),
151 );
152
153/** Escape lone surrogates before UTF-8 hashing, which otherwise merges them with U+FFFD; escape backslashes too. */
154const encodeScopeForDigest = (scope: string): Uint8Array =>
155 new TextEncoder().encode(
156 scope
157 .replace(/\\/g, "\\\\")
158 .replace(
159 /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
160 (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
161 ),
162 );
163
164// Webview guests have no window; use their embedding page.
165const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined => {
166 if (guest === null || guest.isDestroyed()) return undefined;
167 const host = guest.hostWebContents ?? guest;
168 if (host.isDestroyed()) return undefined;
169 return BrowserWindow.fromWebContents(host) ?? undefined;
170};
171
172/** @public */
173export const make = Effect.gen(function* BrowserSessionMake() {
174 const crypto = yield* Crypto.Crypto;
175 const electronDialog = yield* ElectronDialog.ElectronDialog;
176 const runFork = Effect.runForkWith(yield* Effect.context<never>());
177 // One prompt at a time, so a page cannot stack dialogs by looping a deep link.
178 let externalPromptOpen = false;
179 /** Electron launches external protocols after granting openExternal; untrusted pages require confirmation. */
180 const confirmOpenExternal = (
181 requester: WebContents | null,
182 rawUrl: string | undefined,
183 callback: (granted: boolean) => void,
184 ): void => {
185 const url = externalProtocolPromptUrl(rawUrl);
186 if (url === null || externalPromptOpen) {
187 callback(false);
188 return;
189 }
190 externalPromptOpen = true;
191 const settle = (granted: boolean) =>
192 Effect.sync(() => {
193 externalPromptOpen = false;
194 callback(granted);
195 });
196 const shownUrl =
197 url.length > MAX_PROMPT_URL_LENGTH ? `${url.slice(0, MAX_PROMPT_URL_LENGTH)}…` : url;
198 runFork(
199 electronDialog
200 .showMessageBox(
201 {
202 type: "question",
203 buttons: ["Open", "Cancel"],
204 defaultId: 0,
205 cancelId: 1,
206 message: `Open this ${new URL(url).protocol.slice(0, -1)} link?`,
207 detail: `A page in the browser wants to open another application:\n\n${shownUrl}`,
208 },
209 previewHostWindow(requester),
210 )
211 .pipe(
212 Effect.map(({ response }) => response === 0),
213 Effect.orElseSucceed(() => false),
214 Effect.flatMap(settle),
215 Effect.onInterrupt(() => settle(false)),
216 ),
217 );
218 };
219 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
220
221 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
222 scope = "shared",
223 persistent = true,
224 namespace?: BrowserSessionPartitionNamespace,
225 ) {
226 const digest = yield* crypto.digest("SHA-256", encodeScopeForDigest(scope)).pipe(
227 Effect.mapError(
228 (cause) =>
229 new BrowserSessionPartitionDerivationError({
230 scope,
231 cause,
232 }),
233 ),
234 );
235 const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
236 return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Hex.encode(digest).slice(0, 20)}`;
237 });
238
239 const getSession = Effect.fn("BrowserSession.getSession")(function* (
240 scope = "shared",
241 persistent = true,
242 namespace?: BrowserSessionPartitionNamespace,
243 ) {
244 const partition = yield* getPartition(scope, persistent, namespace);
245 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
246 const existing = sessions.get(partition);
247 if (existing) return Effect.succeed([existing, sessions] as const);
248 return Effect.try({
249 try: () => {
250 const browserSession = session.fromPartition(partition);
251 // Rewriting Electron's native User-Agent makes Turnstile fail integrity checks with error 600010.
252 browserSession.setPermissionRequestHandler(
253 (webContents, permission, callback, details) => {
254 if (permission === "openExternal") {
255 confirmOpenExternal(
256 webContents,
257 "externalURL" in details ? details.externalURL : undefined,
258 callback,
259 );
260 return;
261 }
262 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
263 },
264 );
265 browserSession.setPermissionCheckHandler((_webContents, permission) =>
266 ALLOWED_PREVIEW_PERMISSIONS.has(permission),
267 );
268 const next = new Map(sessions);
269 next.set(partition, browserSession);
270 return [browserSession, next] as const;
271 },
272 catch: (cause) =>
273 new BrowserSessionCreationError({
274 scope,
275 partition,
276 cause,
277 }),
278 });
279 });
280 });
281
282 return BrowserSession.of({
283 getPartition,
284 isPartition: (partition) =>
285 partition.startsWith(PREVIEW_PARTITION_PREFIX) ||
286 partition.startsWith(PREVIEW_EPHEMERAL_PARTITION_PREFIX),
287 getSession,
288 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) {
289 const sessions = yield* SynchronizedRef.get(sessionsRef);
290 yield* Effect.forEach(
291 selectSessions(sessions, partitions),
292 ([partition, browserSession]) =>
293 Effect.tryPromise({
294 try: () =>
295 browserSession.clearStorageData({
296 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
297 }),
298 catch: (cause) =>
299 new BrowserSessionStorageClearError({
300 partition,
301 cause,
302 }),
303 }),
304 { concurrency: "unbounded", discard: true },
305 );
306 }),
307 clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
308 const sessions = yield* SynchronizedRef.get(sessionsRef);
309 yield* Effect.forEach(
310 selectSessions(sessions, partitions),
311 ([partition, browserSession]) =>
312 Effect.tryPromise({
313 try: () => browserSession.clearCache(),
314 catch: (cause) =>
315 new BrowserSessionCacheClearError({
316 partition,
317 cause,
318 }),
319 }),
320 { concurrency: "unbounded", discard: true },
321 );
322 }),
323 });
324}).pipe(Effect.withSpan("BrowserSession.make"));
325
326export const layer = Layer.effect(BrowserSession, make);