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

main
ts 285 lines 10.1 KB
Raw
1 import * as fs from "node:fs/promises";
2 import * as NodeHttp from "node:http";
3 import type { AddressInfo, Socket } from "node:net";
4 import * as path from "node:path";
5 import { setTimeout as sleep } from "node:timers/promises";
6 import { URL as NodeURL } from "node:url";
7 import * as vite from "vite";
8 import { expect, onTestFinished, test, vi } from "vitest";
9 import cloudflareVitePlugin from "../plugin.ts";
10 import { forwardWorkerRequest } from "../worker-request.ts";
11
12 // Starts a dev server for a Worker whose module source is `source`.
13 const devServer = async (source: string): Promise<string> => {
14 onTestFinished(() => {
15 vi.unstubAllEnvs();
16 });
17 // Only the local runtime is used; no Cloudflare API calls are made.
18 vi.stubEnv("CLOUDFLARE_API_TOKEN", "local-test-unused");
19 vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "00000000000000000000000000000000");
20 const tmpRoot = path.resolve(import.meta.dirname, "../.cache/test-roots");
21 await fs.mkdir(tmpRoot, { recursive: true });
22 const root = await fs.mkdtemp(path.join(tmpRoot, "dev-proxy-"));
23 onTestFinished(() => fs.rm(root, { recursive: true, force: true }));
24 const entry = path.join(root, "worker.js");
25 await fs.writeFile(entry, source);
26 const server = await vite.createServer({
27 root,
28 configFile: false,
29 cacheDir: path.join(root, ".vite"),
30 logLevel: "silent",
31 server: { host: "127.0.0.1", port: 0 },
32 plugins: [
33 cloudflareVitePlugin({ main: entry, worker: { name: "vite-dev-proxy-test", bindings: [] } }),
34 ],
35 });
36 onTestFinished(() => server.close());
37 await server.listen();
38 return server.resolvedUrls!.local[0]!;
39 };
40
41 // Sends a request with `node:http`, which, unlike `fetch`, can pin requests to
42 // one kept-alive connection.
43 const send = (
44 url: URL,
45 options: { agent: NodeHttp.Agent | false; method?: string; body?: Buffer },
46 ): Promise<{ status: number; body: string }> =>
47 new Promise((resolve, reject) => {
48 const request = NodeHttp.request(url.href, {
49 agent: options.agent,
50 method: options.method ?? "GET",
51 signal: AbortSignal.timeout(10_000),
52 });
53 request.on("error", reject);
54 request.on("response", (response) => {
55 const chunks: Array<Buffer> = [];
56 response.on("data", (chunk: Buffer) => chunks.push(chunk));
57 response.on("error", reject);
58 response.on("end", () =>
59 resolve({ status: response.statusCode!, body: Buffer.concat(chunks).toString() }),
60 );
61 });
62 request.end(options.body);
63 });
64
65 // Listens on a free loopback port until the test finishes.
66 const listen = async (server: NodeHttp.Server): Promise<NodeURL> => {
67 onTestFinished(() => {
68 server.closeAllConnections();
69 return new Promise<void>((resolve) => server.close(() => resolve()));
70 });
71 await new Promise<void>((resolve, reject) => {
72 server.once("error", reject);
73 server.listen(0, "127.0.0.1", resolve);
74 });
75 return new NodeURL(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
76 };
77
78 // Proxies every request to `runtime` the way the dev server does.
79 const proxyTo = (runtime: NodeURL): Promise<NodeURL> => {
80 const logger = vite.createLogger("silent");
81 return listen(
82 NodeHttp.createServer((request, response) => {
83 forwardWorkerRequest(request, response, runtime, "secret", logger);
84 }),
85 );
86 };
87
88 test("stops the Worker's stream when the client hangs up", async () => {
89 // An endless event stream, like a page's SSE subscription, counting the
90 // chunks it is asked for.
91 const url = await devServer(`
92 const encoder = new TextEncoder();
93 let pulls = 0;
94 export default {
95 fetch(request) {
96 if (new URL(request.url).pathname === "/pulls") {
97 return Response.json({ pulls });
98 }
99 return new Response(
100 new ReadableStream({
101 async pull(controller) {
102 pulls++;
103 await new Promise((resolve) => setTimeout(resolve, 50));
104 controller.enqueue(encoder.encode("data: tick\\n\\n"));
105 },
106 }),
107 { headers: { "content-type": "text/event-stream" } },
108 );
109 },
110 };
111 `);
112 const pulls = async () => {
113 const response = await fetch(new URL("/pulls", url), { signal: AbortSignal.timeout(5_000) });
114 return ((await response.json()) as { pulls: number }).pulls;
115 };
116
117 const client = new AbortController();
118 const stream = await fetch(new URL("/events", url), { signal: client.signal });
119 await stream.body!.getReader().read();
120 client.abort();
121
122 // workerd stops pulling once it sees the request cancelled. The cancel can
123 // take a while to land on a loaded machine, so wait for the count to hold
124 // still: a live stream pulls every 50ms and never would.
125 let previous = await pulls();
126 await expect
127 .poll(
128 async () => {
129 await sleep(300);
130 const next = await pulls();
131 const stopped = next === previous;
132 previous = next;
133 return stopped;
134 },
135 { timeout: 15_000, interval: 0 },
136 )
137 .toBe(true);
138 });
139
140 test("keeps connections usable after the Worker answers without reading the body", async () => {
141 // A body size cap, checked before the body is read.
142 const url = await devServer(`
143 export default {
144 fetch(request) {
145 if (Number(request.headers.get("content-length")) > 1024 * 1024) {
146 return new Response("too large", { status: 413 });
147 }
148 return new Response("ok");
149 },
150 };
151 `);
152 const keptAlive = new NodeHttp.Agent({ keepAlive: true, maxSockets: 1 });
153 onTestFinished(() => keptAlive.destroy());
154
155 // Each round trip has a few-percent chance of passing without the fix, so
156 // the test makes several.
157 for (let i = 0; i < 3; i++) {
158 const tooLarge = await send(new URL("/upload", url), {
159 agent: keptAlive,
160 method: "POST",
161 body: Buffer.alloc(1024 * 1024 + 1, "a"),
162 });
163 expect(tooLarge).toEqual({ status: 413, body: "too large" });
164 // The client's connection, which carried the upload, is still usable.
165 expect(await send(new URL("/", url), { agent: keptAlive })).toEqual({
166 status: 200,
167 body: "ok",
168 });
169 }
170 });
171
172 test("streams the Worker's response while the request body is still arriving", async () => {
173 // Echoes the request body: the response starts before the body has been
174 // read.
175 const url = await devServer(`
176 export default {
177 fetch(request) {
178 return new Response(request.body);
179 },
180 };
181 `);
182 const body = Buffer.alloc(4 * 1024 * 1024, "a");
183
184 const echo = await send(new URL("/echo", url), { agent: false, method: "POST", body });
185 expect(echo.status).toBe(200);
186 expect(echo.body.length).toBe(body.length);
187 });
188
189 test("forwards each request on a connection of its own", async () => {
190 // Pins the defensive connection per request (see worker-request.ts). The
191 // reuse failure it guards against hasn't been reproduced with workerd, so a
192 // stand-in plays workerd having closed a connection the proxy still holds:
193 // a second request on any connection finds it gone.
194 const served = new WeakSet<Socket>();
195 const runtime = await listen(
196 NodeHttp.createServer((request, response) => {
197 if (served.has(request.socket)) {
198 request.socket.destroy();
199 return;
200 }
201 served.add(request.socket);
202 response.end("worker");
203 }),
204 );
205 const proxy = await proxyTo(runtime);
206
207 // `fetch` keeps the client's connection alive, so the proxy alone decides
208 // whether its upstream connection is reused.
209 const get = async () => {
210 const response = await fetch(proxy, { signal: AbortSignal.timeout(5_000) });
211 return { status: response.status, body: await response.text() };
212 };
213 expect(await get()).toEqual({ status: 200, body: "worker" });
214 expect(await get()).toEqual({ status: 200, body: "worker" });
215 });
216
217 test("never forwards to a host named in the request path", async () => {
218 // Another service on the machine that a `//host/` path must not reach (#2344).
219 const other = await listen(NodeHttp.createServer((_request, response) => response.end("other")));
220 const url = new NodeURL(
221 await devServer(`
222 export default {
223 fetch(request) {
224 const { pathname, search } = new URL(request.url);
225 return new Response("worker " + pathname + search);
226 },
227 };
228 `),
229 );
230 // `node:http` sends `path` verbatim, the way `curl --path-as-is` does.
231 const get = (path: string): Promise<string> =>
232 new Promise((resolve, reject) => {
233 NodeHttp.get({ host: url.hostname, port: url.port, path, agent: false }, (response) => {
234 const chunks: Array<Buffer> = [];
235 response.on("data", (chunk: Buffer) => chunks.push(chunk));
236 response.on("end", () => resolve(Buffer.concat(chunks).toString()));
237 }).on("error", reject);
238 });
239 expect(await get(`//${other.host}/marker.txt?x=1`)).toBe(`worker //${other.host}/marker.txt?x=1`);
240 expect(await get(`${other.origin}/marker.txt`)).toBe("worker /marker.txt");
241 });
242
243 test("relays the Worker's status text and repeated Set-Cookie request headers", async () => {
244 const url = new NodeURL(
245 await devServer(`
246 export default {
247 fetch(request) {
248 return Response.json(request.headers.getSetCookie(), {
249 status: 231,
250 statusText: "global-before",
251 });
252 },
253 };
254 `),
255 );
256 // Each cookie carries a comma in `Expires`, so joining them would merge
257 // their boundaries.
258 const cookies = [
259 "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT",
260 "b=2; Expires=Thu, 22 Oct 2026 07:28:00 GMT",
261 ];
262 const response = await new Promise<NodeHttp.IncomingMessage & { body: string }>(
263 (resolve, reject) => {
264 NodeHttp.get(
265 {
266 host: url.hostname,
267 port: url.port,
268 path: "/",
269 agent: false,
270 headers: { "set-cookie": cookies },
271 },
272 (response) => {
273 const chunks: Array<Buffer> = [];
274 response.on("data", (chunk: Buffer) => chunks.push(chunk));
275 response.on("end", () =>
276 resolve(Object.assign(response, { body: Buffer.concat(chunks).toString() })),
277 );
278 },
279 ).on("error", reject);
280 },
281 );
282 expect(response.statusCode).toBe(231);
283 expect(response.statusMessage).toBe("global-before");
284 expect(JSON.parse(response.body)).toEqual(cookies);
285 });