@devries-cameron20 / t3code Mirror · read-only / commits / 249b6ae469
Fork 0

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, 18:15 UTC

feat(server): devices on the same network reach background services over LAN (#24588)

Co-authored-by: LukeCommits <dyd.lukas.real@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 24, 2026 at 17:16 UTC 249b6ae469ee1d4723a36caebdcc13677b8e497d
15 files changed +546 -63
apps/server/src/cli/config.test.ts
+55
@@ -23,6 +23,13 @@ import * as NetService from "@t3tools/shared/Net";
23 import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
24 import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
25 import * as NodeServices from "@effect/platform-node/NodeServices";
26 +import * as HostProcess from "@t3tools/shared/HostProcess";
27 +import packageJson from "../../package.json" with { type: "json" };
28 +import { ServiceLauncherHostProcess } from "../cloud/serviceLauncherClient.ts";
29 +import {
30 + SERVICE_LAUNCHER_CONTEXT_ENV,
31 + SERVICE_LAUNCHER_PROTOCOL,
32 +} from "../cloud/serviceProtocol.ts";
33 import { deriveServerPaths } from "../config.ts";
34 import { resolveServerConfig } from "./config.ts";
35
@@ -856,4 +863,52 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
863 expect(resolved.otlpLogsUrl).toBeUndefined();
864 }),
865 );
866 +
867 + it.effect("listens on private networks only under the service launcher with no host set", () =>
868 + Effect.gen(function* () {
869 + const { join } = yield* Path.Path;
870 + const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-service-host");
871 + const resolveHost = (input: {
872 + readonly connected: boolean;
873 + readonly env?: Record<string, string>;
874 + }) =>
875 + resolveServerConfig(minimalWebFlags(baseDir), Option.none()).pipe(
876 + Effect.map(({ host, privateNetworkOnly }) => ({ host, privateNetworkOnly })),
877 + Effect.provide(
878 + Layer.mergeAll(
879 + ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
880 + NetService.layer,
881 + ),
882 + ),
883 + Effect.provideService(HostProcess.Environment, {
884 + [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
885 + protocol: SERVICE_LAUNCHER_PROTOCOL,
886 + childVersion: packageJson.version,
887 + }),
888 + }),
889 + Effect.provideService(ServiceLauncherHostProcess, {
890 + connected: input.connected,
891 + send: () => false,
892 + on: () => undefined,
893 + off: () => undefined,
894 + }),
895 + );
896 +
897 + expect(yield* resolveHost({ connected: true })).toEqual({
898 + host: "0.0.0.0",
899 + privateNetworkOnly: true,
900 + });
901 + // `service.env` reaches the server as its environment.
902 + expect(yield* resolveHost({ connected: true, env: { T3CODE_HOST: "127.0.0.1" } })).toEqual({
903 + host: "127.0.0.1",
904 + privateNetworkOnly: undefined,
905 + });
906 + // Without the launcher's IPC channel the context was inherited, e.g. by
907 + // `t3 serve` started from an agent inside the service.
908 + expect(yield* resolveHost({ connected: false })).toEqual({
909 + host: undefined,
910 + privateNetworkOnly: undefined,
911 + });
912 + }),
913 + );
914 });
apps/server/src/cli/config.ts
+19 -7
@@ -22,6 +22,7 @@ import { Argument, Flag } from "effect/cli";
22 import * as CliError from "effect/cli/CliError";
23
24 import { readBootstrapEnvelope } from "../bootstrap.ts";
25 +import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
26 import * as ServerConfig from "../config.ts";
27 import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
28 import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
@@ -403,13 +404,23 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
404 () => 443,
405 );
406 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
406 - const host = Option.getOrElse(
407 - resolveOptionPrecedence(
408 - normalizedFlags.host,
409 - Option.fromUndefinedOr(env.host),
410 - Option.fromUndefinedOr(bootstrap?.host),
411 - ),
412 - () => (mode === "desktop" ? "127.0.0.1" : undefined),
407 + const explicitHost = resolveOptionPrecedence(
408 + normalizedFlags.host,
409 + Option.fromUndefinedOr(env.host),
410 + Option.fromUndefinedOr(bootstrap?.host),
411 + );
412 + // A background service exists to be reached from other devices, so it
413 + // listens on private networks unless `service.env` sets `T3CODE_HOST`.
414 + // Clients then learn its LAN address and prefer it over T3 Connect.
415 + const privateNetworkOnly =
416 + Option.isNone(explicitHost) &&
417 + mode === "web" &&
418 + (yield* resolveServiceLauncherMode().pipe(
419 + Effect.map((launcher) => launcher.managed),
420 + Effect.orElseSucceed(() => false),
421 + ));
422 + const host = Option.getOrElse(explicitHost, () =>
423 + privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined,
424 );
425 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
426
@@ -475,6 +486,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
486 ...derivedPaths,
487 serverTracePath,
488 host,
489 + ...(privateNetworkOnly ? { privateNetworkOnly } : {}),
490 staticDir,
491 devUrl,
492 ...(devAuthToken === undefined ? {} : { devAuthToken }),
apps/server/src/cli/pair.ts
+8 -1
@@ -145,7 +145,10 @@ export class ServePortOccupiedError extends Schema.TaggedError<ServePortOccupied
145 }
146
147 const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
148 - state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);
148 + state.devUrl ??
149 + resolveHeadlessConnectionString(state.host, state.port, {
150 + privateNetworkOnly: state.privateNetworkOnly,
151 + });
152
153 export class DevServerNotProxiableError extends Schema.TaggedError<DevServerNotProxiableError>()(
154 "DevServerNotProxiableError",
@@ -532,6 +535,10 @@ export const pairCommand = Command.make("pair", {
535 notes.push(
536 "This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
537 );
538 + } else if (target.state.privateNetworkOnly) {
539 + notes.push(
540 + "This URL works only from this machine's local network. From elsewhere, re-run with --tailscale or use T3 Connect.",
541 + );
542 }
543 if (target.variant === "dev" && target.state.devUrl === undefined) {
544 notes.push(
apps/server/src/config.ts
+2
@@ -72,6 +72,8 @@ export class ServerConfig extends Context.Service<
72 readonly mode: RuntimeMode;
73 readonly port: number;
74 readonly host: string | undefined;
75 + /** Set when the host was defaulted to a private-network listener for the service. */
76 + readonly privateNetworkOnly?: boolean | undefined;
77 readonly cwd: string;
78 readonly baseDir: string;
79 readonly staticDir: string | undefined;
apps/server/src/environment/DirectEndpoints.test.ts
+17
@@ -148,6 +148,23 @@ describe("resolveBoundEndpoints", () => {
148 resolveBoundEndpoints({ host: "203.0.113.20", port: 3773, interfaces: INTERFACES }),
149 ).toEqual([]);
150 });
151 +
152 + it("reports only the tailnet address on a cloud VM, whose private network no client shares", () => {
153 + expect(
154 + resolveBoundEndpoints({
155 + host: "0.0.0.0",
156 + port: 3773,
157 + interfaces: INTERFACES,
158 + onCloudVm: true,
159 + }),
160 + ).toEqual([{ kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" }]);
161 + });
162 +
163 + it("never reports an IPv4-mapped host, which can name the client's own loopback", () => {
164 + expect(
165 + resolveBoundEndpoints({ host: "::ffff:127.0.0.1", port: 3773, interfaces: INTERFACES }),
166 + ).toEqual([]);
167 + });
168 });
169
170 const TAILSCALE_STATUS_JSON = JSON.stringify({
apps/server/src/environment/DirectEndpoints.ts
+52 -19
@@ -14,10 +14,16 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14 import * as NodeNet from "node:net";
15 import * as NodeOS from "node:os";
16
17 -import { isPrivateNetworkHost, isTailnetHost } from "@t3tools/shared/hostClassification";
17 +import { isTailnetHost } from "@t3tools/shared/hostClassification";
18
19 import * as ServerConfig from "../config.ts";
20 -import { formatHostForUrl, isLoopbackHost, isWildcardHost } from "../startupAccess.ts";
20 +import {
21 + formatHostForUrl,
22 + isLoopbackHost,
23 + isPrivateNetworkAddress,
24 + isWildcardHost,
25 + VIRTUAL_INTERFACE,
26 +} from "../startupAccess.ts";
27
28 type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
29
@@ -40,19 +46,7 @@ export class DirectEndpoints extends Context.Service<
46 * (`server.local`) can resolve to a different machine on each client's network.
47 */
48 const isAdvertisableAddress = (address: string): boolean =>
43 - NodeNet.isIPv4(address) &&
44 - !address.startsWith("127.") &&
45 - !address.startsWith("169.254.") &&
46 - isPrivateNetworkHost(address);
47 -
48 -/**
49 - * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and
50 - * macOS's `bridge100`+) have private addresses only this machine reaches. A
51 - * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so
52 - * it stays listed.
53 - */
54 -const VIRTUAL_INTERFACE =
55 - /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge1\d\d)/;
49 + NodeNet.isIPv4(address) && !address.startsWith("127.") && isPrivateNetworkAddress(address);
50
51 /**
52 * Tailscale's own interface: `tailscale0` on Linux, "Tailscale" on Windows.
@@ -71,6 +65,8 @@ export function resolveBoundEndpoints(input: {
65 readonly host: string | undefined;
66 readonly port: number;
67 readonly interfaces: NetworkInterfacesMap;
68 + /** A cloud VM's private network is its provider's, which no client shares. */
69 + readonly onCloudVm?: boolean;
70 }): ReadonlyArray<ServerDirectEndpoint> {
71 if (isLoopbackHost(input.host)) return [];
72 const tailscaleAddresses = new Set(
@@ -87,17 +83,53 @@ export function resolveBoundEndpoints(input: {
83 )
84 .map((entry) => entry.address)
85 : [input.host!].filter(isAdvertisableAddress);
90 - return [...new Set(addresses)].map((address) => ({
91 - kind: tailscaleAddresses.has(address) ? "tailnet" : "lan",
92 - httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,
93 - }));
86 + return [...new Set(addresses)]
87 + .filter((address) => !input.onCloudVm || tailscaleAddresses.has(address))
88 + .map((address) => ({
89 + kind: tailscaleAddresses.has(address) ? "tailnet" : "lan",
90 + httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,
91 + }));
92 }
93
94 +/**
95 + * AWS, GCP, Azure, DigitalOcean, Hetzner, Linode, Vultr, and Oracle all serve
96 + * instance metadata at this address. A plain TCP connect skips HTTP proxies,
97 + * which would otherwise answer for a machine that is not in a cloud.
98 + */
99 +const CLOUD_METADATA_ADDRESS = "169.254.169.254";
100 +const CLOUD_METADATA_TIMEOUT_MS = 300;
101 +
102 +const probeCloudMetadata = Effect.callback<boolean>((resume) => {
103 + const socket = NodeNet.connect({
104 + host: CLOUD_METADATA_ADDRESS,
105 + port: 80,
106 + timeout: CLOUD_METADATA_TIMEOUT_MS,
107 + });
108 + let settled = false;
109 + const settle = (found: boolean) => {
110 + if (settled) return;
111 + settled = true;
112 + socket.destroy();
113 + resume(Effect.succeed(found));
114 + };
115 + socket.once("connect", () => settle(true));
116 + socket.once("timeout", () => settle(false));
117 + socket.once("error", () => settle(false));
118 + return Effect.sync(() => socket.destroy());
119 +});
120 +
121 /** @public Service construction is part of the canonical Effect module API. */
122 export const make = Effect.gen(function* () {
123 const config = yield* ServerConfig.ServerConfig;
124 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
125 const httpClient = yield* HttpClient.HttpClient;
126 + // Only the service default listens on every interface without being asked,
127 + // so only it checks once whether it runs in a cloud. The check starts now so
128 + // the first client does not wait for its timeout.
129 + const onCloudVm = config.privateNetworkOnly
130 + ? yield* Effect.cached(probeCloudMetadata)
131 + : Effect.succeed(false);
132 + yield* Effect.forkDetach(onCloudVm);
133
134 const resolve = Effect.gen(function* () {
135 const endpoints = [
@@ -105,6 +137,7 @@ export const make = Effect.gen(function* () {
137 host: config.host,
138 port: config.port,
139 interfaces: NodeOS.networkInterfaces(),
140 + onCloudVm: yield* onCloudVm,
141 }),
142 ];
143 // Tailscale Serve terminates HTTPS on the tailnet name and forwards to
apps/server/src/server.ts
+14 -2
@@ -186,7 +186,7 @@ import * as EventStoreV2 from "./orchestration-v2/EventStore.ts";
186 import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
187 import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";
188 import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts";
189 -import { loopbackUrlHostForAddress } from "./startupAccess.ts";
189 +import { acceptsPrivateNetworkConnection, loopbackUrlHostForAddress } from "./startupAccess.ts";
190 import * as OrchestrationHttp from "./orchestration-v2/http.ts";
191 import * as ProjectHttp from "./project/http.ts";
192 import * as NetService from "@t3tools/shared/Net";
@@ -300,7 +300,19 @@ const layerHttpServer = Layer.unwrap(
300 Effect.gen(function* () {
301 const config = yield* ServerConfig.ServerConfig;
302 return NodeHttpServer.layer(
303 - () => rejectRequestsUntilServing(guardHttpResponseWriteErrors(NodeHttp.createServer())),
303 + () => {
304 + const server = rejectRequestsUntilServing(
305 + guardHttpResponseWriteErrors(NodeHttp.createServer()),
306 + );
307 + if (config.privateNetworkOnly) {
308 + server.on("connection", (socket) => {
309 + if (!acceptsPrivateNetworkConnection(socket)) {
310 + socket.destroy();
311 + }
312 + });
313 + }
314 + return server;
315 + },
316 {
317 host: config.host ?? "127.0.0.1",
318 port: config.port,
apps/server/src/serverRuntimeState.ts
+6 -1
@@ -14,6 +14,7 @@ export const PersistedServerRuntimeState = Schema.Struct({
14 pid: Schema.Int,
15 ownerId: Schema.optional(Schema.String),
16 host: Schema.optional(Schema.String),
17 + privateNetworkOnly: Schema.optional(Schema.Boolean),
18 port: Schema.Int,
19 origin: Schema.String,
20 // Dev is single-origin: browsers must pair through this URL, not `origin`.
@@ -51,7 +52,10 @@ const runtimeOriginForConfig = (
52 };
53
54 export const makePersistedServerRuntimeState = (input: {
54 - readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
55 + readonly config: Pick<
56 + ServerConfig.ServerConfig["Service"],
57 + "host" | "privateNetworkOnly" | "devUrl"
58 + >;
59 readonly port: number;
60 readonly serviceManaged?: boolean;
61 }): Effect.Effect<PersistedServerRuntimeState> =>
@@ -59,6 +63,7 @@ export const makePersistedServerRuntimeState = (input: {
63 version: 1,
64 pid: process.pid,
65 ...(input.config.host ? { host: input.config.host } : {}),
66 + ...(input.config.privateNetworkOnly ? { privateNetworkOnly: true } : {}),
67 port: input.port,
68 origin: runtimeOriginForConfig(input.config, input.port),
69 ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
apps/server/src/startupAccess.test.ts
+67 -22
@@ -1,30 +1,75 @@
1 -import { expect, it } from "@effect/vitest";
1 +import type * as NodeOS from "node:os";
2
3 -import { resolveHeadlessConnectionString } from "./startupAccess.ts";
3 +import { describe, expect, it } from "@effect/vitest";
4 +
5 +import {
6 + acceptsPrivateNetworkConnection,
7 + resolveHeadlessConnectionString,
8 +} from "./startupAccess.ts";
9 +
10 +const ipv4 = (address: string, internal = false): NodeOS.NetworkInterfaceInfo => ({
11 + address,
12 + netmask: "255.255.255.0",
13 + family: "IPv4",
14 + mac: "00:00:00:00:00:00",
15 + internal,
16 + cidr: `${address}/24`,
17 +});
18
19 it("resolves wildcard hosts to a concrete external interface when one is available", () => {
20 const connectionString = resolveHeadlessConnectionString("0.0.0.0", 3773, {
7 - en0: [
8 - {
9 - address: "192.168.1.42",
10 - netmask: "255.255.255.0",
11 - family: "IPv4",
12 - mac: "00:00:00:00:00:00",
13 - internal: false,
14 - cidr: "192.168.1.42/24",
15 - },
16 - ],
17 - lo0: [
18 - {
19 - address: "127.0.0.1",
20 - netmask: "255.0.0.0",
21 - family: "IPv4",
22 - mac: "00:00:00:00:00:00",
23 - internal: true,
24 - cidr: "127.0.0.1/8",
25 - },
26 - ],
21 + interfaces: { en0: [ipv4("192.168.1.42")], lo0: [ipv4("127.0.0.1", true)] },
22 });
23
24 expect(connectionString).toBe("http://192.168.1.42:3773");
25 });
26 +
27 +it("skips public and container addresses for a private-network listener", () => {
28 + const interfaces = {
29 + eth0: [ipv4("203.0.113.7")],
30 + docker0: [ipv4("172.17.0.1")],
31 + bridge200: [ipv4("192.168.64.1")],
32 + eth1: [ipv4("10.0.0.5")],
33 + };
34 +
35 + expect(resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces })).toBe(
36 + "http://203.0.113.7:3773",
37 + );
38 + expect(
39 + resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces, privateNetworkOnly: true }),
40 + ).toBe("http://10.0.0.5:3773");
41 + expect(
42 + resolveHeadlessConnectionString("0.0.0.0", 3773, {
43 + interfaces: { eth0: [ipv4("203.0.113.7")] },
44 + privateNetworkOnly: true,
45 + }),
46 + ).toBe("http://localhost:3773");
47 +});
48 +
49 +it("prefers a LAN address over a tailnet one for a private-network pairing URL", () => {
50 + expect(
51 + resolveHeadlessConnectionString("0.0.0.0", 3773, {
52 + interfaces: { tailscale0: [ipv4("100.101.102.103")], en0: [ipv4("192.168.1.42")] },
53 + privateNetworkOnly: true,
54 + }),
55 + ).toBe("http://192.168.1.42:3773");
56 +});
57 +
58 +describe("acceptsPrivateNetworkConnection", () => {
59 + const accepts = (localAddress: string | undefined, remoteAddress: string | undefined) =>
60 + acceptsPrivateNetworkConnection({ localAddress, remoteAddress });
61 +
62 + it("serves loopback, LAN, and tailnet clients", () => {
63 + expect(accepts("127.0.0.1", "127.0.0.1")).toBe(true);
64 + expect(accepts("::ffff:192.168.1.20", "::ffff:192.168.1.31")).toBe(true);
65 + expect(accepts("100.101.102.103", "100.90.1.2")).toBe(true);
66 + });
67 +
68 + it("closes connections from or to a public address", () => {
69 + // A cloud VM's public address is NATed to a private interface address.
70 + expect(accepts("172.31.4.10", "203.0.113.7")).toBe(false);
71 + expect(accepts("203.0.113.7", "192.168.1.31")).toBe(false);
72 + expect(accepts("169.254.10.1", "169.254.10.2")).toBe(false);
73 + expect(accepts(undefined, "192.168.1.31")).toBe(false);
74 + });
75 +});
apps/server/src/startupAccess.ts
+62 -6
@@ -1,5 +1,7 @@
1 +import * as NodeNet from "node:net";
2 import * as NodeOS from "node:os";
3
4 +import { isPrivateNetworkHost, isSharedAddressSpaceHost } from "@t3tools/shared/hostClassification";
5 import { QrCode } from "@t3tools/shared/qrCode";
6 import * as Effect from "effect/Effect";
7 import { HttpServer } from "effect/http";
@@ -36,6 +38,38 @@ export const isWildcardHost = (host: string | undefined): boolean =>
38 export const formatHostForUrl = (host: string): string =>
39 host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
40
41 +/**
42 + * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and
43 + * macOS's `bridge100`+) have private addresses only this machine reaches. A
44 + * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so
45 + * it stays listed.
46 + */
47 +export const VIRTUAL_INTERFACE =
48 + /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/;
49 +
50 +/**
51 + * Loopback or private-range IPv4 (LAN, tailnet, CGNAT), not link-local, in
52 + * plain or IPv4-mapped IPv6 form.
53 + */
54 +export const isPrivateNetworkAddress = (address: string): boolean => {
55 + const ipv4 = address.replace(/^::ffff:/i, "");
56 + return NodeNet.isIPv4(ipv4) && !ipv4.startsWith("169.254.") && isPrivateNetworkHost(ipv4);
57 +};
58 +
59 +/**
60 + * A private-network listener binds every interface but serves only
61 + * connections that stay on loopback, a LAN, or the tailnet. Both ends must be
62 + * private: a cloud VM or a router port forward hands public clients to a
63 + * private local address.
64 + */
65 +export const acceptsPrivateNetworkConnection = (socket: {
66 + readonly localAddress?: string | undefined;
67 + readonly remoteAddress?: string | undefined;
68 +}): boolean =>
69 + [socket.localAddress, socket.remoteAddress].every(
70 + (address) => address !== undefined && isPrivateNetworkAddress(address),
71 + );
72 +
73 export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string =>
74 address._tag === "InetAddressV6" && NetAddress.isLoopback(address.address)
75 ? "[::1]"
@@ -50,7 +84,8 @@ const isIpv6Family = (family: string | number): boolean => family === "IPv6" ||
84
85 const resolveHeadlessConnectionHost = (
86 host: string | undefined,
53 - interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),
87 + interfaces: NetworkInterfacesMap,
88 + privateNetworkOnly: boolean,
89 ): string => {
90 if (!host) {
91 return "localhost";
@@ -60,13 +95,26 @@ const resolveHeadlessConnectionHost = (
95 return normalizeHost(host);
96 }
97
63 - const interfaceEntries = Object.values(interfaces).flatMap((entries) => entries ?? []);
64 - const externalIpv4 = interfaceEntries.find(
65 - (entry) => !entry.internal && isIpv4Family(entry.family),
98 + const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) =>
99 + privateNetworkOnly && VIRTUAL_INTERFACE.test(name) ? [] : (entries ?? []),
100 );
101 + const externalIpv4Entries = interfaceEntries.filter(
102 + (entry) =>
103 + !entry.internal &&
104 + isIpv4Family(entry.family) &&
105 + (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)),
106 + );
107 + // A tailnet or other CGNAT address reaches fewer devices than the LAN one.
108 + const externalIpv4 = privateNetworkOnly
109 + ? (externalIpv4Entries.find((entry) => !isSharedAddressSpaceHost(entry.address)) ??
110 + externalIpv4Entries[0])
111 + : externalIpv4Entries[0];
112 if (externalIpv4) {
113 return externalIpv4.address;
114 }
115 + if (privateNetworkOnly) {
116 + return "localhost";
117 + }
118
119 const externalIpv6 = interfaceEntries.find(
120 (entry) => !entry.internal && isIpv6Family(entry.family),
@@ -77,9 +125,16 @@ const resolveHeadlessConnectionHost = (
125 export const resolveHeadlessConnectionString = (
126 host: string | undefined,
127 port: number,
80 - interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),
128 + options: {
129 + readonly interfaces?: NetworkInterfacesMap;
130 + readonly privateNetworkOnly?: boolean | undefined;
131 + } = {},
132 ): string => {
82 - const connectionHost = resolveHeadlessConnectionHost(host, interfaces);
133 + const connectionHost = resolveHeadlessConnectionHost(
134 + host,
135 + options.interfaces ?? NodeOS.networkInterfaces(),
136 + options.privateNetworkOnly === true,
137 + );
138 return `http://${formatHostForUrl(connectionHost)}:${port}`;
139 };
140
@@ -143,6 +198,7 @@ export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessI
198 const connectionString = resolveHeadlessConnectionString(
199 serverConfig.host,
200 resolveListeningPort(httpServer.address, serverConfig.port),
201 + { privateNetworkOnly: serverConfig.privateNetworkOnly },
202 );
203 const issued = yield* serverAuth.issueStartupPairingCredential();
204
docs/internals/remote.md
+9
@@ -54,6 +54,15 @@ dropped, which is how a changed LAN address replaces the old one; routes the
54 user saved are never touched. The reported addresses are hints like any advertised endpoint, so a
55 learned route still has to answer as this environment before it is used.
56
57 +A background service with no configured host is what makes this work for
58 +headless machines. It listens on every IPv4 interface and closes each
59 +connection unless both addresses of the direct peer are loopback, private, or
60 +tailnet IPv4. That keeps a VPS's public address closed, including a cloud VM
61 +whose public address is NATed to a private interface. It is not a firewall:
62 +T3 Connect and Tailscale Serve reach the server over loopback by design, and a
63 +proxy that rewrites the source address looks private. One listener per address would
64 +miss a DHCP change, and the wildcard keeps the reported addresses current.
65 +
66 Pull request routing trust covers the whole route list. Adding or changing a route
67 revokes it; reordering does not, because the same addresses remain trusted.
68
docs/user/background-service.md
+10
@@ -40,6 +40,16 @@ downloaded versions after showing you the list and asking once. Your projects,
40 threads, and settings under `~/.t3/userdata` are kept, along with `service.env`
41 under T3 home. Pass `--yes` from a script.
42
43 +## Local network access
44 +
45 +The service listens on your local network and Tailscale addresses, so the
46 +desktop and mobile apps on the same network connect directly instead of through
47 +T3 Connect. The hosted web app at app.t3.codes stays on T3 Connect, because
48 +browsers block plain HTTP from an HTTPS page. The service does not answer on
49 +public addresses, and every device still needs to pair or sign in. To keep the service reachable from this machine only, set
50 +`T3CODE_HOST=127.0.0.1` in `service.env` (below). Any `T3CODE_HOST` value
51 +replaces this default.
52 +
53 ## Configure the service environment
54
55 Put custom environment variables in `service.env` under the service's T3 home
docs/user/remote-access.md
+2 -1
@@ -80,7 +80,8 @@ machine's current LAN and Tailscale addresses and adds them as routes, so
80 pairing once through T3 Connect is enough to use the LAN at home. When the
81 machine's LAN address changes, for example after it joins another Wi-Fi network,
82 the learned route follows it. The machine must allow network access for its LAN
83 -address to be learned. You can reorder a learned route, but not remove it; it
83 +address to be learned. The [background service](./background-service.md#local-network-access)
84 +allows it on private networks by default. You can reorder a learned route, but not remove it; it
85 goes away with the route it was learned through, or when the machine stops
86 reporting that address.
87
packages/client-runtime/src/connection/driver.ts
+24 -4
@@ -41,6 +41,10 @@ export interface EnvironmentConnectionLease {
41 export type RouteCheck = "answered" | "silent" | "unchecked";
42
43 const ROUTE_CHECK_TIMEOUT_MS = 2_500;
44 +// Preferred direct routes share one head start, so a relay connection does not
45 +// wait the full probe timeout for a LAN the device has already left. A route
46 +// that misses it connects over relay, then upgrades with a second reconnect.
47 +const ROUTE_CHECK_HEAD_START_MS = 500;
48
49 export class ConnectionDriver extends Context.Service<
50 ConnectionDriver,
@@ -72,6 +76,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
76 routes.length === 1
77 ? []
78 : yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));
79 + const headStart = yield* Effect.forkChild(Effect.sleep(ROUTE_CHECK_HEAD_START_MS));
80 const attemptScope = yield* Scope.Scope;
81 let transient: ConnectionAttemptError | undefined;
82 let blocked: ConnectionAttemptError | undefined;
@@ -89,11 +94,17 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
94 }
95 return result;
96 });
92 - const silent: Array<ConnectionRoute> = [];
97 + const silent: Array<{ readonly route: ConnectionRoute; readonly index: number }> = [];
98 for (const [index, route] of routes.entries()) {
94 - const check = checks.length === 0 ? "unchecked" : yield* Fiber.join(checks[index]!);
99 + const check =
100 + checks.length === 0
101 + ? "unchecked"
102 + : yield* Effect.raceFirst(
103 + Fiber.join(checks[index]!),
104 + Fiber.join(headStart).pipe(Effect.as<RouteCheck>("silent")),
105 + );
106 if (check === "silent") {
96 - silent.push(route);
107 + silent.push({ route, index });
108 continue;
109 }
110 const result = yield* attempt(route);
@@ -101,7 +112,16 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
112 // An incompatible server is the same server on every route.
113 if (result.failure.reason === "unsupported") return yield* result.failure;
114 }
104 - for (const route of silent) {
115 + // A slow route that answered after the head start goes before one that is
116 + // still dead, which can hold an attempt open far longer than its probe.
117 + const late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), {
118 + concurrency: "unbounded",
119 + });
120 + const retry = [
121 + ...silent.filter((_, position) => late[position] !== "silent"),
122 + ...silent.filter((_, position) => late[position] === "silent"),
123 + ];
124 + for (const { route } of retry) {
125 const result = yield* attempt(route);
126 if (result._tag === "Success") return result.success;
127 if (result.failure.reason === "unsupported") return yield* result.failure;
packages/client-runtime/src/connection/supervisor.test.ts
+199
@@ -1022,6 +1022,205 @@ describe("EnvironmentSupervisor", () => {
1022 });
1023
1024 describe("EnvironmentSupervisor routes", () => {
1025 + it.effect("connects over relay before a slow LAN reachability check times out", () =>
1026 + Effect.gen(function* () {
1027 + const checkingLan = yield* Deferred.make<void>();
1028 + const harness = yield* makeHarness({
1029 + checkRoute: (route) =>
1030 + route.target._tag === "BearerConnectionTarget"
1031 + ? Deferred.succeed(checkingLan, undefined).pipe(
1032 + Effect.andThen(Effect.sleep("2500 millis")),
1033 + Effect.as("silent" as const),
1034 + )
1035 + : Effect.succeed("unchecked"),
1036 + prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
1037 + });
1038 + const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
1039 + initiallyDesired: true,
1040 + }).pipe(Effect.provide(harness.dependencies));
1041 +
1042 + yield* Deferred.await(checkingLan);
1043 + yield* TestClock.adjust("500 millis");
1044 + yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1045 + expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
1046 + "RelayConnectionTarget",
1047 + );
1048 + expect(yield* Ref.get(harness.prepareCount)).toBe(1);
1049 + }).pipe(Effect.provide(TestClock.layer())),
1050 + );
1051 +
1052 + it.effect("shares one head start across several slow LAN routes", () =>
1053 + Effect.gen(function* () {
1054 + const secondLanTarget = new BearerConnectionTarget({
1055 + environmentId: TARGET.environmentId,
1056 + label: TARGET.label,
1057 + connectionId: "bearer:second-lan",
1058 + });
1059 + const entry: ConnectionCatalogEntry = {
1060 + ...LAN_THEN_RELAY_ENTRY,
1061 + alternateRoutes: [
1062 + {
1063 + target: secondLanTarget,
1064 + profile: Option.some(
1065 + new BearerConnectionProfile({
1066 + connectionId: secondLanTarget.connectionId,
1067 + environmentId: TARGET.environmentId,
1068 + label: TARGET.label,
1069 + httpBaseUrl: "http://192.168.56.1:3773/",
1070 + wsBaseUrl: "ws://192.168.56.1:3773/",
1071 + }),
1072 + ),
1073 + },
1074 + { target: RELAY_TARGET, profile: Option.none() },
1075 + ],
1076 + };
1077 + const checking = yield* Ref.make(0);
1078 + const checkingLans = yield* Deferred.make<void>();
1079 + const harness = yield* makeHarness({
1080 + checkRoute: (route) =>
1081 + route.target._tag === "BearerConnectionTarget"
1082 + ? Ref.updateAndGet(checking, (count) => count + 1).pipe(
1083 + Effect.flatMap((count) =>
1084 + count === 2 ? Deferred.succeed(checkingLans, undefined) : Effect.void,
1085 + ),
1086 + Effect.andThen(Effect.sleep("2500 millis")),
1087 + Effect.as("silent" as const),
1088 + )
1089 + : Effect.succeed("unchecked"),
1090 + prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
1091 + });
1092 + const supervisor = yield* EnvironmentSupervisor.make(entry, {
1093 + initiallyDesired: true,
1094 + }).pipe(Effect.provide(harness.dependencies));
1095 +
1096 + yield* Deferred.await(checkingLans);
1097 + yield* TestClock.adjust("500 millis");
1098 + yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1099 + expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
1100 + "RelayConnectionTarget",
1101 + );
1102 + }).pipe(Effect.provide(TestClock.layer())),
1103 + );
1104 +
1105 + it.effect("still prefers a LAN route that responds within its head start", () =>
1106 + Effect.gen(function* () {
1107 + const checkingLan = yield* Deferred.make<void>();
1108 + const harness = yield* makeHarness({
1109 + checkRoute: (route) =>
1110 + route.target._tag === "BearerConnectionTarget"
1111 + ? Deferred.succeed(checkingLan, undefined).pipe(
1112 + Effect.andThen(Effect.sleep("100 millis")),
1113 + Effect.as("answered" as const),
1114 + )
1115 + : Effect.succeed("unchecked"),
1116 + prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
1117 + });
1118 + const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
1119 + initiallyDesired: true,
1120 + }).pipe(Effect.provide(harness.dependencies));
1121 +
1122 + yield* Deferred.await(checkingLan);
1123 + yield* TestClock.adjust("100 millis");
1124 + yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1125 + expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
1126 + "BearerConnectionTarget",
1127 + );
1128 + expect(yield* Ref.get(harness.prepareCount)).toBe(1);
1129 + }).pipe(Effect.provide(TestClock.layer())),
1130 + );
1131 +
1132 + it.effect("tries a slow tailnet route that answered before a dead LAN route", () =>
1133 + Effect.gen(function* () {
1134 + const tailnetTarget = new BearerConnectionTarget({
1135 + environmentId: TARGET.environmentId,
1136 + label: TARGET.label,
1137 + connectionId: "bearer:tailnet",
1138 + });
1139 + // No relay: a Tailscale-only client away from the LAN.
1140 + const entry: ConnectionCatalogEntry = {
1141 + ...LAN_THEN_RELAY_ENTRY,
1142 + alternateRoutes: [
1143 + {
1144 + target: tailnetTarget,
1145 + profile: Option.some(
1146 + new BearerConnectionProfile({
1147 + connectionId: tailnetTarget.connectionId,
1148 + environmentId: TARGET.environmentId,
1149 + label: TARGET.label,
1150 + httpBaseUrl: "http://100.100.1.2:3773/",
1151 + wsBaseUrl: "ws://100.100.1.2:3773/",
1152 + network: "tailscale",
1153 + }),
1154 + ),
1155 + },
1156 + ],
1157 + };
1158 + const checking = yield* Ref.make(0);
1159 + const checkingBoth = yield* Deferred.make<void>();
1160 + const harness = yield* makeHarness({
1161 + checkRoute: (route) =>
1162 + Ref.updateAndGet(checking, (count) => count + 1).pipe(
1163 + Effect.flatMap((count) =>
1164 + count === 2 ? Deferred.succeed(checkingBoth, undefined) : Effect.void,
1165 + ),
1166 + Effect.andThen(
1167 + connectionRouteId(route.target) === LAN_TARGET.connectionId
1168 + ? Effect.sleep("2500 millis").pipe(Effect.as("silent" as const))
1169 + : Effect.sleep("700 millis").pipe(Effect.as("answered" as const)),
1170 + ),
1171 + ),
1172 + // The dead LAN address never answers the connection itself either.
1173 + prepare: (_attempt, target) =>
1174 + target._tag === "BearerConnectionTarget" &&
1175 + target.connectionId === LAN_TARGET.connectionId
1176 + ? Effect.never
1177 + : Effect.succeed(preparedFor(target)),
1178 + });
1179 + const supervisor = yield* EnvironmentSupervisor.make(entry, {
1180 + initiallyDesired: true,
1181 + }).pipe(Effect.provide(harness.dependencies));
1182 +
1183 + yield* Deferred.await(checkingBoth);
1184 + yield* TestClock.adjust("2500 millis");
1185 + yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1186 + expect(
1187 + connectionRouteId(
1188 + Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target,
1189 + ),
1190 + ).toBe("bearer:tailnet");
1191 + }).pipe(Effect.provide(TestClock.layer())),
1192 + );
1193 +
1194 + it.effect("still tries a slow LAN route when relay fails", () =>
1195 + Effect.gen(function* () {
1196 + const checkingLan = yield* Deferred.make<void>();
1197 + const attempted: string[] = [];
1198 + const harness = yield* makeHarness({
1199 + checkRoute: (route) =>
1200 + route.target._tag === "BearerConnectionTarget"
1201 + ? Deferred.succeed(checkingLan, undefined).pipe(
1202 + Effect.andThen(Effect.sleep("2500 millis")),
1203 + Effect.as("answered" as const),
1204 + )
1205 + : Effect.succeed("unchecked"),
1206 + prepare: (_attempt, target) => {
1207 + attempted.push(target._tag);
1208 + return target._tag === "RelayConnectionTarget"
1209 + ? Effect.fail(blocked("Sign in to T3 Connect."))
1210 + : Effect.succeed(preparedFor(target));
1211 + },
1212 + });
1213 + const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
1214 + initiallyDesired: true,
1215 + }).pipe(Effect.provide(harness.dependencies));
1216 +
1217 + yield* Deferred.await(checkingLan);
1218 + yield* TestClock.adjust("2500 millis");
1219 + yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1220 + expect(attempted).toEqual(["RelayConnectionTarget", "BearerConnectionTarget"]);
1221 + }).pipe(Effect.provide(TestClock.layer())),
1222 + );
1223 +
1224 it.effect("skips a silent LAN route and connects over T3 Connect", () =>
1225 Effect.gen(function* () {
1226 const harness = yield* makeHarness({