TypeScript
fix(server): T3 Connect and Tailscale Serve reach servers bound to ::1 (#19902)
Mateoa8e948461092
diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.tsindex 845f20195aa..40855f32546 100644--- a/apps/server/src/cli/pair.test.ts+++ b/apps/server/src/cli/pair.test.ts@@ -13,9 +13,10 @@ import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";+import { FetchHttpClient } from "effect/http";+import { ChildProcess, ChildProcessSpawner } from "effect/process";import * as TestConsole from "effect/testing/TestConsole";import { Command, CliError } from "effect/cli";-import { ChildProcessSpawner } from "effect/process";import { cli } from "../binCli.ts";import {@@ -120,7 +121,10 @@ const testDescriptor = {capabilities: { repositoryIdentity: true },};-const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A, E, R>) =>+const withDescriptorServer = <A, E, R>(+ run: (origin: string) => Effect.Effect<A, E, R>,+ host = "127.0.0.1",+) =>Effect.acquireUseRelease(Effect.callback<NodeHttp.Server>((resume) => {const server = NodeHttp.createServer((request, response) => {@@ -132,19 +136,87 @@ const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A,response.writeHead(404);response.end();});- server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));+ server.listen(0, host, () => resume(Effect.succeed(server)));}),(server) => {const address = server.address();if (address === null || typeof address === "string") {return Effect.die(new Error("Expected a TCP address"));}- return run(`http://127.0.0.1:${String(address.port)}`);+ return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);},(server) => Effect.sync(() => server.close()),);describe("t3 pair", () => {+ it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>+ withDescriptorServer(+ (origin) =>+ Effect.gen(function* () {+ const fetch = yield* FetchHttpClient.Fetch;+ let serving = false;+ const spawner = ChildProcessSpawner.make((command) =>+ Effect.gen(function* () {+ if (!ChildProcess.isStandardCommand(command))+ return yield* Effect.die("Unexpected pipeline");+ if (command.args[0] === "serve") {+ const target = command.args.at(-1)!;+ const descriptor = yield* Effect.promise(async () =>+ (await fetch(new URL("/.well-known/t3/environment", target))).json(),+ );+ expect(descriptor).toEqual(testDescriptor);+ serving = true;+ }+ return ChildProcessSpawner.makeHandle({+ pid: ChildProcessSpawner.ProcessId(1),+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),+ isRunning: Effect.succeed(false),+ kill: () => Effect.void,+ unref: Effect.succeed(Effect.void),+ stdin: Sink.drain,+ stdout: Stream.make(+ new TextEncoder().encode('{"Self":{"DNSName":"pair-test.tail.ts.net."}}'),+ ),+ stderr: Stream.empty,+ all: Stream.empty,+ getInputFd: () => Sink.drain,+ getOutputFd: () => Stream.empty,+ });+ }),+ );++ const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ipv6-test-"));+ yield* persistServerRuntimeState({+ path: NodePath.join(baseDir, "userdata", "server-runtime.json"),+ state: yield* makePersistedServerRuntimeState({+ config: { host: "::1", devUrl: undefined },+ port: Number(new URL(origin).port),+ }),+ });+ const output = yield* captureStdout(+ runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(HostProcess.Platform, "linux"),+ Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {+ if (String(input).startsWith(origin)) return fetch(input, init);+ assert.equal(+ String(input),+ "https://pair-test.tail.ts.net/.well-known/t3/environment",+ );+ return serving+ ? Response.json(testDescriptor)+ : new Response(null, { status: 503 });+ }),+ ),+ );++ expect(serving).toBe(true);+ assert.include(output, "Pairing URL: https://pair-test.tail.ts.net/pair#token=");+ }),+ "::1",+ ).pipe(Effect.provide(NodeServices.layer)),+ );+it.effect("mints a token and prints a QR pairing URL for a live server", () =>withDescriptorServer((origin) =>Effect.gen(function* () {diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.tsindex 89816bf9dda..6abe38de8f9 100644--- a/apps/server/src/cli/pair.ts+++ b/apps/server/src/cli/pair.ts@@ -158,7 +158,7 @@ export const resolveTailscaleLocalTarget = (? { localPort }: { localPort, localHost: devUrl.hostname };}- if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {+ if (state.host !== undefined && !isWildcardHost(state.host)) {return { localPort: state.port, localHost: formatHostForUrl(state.host) };}return { localPort: state.port };diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.tsindex faa11d9c125..35285fddd26 100644--- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts+++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts@@ -240,6 +240,7 @@ describe("releaseManagedTunnelOnShutdown", () => {readonly requests: Array<HttpClientRequest.HttpClientRequest>;readonly onRequest?: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<void>;readonly respond?: () => Response;+ readonly address?: HttpServer.HttpServer["Service"]["address"];readonly respondEffect?: Effect.Effect<Response>;}@@ -274,7 +275,10 @@ describe("releaseManagedTunnelOnShutdown", () => {<A, E, R>(effect: Effect.Effect<A, E, R>) =>effect.pipe(Effect.provide(CloudLink.layer),- Effect.provideService(HttpServer.HttpServer, idleHttpServer),+ Effect.provideService(HttpServer.HttpServer, {+ ...idleHttpServer,+ address: harness.address ?? idleHttpServer.address,+ }),Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),Effect.provideService(@@ -668,6 +672,48 @@ describe("releaseManagedTunnelOnShutdown", () => {);});+ it.effect("registers and starts a managed tunnel at the bound IPv6 loopback address", () => {+ const { store } = makeMemorySecretStore();+ const config = {+ providerKind: "cloudflare_tunnel" as const,+ connectorToken: "existing-token",+ tunnelId: "existing-tunnel",+ };+ const applyConfigCalls: Array<unknown> = [];+ const requests: Array<HttpClientRequest.HttpClientRequest> = [];++ return Effect.gen(function* () {+ const link = yield* CloudLink.CloudLink;+ expect(+ yield* link.applyRelayConfig({+ relayUrl: "https://relay.example.test",+ cloudUserId: "user-123",+ environmentCredential: "environment-credential",+ cloudMintPublicKey:+ "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----",+ endpointRuntime: config,+ }),+ ).toMatchObject({ ok: true, endpointRuntimeStatus: { status: "running" } });+ expect(requests).toHaveLength(1);+ const body = requests[0]!.body;+ if (body._tag !== "Uint8Array") throw new Error("Expected a JSON recovery request");+ expect(+ yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)),+ ).toMatchObject({+ origin: { localHttpHost: "[::1]", localHttpPort: 4884 },+ });+ expect(applyConfigCalls).toEqual([null, config]);+ }).pipe(+ provideReleaseHarness({+ store,+ applyConfigCalls,+ requests,+ address: NetAddress.inetAddressFromIpStringUnsafe("::1", 4884),+ respond: () => Response.json({ status: "ready" }),+ }),+ );+ });+it.effect("marks a link the relay rejects as revoked without dropping or replacing it", () => {const { store, values } = makeMemorySecretStore([[diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.tsindex 04c4cb5997c..945fdeef87d 100644--- a/apps/server/src/cloud/CloudLink.ts+++ b/apps/server/src/cloud/CloudLink.ts@@ -70,6 +70,7 @@ import * as ServerConfig from "../config.ts";import * as ServerEnvironment from "../environment/ServerEnvironment.ts";import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";import { makeRelayEnvironmentClient } from "../relay/relayEnvironmentClient.ts";+import { loopbackUrlHostForAddress } from "../startupAccess.ts";import {type CliDesiredLinkMode,readCliDesiredCloudLink,@@ -1193,7 +1194,7 @@ const make = Effect.gen(function* () {return yield* new CloudLinkInternalError({ operation: "resolve-server-origin" });}const registration = yield* registerManagedTunnelRecovery(- `http://127.0.0.1:${address.port}`,+ `http://${loopbackUrlHostForAddress(address)}:${address.port}`,).pipe(Effect.retry({times: 2,diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex fd8e0824649..b34df02d603 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -180,6 +180,7 @@ import * as EventStoreV2 from "./orchestration-v2/EventStore.ts";import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts";+import { loopbackUrlHostForAddress } from "./startupAccess.ts";import * as OrchestrationHttp from "./orchestration-v2/http.ts";import * as ProjectHttp from "./project/http.ts";import * as NetService from "@t3tools/shared/Net";@@ -783,7 +784,7 @@ const layerMakeServer = Layer.unwrap(return yield* ensureTailscaleServe({localPort,servePort: config.tailscaleServePort,- localHost: "127.0.0.1",+ localHost: loopbackUrlHostForAddress(address),}).pipe(Effect.as({ localPort, servePort: config.tailscaleServePort }),Effect.tap(() =>@@ -853,7 +854,7 @@ const layerMakeServer = Layer.unwrap(const server = yield* HttpServer.HttpServer;const address = server.address;if (typeof address === "string" || !("port" in address)) return;- const localOrigin = `http://127.0.0.1:${address.port}`;+ const localOrigin = `http://${loopbackUrlHostForAddress(address)}:${address.port}`;const endpointRuntime = yield* CloudManagedEndpointRuntime.CloudManagedEndpointRuntime;const runManagedTunnelRecovery = yield* makeManagedTunnelRecovery({recover: (config: RelayManagedEndpointRuntimeConfig) =>diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.tsindex 4bc2578eeca..c37f6849763 100644--- a/apps/server/src/startupAccess.ts+++ b/apps/server/src/startupAccess.ts@@ -3,6 +3,7 @@ import * as NodeOS from "node:os";import { QrCode } from "@t3tools/shared/qrCode";import * as Effect from "effect/Effect";import { HttpServer } from "effect/http";+import * as NetAddress from "effect/net/NetAddress";import * as ServerConfig from "./config.ts";import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";@@ -35,6 +36,11 @@ export const isWildcardHost = (host: string | undefined): boolean =>export const formatHostForUrl = (host: string): string =>host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;+export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string =>+ address._tag === "InetAddressV6" && NetAddress.isLoopback(address.address)+ ? "[::1]"+ : "127.0.0.1";+const normalizeHost = (host: string): string =>host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;