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

ElectronProtocol.ts

292 lines9.9 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Mime from "effect/http/Mime";
8import * as Ref from "effect/Ref";
9import * as Schedule from "effect/Schedule";
10import * as Schema from "effect/Schema";
11import * as Scope from "effect/Scope";
12​
13import * as Electron from "electron";
14​
15export const DESKTOP_HOST = "app";
16const DESKTOP_PRODUCTION_SCHEME = "t3code";
17const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev";
18​
19export function getDesktopScheme(isDevelopment: boolean): string {
20 return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME;
22​
23function getDesktopOrigin(isDevelopment: boolean): string {
24 return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`;
26​
27export function getDesktopUrl(isDevelopment: boolean): string {
28 return `${getDesktopOrigin(isDevelopment)}/`;
30​
31export class ElectronProtocolRegistrationError extends Schema.TaggedError<ElectronProtocolRegistrationError>()(
32 "ElectronProtocolRegistrationError",
33 {
34 scheme: Schema.String,
35 cause: Schema.Defect(),
36 },
37) {
38 override get message(): string {
39 return `Failed to register Electron protocol scheme "${this.scheme}".`;
40 }
42​
43export class ElectronProtocolUnregistrationError extends Schema.TaggedError<ElectronProtocolUnregistrationError>()(
44 "ElectronProtocolUnregistrationError",
45 {
46 scheme: Schema.String,
47 cause: Schema.Defect(),
48 },
49) {
50 override get message(): string {
51 return `Failed to unregister Electron protocol scheme "${this.scheme}".`;
52 }
54​
55export type DesktopProtocolRegistrationInput = {
56 readonly scheme: string;
57 readonly clerkFrontendApiHostname: string | undefined;
58} & ({ readonly targetOrigin: URL } | { readonly assetDirectory: string });
59​
60export class ElectronProtocol extends Context.Service<
61 ElectronProtocol,
62 {
63 readonly registerDesktopProtocol: (
64 input: DesktopProtocolRegistrationInput,
65 ) => Effect.Effect<void, ElectronProtocolRegistrationError, Scope.Scope>;
66 }
67>()("@t3tools/desktop/electron/ElectronProtocol") {}
68​
69function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {
70 const clerkOrigin = input.clerkFrontendApiHostname
71 ? `https://${input.clerkFrontendApiHostname}`
72 : undefined;
73 const scriptSources = [
74 "'self'",
75 "'unsafe-inline'",
76 "'wasm-unsafe-eval'",
77 ...(clerkOrigin ? [clerkOrigin] : []),
78 "https://challenges.cloudflare.com",
79 ];
80​
81 // User-configured environment origins are unknown here, so allow supported network schemes.
82 // GLTFLoader fetches embedded textures through blob URLs.
83 const connectSources = ["'self'", "blob:", "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' blob: http: https:",
95 "object-src 'self' blob: http: https:",
96 "form-action 'self'",
97 ].join("; ");
99​
100function withContentSecurityPolicy(response: Response, policy: string): Response {
101 const headers = new Headers(response.headers);
102 headers.set("Content-Security-Policy", policy);
103 return new Response(response.body, {
104 status: response.status,
105 statusText: response.statusText,
106 headers,
107 });
109​
110// Must run synchronously before Electron emits ready.
111function 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 stream: true,
121 // Custom schemes must opt into V8 caching; dev URLs serve changing code.
122 codeCache: true,
123 },
124 },
125 {
126 scheme: DESKTOP_DEVELOPMENT_SCHEME,
127 privileges: {
128 standard: true,
129 secure: true,
130 supportFetchAPI: true,
131 corsEnabled: true,
132 stream: true,
133 },
134 },
135 ]);
137​
138const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
139 Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
140);
141​
142export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
143​
144class ElectronProtocolFetchError extends Schema.TaggedError<ElectronProtocolFetchError>()(
145 "ElectronProtocolFetchError",
146 { cause: Schema.Defect() },
147) {}
148​
149const netFetch = (url: string, init: RequestInit) =>
150 Effect.tryPromise({
151 try: () => Electron.net.fetch(url, init),
152 catch: (cause) => new ElectronProtocolFetchError({ cause }),
153 });
154​
155const fetchWithTransientRetry = (url: string, init: RequestInit) =>
156 netFetch(url, init).pipe(
157 Effect.retry({ schedule: Schedule.exponential("50 millis", 3), times: 2 }),
158 );
159​
160const proxyRequest = Effect.fn("desktop.protocol.proxyRequest")(function* (
161 request: Request,
162 targetOrigin: URL,
163 contentSecurityPolicy: string,
164) {
165 const requestUrl = new URL(request.url);
166 if (requestUrl.host !== DESKTOP_HOST) {
167 return new Response(null, { status: 404 });
168 }
169​
170 const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
171 const headers = new Headers(request.headers);
172 const headersToRemove: string[] = [];
173 for (const name of headers.keys()) {
174 if (
175 name === "host" ||
176 name === "origin" ||
177 name === "referer" ||
178 name === "connection" ||
179 name === "content-length" ||
180 name === "accept-encoding" ||
181 name === "upgrade-insecure-requests" ||
182 name.startsWith("sec-fetch-")
183 ) {
184 headersToRemove.push(name);
185 }
186 }
187 for (const name of headersToRemove) {
188 headers.delete(name);
189 }
190 const init: RequestInit = {
191 method: request.method,
192 headers,
193 };
194 if (request.method !== "GET" && request.method !== "HEAD") {
195 init.body = request.body;
196 (init as RequestInit & { duplex: "half" }).duplex = "half";
197 }
198 const response =
199 request.method === "GET" || request.method === "HEAD"
200 ? yield* fetchWithTransientRetry(targetUrl.toString(), init)
201 : yield* netFetch(targetUrl.toString(), init);
202 return withContentSecurityPolicy(response, contentSecurityPolicy);
203});
204​
205const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
206 request: Request,
207 assetDirectory: string,
208) {
209 const fileSystem = yield* FileSystem.FileSystem;
210 const path = yield* Path.Path;
211 const url = new URL(request.url);
212 if (url.host !== DESKTOP_HOST) return new Response(null, { status: 404 });
213 if (request.method !== "GET" && request.method !== "HEAD") {
214 return new Response(null, { status: 405 });
215 }
216 const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
217 Effect.orElseSucceed(() => null),
218 );
219 if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
220 const root = path.resolve(assetDirectory);
221 const assetPath = path.resolve(root, `.${pathname}`);
222 if (assetPath !== root && !assetPath.startsWith(root + path.sep)) {
223 return new Response(null, { status: 404 });
224 }
225 const stat = yield* fileSystem.stat(assetPath).pipe(Effect.orElseSucceed(() => null));
226 let filePath = assetPath;
227 if (stat?.type !== "File") {
228 const wantsHtml = request.headers.get("accept")?.includes("text/html") ?? false;
229 if (path.extname(assetPath) !== "" && !wantsHtml) {
230 return new Response(null, { status: 404 });
231 }
232 filePath = path.join(root, "index.html");
233 }
234 const contents = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));
235 if (contents === null) return new Response(null, { status: 404 });
236 return new Response(request.method === "HEAD" ? null : new Uint8Array(contents), {
237 headers: {
238 "content-type": Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream"),
239 },
240 });
241});
242​
243/** @public */
244export const make = Effect.gen(function* () {
245 const registered = yield* Ref.make(false);
246 const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
247 const runPromise = Effect.runPromiseWith(context);
248​
249 const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")(
250 function* (input: DesktopProtocolRegistrationInput) {
251 if (yield* Ref.get(registered)) return;
252​
253 const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input);
254​
255 yield* Effect.acquireRelease(
256 Effect.try({
257 try: () => {
258 Electron.protocol.handle(input.scheme, async (request) => {
259 if ("assetDirectory" in input) {
260 return withContentSecurityPolicy(
261 await runPromise(serveDesktopAsset(request, input.assetDirectory)),
262 contentSecurityPolicy,
263 );
264 }
265 return runPromise(
266 proxyRequest(request, input.targetOrigin, contentSecurityPolicy).pipe(
267 Effect.catchTags({
268 ElectronProtocolFetchError: (error) => Effect.die(error.cause),
269 }),
270 ),
271 );
272 });
273 },
274 catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }),
275 }).pipe(Effect.andThen(Ref.set(registered, true))),
276 () =>
277 Effect.try({
278 try: () => Electron.protocol.unhandle(input.scheme),
279 catch: (cause) =>
280 new ElectronProtocolUnregistrationError({
281 scheme: input.scheme,
282 cause,
283 }),
284 }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie),
285 );
286 },
287 );
288​
289 return ElectronProtocol.of({ registerDesktopProtocol });
290});
291​
292export const layer = Layer.effect(ElectronProtocol, make);