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 22, 23:15 UTC
fix(server): T3 Connect and Tailscale Serve reach servers bound to ::1 (#19902)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Mateo committed
Oct 20, 2026 at 06:55 UTC
a8e948461092f513b7da98f6d074c59919875322
6 files changed
+135
-9
apps/server/src/cli/pair.test.ts
+76
-4
@@ -13,9 +13,10 @@ import * as Effect from "effect/Effect";
13
import * as Layer from "effect/Layer";
14
import * as Sink from "effect/Sink";
15
import * as Stream from "effect/Stream";
16
+import { FetchHttpClient } from "effect/http";
17
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
18
import * as TestConsole from "effect/testing/TestConsole";
19
import { Command, CliError } from "effect/cli";
18
-import { ChildProcessSpawner } from "effect/process";
20
21
import { cli } from "../binCli.ts";
22
import {
@@ -120,7 +121,10 @@ const testDescriptor = {
121
capabilities: { repositoryIdentity: true },
122
};
123
123
-const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A, E, R>) =>
124
+const withDescriptorServer = <A, E, R>(
125
+ run: (origin: string) => Effect.Effect<A, E, R>,
126
+ host = "127.0.0.1",
127
+) =>
128
Effect.acquireUseRelease(
129
Effect.callback<NodeHttp.Server>((resume) => {
130
const server = NodeHttp.createServer((request, response) => {
@@ -132,19 +136,87 @@ const withDescriptorServer = <A, E, R>(run: (origin: string) => Effect.Effect<A,
136
response.writeHead(404);
137
response.end();
138
});
135
- server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server)));
139
+ server.listen(0, host, () => resume(Effect.succeed(server)));
140
}),
141
(server) => {
142
const address = server.address();
143
if (address === null || typeof address === "string") {
144
return Effect.die(new Error("Expected a TCP address"));
145
}
142
- return run(`http://127.0.0.1:${String(address.port)}`);
146
+ return run(`http://${host === "::1" ? "[::1]" : host}:${String(address.port)}`);
147
},
148
(server) => Effect.sync(() => server.close()),
149
);
150
151
describe("t3 pair", () => {
152
+ it.effect("publishes an IPv6-only server through Tailscale Serve when pairing", () =>
153
+ withDescriptorServer(
154
+ (origin) =>
155
+ Effect.gen(function* () {
156
+ const fetch = yield* FetchHttpClient.Fetch;
157
+ let serving = false;
158
+ const spawner = ChildProcessSpawner.make((command) =>
159
+ Effect.gen(function* () {
160
+ if (!ChildProcess.isStandardCommand(command))
161
+ return yield* Effect.die("Unexpected pipeline");
162
+ if (command.args[0] === "serve") {
163
+ const target = command.args.at(-1)!;
164
+ const descriptor = yield* Effect.promise(async () =>
165
+ (await fetch(new URL("/.well-known/t3/environment", target))).json(),
166
+ );
167
+ expect(descriptor).toEqual(testDescriptor);
168
+ serving = true;
169
+ }
170
+ return ChildProcessSpawner.makeHandle({
171
+ pid: ChildProcessSpawner.ProcessId(1),
172
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
173
+ isRunning: Effect.succeed(false),
174
+ kill: () => Effect.void,
175
+ unref: Effect.succeed(Effect.void),
176
+ stdin: Sink.drain,
177
+ stdout: Stream.make(
178
+ new TextEncoder().encode('{"Self":{"DNSName":"pair-test.tail.ts.net."}}'),
179
+ ),
180
+ stderr: Stream.empty,
181
+ all: Stream.empty,
182
+ getInputFd: () => Sink.drain,
183
+ getOutputFd: () => Stream.empty,
184
+ });
185
+ }),
186
+ );
187
+
188
+ const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ipv6-test-"));
189
+ yield* persistServerRuntimeState({
190
+ path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
191
+ state: yield* makePersistedServerRuntimeState({
192
+ config: { host: "::1", devUrl: undefined },
193
+ port: Number(new URL(origin).port),
194
+ }),
195
+ });
196
+ const output = yield* captureStdout(
197
+ runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
198
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
199
+ Effect.provideService(HostProcess.Platform, "linux"),
200
+ Effect.provideService(FetchHttpClient.Fetch, async (input, init) => {
201
+ if (String(input).startsWith(origin)) return fetch(input, init);
202
+ assert.equal(
203
+ String(input),
204
+ "https://pair-test.tail.ts.net/.well-known/t3/environment",
205
+ );
206
+ return serving
207
+ ? Response.json(testDescriptor)
208
+ : new Response(null, { status: 503 });
209
+ }),
210
+ ),
211
+ );
212
+
213
+ expect(serving).toBe(true);
214
+ assert.include(output, "Pairing URL: https://pair-test.tail.ts.net/pair#token=");
215
+ }),
216
+ "::1",
217
+ ).pipe(Effect.provide(NodeServices.layer)),
218
+ );
219
+
220
it.effect("mints a token and prints a QR pairing URL for a live server", () =>
221
withDescriptorServer((origin) =>
222
Effect.gen(function* () {
apps/server/src/cli/pair.ts
+1
-1
@@ -158,7 +158,7 @@ export const resolveTailscaleLocalTarget = (
158
? { localPort }
159
: { localPort, localHost: devUrl.hostname };
160
}
161
- if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {
161
+ if (state.host !== undefined && !isWildcardHost(state.host)) {
162
return { localPort: state.port, localHost: formatHostForUrl(state.host) };
163
}
164
return { localPort: state.port };
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+47
-1
@@ -240,6 +240,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
240
readonly requests: Array<HttpClientRequest.HttpClientRequest>;
241
readonly onRequest?: (request: HttpClientRequest.HttpClientRequest) => Effect.Effect<void>;
242
readonly respond?: () => Response;
243
+ readonly address?: HttpServer.HttpServer["Service"]["address"];
244
readonly respondEffect?: Effect.Effect<Response>;
245
}
246
@@ -274,7 +275,10 @@ describe("releaseManagedTunnelOnShutdown", () => {
275
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
276
effect.pipe(
277
Effect.provide(CloudLink.layer),
277
- Effect.provideService(HttpServer.HttpServer, idleHttpServer),
278
+ Effect.provideService(HttpServer.HttpServer, {
279
+ ...idleHttpServer,
280
+ address: harness.address ?? idleHttpServer.address,
281
+ }),
282
Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),
283
Effect.provideService(AgentAwarenessRelay.AgentAwarenessRelay, idleAwarenessRelay),
284
Effect.provideService(
@@ -668,6 +672,48 @@ describe("releaseManagedTunnelOnShutdown", () => {
672
);
673
});
674
675
+ it.effect("registers and starts a managed tunnel at the bound IPv6 loopback address", () => {
676
+ const { store } = makeMemorySecretStore();
677
+ const config = {
678
+ providerKind: "cloudflare_tunnel" as const,
679
+ connectorToken: "existing-token",
680
+ tunnelId: "existing-tunnel",
681
+ };
682
+ const applyConfigCalls: Array<unknown> = [];
683
+ const requests: Array<HttpClientRequest.HttpClientRequest> = [];
684
+
685
+ return Effect.gen(function* () {
686
+ const link = yield* CloudLink.CloudLink;
687
+ expect(
688
+ yield* link.applyRelayConfig({
689
+ relayUrl: "https://relay.example.test",
690
+ cloudUserId: "user-123",
691
+ environmentCredential: "environment-credential",
692
+ cloudMintPublicKey:
693
+ "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----",
694
+ endpointRuntime: config,
695
+ }),
696
+ ).toMatchObject({ ok: true, endpointRuntimeStatus: { status: "running" } });
697
+ expect(requests).toHaveLength(1);
698
+ const body = requests[0]!.body;
699
+ if (body._tag !== "Uint8Array") throw new Error("Expected a JSON recovery request");
700
+ expect(
701
+ yield* decodeManagedTunnelRecoveryRegistration(new TextDecoder().decode(body.body)),
702
+ ).toMatchObject({
703
+ origin: { localHttpHost: "[::1]", localHttpPort: 4884 },
704
+ });
705
+ expect(applyConfigCalls).toEqual([null, config]);
706
+ }).pipe(
707
+ provideReleaseHarness({
708
+ store,
709
+ applyConfigCalls,
710
+ requests,
711
+ address: NetAddress.inetAddressFromIpStringUnsafe("::1", 4884),
712
+ respond: () => Response.json({ status: "ready" }),
713
+ }),
714
+ );
715
+ });
716
+
717
it.effect("marks a link the relay rejects as revoked without dropping or replacing it", () => {
718
const { store, values } = makeMemorySecretStore([
719
[
apps/server/src/cloud/CloudLink.ts
+2
-1
@@ -70,6 +70,7 @@ import * as ServerConfig from "../config.ts";
70
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
71
import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
72
import { makeRelayEnvironmentClient } from "../relay/relayEnvironmentClient.ts";
73
+import { loopbackUrlHostForAddress } from "../startupAccess.ts";
74
import {
75
type CliDesiredLinkMode,
76
readCliDesiredCloudLink,
@@ -1193,7 +1194,7 @@ const make = Effect.gen(function* () {
1194
return yield* new CloudLinkInternalError({ operation: "resolve-server-origin" });
1195
}
1196
const registration = yield* registerManagedTunnelRecovery(
1196
- `http://127.0.0.1:${address.port}`,
1197
+ `http://${loopbackUrlHostForAddress(address)}:${address.port}`,
1198
).pipe(
1199
Effect.retry({
1200
times: 2,
apps/server/src/server.ts
+3
-2
@@ -180,6 +180,7 @@ import * as EventStoreV2 from "./orchestration-v2/EventStore.ts";
180
import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
181
import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";
182
import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts";
183
+import { loopbackUrlHostForAddress } from "./startupAccess.ts";
184
import * as OrchestrationHttp from "./orchestration-v2/http.ts";
185
import * as ProjectHttp from "./project/http.ts";
186
import * as NetService from "@t3tools/shared/Net";
@@ -783,7 +784,7 @@ const layerMakeServer = Layer.unwrap(
784
return yield* ensureTailscaleServe({
785
localPort,
786
servePort: config.tailscaleServePort,
786
- localHost: "127.0.0.1",
787
+ localHost: loopbackUrlHostForAddress(address),
788
}).pipe(
789
Effect.as({ localPort, servePort: config.tailscaleServePort }),
790
Effect.tap(() =>
@@ -853,7 +854,7 @@ const layerMakeServer = Layer.unwrap(
854
const server = yield* HttpServer.HttpServer;
855
const address = server.address;
856
if (typeof address === "string" || !("port" in address)) return;
856
- const localOrigin = `http://127.0.0.1:${address.port}`;
857
+ const localOrigin = `http://${loopbackUrlHostForAddress(address)}:${address.port}`;
858
const endpointRuntime = yield* CloudManagedEndpointRuntime.CloudManagedEndpointRuntime;
859
const runManagedTunnelRecovery = yield* makeManagedTunnelRecovery({
860
recover: (config: RelayManagedEndpointRuntimeConfig) =>
apps/server/src/startupAccess.ts
+6
@@ -3,6 +3,7 @@ import * as NodeOS from "node:os";
3
import { QrCode } from "@t3tools/shared/qrCode";
4
import * as Effect from "effect/Effect";
5
import { HttpServer } from "effect/http";
6
+import * as NetAddress from "effect/net/NetAddress";
7
8
import * as ServerConfig from "./config.ts";
9
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
@@ -35,6 +36,11 @@ export const isWildcardHost = (host: string | undefined): boolean =>
36
export const formatHostForUrl = (host: string): string =>
37
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
38
39
+export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string =>
40
+ address._tag === "InetAddressV6" && NetAddress.isLoopback(address.address)
41
+ ? "[::1]"
42
+ : "127.0.0.1";
43
+
44
const normalizeHost = (host: string): string =>
45
host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
46