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

BrowserSession.ts

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