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 },
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
150async function proxyRequest(
151 request: Request,
152 targetOrigin: URL,
153 contentSecurityPolicy: string,
154): Promise<Response> {
155 const requestUrl = new URL(request.url);
156 if (requestUrl.host !== DESKTOP_HOST) {
157 return new Response(null, { status: 404 });
158 }
159
160 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
161 const headers = new Headers(request.headers);
162 const headersToRemove: string[] = [];
163 for (const name of headers.keys()) {
164 if (
165 name === "host" ||
166 name === "origin" ||
167 name === "referer" ||
168 name === "connection" ||
169 name === "content-length" ||
170 name === "accept-encoding" ||
171 name === "upgrade-insecure-requests" ||
172 name.startsWith("sec-fetch-")
173 ) {
174 headersToRemove.push(name);
175 }
176 }
177 for (const name of headersToRemove) {
178 headers.delete(name);
179 }
180 const init: RequestInit = {
181 method: request.method,
182 headers,
183 };
184 if (request.method !== "GET" && request.method !== "HEAD") {
185 init.body = request.body;
186 (init as RequestInit & { duplex: "half" }).duplex = "half";
187 }
188 const response =
189 request.method === "GET" || request.method === "HEAD"
190 ? await fetchWithTransientRetry(targetUrl.toString(), init)
191 : await Electron.net.fetch(targetUrl.toString(), init);
192 return withContentSecurityPolicy(response, contentSecurityPolicy);
193}
194
195const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
196
197// Serves the packaged web client without a backend: files resolve within the
198// asset directory, and any other path falls back to index.html so the SPA
199// router handles it, except for asset-shaped misses (`/missing.js`) which 404.
200const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
201 request: Request,
202 assetDirectory: string,
203) {
204 const fileSystem = yield* FileSystem.FileSystem;
205 const path = yield* Path.Path;
206 const url = new URL(request.url);
207 if (url.host !== DESKTOP_HOST) return new Response(null, { status: 404 });
208 if (request.method !== "GET" && request.method !== "HEAD") {
209 return new Response(null, { status: 405 });
210 }
211 const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
212 Effect.orElseSucceed(() => null),
213 );
214 if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
215 const root = path.resolve(assetDirectory);
216 const assetPath = path.resolve(root, `.${pathname}`);
217 if (assetPath !== root && !assetPath.startsWith(root + path.sep)) {
218 return new Response(null, { status: 404 });
219 }
220 const stat = yield* fileSystem.stat(assetPath).pipe(Effect.orElseSucceed(() => null));
221 let filePath = assetPath;
222 if (stat?.type !== "File") {
223 const wantsHtml = request.headers.get("accept")?.includes("text/html") ?? false;
224 if (path.extname(assetPath) !== "" && !wantsHtml) {
225 return new Response(null, { status: 404 });
226 }
227 filePath = path.join(root, "index.html");
228 }
229 const contents = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
230 if (contents === null) return new Response(null, { status: 404 });
231 return new Response(request.method === "HEAD" ? null : new Uint8Array(contents), {
232 headers: {
233 "content-type": Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream"),
234 },
235 });
236});
237
238async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
239 let lastError: unknown;
240
241 for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
242 if (delayMs > 0) {
243 await NodeTimersPromises.setTimeout(delayMs);
244 }
245
246 try {
247 return await Electron.net.fetch(url, init);
248 } catch (error) {
249 lastError = error;
250 }
251 }
252
253 throw lastError;
254}
255
256/** @public Service construction is part of the canonical Effect module API. */
257export const make = Effect.gen(function* () {
258 const registered = yield* Ref.make(false);
259 const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
260 const runPromise = Effect.runPromiseWith(context);
261
262 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
263 function* (input: DesktopProtocolRegistrationInput) {
264 if (yield* Ref.get(registered)) return;
265
266 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
267
268 yield* Effect.acquireRelease(
269 Effect.try({
270 try: () => {
271 Electron.protocol.handle(input.scheme, async (request) => {
272 if ("assetDirectory" in input) {
273 return withContentSecurityPolicy(
274 await runPromise(serveDesktopAsset(request, input.assetDirectory)),
275 contentSecurityPolicy,
276 );
277 }
278 return proxyRequest(request, input.targetOrigin, contentSecurityPolicy);
279 });
280 },
281 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
282 }).pipe(Effect.andThen(Ref.set(registered, true))),
283 () =>
284 Effect.try({
285 try: () => Electron.protocol.unhandle(input.scheme),
286 catch: (cause) =>
287 new ElectronProtocolUnregistrationError({
288 scheme: input.scheme,
289 cause,
290 }),
291 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
292 );
293 },
294 );
295
296 return ElectronProtocol.of({ registerDesktopProtocol });
297});
298
299export const layer = Layer.effect(ElectronProtocol, make);