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

main
ts 85 lines 2.97 KB
Raw
1 import type { IncomingMessage } from "node:http";
2 import { describe, expect, test } from "vitest";
3 import { proxyRequestHeaders, resolveForwardedHost } from "../forwarded-host.ts";
4
5 describe("resolveForwardedHost", () => {
6 test("prefers the forwarded host over the immediate proxy host", () => {
7 expect(
8 resolveForwardedHost(
9 { host: "localhost:5173", "x-forwarded-host": "example.ngrok.app" },
10 "127.0.0.1:9999",
11 ),
12 ).toBe("example.ngrok.app");
13 });
14
15 test("uses the first forwarded host when a proxy chain appends to the header", () => {
16 expect(
17 resolveForwardedHost(
18 {
19 host: "localhost:5173",
20 "x-forwarded-host": "example.ngrok.app, localhost:5173",
21 },
22 "127.0.0.1:9999",
23 ),
24 ).toBe("example.ngrok.app");
25 });
26
27 test("uses the first forwarded host when Node exposes repeated headers as an array", () => {
28 expect(
29 resolveForwardedHost(
30 {
31 host: "localhost:5173",
32 "x-forwarded-host": ["example.ngrok.app", "localhost:5173"],
33 },
34 "127.0.0.1:9999",
35 ),
36 ).toBe("example.ngrok.app");
37 });
38
39 test("falls back to the request host or the provided fallback", () => {
40 expect(resolveForwardedHost({ host: "localhost:5173" }, "127.0.0.1:9999")).toBe(
41 "localhost:5173",
42 );
43 expect(resolveForwardedHost({}, "127.0.0.1:9999")).toBe("127.0.0.1:9999");
44 });
45 });
46
47 describe("proxyRequestHeaders", () => {
48 const proxySharedSecret = "server-instance-secret";
49 test.each([
50 [{ host: "localhost:5173" }, false, "http://localhost:5173"],
51 [{ host: "localhost:5173" }, true, "https://localhost:5173"],
52 [{ host: "localhost:80" }, true, "https://localhost:80"],
53 [
54 {
55 host: "localhost:5173",
56 "x-forwarded-host": "public.example, proxy.internal",
57 "x-forwarded-proto": "https, http",
58 },
59 false,
60 "https://public.example",
61 ],
62 [{ host: "localhost:5173", "x-forwarded-proto": "HTTPS" }, false, "https://localhost:5173"],
63 ])("signs the original URL including protocol and port", (headers, encrypted, origin) => {
64 const result = proxyRequestHeaders(
65 {
66 headers: {
67 ...headers,
68 "alchemy-runtime-original-url": "https://forged.example/",
69 "alchemy-runtime-proxy-shared-secret": "forged",
70 },
71 socket: { encrypted },
72 } as unknown as IncomingMessage,
73 new URL("http://127.0.0.1:9999//callback/%2F?x=1&x=2"),
74 proxySharedSecret,
75 );
76 expect(result["alchemy-runtime-original-url"]).toBe(`${origin}//callback/%2F?x=1&x=2`);
77 expect(result.host).toBe(new URL(origin).host);
78 expect(result["alchemy-runtime-proxy-shared-secret"]).toBe(proxySharedSecret);
79 // A client's own `X-Forwarded-Host` passes through; otherwise it is the
80 // dev server's host, as under `@cloudflare/vite-plugin`.
81 expect(result["x-forwarded-host"]).toBe(
82 "x-forwarded-host" in headers ? headers["x-forwarded-host"] : headers.host,
83 );
84 });
85 });