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

BrowserSession.ts

202 lines7.5 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// Permissions granted to preview web content. `clipboard-sanitized-write` is the
15// Electron permission behind `navigator.clipboard.writeText()` — note it is NOT
16// `clipboard-write`, which is not a valid Electron permission name. Async
17// clipboard writes are gated by the permission *check* handler (not only the
18// request handler), so both handlers must allow it; otherwise built-in "Copy"
19// buttons — e.g. the Next.js / Vercel error overlay — fail with
20// `Failed to execute 'writeText' on 'Clipboard': Write permission denied`.
21const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
22 "clipboard-read",
23 "clipboard-sanitized-write",
24 "notifications",
25 "geolocation",
26 // Deliberately NOT local-fonts: preview sessions run untrusted web content,
27 // and silently granting it would hand every page the user's installed-font
28 // fingerprint (and font file bytes via FontData.blob()). The app's own font
29 // picker runs in the main window session, which is unaffected by this list.
30]);
31​
32export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
33 "BrowserSessionPartitionDerivationError",
34 {
35 scope: Schema.String,
36 cause: Schema.instanceOf(PlatformError.PlatformError),
37 },
38) {
39 override get message(): string {
40 return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
41 }
43​
44export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
45 "BrowserSessionCreationError",
46 {
47 scope: Schema.String,
48 partition: Schema.String,
49 cause: Schema.Defect(),
50 },
51) {
52 override get message(): string {
53 return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
54 }
56​
57export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
58 "BrowserSessionStorageClearError",
59 {
60 partition: Schema.String,
61 cause: Schema.Defect(),
62 },
63) {
64 override get message(): string {
65 return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
66 }
68​
69export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
70 "BrowserSessionCacheClearError",
71 {
72 partition: Schema.String,
73 cause: Schema.Defect(),
74 },
75) {
76 override get message(): string {
77 return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
78 }
80​
81export const BrowserSessionGetSessionError = Schema.Union([
82 BrowserSessionPartitionDerivationError,
83 BrowserSessionCreationError,
84]);
85export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
86export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
87​
88export const BrowserSessionError = Schema.Union([
89 BrowserSessionPartitionDerivationError,
90 BrowserSessionCreationError,
91 BrowserSessionStorageClearError,
92 BrowserSessionCacheClearError,
93]);
94export type BrowserSessionError = typeof BrowserSessionError.Type;
95export const isBrowserSessionError = Schema.is(BrowserSessionError);
96​
97export class BrowserSession extends Context.Service<
98 BrowserSession,
99 {
100 readonly getPartition: (
101 scope?: string,
102 ) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
103 readonly isPartition: (partition: string) => boolean;
104 readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
105 readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
106 readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
107 }
108>()("@t3tools/desktop/preview/BrowserSession") {}
109​
110export const make = Effect.gen(function* BrowserSessionMake() {
111 const crypto = yield* Crypto.Crypto;
112 const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
113​
114 const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
115 const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
116 Effect.mapError(
117 (cause) =>
118 new BrowserSessionPartitionDerivationError({
119 scope,
120 cause,
121 }),
122 ),
123 );
124 return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
125 });
126​
127 const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
128 const partition = yield* getPartition(scope);
129 return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
130 const existing = sessions.get(partition);
131 if (existing) return Effect.succeed([existing, sessions] as const);
132 return Effect.try({
133 try: () => {
134 const browserSession = session.fromPartition(partition);
135 const userAgent = browserSession
136 .getUserAgent()
137 .replace(/Electron\/[\d.]+ /, "")
138 .replace(/\s*t3code\/[\d.]+/, "");
139 browserSession.setUserAgent(userAgent);
140 browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
141 callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission));
142 });
143 browserSession.setPermissionCheckHandler((_webContents, permission) =>
144 ALLOWED_PREVIEW_PERMISSIONS.has(permission),
145 );
146 const next = new Map(sessions);
147 next.set(partition, browserSession);
148 return [browserSession, next] as const;
149 },
150 catch: (cause) =>
151 new BrowserSessionCreationError({
152 scope,
153 partition,
154 cause,
155 }),
156 });
157 });
158 });
159​
160 return BrowserSession.of({
161 getPartition,
162 isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
163 getSession,
164 clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
165 const sessions = yield* SynchronizedRef.get(sessionsRef);
166 yield* Effect.all(
167 [...sessions.entries()].map(([partition, browserSession]) =>
168 Effect.tryPromise({
169 try: () =>
170 browserSession.clearStorageData({
171 storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
172 }),
173 catch: (cause) =>
174 new BrowserSessionStorageClearError({
175 partition,
176 cause,
177 }),
178 }),
179 ),
180 { concurrency: "unbounded", discard: true },
181 );
182 }),
183 clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
184 const sessions = yield* SynchronizedRef.get(sessionsRef);
185 yield* Effect.all(
186 [...sessions.entries()].map(([partition, browserSession]) =>
187 Effect.tryPromise({
188 try: () => browserSession.clearCache(),
189 catch: (cause) =>
190 new BrowserSessionCacheClearError({
191 partition,
192 cause,
193 }),
194 }),
195 ),
196 { concurrency: "unbounded", discard: true },
197 );
198 }),
199 });
200}).pipe(Effect.withSpan("BrowserSession.make"));
201​
202export const layer = Layer.effect(BrowserSession, make);