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

ElectronProtocol.ts

206 lines6.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 ...(clerkOrigin ? [clerkOrigin] : []),
75 "https://challenges.cloudflare.com",
76 ];
77​
78 // The renderer connects directly to user-configured environments in addition to
79 // the build-configured Clerk, relay, and OTLP endpoints. Those environment
80 // origins are not known when this response policy is created, so restrict
81 // connections by the network schemes the client supports instead of by host.
82 const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];
83​
84 return [
85 "default-src 'self'",
86 `script-src ${scriptSources.join(" ")}`,
87 `connect-src ${connectSources.join(" ")}`,
88 `img-src 'self' ${input.scheme}: blob: data: http: https:`,
89 "style-src 'self' 'unsafe-inline'",
90 `font-src 'self' ${input.scheme}: data:`,
91 "worker-src 'self' blob:",
92 "frame-src 'self' https://challenges.cloudflare.com",
93 "form-action 'self'",
94 ].join("; ");
96​
97function withContentSecurityPolicy(response: Response, policy: string): Response {
98 const headers = new Headers(response.headers);
99 headers.set("Content-Security-Policy", policy);
100 return new Response(response.body, {
101 status: response.status,
102 statusText: response.statusText,
103 headers,
104 });
106​
107async function proxyRequest(
108 request: Request,
109 targetOrigin: URL,
110 contentSecurityPolicy: string,
111): Promise<Response> {
112 const requestUrl = new URL(request.url);
113 if (requestUrl.host !== DESKTOP_HOST) {
114 return new Response(null, { status: 404 });
115 }
116​
117 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
118 const headers = new Headers(request.headers);
119 const headersToRemove: string[] = [];
120 for (const name of headers.keys()) {
121 if (
122 name === "host" ||
123 name === "origin" ||
124 name === "referer" ||
125 name === "connection" ||
126 name === "content-length" ||
127 name === "accept-encoding" ||
128 name === "upgrade-insecure-requests" ||
129 name.startsWith("sec-fetch-")
130 ) {
131 headersToRemove.push(name);
132 }
133 }
134 for (const name of headersToRemove) {
135 headers.delete(name);
136 }
137 const init: RequestInit = {
138 method: request.method,
139 headers,
140 };
141 if (request.method !== "GET" && request.method !== "HEAD") {
142 init.body = request.body;
143 (init as RequestInit & { duplex: "half" }).duplex = "half";
144 }
145 const response =
146 request.method === "GET" || request.method === "HEAD"
147 ? await fetchWithTransientRetry(targetUrl.toString(), init)
148 : await Electron.net.fetch(targetUrl.toString(), init);
149 return withContentSecurityPolicy(response, contentSecurityPolicy);
151​
152const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
153​
154async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
155 let lastError: unknown;
156​
157 for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
158 if (delayMs > 0) {
159 await NodeTimersPromises.setTimeout(delayMs);
160 }
161​
162 try {
163 return await Electron.net.fetch(url, init);
164 } catch (error) {
165 lastError = error;
166 }
167 }
168​
169 throw lastError;
171​
172export const make = Effect.gen(function* () {
173 const registered = yield* Ref.make(false);
174​
175 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
176 function* (input: DesktopProtocolRegistrationInput) {
177 if (yield* Ref.get(registered)) return;
178​
179 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
180​
181 yield* Effect.acquireRelease(
182 Effect.try({
183 try: () => {
184 Electron.protocol.handle(input.scheme, (request) =>
185 proxyRequest(request, input.targetOrigin, contentSecurityPolicy),
186 );
187 },
188 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
189 }).pipe(Effect.andThen(Ref.set(registered, true))),
190 () =>
191 Effect.try({
192 try: () => Electron.protocol.unhandle(input.scheme),
193 catch: (cause) =>
194 new ElectronProtocolUnregistrationError({
195 scheme: input.scheme,
196 cause,
197 }),
198 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
199 );
200 },
201 );
202​
203 return ElectronProtocol.of({ registerDesktopProtocol });
204});
205​
206export const layer = Layer.effect(ElectronProtocol, make);