Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as NodeTimersPromises from "node:timers/promises";
5import * as Ref from "effect/Ref";
6import * as Schema from "effect/Schema";
7import * as Scope from "effect/Scope";
8
9import * as Electron from "electron";
10
11export const DESKTOP_HOST = "app";
12const DESKTOP_PRODUCTION_SCHEME = "t3code";
13const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
14
15export function getDesktopScheme(isDevelopment: boolean): string {
16 return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
17}
18
19function getDesktopOrigin(isDevelopment: boolean): string {
20 return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
21}
22
23export function getDesktopUrl(isDevelopment: boolean): string {
24 return `${getDesktopOrigin(isDevelopment)}/`;
25}
26
27export class ElectronProtocolRegistrationError extends Schema.TaggedError<ElectronProtocolRegistrationError>()(
28 "ElectronProtocolRegistrationError",
29 {
30 scheme: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return `Failed to register Electron protocol scheme "${this.scheme}".`;
36 }
37}
38
39export class ElectronProtocolUnregistrationError extends Schema.TaggedError<ElectronProtocolUnregistrationError>()(
40 "ElectronProtocolUnregistrationError",
41 {
42 scheme: Schema.String,
43 cause: Schema.Defect(),
44 },
45) {
46 override get message(): string {
47 return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
48 }
49}
50
51export interface DesktopProtocolRegistrationInput {
52 readonly scheme: string;
53 readonly targetOrigin: URL;
54 readonly backendOrigin: URL;
55 readonly clerkFrontendApiHostname: string | undefined;
56}
57
58export class ElectronProtocol extends Context.Service<
59 ElectronProtocol,
60 {
61 readonly registerDesktopProtocol: (
62 input: DesktopProtocolRegistrationInput,
63 ) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
64 }
65>()("@t3tools/desktop/electron/ElectronProtocol") {}
66
67export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
68 const clerkOrigin = input.clerkFrontendApiHostname
69 ? `https://${input.clerkFrontendApiHostname}`
70 : undefined;
71 const scriptSources = [
72 "'self'",
73 "'unsafe-inline'",
74 "'wasm-unsafe-eval'",
75 ...(clerkOrigin ? [clerkOrigin] : []),
76 "https://challenges.cloudflare.com",
77 ];
78
79 // The renderer connects directly to user-configured environments in addition to
80 // the build-configured Clerk, relay, and OTLP endpoints. Those environment
81 // origins are not known when this response policy is created, so restrict
82 // connections by the network schemes the client supports instead of by host.
83 const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
84
85 return [
86 "default-src 'self'",
87 `script-src ${scriptSources.join(" ")}`,
88 `connect-src ${connectSources.join(" ")}`,
89 `img-src 'self' ${input.scheme}: blob: data: http: https:`,
90 `media-src 'self' ${input.scheme}: blob: http: https:`,
91 "style-src 'self' 'unsafe-inline'",
92 `font-src 'self' ${input.scheme}: data:`,
93 "worker-src 'self' blob:",
94 // Document viewers use local Blob URLs and signed assets from runtime environments.
95 // HTML viewers retain their own sandbox; the renderer's script policy stays unchanged.
96 "frame-src 'self' blob: http: https:",
97 "form-action 'self'",
98 ].join("; ");
99}
100
101function withContentSecurityPolicy(response: Response, policy: string): Response {
102 const headers = new Headers(response.headers);
103 headers.set("Content-Security-Policy", policy);
104 return new Response(response.body, {
105 status: response.status,
106 statusText: response.statusText,
107 headers,
108 });
109}
110
111/**
112 * Must run synchronously during process bootstrap, before Electron emits `ready`.
113 */
114function registerDesktopSchemePrivilegesSync(): void {
115 Electron.protocol.registerSchemesAsPrivileged([
116 {
117 scheme: DESKTOP_PRODUCTION_SCHEME,
118 privileges: {
119 standard: true,
120 secure: true,
121 supportFetchAPI: true,
122 corsEnabled: true,
123 stream: true,
124 },
125 },
126 {
127 scheme: DESKTOP_DEVELOPMENT_SCHEME,
128 privileges: {
129 standard: true,
130 secure: true,
131 supportFetchAPI: true,
132 corsEnabled: true,
133 stream: true,
134 },
135 },
136 ]);
137}
138
139const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
140 Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
141);
142
143export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
144
145async function proxyRequest(
146 request: Request,
147 targetOrigin: URL,
148 contentSecurityPolicy: string,
149): Promise<Response> {
150 const requestUrl = new URL(request.url);
151 if (requestUrl.host !== DESKTOP_HOST) {
152 return new Response(null, { status: 404 });
153 }
154
155 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
156 const headers = new Headers(request.headers);
157 const headersToRemove: string[] = [];
158 for (const name of headers.keys()) {
159 if (
160 name === "host" ||
161 name === "origin" ||
162 name === "referer" ||
163 name === "connection" ||
164 name === "content-length" ||
165 name === "accept-encoding" ||
166 name === "upgrade-insecure-requests" ||
167 name.startsWith("sec-fetch-")
168 ) {
169 headersToRemove.push(name);
170 }
171 }
172 for (const name of headersToRemove) {
173 headers.delete(name);
174 }
175 const init: RequestInit = {
176 method: request.method,
177 headers,
178 };
179 if (request.method !== "GET" && request.method !== "HEAD") {
180 init.body = request.body;
181 (init as RequestInit & { duplex: "half" }).duplex = "half";
182 }
183 const response =
184 request.method === "GET" || request.method === "HEAD"
185 ? await fetchWithTransientRetry(targetUrl.toString(), init)
186 : await Electron.net.fetch(targetUrl.toString(), init);
187 return withContentSecurityPolicy(response, contentSecurityPolicy);
188}
189
190const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
191
192async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
193 let lastError: unknown;
194
195 for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
196 if (delayMs > 0) {
197 await NodeTimersPromises.setTimeout(delayMs);
198 }
199
200 try {
201 return await Electron.net.fetch(url, init);
202 } catch (error) {
203 lastError = error;
204 }
205 }
206
207 throw lastError;
208}
209
210/** @public Service construction is part of the canonical Effect module API. */
211export const make = Effect.gen(function* () {
212 const registered = yield* Ref.make(false);
213
214 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
215 function* (input: DesktopProtocolRegistrationInput) {
216 if (yield* Ref.get(registered)) return;
217
218 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
219
220 yield* Effect.acquireRelease(
221 Effect.try({
222 try: () => {
223 Electron.protocol.handle(input.scheme, (request) =>
224 proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
225 );
226 },
227 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
228 }).pipe(Effect.andThen(Ref.set(registered, true))),
229 () =>
230 Effect.try({
231 try: () => Electron.protocol.unhandle(input.scheme),
232 catch: (cause) =>
233 new ElectronProtocolUnregistrationError({
234 scheme: input.scheme,
235 cause,
236 }),
237 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
238 );
239 },
240 );
241
242 return ElectronProtocol.of({ registerDesktopProtocol });
243});
244
245export const layer = Layer.effect(ElectronProtocol, make);