The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // An async Web Function: a plain Node server, deployed as-is. It listens |
| 2 | // where Lambda says, the same way any Express, Hono, or Fastify app would. |
| 3 | import { Resolver } from "node:dns/promises"; |
| 4 | import * as http from "node:http"; |
| 5 | |
| 6 | const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 7 | |
| 8 | const readBody = async (req: http.IncomingMessage) => { |
| 9 | const chunks: Buffer[] = []; |
| 10 | for await (const chunk of req) chunks.push(chunk as Buffer); |
| 11 | return Buffer.concat(chunks).toString("utf8"); |
| 12 | }; |
| 13 | |
| 14 | const json = (res: http.ServerResponse, value: unknown) => { |
| 15 | res.writeHead(200, { "content-type": "application/json" }); |
| 16 | res.end(JSON.stringify(value)); |
| 17 | }; |
| 18 | |
| 19 | const [host, port] = (process.env.AWS_LAMBDA_HTTP_ENDPOINT ?? "localhost:3000").split(":"); |
| 20 | |
| 21 | http |
| 22 | .createServer(async (req, res) => { |
| 23 | const url = new URL(req.url ?? "/", "http://localhost"); |
| 24 | |
| 25 | if (url.pathname === "/stream") { |
| 26 | res.writeHead(200, { "content-type": "text/plain" }); |
| 27 | for (const [i, chunk] of ["one\n", "two\n", "three\n"].entries()) { |
| 28 | if (i > 0) await sleep(600); |
| 29 | res.write(chunk); |
| 30 | } |
| 31 | res.end(); |
| 32 | return; |
| 33 | } |
| 34 | |
| 35 | if (url.pathname === "/dns") { |
| 36 | // Query a specific DNS server, e.g. a VPC's Amazon-provided resolver, |
| 37 | // which is only reachable from inside that VPC. |
| 38 | const resolver = new Resolver({ timeout: 2000, tries: 1 }); |
| 39 | resolver.setServers([url.searchParams.get("server")!]); |
| 40 | try { |
| 41 | const addresses = await resolver.resolve4(url.searchParams.get("name") ?? "aws.amazon.com"); |
| 42 | return json(res, { ok: true, addresses }); |
| 43 | } catch (error) { |
| 44 | return json(res, { ok: false, error: String(error) }); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | if (url.pathname === "/endpoint") { |
| 49 | // Lambda sets this header; callers can't forge it. |
| 50 | res.end(req.headers["lambda-web-endpoint-name"] ?? "missing"); |
| 51 | return; |
| 52 | } |
| 53 | |
| 54 | if (url.pathname === "/echo" && req.method === "POST") { |
| 55 | return json(res, { method: req.method, body: await readBody(req) }); |
| 56 | } |
| 57 | |
| 58 | res.writeHead(200, { |
| 59 | "content-type": "text/plain", |
| 60 | "set-cookie": "a=1", |
| 61 | "x-fixture": "async-server", |
| 62 | // Alchemy doesn't wrap the server or set listen variables for it. |
| 63 | "x-port-env": process.env.PORT ?? "unset", |
| 64 | }); |
| 65 | res.end(`greeting=${process.env.GREETING ?? "missing"}`); |
| 66 | }) |
| 67 | .listen(Number(port), host); |