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

main
ts 207 lines 6.56 KB
Raw
1 import * as NodeFs from "node:fs";
2 import * as NodeNet from "node:net";
3 import * as NodeOs from "node:os";
4 import * as NodePath from "node:path";
5
6 /**
7 * Hostname rewritten into container env so loopback still looks local
8 * (Prisma's `prisma+postgres://` plain-HTTP gate). Mapped in the sidecar
9 * ExtraHosts — to `127.0.0.1` on native Linux (unix-socket tunnel) or
10 * Docker `host-gateway` on Docker Desktop.
11 */
12 export const CONTAINER_LOOPBACK_ALIAS = "host.docker.localhost";
13
14 /** Bind-mount target inside the workerd `<name>-proxy` sidecar. */
15 export const CONTAINER_LOOPBACK_MOUNT = "/alchemy/host-loopback";
16
17 const LOOPBACK_HOST_IN_VALUE =
18 /(?:^|[\s,;=]|\/\/(?:[^/\s@]*@)?)(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|host\.docker\.localhost)(?=[:/?#]|[\s,;]|$)/i;
19
20 const LOOPBACK_HOST_PORT =
21 /(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|host\.docker\.localhost):(\d{1,5})\b/gi;
22
23 const DSN_PORT = /(?:^|[\s;])port=(\d{1,5})\b/gi;
24
25 const unixServers = new Map<number, NodeNet.Server>();
26
27 /**
28 * Native Linux Docker: a SYN to `host-gateway` (bridge IP) is host INPUT
29 * and UFW/nftables can drop it. Docker Desktop's gateway already reaches
30 * host loopback, so the unix-socket path is Linux-only.
31 */
32 export const usesUnixSocketLoopback = () => process.platform === "linux";
33
34 export const loopbackSocketDir = () => NodePath.join(NodeOs.tmpdir(), "alchemy-dev-loopback");
35
36 const addPort = (ports: Set<number>, raw: string) => {
37 const port = Number(raw);
38 if (Number.isInteger(port) && port > 0 && port <= 65535) ports.add(port);
39 };
40
41 /**
42 * Ports a container will dial if this env value is a loopback URL / DSN.
43 * Empty when the value is not loopback (Neon, PlanetScale, …).
44 */
45 export const loopbackPortsFromEnvValue = (value: string): number[] => {
46 if (!LOOPBACK_HOST_IN_VALUE.test(value)) return [];
47 LOOPBACK_HOST_IN_VALUE.lastIndex = 0;
48 const ports = new Set<number>();
49 for (const match of value.matchAll(LOOPBACK_HOST_PORT)) {
50 if (match[1] !== undefined) addPort(ports, match[1]);
51 }
52 for (const match of value.matchAll(DSN_PORT)) {
53 if (match[1] !== undefined) addPort(ports, match[1]);
54 }
55 return [...ports];
56 };
57
58 export const loopbackPortsFromEnv = (
59 env: Record<string, string> | ReadonlyArray<string> | undefined,
60 ): number[] => {
61 const ports = new Set<number>();
62 if (env === undefined) return [];
63 const values = Array.isArray(env)
64 ? env.map((entry) => {
65 const eq = entry.indexOf("=");
66 return eq === -1 ? "" : entry.slice(eq + 1);
67 })
68 : Object.values(env);
69 for (const value of values) {
70 for (const port of loopbackPortsFromEnvValue(value)) ports.add(port);
71 }
72 return [...ports];
73 };
74
75 export const sidecarLoopbackExtraHost = () =>
76 usesUnixSocketLoopback()
77 ? `${CONTAINER_LOOPBACK_ALIAS}:127.0.0.1`
78 : `${CONTAINER_LOOPBACK_ALIAS}:host-gateway`;
79
80 export const sidecarLoopbackBinds = (ports: readonly number[]): readonly string[] => {
81 if (!usesUnixSocketLoopback() || ports.length === 0) return [];
82 return [`${loopbackSocketDir()}:${CONTAINER_LOOPBACK_MOUNT}`];
83 };
84
85 type HostConfig = {
86 ExtraHosts?: Array<string>;
87 Binds?: Array<string>;
88 };
89
90 export const mergeSidecarLoopbackHostConfig = <T extends HostConfig>(
91 original: T | undefined,
92 ports: readonly number[],
93 ): T & { ExtraHosts: string[]; Binds?: string[] } => {
94 const extraHost = sidecarLoopbackExtraHost();
95 const extraHosts = [...(original?.ExtraHosts ?? [])];
96 if (!extraHosts.includes(extraHost)) extraHosts.push(extraHost);
97 const binds = [...(original?.Binds ?? [])];
98 for (const bind of sidecarLoopbackBinds(ports)) {
99 if (!binds.includes(bind)) binds.push(bind);
100 }
101 return {
102 ...(original as T),
103 ExtraHosts: extraHosts,
104 ...(binds.length > 0 ? { Binds: binds } : {}),
105 };
106 };
107
108 const pipeSockets = (incoming: NodeNet.Socket, outgoing: NodeNet.Socket) => {
109 incoming.pipe(outgoing);
110 outgoing.pipe(incoming);
111 const fail = () => {
112 incoming.destroy();
113 outgoing.destroy();
114 };
115 incoming.on("error", fail);
116 outgoing.on("error", fail);
117 };
118
119 const socketPathFor = (port: number) => NodePath.join(loopbackSocketDir(), `${port}.sock`);
120
121 const FORWARDER_SOURCE = `\
122 import * as net from "node:net";
123 import * as path from "node:path";
124
125 const dir = process.argv[2];
126 const ports = process.argv.slice(3).map(Number).filter((p) => p > 0 && p <= 65535);
127 if (dir === undefined || ports.length === 0) process.exit(1);
128
129 let pending = ports.length;
130 for (const port of ports) {
131 const server = net.createServer((incoming) => {
132 const outgoing = net.connect(path.join(dir, \`\${port}.sock\`));
133 incoming.pipe(outgoing);
134 outgoing.pipe(incoming);
135 const fail = () => {
136 incoming.destroy();
137 outgoing.destroy();
138 };
139 incoming.on("error", fail);
140 outgoing.on("error", fail);
141 });
142 server.on("error", (error) => {
143 console.error(error);
144 process.exit(1);
145 });
146 server.listen({ host: "127.0.0.1", port }, () => {
147 if (--pending === 0) console.log("ALCHEMY_LOOPBACK_READY");
148 });
149 }
150 `;
151
152 const writeForwarderScript = (dir: string) => {
153 const file = NodePath.join(dir, "forward.mjs");
154 NodeFs.writeFileSync(file, FORWARDER_SOURCE);
155 return file;
156 };
157
158 /**
159 * Host unix socket per port → `127.0.0.1:port`. The container never SYNs
160 * the docker bridge; UFW INPUT is not on this path.
161 */
162 export const ensureLoopbackUnixSockets = (ports: readonly number[]) => {
163 if (!usesUnixSocketLoopback()) return;
164 const unique = [...new Set(ports.filter((port) => Number.isInteger(port) && port > 0))];
165 if (unique.length === 0) return;
166 const dir = loopbackSocketDir();
167 NodeFs.mkdirSync(dir, { recursive: true });
168 writeForwarderScript(dir);
169 for (const port of unique) {
170 if (unixServers.has(port)) continue;
171 const sock = socketPathFor(port);
172 try {
173 NodeFs.unlinkSync(sock);
174 } catch {
175 // no leftover socket
176 }
177 const server = NodeNet.createServer((incoming) => {
178 const outgoing = NodeNet.connect({ host: "127.0.0.1", port });
179 pipeSockets(incoming, outgoing);
180 });
181 server.on("error", () => {
182 unixServers.delete(port);
183 });
184 server.listen(sock);
185 unixServers.set(port, server);
186 }
187 };
188
189 export const closeLoopbackUnixSockets = () => {
190 for (const [port, server] of unixServers) {
191 unixServers.delete(port);
192 server.close();
193 try {
194 NodeFs.unlinkSync(socketPathFor(port));
195 } catch {
196 // already gone
197 }
198 }
199 };
200
201 export const isContainerStartPath = (url: string | undefined) =>
202 url !== undefined && /\/containers\/[^/]+\/start(?:\?|$)/.test(url);
203
204 export const containerIdFromPath = (url: string | undefined) => {
205 if (url === undefined) return undefined;
206 return /\/containers\/([^/?]+)/.exec(url)?.[1];
207 };