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

ElectronProtocol.ts

239 lines7.4 KB

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";
12export const DESKTOP_PRODUCTION_SCHEME = "t3code";
13export const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
14​
15export function getDesktopScheme(isDevelopment: boolean): string {
16 return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
18​
19export function getDesktopOrigin(isDevelopment: boolean): string {
20 return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
22​
23export function getDesktopUrl(isDevelopment: boolean): string {
24 return `${getDesktopOrigin(isDevelopment)}/`;
26​
27export class ElectronProtocolRegistrationError extends Schema.TaggedErrorClass<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 }
38​
39export class ElectronProtocolUnregistrationError extends Schema.TaggedErrorClass<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 }
50​
51export interface DesktopProtocolRegistrationInput {
52 readonly scheme: string;
53 readonly targetOrigin: URL;
54 readonly backendOrigin: URL;
55 readonly clerkFrontendApiHostname: string | undefined;
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 "style-src 'self' 'unsafe-inline'",
91 `font-src 'self' ${input.scheme}: data:`,
92 "worker-src 'self' blob:",
93 "frame-src 'self' https://challenges.cloudflare.com",
94 "form-action 'self'",
95 ].join("; ");
97​
98function withContentSecurityPolicy(response: Response, policy: string): Response {
99 const headers = new Headers(response.headers);
100 headers.set("Content-Security-Policy", policy);
101 return new Response(response.body, {
102 status: response.status,
103 statusText: response.statusText,
104 headers,
105 });
107​
108/**
109 * Must run synchronously during process bootstrap, before Electron emits `ready`.
110 */
111export function registerDesktopSchemePrivilegesSync(): void {
112 Electron.protocol.registerSchemesAsPrivileged([
113 {
114 scheme: DESKTOP_PRODUCTION_SCHEME,
115 privileges: {
116 standard: true,
117 secure: true,
118 supportFetchAPI: true,
119 corsEnabled: true,
120 },
121 },
122 {
123 scheme: DESKTOP_DEVELOPMENT_SCHEME,
124 privileges: {
125 standard: true,
126 secure: true,
127 supportFetchAPI: true,
128 corsEnabled: true,
129 },
130 },
131 ]);
133​
134const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
135 Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
136);
137​
138export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
139​
140async function proxyRequest(
141 request: Request,
142 targetOrigin: URL,
143 contentSecurityPolicy: string,
144): Promise<Response> {
145 const requestUrl = new URL(request.url);
146 if (requestUrl.host !== DESKTOP_HOST) {
147 return new Response(null, { status: 404 });
148 }
149​
150 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
151 const headers = new Headers(request.headers);
152 const headersToRemove: string[] = [];
153 for (const name of headers.keys()) {
154 if (
155 name === "host" ||
156 name === "origin" ||
157 name === "referer" ||
158 name === "connection" ||
159 name === "content-length" ||
160 name === "accept-encoding" ||
161 name === "upgrade-insecure-requests" ||
162 name.startsWith("sec-fetch-")
163 ) {
164 headersToRemove.push(name);
165 }
166 }
167 for (const name of headersToRemove) {
168 headers.delete(name);
169 }
170 const init: RequestInit = {
171 method: request.method,
172 headers,
173 };
174 if (request.method !== "GET" && request.method !== "HEAD") {
175 init.body = request.body;
176 (init as RequestInit & { duplex: "half" }).duplex = "half";
177 }
178 const response =
179 request.method === "GET" || request.method === "HEAD"
180 ? await fetchWithTransientRetry(targetUrl.toString(), init)
181 : await Electron.net.fetch(targetUrl.toString(), init);
182 return withContentSecurityPolicy(response, contentSecurityPolicy);
184​
185const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
186​
187async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
188 let lastError: unknown;
189​
190 for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
191 if (delayMs > 0) {
192 await NodeTimersPromises.setTimeout(delayMs);
193 }
194​
195 try {
196 return await Electron.net.fetch(url, init);
197 } catch (error) {
198 lastError = error;
199 }
200 }
201​
202 throw lastError;
204​
205export const make = Effect.gen(function* () {
206 const registered = yield* Ref.make(false);
207​
208 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
209 function* (input: DesktopProtocolRegistrationInput) {
210 if (yield* Ref.get(registered)) return;
211​
212 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
213​
214 yield* Effect.acquireRelease(
215 Effect.try({
216 try: () => {
217 Electron.protocol.handle(input.scheme, (request) =>
218 proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
219 );
220 },
221 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
222 }).pipe(Effect.andThen(Ref.set(registered, true))),
223 () =>
224 Effect.try({
225 try: () => Electron.protocol.unhandle(input.scheme),
226 catch: (cause) =>
227 new ElectronProtocolUnregistrationError({
228 scheme: input.scheme,
229 cause,
230 }),
231 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
232 );
233 },
234 );
235​
236 return ElectronProtocol.of({ registerDesktopProtocol });
237});
238​
239export const layer = Layer.effect(ElectronProtocol, make);