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 NodeTimersPromises from "node:timers/promises";
7import * as Path from "effect/Path";
8import * as Mime from "effect/unstable/http/Mime";
9import * as Ref from "effect/Ref";
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
55// The scheme either proxies to a dev server (`targetOrigin`) or serves the
56// built client from disk (`assetDirectory`).
57export type DesktopProtocolRegistrationInput = {
58 readonly scheme: string;
59 readonly clerkFrontendApiHostname: string | undefined;
60} & ({ readonly targetOrigin: URL } | { readonly assetDirectory: string });
61
62export class ElectronProtocol extends Context.Service<
63 ElectronProtocol,
64 {
65 readonly registerDesktopProtocol: (
66 input: DesktopProtocolRegistrationInput,
67 ) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
68 }
69>()("@t3tools/desktop/electron/ElectronProtocol") {}
70
71export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
72 const clerkOrigin = input.clerkFrontendApiHostname
73 ? `https://${input.clerkFrontendApiHostname}`
74 : undefined;
75 const scriptSources = [
76 "'self'",
77 "'unsafe-inline'",
78 "'wasm-unsafe-eval'",
79 ...(clerkOrigin ? [clerkOrigin] : []),
80 "https://challenges.cloudflare.com",
81 ];
82
83 // The renderer connects directly to user-configured environments in addition to
84 // the build-configured Clerk, relay, and OTLP endpoints. Those environment
85 // origins are not known when this response policy is created, so restrict
86 // connections by the network schemes the client supports instead of by host.
87 // GLTFLoader fetches embedded textures through blob URLs after parsing the model.
88 const connectSources = ["'self'", "blob:", "http:", "https:", "ws:", "wss:"];
89
90 return [
91 "default-src 'self'",
92 `script-src ${scriptSources.join(" ")}`,
93 `connect-src ${connectSources.join(" ")}`,
94 `img-src 'self' ${input.scheme}: blob: data: http: https:`,
95 `media-src 'self' ${input.scheme}: blob: http: https:`,
96 "style-src 'self' 'unsafe-inline'",
97 `font-src 'self' ${input.scheme}: data:`,
98 "worker-src 'self' blob:",
99 // Document viewers use local Blob URLs and signed assets from runtime environments.
100 // HTML viewers retain their own sandbox; the renderer's script policy stays unchanged.
101 "frame-src 'self' blob: http: https:",
102 "form-action 'self'",
103 ].join("; ");
104}
105
106function withContentSecurityPolicy(response: Response, policy: string): Response {
107 const headers = new Headers(response.headers);
108 headers.set("Content-Security-Policy", policy);
109 return new Response(response.body, {
110 status: response.status,
111 statusText: response.statusText,
112 headers,
113 });
114}
115
116/**
117 * Must run synchronously during process bootstrap, before Electron emits `ready`.
118 */
119function registerDesktopSchemePrivilegesSync(): void {
120 Electron.protocol.registerSchemesAsPrivileged([
121 {
122 scheme: DESKTOP_PRODUCTION_SCHEME,
123 privileges: {
124 standard: true,
125 secure: true,
126 supportFetchAPI: true,
127 corsEnabled: true,
128 stream: true,
129 // Custom schemes skip Chromium's V8 code cache unless they opt in.
130 // Dev stays off: Vite serves changing code at stable URLs.
131 codeCache: true,
132 },
133 },
134 {
135 scheme: DESKTOP_DEVELOPMENT_SCHEME,
136 privileges: {
137 standard: true,
138 secure: true,
139 supportFetchAPI: true,
140 corsEnabled: true,
141 stream: true,
142 },
143 },
144 ]);
145}
146
147const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
148 Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
149);
150
151export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
152
153async function proxyRequest(
154 request: Request,
155 targetOrigin: URL,
156 contentSecurityPolicy: string,
157): Promise<Response> {
158 const requestUrl = new URL(request.url);
159 if (requestUrl.host !== DESKTOP_HOST) {
160 return new Response(null, { status: 404 });
161 }
162
163 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
164 const headers = new Headers(request.headers);
165 const headersToRemove: string[] = [];
166 for (const name of headers.keys()) {
167 if (
168 name === "host" ||
169 name === "origin" ||
170 name === "referer" ||
171 name === "connection" ||
172 name === "content-length" ||
173 name === "accept-encoding" ||
174 name === "upgrade-insecure-requests" ||
175 name.startsWith("sec-fetch-")
176 ) {
177 headersToRemove.push(name);
178 }
179 }
180 for (const name of headersToRemove) {
181 headers.delete(name);
182 }
183 const init: RequestInit = {
184 method: request.method,
185 headers,
186 };
187 if (request.method !== "GET" && request.method !== "HEAD") {
188 init.body = request.body;
189 (init as RequestInit & { duplex: "half" }).duplex = "half";
190 }
191 const response =
192 request.method === "GET" || request.method === "HEAD"
193 ? await fetchWithTransientRetry(targetUrl.toString(), init)
194 : await Electron.net.fetch(targetUrl.toString(), init);
195 return withContentSecurityPolicy(response, contentSecurityPolicy);
196}
197
198const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
199
200// Serves the packaged web client without a backend: files resolve within the
201// asset directory, and any other path falls back to index.html so the SPA
202// router handles it, except for asset-shaped misses (`/missing.js`) which 404.
203const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
204 request: Request,
205 assetDirectory: string,
206) {
207 const fileSystem = yield* FileSystem.FileSystem;
208 const path = yield* Path.Path;
209 const url = new URL(request.url);
210 if (url.host !== DESKTOP_HOST) return new Response(null, { status: 404 });
211 if (request.method !== "GET" && request.method !== "HEAD") {
212 return new Response(null, { status: 405 });
213 }
214 const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
215 Effect.orElseSucceed(() => null),
216 );
217 if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
218 const root = path.resolve(assetDirectory);
219 const assetPath = path.resolve(root, `.${pathname}`);
220 if (assetPath !== root && !assetPath.startsWith(root + path.sep)) {
221 return new Response(null, { status: 404 });
222 }
223 const stat = yield* fileSystem.stat(assetPath).pipe(Effect.orElseSucceed(() => null));
224 let filePath = assetPath;
225 if (stat?.type !== "File") {
226 const wantsHtml = request.headers.get("accept")?.includes("text/html") ?? false;
227 if (path.extname(assetPath) !== "" && !wantsHtml) {
228 return new Response(null, { status: 404 });
229 }
230 filePath = path.join(root, "index.html");
231 }
232 const contents = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
233 if (contents === null) return new Response(null, { status: 404 });
234 return new Response(request.method === "HEAD" ? null : new Uint8Array(contents), {
235 headers: {
236 "content-type": Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream"),
237 },
238 });
239});
240
241async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
242 let lastError: unknown;
243
244 for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
245 if (delayMs > 0) {
246 await NodeTimersPromises.setTimeout(delayMs);
247 }
248
249 try {
250 return await Electron.net.fetch(url, init);
251 } catch (error) {
252 lastError = error;
253 }
254 }
255
256 throw lastError;
257}
258
259/** @public Service construction is part of the canonical Effect module API. */
260export const make = Effect.gen(function* () {
261 const registered = yield* Ref.make(false);
262 const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
263 const runPromise = Effect.runPromiseWith(context);
264
265 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
266 function* (input: DesktopProtocolRegistrationInput) {
267 if (yield* Ref.get(registered)) return;
268
269 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
270
271 yield* Effect.acquireRelease(
272 Effect.try({
273 try: () => {
274 Electron.protocol.handle(input.scheme, async (request) => {
275 if ("assetDirectory" in input) {
276 return withContentSecurityPolicy(
277 await runPromise(serveDesktopAsset(request, input.assetDirectory)),
278 contentSecurityPolicy,
279 );
280 }
281 return proxyRequest(request, input.targetOrigin, contentSecurityPolicy);
282 });
283 },
284 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
285 }).pipe(Effect.andThen(Ref.set(registered, true))),
286 () =>
287 Effect.try({
288 try: () => Electron.protocol.unhandle(input.scheme),
289 catch: (cause) =>
290 new ElectronProtocolUnregistrationError({
291 scheme: input.scheme,
292 cause,
293 }),
294 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
295 );
296 },
297 );
298
299 return ElectronProtocol.of({ registerDesktopProtocol });
300});
301
302export const layer = Layer.effect(ElectronProtocol, make);