The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as Context from "effect/Context"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as FileSystem from "effect/FileSystem"; |
| 4 | import * as Layer from "effect/Layer"; |
| 5 | import * as Option from "effect/Option"; |
| 6 | import * as Path from "effect/Path"; |
| 7 | import * as Mime from "effect/http/Mime"; |
| 8 | import * as Ref from "effect/Ref"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Schema from "effect/Schema"; |
| 11 | import * as Scope from "effect/Scope"; |
| 12 | |
| 13 | import * as Electron from "electron"; |
| 14 | |
| 15 | export const DESKTOP_HOST = "app"; |
| 16 | const DESKTOP_PRODUCTION_SCHEME = "t3code"; |
| 17 | const DESKTOP_DEVELOPMENT_SCHEME = "t3code-dev"; |
| 18 | |
| 19 | export function getDesktopScheme(isDevelopment: boolean): string { |
| 20 | return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME; |
| 21 | } |
| 22 | |
| 23 | function getDesktopOrigin(isDevelopment: boolean): string { |
| 24 | return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`; |
| 25 | } |
| 26 | |
| 27 | export function getDesktopUrl(isDevelopment: boolean): string { |
| 28 | return `${getDesktopOrigin(isDevelopment)}/`; |
| 29 | } |
| 30 | |
| 31 | export 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 | } |
| 41 | } |
| 42 | |
| 43 | export 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 | } |
| 53 | } |
| 54 | |
| 55 | export type DesktopProtocolRegistrationInput = { |
| 56 | readonly scheme: string; |
| 57 | readonly clerkFrontendApiHostname: string | undefined; |
| 58 | } & ({ readonly targetOrigin: URL } | { readonly assetDirectory: string }); |
| 59 | |
| 60 | export 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 | |
| 69 | function 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("; "); |
| 98 | } |
| 99 | |
| 100 | function 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 | }); |
| 108 | } |
| 109 | |
| 110 | // Must run synchronously before Electron emits ready. |
| 111 | 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 | 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 | ]); |
| 136 | } |
| 137 | |
| 138 | const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe( |
| 139 | Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"), |
| 140 | ); |
| 141 | |
| 142 | export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges); |
| 143 | |
| 144 | class ElectronProtocolFetchError extends Schema.TaggedError<ElectronProtocolFetchError>()( |
| 145 | "ElectronProtocolFetchError", |
| 146 | { cause: Schema.Defect() }, |
| 147 | ) {} |
| 148 | |
| 149 | const netFetch = (url: string, init: RequestInit) => |
| 150 | Effect.tryPromise({ |
| 151 | try: () => Electron.net.fetch(url, init), |
| 152 | catch: (cause) => new ElectronProtocolFetchError({ cause }), |
| 153 | }); |
| 154 | |
| 155 | const fetchWithTransientRetry = (url: string, init: RequestInit) => |
| 156 | netFetch(url, init).pipe( |
| 157 | Effect.retry({ schedule: Schedule.exponential("50 millis", 3), times: 2 }), |
| 158 | ); |
| 159 | |
| 160 | const 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 | // Assign the path so leading slashes cannot replace the configured host. |
| 171 | const targetUrl = new URL(targetOrigin); |
| 172 | targetUrl.pathname = requestUrl.pathname; |
| 173 | targetUrl.search = requestUrl.search; |
| 174 | const headers = new Headers(request.headers); |
| 175 | const headersToRemove: string[] = []; |
| 176 | for (const name of headers.keys()) { |
| 177 | if ( |
| 178 | name === "host" || |
| 179 | name === "origin" || |
| 180 | name === "referer" || |
| 181 | name === "connection" || |
| 182 | name === "content-length" || |
| 183 | name === "accept-encoding" || |
| 184 | name === "upgrade-insecure-requests" || |
| 185 | name.startsWith("sec-fetch-") |
| 186 | ) { |
| 187 | headersToRemove.push(name); |
| 188 | } |
| 189 | } |
| 190 | for (const name of headersToRemove) { |
| 191 | headers.delete(name); |
| 192 | } |
| 193 | const init: RequestInit = { |
| 194 | method: request.method, |
| 195 | headers, |
| 196 | }; |
| 197 | if (request.method !== "GET" && request.method !== "HEAD") { |
| 198 | init.body = request.body; |
| 199 | (init as RequestInit & { duplex: "half" }).duplex = "half"; |
| 200 | } |
| 201 | const response = |
| 202 | request.method === "GET" || request.method === "HEAD" |
| 203 | ? yield* fetchWithTransientRetry(targetUrl.toString(), init) |
| 204 | : yield* netFetch(targetUrl.toString(), init); |
| 205 | return withContentSecurityPolicy(response, contentSecurityPolicy); |
| 206 | }); |
| 207 | |
| 208 | const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* ( |
| 209 | request: Request, |
| 210 | assetDirectory: string, |
| 211 | ) { |
| 212 | const fileSystem = yield* FileSystem.FileSystem; |
| 213 | const path = yield* Path.Path; |
| 214 | const url = new URL(request.url); |
| 215 | if (url.host !== DESKTOP_HOST) return new Response(null, { status: 404 }); |
| 216 | if (request.method !== "GET" && request.method !== "HEAD") { |
| 217 | return new Response(null, { status: 405 }); |
| 218 | } |
| 219 | const pathname = Option.getOrNull(Option.liftThrowable(decodeURIComponent)(url.pathname)); |
| 220 | if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 }); |
| 221 | const root = path.resolve(assetDirectory); |
| 222 | const assetPath = path.resolve(root, `.${pathname}`); |
| 223 | if (assetPath !== root && !assetPath.startsWith(root + path.sep)) { |
| 224 | return new Response(null, { status: 404 }); |
| 225 | } |
| 226 | const stat = yield* fileSystem.stat(assetPath).pipe(Effect.orElseSucceed(() => null)); |
| 227 | let filePath = assetPath; |
| 228 | if (stat?.type !== "File") { |
| 229 | const wantsHtml = request.headers.get("accept")?.includes("text/html") ?? false; |
| 230 | if (path.extname(assetPath) !== "" && !wantsHtml) { |
| 231 | return new Response(null, { status: 404 }); |
| 232 | } |
| 233 | filePath = path.join(root, "index.html"); |
| 234 | } |
| 235 | const contents = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null)); |
| 236 | if (contents === null) return new Response(null, { status: 404 }); |
| 237 | return new Response(request.method === "HEAD" ? null : new Uint8Array(contents), { |
| 238 | headers: { |
| 239 | "content-type": Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream"), |
| 240 | }, |
| 241 | }); |
| 242 | }); |
| 243 | |
| 244 | /** @public */ |
| 245 | export const make = Effect.gen(function* () { |
| 246 | const registered = yield* Ref.make(false); |
| 247 | const context = yield* Effect.context<FileSystem.FileSystem | Path.Path>(); |
| 248 | const runPromise = Effect.runPromiseWith(context); |
| 249 | |
| 250 | const registerDesktopProtocol = Effect.fn("desktop.electron.protocol.registerDesktopProtocol")( |
| 251 | function* (input: DesktopProtocolRegistrationInput) { |
| 252 | if (yield* Ref.get(registered)) return; |
| 253 | |
| 254 | const contentSecurityPolicy = makeDesktopContentSecurityPolicy(input); |
| 255 | |
| 256 | yield* Effect.acquireRelease( |
| 257 | Effect.try({ |
| 258 | try: () => { |
| 259 | Electron.protocol.handle(input.scheme, async (request) => { |
| 260 | if ("assetDirectory" in input) { |
| 261 | return withContentSecurityPolicy( |
| 262 | await runPromise(serveDesktopAsset(request, input.assetDirectory)), |
| 263 | contentSecurityPolicy, |
| 264 | ); |
| 265 | } |
| 266 | return runPromise( |
| 267 | proxyRequest(request, input.targetOrigin, contentSecurityPolicy).pipe( |
| 268 | Effect.catchTags({ |
| 269 | ElectronProtocolFetchError: (error) => Effect.die(error.cause), |
| 270 | }), |
| 271 | ), |
| 272 | ); |
| 273 | }); |
| 274 | }, |
| 275 | catch: (cause) => new ElectronProtocolRegistrationError({ scheme: input.scheme, cause }), |
| 276 | }).pipe(Effect.andThen(Ref.set(registered, true))), |
| 277 | () => |
| 278 | Effect.try({ |
| 279 | try: () => Electron.protocol.unhandle(input.scheme), |
| 280 | catch: (cause) => |
| 281 | new ElectronProtocolUnregistrationError({ |
| 282 | scheme: input.scheme, |
| 283 | cause, |
| 284 | }), |
| 285 | }).pipe(Effect.andThen(Ref.set(registered, false)), Effect.orDie), |
| 286 | ); |
| 287 | }, |
| 288 | ); |
| 289 | |
| 290 | return ElectronProtocol.of({ registerDesktopProtocol }); |
| 291 | }); |
| 292 | |
| 293 | export const layer = Layer.effect(ElectronProtocol, make); |