The best way to control Claude Code, Codex and more from any computer or phone

main
ts 56 lines 2.18 KB
Raw
1 import type { IncomingMessage } from "node:http";
2 import type { IncomingHttpHeaders } from "node:http";
3 import type { TLSSocket } from "node:tls";
4 import {
5 HEADER_ORIGINAL_URL,
6 HEADER_PROXY_SHARED_SECRET,
7 } from "../core/globals/ProxyHeaders.shared.ts";
8
9 /**
10 * Resolves the client-facing host of an incoming dev-server request.
11 *
12 * When the dev server runs behind a proxy or tunnel (e.g. ngrok or
13 * `cloudflared`), the `Host` header carries the local address while the
14 * public host arrives in `X-Forwarded-Host`. Preferring the forwarded host
15 * lets the worker see the URL the client actually requested.
16 */
17 export function resolveForwardedHost(headers: IncomingHttpHeaders, fallbackHost: string): string {
18 return (
19 firstHeaderValue(headers["x-forwarded-host"]) ?? firstHeaderValue(headers.host) ?? fallbackHost
20 );
21 }
22
23 function firstHeaderValue(value: string | Array<string> | undefined): string | undefined {
24 // Proxy chains may append to a single header ("host1, host2") instead of
25 // repeating it; only the first entry is the client-facing host.
26 const raw = Array.isArray(value) ? value[0] : value;
27 const first = raw?.split(",")[0]?.trim();
28 return first ? first : undefined;
29 }
30
31 /** Sign the client-facing URL for the runtime entry worker, including TLS termination. */
32 export function proxyRequestHeaders(
33 request: IncomingMessage,
34 target: URL,
35 proxySharedSecret: string,
36 ): IncomingHttpHeaders {
37 const original = new URL(target);
38 const protocol = firstHeaderValue(request.headers["x-forwarded-proto"])?.toLowerCase();
39 original.protocol =
40 protocol === "https" || protocol === "http"
41 ? `${protocol}:`
42 : (request.socket as TLSSocket).encrypted
43 ? "https:"
44 : "http:";
45 original.port = "";
46 original.host = resolveForwardedHost(request.headers, target.host);
47 return {
48 // The Worker sees the dev server's host in `X-Forwarded-Host` when the
49 // client sent none, as under `@cloudflare/vite-plugin`.
50 "x-forwarded-host": firstHeaderValue(request.headers.host) ?? target.host,
51 ...request.headers,
52 host: original.host,
53 [HEADER_ORIGINAL_URL.toLowerCase()]: original.href,
54 [HEADER_PROXY_SHARED_SECRET.toLowerCase()]: proxySharedSecret,
55 };
56 }