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 "form-action 'self'",
99 ].join("; ");
100}
101
102function withContentSecurityPolicy(response: Response, policy: string): Response {
103 const headers = new Headers(response.headers);
104 headers.set("Content-Security-Policy", policy);
105 return new Response(response.body, {
106 status: response.status,
107 statusText: response.statusText,
108 headers,
109 });
110}
111
112/**
113 * Must run synchronously during process bootstrap, before Electron emits `ready`.
114 */
115function registerDesktopSchemePrivilegesSync(): void {
116 Electron.protocol.registerSchemesAsPrivileged([
117 {
118 scheme: DESKTOP_PRODUCTION_SCHEME,
119 privileges: {
120 standard: true,
121 secure: true,
122 supportFetchAPI: true,
123 corsEnabled: true,
124 stream: true,
125 // Custom schemes skip Chromium's V8 code cache unless they opt in.
126 // Dev stays off: Vite serves changing code at stable URLs.
127 codeCache: 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
149class ElectronProtocolFetchError extends Schema.TaggedError<ElectronProtocolFetchError>()(
150 "ElectronProtocolFetchError",
151 { cause: Schema.Defect() },
152) {}
153
154const netFetch = (url: string, init: RequestInit) =>
155 Effect.tryPromise({
156 try: () => Electron.net.fetch(url, init),
157 catch: (cause) => new ElectronProtocolFetchError({ cause }),
158 });
159
160const fetchWithTransientRetry = (url: string, init: RequestInit) =>
161 netFetch(url, init).pipe(
162 Effect.retry({ schedule: Schedule.exponential("50 millis", 3), times: 2 }),
163 );
164
165const proxyRequest = Effect.fn("desktop.protocol.proxyRequest")(function* (
166 request: Request,
167 targetOrigin: URL,
168 contentSecurityPolicy: string,
169) {
170 const requestUrl = new URL(request.url);
171 if (requestUrl.host !== DESKTOP_HOST) {
172 return new Response(null, { status: 404 });
173 }
174
175 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
176 const headers = new Headers(request.headers);
177 const headersToRemove: string[] = [];
178 for (const name of headers.keys()) {
179 if (
180 name === "host" ||
181 name === "origin" ||
182 name === "referer" ||
183 name === "connection" ||
184 name === "content-length" ||
185 name === "accept-encoding" ||
186 name === "upgrade-insecure-requests" ||
187 name.startsWith("sec-fetch-")
188 ) {
189 headersToRemove.push(name);
190 }
191 }
192 for (const name of headersToRemove) {
193 headers.delete(name);
194 }
195 const init: RequestInit = {
196 method: request.method,
197 headers,
198 };
199 if (request.method !== "GET" && request.method !== "HEAD") {
200 init.body = request.body;
201 (init as RequestInit & { duplex: "half" }).duplex = "half";
202 }
203 const response =
204 request.method === "GET" || request.method === "HEAD"
205 ? yield* fetchWithTransientRetry(targetUrl.toString(), init)
206 : yield* netFetch(targetUrl.toString(), init);
207 return withContentSecurityPolicy(response, contentSecurityPolicy);
208});
209
210const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
211 request: Request,
212 assetDirectory: string,
213) {
214 const fileSystem = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const url = new URL(request.url);
217 if (url.host !== DESKTOP_HOST) return new Response(null, { status: 404 });
218 if (request.method !== "GET" && request.method !== "HEAD") {
219 return new Response(null, { status: 405 });
220 }
221 const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
222 Effect.orElseSucceed(() => null),
223 );
224 if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
225 const root = path.resolve(assetDirectory);
226 const assetPath = path.resolve(root, `.${pathname}`);
227 if (assetPath !== root && !assetPath.startsWith(root + path.sep)) {
228 return new Response(null, { status: 404 });
229 }
230 const stat = yield* fileSystem.stat(assetPath).pipe(Effect.orElseSucceed(() => null));
231 let filePath = assetPath;
232 if (stat?.type !== "File") {
233 const wantsHtml = request.headers.get("accept")?.includes("text/html") ?? false;
234 if (path.extname(assetPath) !== "" && !wantsHtml) {
235 return new Response(null, { status: 404 });
236 }
237 filePath = path.join(root, "index.html");
238 }
239 const contents = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
240 if (contents === null) return new Response(null, { status: 404 });
241 return new Response(request.method === "HEAD" ? null : new Uint8Array(contents), {
242 headers: {
243 "content-type": Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream"),
244 },
245 });
246});
247
248/** @public Service construction is part of the canonical Effect module API. */
249export const make = Effect.gen(function* () {
250 const registered = yield* Ref.make(false);
251 const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
252 const runPromise = Effect.runPromiseWith(context);
253
254 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
255 function* (input: DesktopProtocolRegistrationInput) {
256 if (yield* Ref.get(registered)) return;
257
258 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
259
260 yield* Effect.acquireRelease(
261 Effect.try({
262 try: () => {
263 Electron.protocol.handle(input.scheme, async (request) => {
264 if ("assetDirectory" in input) {
265 return withContentSecurityPolicy(
266 await runPromise(serveDesktopAsset(request, input.assetDirectory)),
267 contentSecurityPolicy,
268 );
269 }
270 return runPromise(
271 proxyRequest(request, input.targetOrigin, contentSecurityPolicy).pipe(
272 Effect.catchTags({
273 ElectronProtocolFetchError: (error) => Effect.die(error.cause),
274 }),
275 ),
276 );
277 });
278 },
279 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
280 }).pipe(Effect.andThen(Ref.set(registered, true))),
281 () =>
282 Effect.try({
283 try: () => Electron.protocol.unhandle(input.scheme),
284 catch: (cause) =>
285 new ElectronProtocolUnregistrationError({
286 scheme: input.scheme,
287 cause,
288 }),
289 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
290 );
291 },
292 );
293
294 return ElectronProtocol.of({ registerDesktopProtocol });
295});
296
297export const layer = Layer.effect(ElectronProtocol, make);