Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ElectronProtocol.ts

307 lines11.0 KB

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