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

ElectronProtocol.ts

295 lines10.2 KB

1import Mime from "@effect/platform-node/Mime";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as NodeTimersPromises from "node:timers/promises";
7import * as Path from "effect/Path";
8import * as Ref from "effect/Ref";
9import * as Schema from "effect/Schema";
10import * as Scope from "effect/Scope";
11​
12import * as Electron from "electron";
13​
14export const DESKTOP_HOST = "app";
15const DESKTOP_PRODUCTION_SCHEME = "t3code";
16const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
17​
18export function getDesktopScheme(isDevelopment: boolean): string {
19 return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
21​
22function getDesktopOrigin(isDevelopment: boolean): string {
23 return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
25​
26export function getDesktopUrl(isDevelopment: boolean): string {
27 return `${getDesktopOrigin(isDevelopment)}/`;
29​
30export class ElectronProtocolRegistrationError extends Schema.TaggedError<ElectronProtocolRegistrationError>()(
31 "ElectronProtocolRegistrationError",
32 {
33 scheme: Schema.String,
34 cause: Schema.Defect(),
35 },
36) {
37 override get message(): string {
38 return `Failed to register Electron protocol scheme "${this.scheme}".`;
39 }
41​
42export class ElectronProtocolUnregistrationError extends Schema.TaggedError<ElectronProtocolUnregistrationError>()(
43 "ElectronProtocolUnregistrationError",
44 {
45 scheme: Schema.String,
46 cause: Schema.Defect(),
47 },
48) {
49 override get message(): string {
50 return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
51 }
53​
54// The scheme either proxies to a dev server (`targetOrigin`) or serves the
55// built client from disk (`assetDirectory`).
56export type DesktopProtocolRegistrationInput = {
57 readonly scheme: string;
58 readonly clerkFrontendApiHostname: string | undefined;
59} & ({ readonly targetOrigin: URL } | { readonly assetDirectory: string });
60​
61export class ElectronProtocol extends Context.Service<
62 ElectronProtocol,
63 {
64 readonly registerDesktopProtocol: (
65 input: DesktopProtocolRegistrationInput,
66 ) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
67 }
68>()("@t3tools/desktop/electron/ElectronProtocol") {}
69​
70export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
71 const clerkOrigin = input.clerkFrontendApiHostname
72 ? `https://${input.clerkFrontendApiHostname}`
73 : undefined;
74 const scriptSources = [
75 "'self'",
76 "'unsafe-inline'",
77 "'wasm-unsafe-eval'",
78 ...(clerkOrigin ? [clerkOrigin] : []),
79 "https://challenges.cloudflare.com",
80 ];
81​
82 // The renderer connects directly to user-configured environments in addition to
83 // the build-configured Clerk, relay, and OTLP endpoints. Those environment
84 // origins are not known when this response policy is created, so restrict
85 // connections by the network schemes the client supports instead of by host.
86 const connectSources = ["'self'", "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 // Document viewers use local Blob URLs and signed assets from runtime environments.
98 // HTML viewers retain their own sandbox; the renderer's script policy stays unchanged.
99 "frame-src 'self' blob: http: https:",
100 "form-action 'self'",
101 ].join("; ");
103​
104function withContentSecurityPolicy(response: Response, policy: string): Response {
105 const headers = new Headers(response.headers);
106 headers.set("Content-Security-Policy", policy);
107 return new Response(response.body, {
108 status: response.status,
109 statusText: response.statusText,
110 headers,
111 });
113​
114/**
115 * Must run synchronously during process bootstrap, before Electron emits `ready`.
116 */
117function registerDesktopSchemePrivilegesSync(): void {
118 Electron.protocol.registerSchemesAsPrivileged([
119 {
120 scheme: DESKTOP_PRODUCTION_SCHEME,
121 privileges: {
122 standard: true,
123 secure: true,
124 supportFetchAPI: true,
125 corsEnabled: true,
126 stream: true,
127 },
128 },
129 {
130 scheme: DESKTOP_DEVELOPMENT_SCHEME,
131 privileges: {
132 standard: true,
133 secure: true,
134 supportFetchAPI: true,
135 corsEnabled: true,
136 stream: true,
137 },
138 },
139 ]);
141​
142const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
143 Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
144);
145​
146export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
147​
148async function proxyRequest(
149 request: Request,
150 targetOrigin: URL,
151 contentSecurityPolicy: string,
152): Promise<Response> {
153 const requestUrl = new URL(request.url);
154 if (requestUrl.host !== DESKTOP_HOST) {
155 return new Response(null, { status: 404 });
156 }
157​
158 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
159 const headers = new Headers(request.headers);
160 const headersToRemove: string[] = [];
161 for (const name of headers.keys()) {
162 if (
163 name === "host" ||
164 name === "origin" ||
165 name === "referer" ||
166 name === "connection" ||
167 name === "content-length" ||
168 name === "accept-encoding" ||
169 name === "upgrade-insecure-requests" ||
170 name.startsWith("sec-fetch-")
171 ) {
172 headersToRemove.push(name);
173 }
174 }
175 for (const name of headersToRemove) {
176 headers.delete(name);
177 }
178 const init: RequestInit = {
179 method: request.method,
180 headers,
181 };
182 if (request.method !== "GET" && request.method !== "HEAD") {
183 init.body = request.body;
184 (init as RequestInit & { duplex: "half" }).duplex = "half";
185 }
186 const response =
187 request.method === "GET" || request.method === "HEAD"
188 ? await fetchWithTransientRetry(targetUrl.toString(), init)
189 : await Electron.net.fetch(targetUrl.toString(), init);
190 return withContentSecurityPolicy(response, contentSecurityPolicy);
192​
193const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
194​
195// Serves the packaged web client without a backend: files resolve within the
196// asset directory, and any other path falls back to index.html so the SPA
197// router handles it, except for asset-shaped misses (`/missing.js`) which 404.
198const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
199 request: Request,
200 assetDirectory: string,
201) {
202 const fileSystem = yield* FileSystem.FileSystem;
203 const path = yield* Path.Path;
204 const url = new URL(request.url);
205 if (url.host !== DESKTOP_HOST) return new Response(null, { status: 404 });
206 if (request.method !== "GET" && request.method !== "HEAD") {
207 return new Response(null, { status: 405 });
208 }
209 const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
210 Effect.orElseSucceed(() => null),
211 );
212 if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
213 const root = path.resolve(assetDirectory);
214 const assetPath = path.resolve(root, `.${pathname}`);
215 if (assetPath !== root && !assetPath.startsWith(root + path.sep)) {
216 return new Response(null, { status: 404 });
217 }
218 const stat = yield* fileSystem.stat(assetPath).pipe(Effect.orElseSucceed(() => null));
219 let filePath = assetPath;
220 if (stat?.type !== "File") {
221 const wantsHtml = request.headers.get("accept")?.includes("text/html") ?? false;
222 if (path.extname(assetPath) !== "" && !wantsHtml) {
223 return new Response(null, { status: 404 });
224 }
225 filePath = path.join(root, "index.html");
226 }
227 const contents = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
228 if (contents === null) return new Response(null, { status: 404 });
229 return new Response(request.method === "HEAD" ? null : new Uint8Array(contents), {
230 headers: { "content-type": Mime.getType(filePath) ?? "application/octet-stream" },
231 });
232});
233​
234async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
235 let lastError: unknown;
236​
237 for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
238 if (delayMs > 0) {
239 await NodeTimersPromises.setTimeout(delayMs);
240 }
241​
242 try {
243 return await Electron.net.fetch(url, init);
244 } catch (error) {
245 lastError = error;
246 }
247 }
248​
249 throw lastError;
251​
252/** @public Service construction is part of the canonical Effect module API. */
253export const make = Effect.gen(function* () {
254 const registered = yield* Ref.make(false);
255 const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
256 const runPromise = Effect.runPromiseWith(context);
257​
258 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
259 function* (input: DesktopProtocolRegistrationInput) {
260 if (yield* Ref.get(registered)) return;
261​
262 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
263​
264 yield* Effect.acquireRelease(
265 Effect.try({
266 try: () => {
267 Electron.protocol.handle(input.scheme, async (request) => {
268 if ("assetDirectory" in input) {
269 return withContentSecurityPolicy(
270 await runPromise(serveDesktopAsset(request, input.assetDirectory)),
271 contentSecurityPolicy,
272 );
273 }
274 return proxyRequest(request, input.targetOrigin, contentSecurityPolicy);
275 });
276 },
277 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
278 }).pipe(Effect.andThen(Ref.set(registered, true))),
279 () =>
280 Effect.try({
281 try: () => Electron.protocol.unhandle(input.scheme),
282 catch: (cause) =>
283 new ElectronProtocolUnregistrationError({
284 scheme: input.scheme,
285 cause,
286 }),
287 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
288 );
289 },
290 );
291​
292 return ElectronProtocol.of({ registerDesktopProtocol });
293});
294​
295export const layer = Layer.effect(ElectronProtocol, make);