The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics nodeBuiltinImport:off - The private-network gate guards the node:http server. |
| 2 | import type * as NodeHttp from "node:http"; |
| 3 | import * as NodeNet from "node:net"; |
| 4 | import * as NodeOS from "node:os"; |
| 5 | |
| 6 | import { |
| 7 | formatHostForUrl, |
| 8 | isPrivateNetworkHost, |
| 9 | isSharedAddressSpaceHost, |
| 10 | isWildcardHost, |
| 11 | } from "@t3tools/shared/hostClassification"; |
| 12 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 13 | import { QrCode } from "@t3tools/shared/qrCode"; |
| 14 | import { buildPairingAppLink } from "@t3tools/shared/remote"; |
| 15 | import * as Clock from "effect/Clock"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import { HttpServer } from "effect/http"; |
| 18 | import * as NetAddress from "effect/net/NetAddress"; |
| 19 | |
| 20 | import * as ServerConfig from "./config.ts"; |
| 21 | import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; |
| 22 | |
| 23 | export interface HeadlessServeAccessInfo { |
| 24 | readonly connectionString: string; |
| 25 | readonly token: string; |
| 26 | readonly pairingUrl: string; |
| 27 | } |
| 28 | |
| 29 | type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>; |
| 30 | |
| 31 | export const isLoopbackHost = (host: string | undefined): boolean => { |
| 32 | if (!host || host.length === 0) { |
| 33 | return true; |
| 34 | } |
| 35 | |
| 36 | return ( |
| 37 | host === "localhost" || |
| 38 | host === "127.0.0.1" || |
| 39 | host === "::1" || |
| 40 | host === "[::1]" || |
| 41 | host.startsWith("127.") |
| 42 | ); |
| 43 | }; |
| 44 | |
| 45 | /** |
| 46 | * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and |
| 47 | * macOS's `bridge100`+) have private addresses only this machine reaches. A |
| 48 | * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so |
| 49 | * it stays listed. |
| 50 | */ |
| 51 | const VIRTUAL_INTERFACE = |
| 52 | /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/; |
| 53 | |
| 54 | /** |
| 55 | * systemd-nspawn's `ve-*`/`vz-*` and NixOS containers' `vb-*` name host-side |
| 56 | * veths after the machine. Windows aliases are user-renameable, so these |
| 57 | * prefixes only apply to Linux interface discovery. |
| 58 | */ |
| 59 | const LINUX_CONTAINER_INTERFACE = /^(ve-|vb-|vz-)/; |
| 60 | |
| 61 | export const isVirtualInterface = (name: string, platform: NodeJS.Platform): boolean => |
| 62 | VIRTUAL_INTERFACE.test(name) || (platform === "linux" && LINUX_CONTAINER_INTERFACE.test(name)); |
| 63 | |
| 64 | /** |
| 65 | * Loopback or private-range IPv4 (LAN, tailnet, CGNAT), not link-local, in |
| 66 | * plain or IPv4-mapped IPv6 form. |
| 67 | */ |
| 68 | export const isPrivateNetworkAddress = (address: string): boolean => { |
| 69 | const ipv4 = address.replace(/^::ffff:/i, ""); |
| 70 | return NodeNet.isIPv4(ipv4) && !ipv4.startsWith("169.254.") && isPrivateNetworkHost(ipv4); |
| 71 | }; |
| 72 | |
| 73 | /** |
| 74 | * A private-network listener binds every interface but serves only |
| 75 | * connections that stay on loopback, a LAN, or the tailnet. Both ends must be |
| 76 | * private: a cloud VM or a router port forward hands public clients to a |
| 77 | * private local address. |
| 78 | */ |
| 79 | export const acceptsPrivateNetworkConnection = (socket: { |
| 80 | readonly localAddress?: string | undefined; |
| 81 | readonly remoteAddress?: string | undefined; |
| 82 | }): boolean => |
| 83 | [socket.localAddress, socket.remoteAddress].every( |
| 84 | (address) => address !== undefined && isPrivateNetworkAddress(address), |
| 85 | ); |
| 86 | |
| 87 | const CLOSED_CONNECTION_LOG_INTERVAL_NANOS = 60_000_000_000n; |
| 88 | |
| 89 | /** |
| 90 | * Closing is silent to the client, so closed connections are logged with both |
| 91 | * addresses: the first at once, then at most one line a minute with a count, so |
| 92 | * a connect flood from outside cannot grow the service log without bound. |
| 93 | */ |
| 94 | // Untraced: the captured context would otherwise tie every later warning to a span that ended at startup. |
| 95 | export const closeNonPrivateNetworkConnections = Effect.fnUntraced(function* ( |
| 96 | server: NodeHttp.Server, |
| 97 | ) { |
| 98 | const runSync = Effect.runSyncWith(yield* Effect.context<never>()); |
| 99 | let nextLogAt: bigint | undefined; |
| 100 | let closedSinceLastLog = 0; |
| 101 | server.on("connection", (socket) => { |
| 102 | if (acceptsPrivateNetworkConnection(socket)) return; |
| 103 | // Read before destroy: Node forgets localAddress once the handle closes. |
| 104 | const addresses = { localAddress: socket.localAddress, remoteAddress: socket.remoteAddress }; |
| 105 | socket.destroy(); |
| 106 | runSync( |
| 107 | Effect.gen(function* () { |
| 108 | // Monotonic: a wall clock set backwards must not silence the warnings. |
| 109 | const now = yield* Clock.monotonicTimeNanos; |
| 110 | if (nextLogAt !== undefined && now < nextLogAt) { |
| 111 | closedSinceLastLog += 1; |
| 112 | return; |
| 113 | } |
| 114 | nextLogAt = now + CLOSED_CONNECTION_LOG_INTERVAL_NANOS; |
| 115 | yield* Effect.logWarning("closed a connection outside the private network", { |
| 116 | ...addresses, |
| 117 | ...(closedSinceLastLog > 0 ? { closedSinceLastLog } : {}), |
| 118 | }); |
| 119 | closedSinceLastLog = 0; |
| 120 | }), |
| 121 | ); |
| 122 | }); |
| 123 | }); |
| 124 | |
| 125 | export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string => |
| 126 | NetAddress.isUnspecified(address.address) |
| 127 | ? "127.0.0.1" |
| 128 | : NetAddress.formatUrlHostString(NetAddress.formatIp(address.address)); |
| 129 | |
| 130 | const normalizeHost = (host: string): string => |
| 131 | host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; |
| 132 | |
| 133 | const isIpv4Family = (family: string | number): boolean => family === "IPv4" || family === 4; |
| 134 | |
| 135 | const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6; |
| 136 | |
| 137 | const resolveHeadlessConnectionHost = ( |
| 138 | host: string | undefined, |
| 139 | interfaces: NetworkInterfacesMap, |
| 140 | privateNetworkOnly: boolean, |
| 141 | platform: NodeJS.Platform, |
| 142 | ): string => { |
| 143 | if (!host) { |
| 144 | return "localhost"; |
| 145 | } |
| 146 | |
| 147 | if (!isWildcardHost(host)) { |
| 148 | return normalizeHost(host); |
| 149 | } |
| 150 | |
| 151 | const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) => |
| 152 | privateNetworkOnly && isVirtualInterface(name, platform) ? [] : (entries ?? []), |
| 153 | ); |
| 154 | const externalIpv4Entries = interfaceEntries.filter( |
| 155 | (entry) => |
| 156 | !entry.internal && |
| 157 | isIpv4Family(entry.family) && |
| 158 | (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)), |
| 159 | ); |
| 160 | // A tailnet or other CGNAT address reaches fewer devices than the LAN one. |
| 161 | const externalIpv4 = privateNetworkOnly |
| 162 | ? (externalIpv4Entries.find((entry) => !isSharedAddressSpaceHost(entry.address)) ?? |
| 163 | externalIpv4Entries[0]) |
| 164 | : externalIpv4Entries[0]; |
| 165 | if (externalIpv4) { |
| 166 | return externalIpv4.address; |
| 167 | } |
| 168 | if (privateNetworkOnly) { |
| 169 | return "localhost"; |
| 170 | } |
| 171 | |
| 172 | const externalIpv6 = interfaceEntries.find( |
| 173 | (entry) => !entry.internal && isIpv6Family(entry.family), |
| 174 | ); |
| 175 | return externalIpv6 ? normalizeHost(externalIpv6.address) : "localhost"; |
| 176 | }; |
| 177 | |
| 178 | export const resolveHeadlessConnectionString = ( |
| 179 | host: string | undefined, |
| 180 | port: number, |
| 181 | options: { |
| 182 | readonly interfaces?: NetworkInterfacesMap; |
| 183 | readonly privateNetworkOnly?: boolean | undefined; |
| 184 | readonly platform: NodeJS.Platform; |
| 185 | }, |
| 186 | ): string => { |
| 187 | const connectionHost = resolveHeadlessConnectionHost( |
| 188 | host, |
| 189 | options.interfaces ?? NodeOS.networkInterfaces(), |
| 190 | options.privateNetworkOnly === true, |
| 191 | options.platform, |
| 192 | ); |
| 193 | return `http://${formatHostForUrl(connectionHost)}:${port}`; |
| 194 | }; |
| 195 | |
| 196 | const resolveListeningPort = (address: unknown, fallbackPort: number): number => { |
| 197 | if ( |
| 198 | typeof address === "object" && |
| 199 | address !== null && |
| 200 | "port" in address && |
| 201 | typeof address.port === "number" |
| 202 | ) { |
| 203 | return address.port; |
| 204 | } |
| 205 | return fallbackPort; |
| 206 | }; |
| 207 | |
| 208 | export const buildPairingUrl = (connectionString: string, token: string): string => { |
| 209 | const url = new URL(connectionString); |
| 210 | url.pathname = "/pair"; |
| 211 | url.searchParams.delete("token"); |
| 212 | url.hash = new URLSearchParams([["token", token]]).toString(); |
| 213 | return url.toString(); |
| 214 | }; |
| 215 | |
| 216 | export const renderTerminalQrCode = (value: string, margin = 2): string => { |
| 217 | const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM); |
| 218 | const rows: Array<string> = []; |
| 219 | const isDark = (x: number, y: number): boolean => |
| 220 | x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y); |
| 221 | |
| 222 | for (let y = -margin; y < qrCode.size + margin; y += 2) { |
| 223 | let row = ""; |
| 224 | |
| 225 | for (let x = -margin; x < qrCode.size + margin; x += 1) { |
| 226 | const topDark = isDark(x, y); |
| 227 | const bottomDark = isDark(x, y + 1); |
| 228 | |
| 229 | row += topDark ? (bottomDark ? "█" : "▀") : bottomDark ? "▄" : " "; |
| 230 | } |
| 231 | |
| 232 | rows.push(row); |
| 233 | } |
| 234 | |
| 235 | return rows.join("\n"); |
| 236 | }; |
| 237 | |
| 238 | export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): string => |
| 239 | [ |
| 240 | "T3 Code server is ready.", |
| 241 | `Connection string: ${accessInfo.connectionString}`, |
| 242 | `Token: ${accessInfo.token}`, |
| 243 | `Pairing URL: ${accessInfo.pairingUrl}`, |
| 244 | `App link: ${buildPairingAppLink(accessInfo.pairingUrl)}`, |
| 245 | ...(isLoopbackHost(new URL(accessInfo.connectionString).hostname) |
| 246 | ? [] |
| 247 | : [ |
| 248 | "", |
| 249 | "Warning: this address uses plain HTTP. Anyone on the same network can read the", |
| 250 | "token and control this machine. Use it over a VPN or tailnet you trust.", |
| 251 | ]), |
| 252 | "", |
| 253 | renderTerminalQrCode(accessInfo.pairingUrl), |
| 254 | "", |
| 255 | ].join("\n"); |
| 256 | |
| 257 | export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () { |
| 258 | const serverConfig = yield* ServerConfig.ServerConfig; |
| 259 | const httpServer = yield* HttpServer.HttpServer; |
| 260 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 261 | const platform = yield* HostProcess.Platform; |
| 262 | const connectionString = resolveHeadlessConnectionString( |
| 263 | serverConfig.host, |
| 264 | resolveListeningPort(httpServer.address, serverConfig.port), |
| 265 | { privateNetworkOnly: serverConfig.privateNetworkOnly, platform }, |
| 266 | ); |
| 267 | const issued = yield* serverAuth.issueStartupPairingCredential(); |
| 268 | |
| 269 | return { |
| 270 | connectionString, |
| 271 | token: issued.credential, |
| 272 | pairingUrl: buildPairingUrl(connectionString, issued.credential), |
| 273 | } satisfies HeadlessServeAccessInfo; |
| 274 | }); |