Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Mime from "effect/http/Mime";
8import * as Ref from "effect/Ref";
9import * as Schedule from "effect/Schedule";
10import * as Schema from "effect/Schema";
11import * as Scope from "effect/Scope";
12
13import * as Electron from "electron";
14
15export const DESKTOP_HOST = "app";
16const DESKTOP_PRODUCTION_SCHEME = "t3code";
17const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
18
19export function getDesktopScheme(isDevelopment: boolean): string {
20 return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
21}
22
23function getDesktopOrigin(isDevelopment: boolean): string {
24 return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
25}
26
27export function getDesktopUrl(isDevelopment: boolean): string {
28 return `${getDesktopOrigin(isDevelopment)}/`;
29}
30
31export class ElectronProtocolRegistrationError extends Schema.TaggedError<ElectronProtocolRegistrationError>()(
32 "ElectronProtocolRegistrationError",
33 {
34 scheme: Schema.String,
35 cause: Schema.Defect(),
36 },
37) {
38 override get message(): string {
39 return `Failed to register Electron protocol scheme "${this.scheme}".`;
40 }
41}
42
43export class ElectronProtocolUnregistrationError extends Schema.TaggedError<ElectronProtocolUnregistrationError>()(
44 "ElectronProtocolUnregistrationError",
45 {
46 scheme: Schema.String,
47 cause: Schema.Defect(),
48 },
49) {
50 override get message(): string {
51 return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
52 }
53}
54
55export type DesktopProtocolRegistrationInput = {
56 readonly scheme: string;
57 readonly clerkFrontendApiHostname: string | undefined;
58} & ({ readonly targetOrigin: URL } | { readonly assetDirectory: string });
59
60export class ElectronProtocol extends Context.Service<
61 ElectronProtocol,
62 {
63 readonly registerDesktopProtocol: (
64 input: DesktopProtocolRegistrationInput,
65 ) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
66 }
67>()("@t3tools/desktop/electron/ElectronProtocol") {}
68
69export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
70 const clerkOrigin = input.clerkFrontendApiHostname
71 ? `https://${input.clerkFrontendApiHostname}`
72 : undefined;
73 const scriptSources = [
74 "'self'",
75 "'unsafe-inline'",
76 "'wasm-unsafe-eval'",
77 ...(clerkOrigin ? [clerkOrigin] : []),
78 "https://challenges.cloudflare.com",
79 ];
80
81 // The renderer connects directly to user-configured environments in addition to
82 // the build-configured Clerk, relay, and OTLP endpoints. Those environment
83 // origins are not known when this response policy is created, so restrict
84 // connections by the network schemes the client supports instead of by host.
85 // GLTFLoader fetches embedded textures through blob URLs after parsing the model.
86 const connectSources = ["'self'", "blob:", "http:", "https:", "ws:", "wss:"];
87
88 return [
89 "default-src 'self'",
90 `script-src ${scriptSources.join(" ")}`,
91 `connect-src ${connectSources.join(" ")}`,
92 `img-src 'self' ${input.scheme}: blob: data: http: https:`,
93 `media-src 'self' ${input.scheme}: blob: http: https:`,
94 "style-src 'self' 'unsafe-inline'",
95 `font-src 'self' ${input.scheme}: data:`,
96 "worker-src 'self' blob:",
97 "frame-src 'self' blob: http: https:",
98 "object-src 'self' blob: http: https:",
99 "form-action 'self'",
100 ].join("; ");
101}
102
103function withContentSecurityPolicy(response: Response, policy: string): Response {
104 const headers = new Headers(response.headers);
105 headers.set("Content-Security-Policy", policy);
106 return new Response(response.body, {
107 status: response.status,
108 statusText: response.statusText,
109 headers,
110 });
111}
112
113/**
114 * Must run synchronously during process bootstrap, before Electron emits `ready`.
115 */
116function registerDesktopSchemePrivilegesSync(): void {
117 Electron.protocol.registerSchemesAsPrivileged([
118 {
119 scheme: DESKTOP_PRODUCTION_SCHEME,
120 privileges: {
121 standard: true,
122 secure: true,
123 supportFetchAPI: true,
124 corsEnabled: true,
125 stream: true,
126 // Custom schemes skip Chromium's V8 code cache unless they opt in.
127 // Dev stays off: Vite serves changing code at stable URLs.
128 codeCache: true,
129 },
130 },
131 {
132 scheme: DESKTOP_DEVELOPMENT_SCHEME,
133 privileges: {
134 standard: true,
135 secure: true,
136 supportFetchAPI: true,
137 corsEnabled: true,
138 stream: true,
139 },
140 },
141 ]);
142}
143
144const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
145 Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
146);
147
148export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
149
150class ElectronProtocolFetchError extends Schema.TaggedError<ElectronProtocolFetchError>()(
151 "ElectronProtocolFetchError",
152 { cause: Schema.Defect() },
153) {}
154
155const netFetch = (url: string, init: RequestInit) =>
156 Effect.tryPromise({
157 try: () => Electron.net.fetch(url, init),
158 catch: (cause) => new ElectronProtocolFetchError({ cause }),
159 });
160
161const fetchWithTransientRetry = (url: string, init: RequestInit) =>
162 netFetch(url, init).pipe(
163 Effect.retry({ schedule: Schedule.exponential("50 millis", 3), times: 2 }),
164 );
165
166const proxyRequest = Effect.fn("desktop.protocol.proxyRequest")(function* (
167 request: Request,
168 targetOrigin: URL,
169 contentSecurityPolicy: string,
170) {
171 const requestUrl = new URL(request.url);
172 if (requestUrl.host !== DESKTOP_HOST) {
173 return new Response(null, { status: 404 });
174 }
175
176 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
177 const headers = new Headers(request.headers);
178 const headersToRemove: string[] = [];
179 for (const name of headers.keys()) {
180 if (
181 name === "host" ||
182 name === "origin" ||
183 name === "referer" ||
184 name === "connection" ||
185 name === "content-length" ||
186 name === "accept-encoding" ||
187 name === "upgrade-insecure-requests" ||
188 name.startsWith("sec-fetch-")
189 ) {
190 headersToRemove.push(name);
191 }
192 }
193 for (const name of headersToRemove) {
194 headers.delete(name);
195 }
196 const init: RequestInit = {
197 method: request.method,
198 headers,
199 };
200 if (request.method !== "GET" && request.method !== "HEAD") {
201 init.body = request.body;
202 (init as RequestInit & { duplex: "half" }).duplex = "half";
203 }
204 const response =
205 request.method === "GET" || request.method === "HEAD"
206 ? yield* fetchWithTransientRetry(targetUrl.toString(), init)
207 : yield* netFetch(targetUrl.toString(), init);
208 return withContentSecurityPolicy(response, contentSecurityPolicy);
209});
210
211const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
212 request: Request,
213 assetDirectory: string,
214) {
215 const fileSystem = yield* FileSystem.FileSystem;
216 const path = yield* Path.Path;
217 const url = new URL(request.url);
218 if (url.host !== DESKTOP_HOST) return new Response(null, { status: 404 });
219 if (request.method !== "GET" && request.method !== "HEAD") {
220 return new Response(null, { status: 405 });
221 }
222 const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
223 Effect.orElseSucceed(() => null),
224 );
225 if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
226 const root = path.resolve(assetDirectory);
227 const assetPath = path.resolve(root, `.${pathname}`);
228 if (assetPath !== root && !assetPath.startsWith(root + path.sep)) {
229 return new Response(null, { status: 404 });
230 }
231 const stat = yield* fileSystem.stat(assetPath).pipe(Effect.orElseSucceed(() => null));
232 let filePath = assetPath;
233 if (stat?.type !== "File") {
234 const wantsHtml = request.headers.get("accept")?.includes("text/html") ?? false;
235 if (path.extname(assetPath) !== "" && !wantsHtml) {
236 return new Response(null, { status: 404 });
237 }
238 filePath = path.join(root, "index.html");
239 }
240 const contents = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
241 if (contents === null) return new Response(null, { status: 404 });
242 return new Response(request.method === "HEAD" ? null : new Uint8Array(contents), {
243 headers: {
244 "content-type": Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream"),
245 },
246 });
247});
248
249/** @public Service construction is part of the canonical Effect module API. */
250export const make = Effect.gen(function* () {
251 const registered = yield* Ref.make(false);
252 const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
253 const runPromise = Effect.runPromiseWith(context);
254
255 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
256 function* (input: DesktopProtocolRegistrationInput) {
257 if (yield* Ref.get(registered)) return;
258
259 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
260
261 yield* Effect.acquireRelease(
262 Effect.try({
263 try: () => {
264 Electron.protocol.handle(input.scheme, async (request) => {
265 if ("assetDirectory" in input) {
266 return withContentSecurityPolicy(
267 await runPromise(serveDesktopAsset(request, input.assetDirectory)),
268 contentSecurityPolicy,
269 );
270 }
271 return runPromise(
272 proxyRequest(request, input.targetOrigin, contentSecurityPolicy).pipe(
273 Effect.catchTags({
274 ElectronProtocolFetchError: (error) => Effect.die(error.cause),
275 }),
276 ),
277 );
278 });
279 },
280 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
281 }).pipe(Effect.andThen(Ref.set(registered, true))),
282 () =>
283 Effect.try({
284 try: () => Electron.protocol.unhandle(input.scheme),
285 catch: (cause) =>
286 new ElectronProtocolUnregistrationError({
287 scheme: input.scheme,
288 cause,
289 }),
290 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
291 );
292 },
293 );
294
295 return ElectronProtocol.of({ registerDesktopProtocol });
296});
297
298export const layer = Layer.effect(ElectronProtocol, make);