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

ElectronProtocol.ts

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