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

BrowserSession.ts

270 lines10.4 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 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​
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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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;
96​
97export const BrowserSessionError = Schema.Union([
98 BrowserSessionPartitionDerivationError,
99 BrowserSessionCreationError,
100 BrowserSessionStorageClearError,
101 BrowserSessionCacheClearError,
102]);
103export type BrowserSessionError = typeof BrowserSessionError.Type;
104​
105export class BrowserSession extends Context.Service<
106 BrowserSession,
107 {
108 readonly getPartition: (
109 scope?: string,
110 persistent?: boolean,
111 namespace?: BrowserSessionPartitionNamespace,
112 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
113 readonly isPartition: (partition: string) => boolean;
114 readonly getSession: (
115 scope?: string,
116 persistent?: boolean,
117 namespace?: BrowserSessionPartitionNamespace,
118 ) => Effect.Effect<Session, BrowserSessionGetSessionError>;
119 /** Omit `partitions` to clear every known partition. */
120 readonly clearCookies: (
121 partitions?: ReadonlyArray<string>,
122 ) => Effect.Effect<void, BrowserSessionStorageClearError>;
123 readonly clearCache: (
124 partitions?: ReadonlyArray<string>,
125 ) => Effect.Effect<void, BrowserSessionCacheClearError>;
126 }
127>()("@t3tools/desktop/preview/BrowserSession") {}
128​
129/**
130 * Restricts a clear to the given partitions. Omitting them keeps the historical
131 * "every partition" behaviour, which callers now only use for an explicit
132 * "all profiles" action — a per-profile clear must never reach across profiles.
133 */
134const selectSessions = (
135 sessions: ReadonlyMap<string, Session>,
136 partitions: ReadonlyArray<string> | undefined,
137): ReadonlyArray<readonly [string, Session]> =>
138 [...sessions.entries()].filter(
139 ([partition]) => partitions === undefined || partitions.includes(partition),
140 );
141​
142/**
143 * Scope bytes for the partition digest.
144 *
145 * `TextEncoder` replaces a lone UTF-16 surrogate with U+FFFD, so `"p\ud800"`
146 * and `"p\ufffd"` would hash to the same partition and share cookies. Those
147 * are distinct, supported ids, so lone surrogates are escaped to `\uXXXX`
148 * first — and a literal backslash is doubled so the escape cannot be forged.
149 * Every well-formed scope passes through byte-for-byte unchanged, which keeps
150 * existing partitions (and the logins in them) where they are.
151 */
152const encodeScopeForDigest = (scope: string): Uint8Array =>
153 new TextEncoder().encode(
154 scope
155 .replace(/\\/g, "\\\\")
156 .replace(
157 /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,
158 (unit) => `\\u${unit.charCodeAt(0).toString(16).padStart(4, "0")}`,
159 ),
160 );
161​
162/** @public Service construction is part of the canonical Effect module API. */
163export const make = Effect.gen(function* BrowserSessionMake() {
164 const crypto = yield* Crypto.Crypto;
165 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
166​
167 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
168 scope = "shared",
169 persistent = true,
170 namespace?: BrowserSessionPartitionNamespace,
171 ) {
172 const digest = yield* crypto.digest("SHA-256", encodeScopeForDigest(scope)).pipe(
173 Effect.mapError(
174 (cause) =>
175 new BrowserSessionPartitionDerivationError({
176 scope,
177 cause,
178 }),
179 ),
180 );
181 const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
182 // Legacy/default partitions are prefix + hex digest. The non-hex profile
183 // marker creates a disjoint namespace while leaving every legacy default
184 // partition byte-for-byte unchanged.
185 return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Hex.encode(digest).slice(0, 20)}`;
186 });
187​
188 const getSession = Effect.fn("BrowserSession.getSession")(function* (
189 scope = "shared",
190 persistent = true,
191 namespace?: BrowserSessionPartitionNamespace,
192 ) {
193 const partition = yield* getPartition(scope, persistent, namespace);
194 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
195 const existing = sessions.get(partition);
196 if (existing) return Effect.succeed([existing, sessions] as const);
197 return Effect.try({
198 try: () => {
199 const browserSession = session.fromPartition(partition);
200 // The guest keeps Electron's native User-Agent. Rewriting it in any
201 // form — even variants that keep the Electron token — makes Cloudflare
202 // Turnstile fail its integrity check with error 600010 and recreate
203 // the challenge every few seconds, so logins behind it never complete
204 // (#5002). Re-setting the unchanged native string is harmless, so it
205 // is the rewritten string itself that trips the check.
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.forEach(
235 selectSessions(sessions, partitions),
236 ([partition, browserSession]) =>
237 Effect.tryPromise({
238 try: () =>
239 browserSession.clearStorageData({
240 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
241 }),
242 catch: (cause) =>
243 new BrowserSessionStorageClearError({
244 partition,
245 cause,
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.forEach(
254 selectSessions(sessions, partitions),
255 ([partition, browserSession]) =>
256 Effect.tryPromise({
257 try: () => browserSession.clearCache(),
258 catch: (cause) =>
259 new BrowserSessionCacheClearError({
260 partition,
261 cause,
262 }),
263 }),
264 { concurrency: "unbounded", discard: true },
265 );
266 }),
267 });
268}).pipe(Effect.withSpan("BrowserSession.make"));
269​
270export const layer = Layer.effect(BrowserSession, make);