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

BrowserSession.ts

403 lines14.1 KB

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