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

ElectronProtocol.ts

242 lines7.5 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: http: https:`,
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 stream: true,
122 },
123 },
124 {
125 scheme: DESKTOP_DEVELOPMENT_SCHEME,
126 privileges: {
127 standard: true,
128 secure: true,
129 supportFetchAPI: true,
130 corsEnabled: true,
131 stream: true,
132 },
133 },
134 ]);
136​
137const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
138 Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
139);
140​
141export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
142​
143async function proxyRequest(
144 request: Request,
145 targetOrigin: URL,
146 contentSecurityPolicy: string,
147): Promise<Response> {
148 const requestUrl = new URL(request.url);
149 if (requestUrl.host !== DESKTOP_HOST) {
150 return new Response(null, { status: 404 });
151 }
152​
153 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
154 const headers = new Headers(request.headers);
155 const headersToRemove: string[] = [];
156 for (const name of headers.keys()) {
157 if (
158 name === "host" ||
159 name === "origin" ||
160 name === "referer" ||
161 name === "connection" ||
162 name === "content-length" ||
163 name === "accept-encoding" ||
164 name === "upgrade-insecure-requests" ||
165 name.startsWith("sec-fetch-")
166 ) {
167 headersToRemove.push(name);
168 }
169 }
170 for (const name of headersToRemove) {
171 headers.delete(name);
172 }
173 const init: RequestInit = {
174 method: request.method,
175 headers,
176 };
177 if (request.method !== "GET" && request.method !== "HEAD") {
178 init.body = request.body;
179 (init as RequestInit & { duplex: "half" }).duplex = "half";
180 }
181 const response =
182 request.method === "GET" || request.method === "HEAD"
183 ? await fetchWithTransientRetry(targetUrl.toString(), init)
184 : await Electron.net.fetch(targetUrl.toString(), init);
185 return withContentSecurityPolicy(response, contentSecurityPolicy);
187​
188const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
189​
190async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
191 let lastError: unknown;
192​
193 for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
194 if (delayMs > 0) {
195 await NodeTimersPromises.setTimeout(delayMs);
196 }
197​
198 try {
199 return await Electron.net.fetch(url, init);
200 } catch (error) {
201 lastError = error;
202 }
203 }
204​
205 throw lastError;
207​
208export const make = Effect.gen(function* () {
209 const registered = yield* Ref.make(false);
210​
211 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
212 function* (input: DesktopProtocolRegistrationInput) {
213 if (yield* Ref.get(registered)) return;
214​
215 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
216​
217 yield* Effect.acquireRelease(
218 Effect.try({
219 try: () => {
220 Electron.protocol.handle(input.scheme, (request) =>
221 proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
222 );
223 },
224 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
225 }).pipe(Effect.andThen(Ref.set(registered, true))),
226 () =>
227 Effect.try({
228 try: () => Electron.protocol.unhandle(input.scheme),
229 catch: (cause) =>
230 new ElectronProtocolUnregistrationError({
231 scheme: input.scheme,
232 cause,
233 }),
234 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
235 );
236 },
237 );
238​
239 return ElectronProtocol.of({ registerDesktopProtocol });
240});
241​
242export const layer = Layer.effect(ElectronProtocol, make);