Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BrowserSession.ts

400 lines13.9 KB

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