Open History to see the last commit
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 }
52}
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 }
65}
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 }
77}
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 }
89}
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
162export const make = Effect.gen(function* BrowserSessionMake() {
163 const crypto = yield* Crypto.Crypto;
164 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
165
166 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (
167 scope = "shared",
168 persistent = true,
169 namespace?: BrowserSessionPartitionNamespace,
170 ) {
171 const digest = yield* crypto.digest("SHA-256", encodeScopeForDigest(scope)).pipe(
172 Effect.mapError(
173 (cause) =>
174 new BrowserSessionPartitionDerivationError({
175 scope,
176 cause,
177 }),
178 ),
179 );
180 const prefix = persistent ? PREVIEW_PARTITION_PREFIX : PREVIEW_EPHEMERAL_PARTITION_PREFIX;
181 // Legacy/default partitions are prefix + hex digest. The non-hex profile
182 // marker creates a disjoint namespace while leaving every legacy default
183 // partition byte-for-byte unchanged.
184 return `${prefix}${namespace === "profile" ? PROFILE_PARTITION_MARKER : ""}${Encoding.encodeHex(digest).slice(0, 20)}`;
185 });
186
187 const getSession = Effect.fn("BrowserSession.getSession")(function* (
188 scope = "shared",
189 persistent = true,
190 namespace?: BrowserSessionPartitionNamespace,
191 ) {
192 const partition = yield* getPartition(scope, persistent, namespace);
193 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
194 const existing = sessions.get(partition);
195 if (existing) return Effect.succeed([existing, sessions] as const);
196 return Effect.try({
197 try: () => {
198 const browserSession = session.fromPartition(partition);
199 const userAgent = browserSession
200 .getUserAgent()
201 .replace(/Electron\/[\d.]+ /, "")
202 .replace(/\s*t3code\/[\d.]+/, "");
203 browserSession.setUserAgent(userAgent);
204 browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
205 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
206 });
207 browserSession.setPermissionCheckHandler((_webContents, permission) =>
208 ALLOWED_PREVIEW_PERMISSIONS.has(permission),
209 );
210 const next = new Map(sessions);
211 next.set(partition, browserSession);
212 return [browserSession, next] as const;
213 },
214 catch: (cause) =>
215 new BrowserSessionCreationError({
216 scope,
217 partition,
218 cause,
219 }),
220 });
221 });
222 });
223
224 return BrowserSession.of({
225 getPartition,
226 isPartition: (partition) =>
227 partition.startsWith(PREVIEW_PARTITION_PREFIX) ||
228 partition.startsWith(PREVIEW_EPHEMERAL_PARTITION_PREFIX),
229 getSession,
230 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) {
231 const sessions = yield* SynchronizedRef.get(sessionsRef);
232 yield* Effect.all(
233 selectSessions(sessions, partitions).map(([partition, browserSession]) =>
234 Effect.tryPromise({
235 try: () =>
236 browserSession.clearStorageData({
237 storages: ["cookies", "localstorage", "indexdb", "serviceworkers"],
238 }),
239 catch: (cause) =>
240 new BrowserSessionStorageClearError({
241 partition,
242 cause,
243 }),
244 }),
245 ),
246 { concurrency: "unbounded", discard: true },
247 );
248 }),
249 clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) {
250 const sessions = yield* SynchronizedRef.get(sessionsRef);
251 yield* Effect.all(
252 selectSessions(sessions, partitions).map(([partition, browserSession]) =>
253 Effect.tryPromise({
254 try: () => browserSession.clearCache(),
255 catch: (cause) =>
256 new BrowserSessionCacheClearError({
257 partition,
258 cause,
259 }),
260 }),
261 ),
262 { concurrency: "unbounded", discard: true },
263 );
264 }),
265 });
266}).pipe(Effect.withSpan("BrowserSession.make"));
267
268export const layer = Layer.effect(BrowserSession, make);