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

BrowserSession.ts

270 lines10.3 KB

1import type { Session } from "electron";
2import { session } from "electron";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Encoding from "effect/Encoding";
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​
12const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
13/**
14 * Incognito partitions deliberately omit the `persist:` prefix, which is what
15 * makes Chromium keep them in memory and discard them with the process. They
16 * still carry the product prefix so `isPartition` can admit them — the
17 * `will-attach-webview` gate rejects anything it does not recognise.
18 */
19const PREVIEW_EPHEMERAL_PARTITION_PREFIX = "t3code-preview-ephemeral-";
20const PROFILE_PARTITION_MARKER = "profile-";
21​
22export type BrowserSessionPartitionNamespace = "profile";
23​
24// Permissions granted to preview web content. `clipboard-sanitized-write` is the
25// Electron permission behind `navigator.clipboard.writeText()` — note it is NOT
26// `clipboard-write`, which is not a valid Electron permission name. Async
27// clipboard writes are gated by the permission *check* handler (not only the
28// request handler), so both handlers must allow it; otherwise built-in "Copy"
29// buttons — e.g. the Next.js / Vercel error overlay — fail with
30// `Failed to execute 'writeText' on 'Clipboard': Write permission denied`.
31const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
32 "clipboard-read",
33 "clipboard-sanitized-write",
34 "notifications",
35 "geolocation",
36 // Deliberately NOT local-fonts: preview sessions run untrusted web content,
37 // and silently granting it would hand every page the user's installed-font
38 // fingerprint (and font file bytes via FontData.blob()). The app's own font
39 // picker runs in the main window session, which is unaffected by this list.
40]);
41​
42export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
43 "BrowserSessionPartitionDerivationError",
44 {
45 scope: Schema.String,
46 cause: Schema.instanceOf(PlatformError.PlatformError),
47 },
48) {
49 override get message(): string {
50 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
51 }
53​
54export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
55 "BrowserSessionCreationError",
56 {
57 scope: Schema.String,
58 partition: Schema.String,
59 cause: Schema.Defect(),
60 },
61) {
62 override get message(): string {
63 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
64 }
66​
67export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
68 "BrowserSessionStorageClearError",
69 {
70 partition: Schema.String,
71 cause: Schema.Defect(),
72 },
73) {
74 override get message(): string {
75 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
76 }
78​
79export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
80 "BrowserSessionCacheClearError",
81 {
82 partition: Schema.String,
83 cause: Schema.Defect(),
84 },
85) {
86 override get message(): string {
87 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
88 }
90​
91export const BrowserSessionGetSessionError = Schema.Union([
92 BrowserSessionPartitionDerivationError,
93 BrowserSessionCreationError,
94]);
95export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
96export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
97​
98export const BrowserSessionError = Schema.Union([
99 BrowserSessionPartitionDerivationError,
100 BrowserSessionCreationError,
101 BrowserSessionStorageClearError,
102 BrowserSessionCacheClearError,
103]);
104export type BrowserSessionError = typeof BrowserSessionError.Type;
105export const isBrowserSessionError = Schema.is(BrowserSessionError);
106​
107export class BrowserSession extends Context.Service<
108 BrowserSession,
109 {
110 readonly getPartition: (
111 scope?: string,
112 persistent?: boolean,
113 namespace?: BrowserSessionPartitionNamespace,
114 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
115 readonly isPartition: (partition: string) => boolean;
116 readonly getSession: (
117 scope?: string,
118 persistent?: boolean,
119 namespace?: BrowserSessionPartitionNamespace,
120 ) => Effect.Effect<Session, BrowserSessionGetSessionError>;
121 /** Omit `partitions` to clear every known partition. */
122 readonly clearCookies: (
123 partitions?: ReadonlyArray<string>,
124 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
125 readonly clearCache: (
126 partitions?: ReadonlyArray<string>,
127 ) => Effect.Effect<void, BrowserSessionCacheClearError>;
128 }
129>()("@t3tools/desktop/preview/BrowserSession") {}
130​
131/**
132 * Restricts a clear to the given partitions. Omitting them keeps the historical
133 * "every partition" behaviour, which callers now only use for an explicit
134 * "all profiles" action — a per-profile clear must never reach across profiles.
135 */
136const selectSessions = (
137 sessions: ReadonlyMap<string, Session>,
138 partitions: ReadonlyArray<string> | undefined,
139): ReadonlyArray<readonly [string, Session]> =>
140 [...sessions.entries()].filter(
141 ([partition]) => partitions === undefined || partitions.includes(partition),
142 );
143​
144/**
145 * Scope bytes for the partition digest.
146 *
147 * `TextEncoder` replaces a lone UTF-16 surrogate with U+FFFD, so `"p\ud800"`
148 * and `"p\ufffd"` would hash to the same partition and share cookies. Those
149 * are distinct, supported ids, so lone surrogates are escaped to `\uXXXX`
150 * first — and a literal backslash is doubled so the escape cannot be forged.
151 * Every well-formed scope passes through byte-for-byte unchanged, which keeps
152 * existing partitions (and the logins in them) where they are.
153 */
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​
164export const make = Effect.gen(function* BrowserSessionMake() {
165 const crypto = yield* Crypto.Crypto;
166 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
167​
168 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
169 scope = "shared",
170 persistent = true,
171 namespace?: BrowserSessionPartitionNamespace,
172 ) {
173 const digest = yield* crypto.digest("SHA-256", encodeScopeForDigest(scope)).pipe(
174 Effect.mapError(
175 (cause) =>
176 new BrowserSessionPartitionDerivationError({
177 scope,
178 cause,
179 }),
180 ),
181 );
182 const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
183 // Legacy/default partitions are prefix + hex digest. The non-hex profile
184 // marker creates a disjoint namespace while leaving every legacy default
185 // partition byte-for-byte unchanged.
186 return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Encoding.encodeHex(digest).slice(0, 20)}`;
187 });
188​
189 const getSession = Effect.fn("BrowserSession.getSession")(function* (
190 scope = "shared",
191 persistent = true,
192 namespace?: BrowserSessionPartitionNamespace,
193 ) {
194 const partition = yield* getPartition(scope, persistent, namespace);
195 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
196 const existing = sessions.get(partition);
197 if (existing) return Effect.succeed([existing, sessions] as const);
198 return Effect.try({
199 try: () => {
200 const browserSession = session.fromPartition(partition);
201 const userAgent = browserSession
202 .getUserAgent()
203 .replace(/Electron\/[\d.]+ /, "")
204 .replace(/\s*t3code\/[\d.]+/, "");
205 browserSession.setUserAgent(userAgent);
206 browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
207 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
208 });
209 browserSession.setPermissionCheckHandler((_webContents, permission) =>
210 ALLOWED_PREVIEW_PERMISSIONS.has(permission),
211 );
212 const next = new Map(sessions);
213 next.set(partition, browserSession);
214 return [browserSession, next] as const;
215 },
216 catch: (cause) =>
217 new BrowserSessionCreationError({
218 scope,
219 partition,
220 cause,
221 }),
222 });
223 });
224 });
225​
226 return BrowserSession.of({
227 getPartition,
228 isPartition: (partition) =>
229 partition.startsWith(PREVIEW_PARTITION_PREFIX) ||
230 partition.startsWith(PREVIEW_EPHEMERAL_PARTITION_PREFIX),
231 getSession,
232 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) {
233 const sessions = yield* SynchronizedRef.get(sessionsRef);
234 yield* Effect.all(
235 selectSessions(sessions, partitions).map(([partition, browserSession]) =>
236 Effect.tryPromise({
237 try: () =>
238 browserSession.clearStorageData({
239 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
240 }),
241 catch: (cause) =>
242 new BrowserSessionStorageClearError({
243 partition,
244 cause,
245 }),
246 }),
247 ),
248 { concurrency: "unbounded", discard: true },
249 );
250 }),
251 clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
252 const sessions = yield* SynchronizedRef.get(sessionsRef);
253 yield* Effect.all(
254 selectSessions(sessions, partitions).map(([partition, browserSession]) =>
255 Effect.tryPromise({
256 try: () => browserSession.clearCache(),
257 catch: (cause) =>
258 new BrowserSessionCacheClearError({
259 partition,
260 cause,
261 }),
262 }),
263 ),
264 { concurrency: "unbounded", discard: true },
265 );
266 }),
267 });
268}).pipe(Effect.withSpan("BrowserSession.make"));
269​
270export const layer = Layer.effect(BrowserSession, make);