The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import type { ServerDirectEndpoint } from "@t3tools/contracts"; |
| 2 | import { |
| 3 | buildTailscaleHttpsBaseUrl, |
| 4 | probeTailscaleHttpsEndpoint, |
| 5 | readTailscaleStatus, |
| 6 | } from "@t3tools/tailscale"; |
| 7 | import * as Context from "effect/Context"; |
| 8 | import * as Duration from "effect/Duration"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Layer from "effect/Layer"; |
| 11 | import * as Option from "effect/Option"; |
| 12 | import * as Ref from "effect/Ref"; |
| 13 | import { HttpClient } from "effect/http"; |
| 14 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 15 | import * as NodeNet from "node:net"; |
| 16 | import * as NodeOS from "node:os"; |
| 17 | |
| 18 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 19 | import { |
| 20 | formatHostForUrl, |
| 21 | isTailnetHost, |
| 22 | isWildcardHost, |
| 23 | } from "@t3tools/shared/hostClassification"; |
| 24 | |
| 25 | import * as ServerConfig from "../config.ts"; |
| 26 | import * as ServerEnvironment from "./ServerEnvironment.ts"; |
| 27 | import { isLoopbackHost, isPrivateNetworkAddress, isVirtualInterface } from "../startupAccess.ts"; |
| 28 | |
| 29 | type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>; |
| 30 | |
| 31 | // Stay below the config discovery timeout so slow Tailscale drops only the tailnet name. |
| 32 | const TAILSCALE_ENDPOINT_TIMEOUT = Duration.seconds(3); |
| 33 | |
| 34 | export class DirectEndpoints extends Context.Service< |
| 35 | DirectEndpoints, |
| 36 | { |
| 37 | readonly resolveAvailable: () => Effect.Effect<ReadonlyArray<ServerDirectEndpoint>>; |
| 38 | readonly resolve: () => Effect.Effect<ReadonlyArray<ServerDirectEndpoint>>; |
| 39 | } |
| 40 | >()("t3/environment/DirectEndpoints") {} |
| 41 | |
| 42 | // Credentials travel over HTTP; public IPs leak them and hostnames can resolve differently per client. |
| 43 | // Wildcard binds stay IPv4: the private-network listener check accepts only IPv4 peers. |
| 44 | const isAdvertisableAddress = (address: string): boolean => |
| 45 | NodeNet.isIPv4(address) && !address.startsWith("127.") && isPrivateNetworkAddress(address); |
| 46 | |
| 47 | // macOS utun names need Tailscale's IPv6 range to identify them; WARP shares its IPv4 range. |
| 48 | const isTailscaleInterface = ( |
| 49 | name: string, |
| 50 | entries: ReadonlyArray<NodeOS.NetworkInterfaceInfo>, |
| 51 | ): boolean => |
| 52 | /^tailscale/i.test(name) || |
| 53 | entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address)); |
| 54 | |
| 55 | // Windows adapter names are mutable; Linux bridges can inherit these MACs. |
| 56 | const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; |
| 57 | |
| 58 | export function resolveBoundEndpoints(input: { |
| 59 | readonly platform: NodeJS.Platform; |
| 60 | readonly host: string | undefined; |
| 61 | readonly port: number; |
| 62 | readonly interfaces: NetworkInterfacesMap; |
| 63 | /** A cloud VM's private network is its provider's, which no client shares. */ |
| 64 | readonly onCloudVm?: boolean; |
| 65 | }): ReadonlyArray<ServerDirectEndpoint> { |
| 66 | if (isLoopbackHost(input.host)) return []; |
| 67 | const tailscaleAddresses = new Set( |
| 68 | Object.entries(input.interfaces).flatMap(([name, entries = []]) => |
| 69 | isTailscaleInterface(name, entries) ? entries.map((entry) => entry.address) : [], |
| 70 | ), |
| 71 | ); |
| 72 | const addresses = isWildcardHost(input.host) |
| 73 | ? Object.entries(input.interfaces) |
| 74 | .flatMap(([name, entries]) => |
| 75 | isVirtualInterface(name, input.platform) ? [] : (entries ?? []), |
| 76 | ) |
| 77 | .filter( |
| 78 | (entry) => |
| 79 | !entry.internal && |
| 80 | entry.family === "IPv4" && |
| 81 | isAdvertisableAddress(entry.address) && |
| 82 | !(input.platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)), |
| 83 | ) |
| 84 | .map((entry) => entry.address) |
| 85 | : [input.host!].filter( |
| 86 | (address) => |
| 87 | isAdvertisableAddress(address) || (NodeNet.isIPv6(address) && isTailnetHost(address)), |
| 88 | ); |
| 89 | return [...new Set(addresses)] |
| 90 | .filter((address) => !input.onCloudVm || tailscaleAddresses.has(address)) |
| 91 | .map((address) => ({ |
| 92 | kind: tailscaleAddresses.has(address) ? "tailnet" : "lan", |
| 93 | httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`, |
| 94 | })); |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * AWS, GCP, Azure, DigitalOcean, Hetzner, Linode, Vultr, and Oracle all serve |
| 99 | * instance metadata at this address. A plain TCP connect skips HTTP proxies, |
| 100 | * which would otherwise answer for a machine that is not in a cloud. |
| 101 | */ |
| 102 | const CLOUD_METADATA_ADDRESS = "169.254.169.254"; |
| 103 | const CLOUD_METADATA_TIMEOUT_MS = 300; |
| 104 | |
| 105 | const probeCloudMetadata = Effect.callback<boolean>((resume) => { |
| 106 | const socket = NodeNet.connect({ |
| 107 | host: CLOUD_METADATA_ADDRESS, |
| 108 | port: 80, |
| 109 | timeout: CLOUD_METADATA_TIMEOUT_MS, |
| 110 | }); |
| 111 | let settled = false; |
| 112 | const settle = (found: boolean) => { |
| 113 | if (settled) return; |
| 114 | settled = true; |
| 115 | socket.destroy(); |
| 116 | resume(Effect.succeed(found)); |
| 117 | }; |
| 118 | socket.once("connect", () => settle(true)); |
| 119 | socket.once("timeout", () => settle(false)); |
| 120 | socket.once("error", () => settle(false)); |
| 121 | return Effect.sync(() => socket.destroy()); |
| 122 | }); |
| 123 | |
| 124 | /** @public */ |
| 125 | export const make = Effect.gen(function* () { |
| 126 | const config = yield* ServerConfig.ServerConfig; |
| 127 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 128 | const httpClient = yield* HttpClient.HttpClient; |
| 129 | const platform = yield* HostProcess.Platform; |
| 130 | const environmentId = yield* (yield* ServerEnvironment.ServerEnvironment).getEnvironmentId; |
| 131 | // Only the service default listens on every interface without being asked, |
| 132 | // so only it checks once whether it runs in a cloud. The check starts now so |
| 133 | // the first client does not wait for its timeout. |
| 134 | const onCloudVm = config.privateNetworkOnly |
| 135 | ? yield* Effect.cached(probeCloudMetadata) |
| 136 | : Effect.succeed(false); |
| 137 | yield* Effect.forkDetach(onCloudVm); |
| 138 | |
| 139 | const servedEndpoint = yield* Ref.make<Option.Option<string>>(Option.none()); |
| 140 | const resolveAvailable = Effect.fn("DirectEndpoints.resolveAvailable")(function* () { |
| 141 | const endpoints = [ |
| 142 | ...resolveBoundEndpoints({ |
| 143 | platform, |
| 144 | host: config.host, |
| 145 | port: config.port, |
| 146 | interfaces: NodeOS.networkInterfaces(), |
| 147 | onCloudVm: yield* onCloudVm, |
| 148 | }), |
| 149 | ]; |
| 150 | const servedUrl = yield* Ref.get(servedEndpoint); |
| 151 | if (Option.isSome(servedUrl)) endpoints.push({ kind: "tailnet", httpBaseUrl: servedUrl.value }); |
| 152 | return endpoints; |
| 153 | }); |
| 154 | |
| 155 | const resolve = Effect.gen(function* () { |
| 156 | // Serve setup can fail without stopping startup; advertise only after it answers as this server. |
| 157 | if (config.tailscaleServeEnabled) { |
| 158 | const servedUrl = yield* readTailscaleStatus.pipe( |
| 159 | Effect.map((status) => status.magicDnsName), |
| 160 | Effect.flatMap((magicDnsName) => { |
| 161 | if (magicDnsName === null) return Effect.succeed(null); |
| 162 | const httpBaseUrl = buildTailscaleHttpsBaseUrl({ |
| 163 | magicDnsName, |
| 164 | servePort: config.tailscaleServePort, |
| 165 | }); |
| 166 | return probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl, environmentId }).pipe( |
| 167 | Effect.map((reachable) => (reachable ? httpBaseUrl : null)), |
| 168 | ); |
| 169 | }), |
| 170 | Effect.timeoutOption(TAILSCALE_ENDPOINT_TIMEOUT), |
| 171 | Effect.map(Option.flatMap(Option.fromNullishOr)), |
| 172 | Effect.orElseSucceed(() => Option.none<string>()), |
| 173 | Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 174 | Effect.provideService(HttpClient.HttpClient, httpClient), |
| 175 | ); |
| 176 | yield* Ref.set(servedEndpoint, servedUrl); |
| 177 | } |
| 178 | return yield* resolveAvailable(); |
| 179 | }); |
| 180 | |
| 181 | return DirectEndpoints.of({ |
| 182 | resolveAvailable, |
| 183 | resolve: Effect.fn("DirectEndpoints.resolve")(function () { |
| 184 | return resolve; |
| 185 | }), |
| 186 | }); |
| 187 | }); |
| 188 | |
| 189 | export const layer = Layer.effect(DirectEndpoints, make); |