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 const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
88
89 return [
90 "default-src 'self'",
91 `script-src ${scriptSources.join(" ")}`,
92 `connect-src ${connectSources.join(" ")}`,
93 `img-src 'self' ${input.scheme}: blob: data: http: https:`,
94 `media-src 'self' ${input.scheme}: blob: http: https:`,
95 "style-src 'self' 'unsafe-inline'",
96 `font-src 'self' ${input.scheme}: data:`,
97 "worker-src 'self' blob:",
98 // Document viewers use local Blob URLs and signed assets from runtime environments.
99 // HTML viewers retain their own sandbox; the renderer's script policy stays unchanged.
100 "frame-src 'self' blob: http: https:",
101 "form-action 'self'",
102 ].join("; ");
103}
104
105function withContentSecurityPolicy(response: Response, policy: string): Response {
106 const headers = new Headers(response.headers);
107 headers.set("Content-Security-Policy", policy);
108 return new Response(response.body, {
109 status: response.status,
110 statusText: response.statusText,
111 headers,
112 });
113}
114
115/**
116 * Must run synchronously during process bootstrap, before Electron emits `ready`.
117 */
118function registerDesktopSchemePrivilegesSync(): void {
119 Electron.protocol.registerSchemesAsPrivileged([
120 {
121 scheme: DESKTOP_PRODUCTION_SCHEME,
122 privileges: {
123 standard: true,
124 secure: true,
125 supportFetchAPI: true,
126 corsEnabled: true,
127 stream: true,
128 },
129 },
130 {
131 scheme: DESKTOP_DEVELOPMENT_SCHEME,
132 privileges: {
133 standard: true,
134 secure: true,
135 supportFetchAPI: true,
136 corsEnabled: true,
137 stream: true,
138 },
139 },
140 ]);
141}
142
143const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
144 Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
145);
146
147export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
148
149async function proxyRequest(
150 request: Request,
151 targetOrigin: URL,
152 contentSecurityPolicy: string,
153): Promise<Response> {
154 const requestUrl = new URL(request.url);
155 if (requestUrl.host !== DESKTOP_HOST) {
156 return new Response(null, { status: 404 });
157 }
158
159 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
160 const headers = new Headers(request.headers);
161 const headersToRemove: string[] = [];
162 for (const name of headers.keys()) {
163 if (
164 name === "host" ||
165 name === "origin" ||
166 name === "referer" ||
167 name === "connection" ||
168 name === "content-length" ||
169 name === "accept-encoding" ||
170 name === "upgrade-insecure-requests" ||
171 name.startsWith("sec-fetch-")
172 ) {
173 headersToRemove.push(name);
174 }
175 }
176 for (const name of headersToRemove) {
177 headers.delete(name);
178 }
179 const init: RequestInit = {
180 method: request.method,
181 headers,
182 };
183 if (request.method !== "GET" && request.method !== "HEAD") {
184 init.body = request.body;
185 (init as RequestInit & { duplex: "half" }).duplex = "half";
186 }
187 const response =
188 request.method === "GET" || request.method === "HEAD"
189 ? await fetchWithTransientRetry(targetUrl.toString(), init)
190 : await Electron.net.fetch(targetUrl.toString(), init);
191 return withContentSecurityPolicy(response, contentSecurityPolicy);
192}
193
194const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
195
196// Serves the packaged web client without a backend: files resolve within the
197// asset directory, and any other path falls back to index.html so the SPA
198// router handles it, except for asset-shaped misses (`/missing.js`) which 404.
199const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
200 request: Request,
201 assetDirectory: string,
202) {
203 const fileSystem = yield* FileSystem.FileSystem;
204 const path = yield* Path.Path;
205 const url = new URL(request.url);
206 if (url.host !== DESKTOP_HOST) return new Response(null, { status: 404 });
207 if (request.method !== "GET" && request.method !== "HEAD") {
208 return new Response(null, { status: 405 });
209 }
210 const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
211 Effect.orElseSucceed(() => null),
212 );
213 if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
214 const root = path.resolve(assetDirectory);
215 const assetPath = path.resolve(root, `.${pathname}`);
216 if (assetPath !== root && !assetPath.startsWith(root + path.sep)) {
217 return new Response(null, { status: 404 });
218 }
219 const stat = yield* fileSystem.stat(assetPath).pipe(Effect.orElseSucceed(() => null));
220 let filePath = assetPath;
221 if (stat?.type !== "File") {
222 const wantsHtml = request.headers.get("accept")?.includes("text/html") ?? false;
223 if (path.extname(assetPath) !== "" && !wantsHtml) {
224 return new Response(null, { status: 404 });
225 }
226 filePath = path.join(root, "index.html");
227 }
228 const contents = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
229 if (contents === null) return new Response(null, { status: 404 });
230 return new Response(request.method === "HEAD" ? null : new Uint8Array(contents), {
231 headers: {
232 "content-type": Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream"),
233 },
234 });
235});
236
237async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
238 let lastError: unknown;
239
240 for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
241 if (delayMs > 0) {
242 await NodeTimersPromises.setTimeout(delayMs);
243 }
244
245 try {
246 return await Electron.net.fetch(url, init);
247 } catch (error) {
248 lastError = error;
249 }
250 }
251
252 throw lastError;
253}
254
255/** @public Service construction is part of the canonical Effect module API. */
256export const make = Effect.gen(function* () {
257 const registered = yield* Ref.make(false);
258 const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
259 const runPromise = Effect.runPromiseWith(context);
260
261 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
262 function* (input: DesktopProtocolRegistrationInput) {
263 if (yield* Ref.get(registered)) return;
264
265 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
266
267 yield* Effect.acquireRelease(
268 Effect.try({
269 try: () => {
270 Electron.protocol.handle(input.scheme, async (request) => {
271 if ("assetDirectory" in input) {
272 return withContentSecurityPolicy(
273 await runPromise(serveDesktopAsset(request, input.assetDirectory)),
274 contentSecurityPolicy,
275 );
276 }
277 return proxyRequest(request, input.targetOrigin, contentSecurityPolicy);
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);