Skip to content
TypeScript

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

Theo Browne249b6ae469ee
diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts
index 8de5df4b189..076b50be67b 100644
--- a/apps/server/src/cli/config.test.ts
+++ b/apps/server/src/cli/config.test.ts
@@ -23,6 +23,13 @@ import * as NetService from "@t3tools/shared/Net";
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
import * as NodeServices from "@effect/platform-node/NodeServices";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import packageJson from "../../package.json" with { type: "json" };
+import { ServiceLauncherHostProcess } from "../cloud/serviceLauncherClient.ts";
+import {
+ SERVICE_LAUNCHER_CONTEXT_ENV,
+ SERVICE_LAUNCHER_PROTOCOL,
+} from "../cloud/serviceProtocol.ts";
import { deriveServerPaths } from "../config.ts";
import { resolveServerConfig } from "./config.ts";
@@ -856,4 +863,52 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
expect(resolved.otlpLogsUrl).toBeUndefined();
}),
);
+
+ it.effect("listens on private networks only under the service launcher with no host set", () =>
+ Effect.gen(function* () {
+ const { join } = yield* Path.Path;
+ const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-service-host");
+ const resolveHost = (input: {
+ readonly connected: boolean;
+ readonly env?: Record<string, string>;
+ }) =>
+ resolveServerConfig(minimalWebFlags(baseDir), Option.none()).pipe(
+ Effect.map(({ host, privateNetworkOnly }) => ({ host, privateNetworkOnly })),
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
+ NetService.layer,
+ ),
+ ),
+ Effect.provideService(HostProcess.Environment, {
+ [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
+ protocol: SERVICE_LAUNCHER_PROTOCOL,
+ childVersion: packageJson.version,
+ }),
+ }),
+ Effect.provideService(ServiceLauncherHostProcess, {
+ connected: input.connected,
+ send: () => false,
+ on: () => undefined,
+ off: () => undefined,
+ }),
+ );
+
+ expect(yield* resolveHost({ connected: true })).toEqual({
+ host: "0.0.0.0",
+ privateNetworkOnly: true,
+ });
+ // `service.env` reaches the server as its environment.
+ expect(yield* resolveHost({ connected: true, env: { T3CODE_HOST: "127.0.0.1" } })).toEqual({
+ host: "127.0.0.1",
+ privateNetworkOnly: undefined,
+ });
+ // Without the launcher's IPC channel the context was inherited, e.g. by
+ // `t3 serve` started from an agent inside the service.
+ expect(yield* resolveHost({ connected: false })).toEqual({
+ host: undefined,
+ privateNetworkOnly: undefined,
+ });
+ }),
+ );
});
diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts
index 0ac80602221..00621e332de 100644
--- a/apps/server/src/cli/config.ts
+++ b/apps/server/src/cli/config.ts
@@ -22,6 +22,7 @@ import { Argument, Flag } from "effect/cli";
import * as CliError from "effect/cli/CliError";
import { readBootstrapEnvelope } from "../bootstrap.ts";
+import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
import * as ServerConfig from "../config.ts";
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
@@ -403,13 +404,23 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
() => 443,
);
const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
- const host = Option.getOrElse(
- resolveOptionPrecedence(
- normalizedFlags.host,
- Option.fromUndefinedOr(env.host),
- Option.fromUndefinedOr(bootstrap?.host),
- ),
- () => (mode === "desktop" ? "127.0.0.1" : undefined),
+ const explicitHost = resolveOptionPrecedence(
+ normalizedFlags.host,
+ Option.fromUndefinedOr(env.host),
+ Option.fromUndefinedOr(bootstrap?.host),
+ );
+ // A background service exists to be reached from other devices, so it
+ // listens on private networks unless `service.env` sets `T3CODE_HOST`.
+ // Clients then learn its LAN address and prefer it over T3 Connect.
+ const privateNetworkOnly =
+ Option.isNone(explicitHost) &&
+ mode === "web" &&
+ (yield* resolveServiceLauncherMode().pipe(
+ Effect.map((launcher) => launcher.managed),
+ Effect.orElseSucceed(() => false),
+ ));
+ const host = Option.getOrElse(explicitHost, () =>
+ privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined,
);
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
@@ -475,6 +486,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
...derivedPaths,
serverTracePath,
host,
+ ...(privateNetworkOnly ? { privateNetworkOnly } : {}),
staticDir,
devUrl,
...(devAuthToken === undefined ? {} : { devAuthToken }),
diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts
index ec30508d2b7..ea492705973 100644
--- a/apps/server/src/cli/pair.ts
+++ b/apps/server/src/cli/pair.ts
@@ -145,7 +145,10 @@ export class ServePortOccupiedError extends Schema.TaggedError<ServePortOccupied
}
const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>
- state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);
+ state.devUrl ??
+ resolveHeadlessConnectionString(state.host, state.port, {
+ privateNetworkOnly: state.privateNetworkOnly,
+ });
export class DevServerNotProxiableError extends Schema.TaggedError<DevServerNotProxiableError>()(
"DevServerNotProxiableError",
@@ -532,6 +535,10 @@ export const pairCommand = Command.make("pair", {
notes.push(
"This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
);
+ } else if (target.state.privateNetworkOnly) {
+ notes.push(
+ "This URL works only from this machine's local network. From elsewhere, re-run with --tailscale or use T3 Connect.",
+ );
}
if (target.variant === "dev" && target.state.devUrl === undefined) {
notes.push(
diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts
index d0bc87cf0ff..11628ae95c3 100644
--- a/apps/server/src/config.ts
+++ b/apps/server/src/config.ts
@@ -72,6 +72,8 @@ export class ServerConfig extends Context.Service<
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
+ /** Set when the host was defaulted to a private-network listener for the service. */
+ readonly privateNetworkOnly?: boolean | undefined;
readonly cwd: string;
readonly baseDir: string;
readonly staticDir: string | undefined;
diff --git a/apps/server/src/environment/DirectEndpoints.test.ts b/apps/server/src/environment/DirectEndpoints.test.ts
index 793f2d1d59f..08b16959e86 100644
--- a/apps/server/src/environment/DirectEndpoints.test.ts
+++ b/apps/server/src/environment/DirectEndpoints.test.ts
@@ -148,6 +148,23 @@ describe("resolveBoundEndpoints", () => {
resolveBoundEndpoints({ host: "203.0.113.20", port: 3773, interfaces: INTERFACES }),
).toEqual([]);
});
+
+ it("reports only the tailnet address on a cloud VM, whose private network no client shares", () => {
+ expect(
+ resolveBoundEndpoints({
+ host: "0.0.0.0",
+ port: 3773,
+ interfaces: INTERFACES,
+ onCloudVm: true,
+ }),
+ ).toEqual([{ kind: "tailnet", httpBaseUrl: "http://100.101.102.103:3773/" }]);
+ });
+
+ it("never reports an IPv4-mapped host, which can name the client's own loopback", () => {
+ expect(
+ resolveBoundEndpoints({ host: "::ffff:127.0.0.1", port: 3773, interfaces: INTERFACES }),
+ ).toEqual([]);
+ });
});
const TAILSCALE_STATUS_JSON = JSON.stringify({
diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts
index 91237856489..a61c7812da9 100644
--- a/apps/server/src/environment/DirectEndpoints.ts
+++ b/apps/server/src/environment/DirectEndpoints.ts
@@ -14,10 +14,16 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as NodeNet from "node:net";
import * as NodeOS from "node:os";
-import { isPrivateNetworkHost, isTailnetHost } from "@t3tools/shared/hostClassification";
+import { isTailnetHost } from "@t3tools/shared/hostClassification";
import * as ServerConfig from "../config.ts";
-import { formatHostForUrl, isLoopbackHost, isWildcardHost } from "../startupAccess.ts";
+import {
+ formatHostForUrl,
+ isLoopbackHost,
+ isPrivateNetworkAddress,
+ isWildcardHost,
+ VIRTUAL_INTERFACE,
+} from "../startupAccess.ts";
type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
@@ -40,19 +46,7 @@ export class DirectEndpoints extends Context.Service<
* (`server.local`) can resolve to a different machine on each client's network.
*/
const isAdvertisableAddress = (address: string): boolean =>
- NodeNet.isIPv4(address) &&
- !address.startsWith("127.") &&
- !address.startsWith("169.254.") &&
- isPrivateNetworkHost(address);
-
-/**
- * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and
- * macOS's `bridge100`+) have private addresses only this machine reaches. A
- * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so
- * it stays listed.
- */
-const VIRTUAL_INTERFACE =
- /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge1\d\d)/;
+ NodeNet.isIPv4(address) && !address.startsWith("127.") && isPrivateNetworkAddress(address);
/**
* Tailscale's own interface: `tailscale0` on Linux, "Tailscale" on Windows.
@@ -71,6 +65,8 @@ export function resolveBoundEndpoints(input: {
readonly host: string | undefined;
readonly port: number;
readonly interfaces: NetworkInterfacesMap;
+ /** A cloud VM's private network is its provider's, which no client shares. */
+ readonly onCloudVm?: boolean;
}): ReadonlyArray<ServerDirectEndpoint> {
if (isLoopbackHost(input.host)) return [];
const tailscaleAddresses = new Set(
@@ -87,17 +83,53 @@ export function resolveBoundEndpoints(input: {
)
.map((entry) => entry.address)
: [input.host!].filter(isAdvertisableAddress);
- return [...new Set(addresses)].map((address) => ({
- kind: tailscaleAddresses.has(address) ? "tailnet" : "lan",
- httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,
- }));
+ return [...new Set(addresses)]
+ .filter((address) => !input.onCloudVm || tailscaleAddresses.has(address))
+ .map((address) => ({
+ kind: tailscaleAddresses.has(address) ? "tailnet" : "lan",
+ httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,
+ }));
}
+/**
+ * AWS, GCP, Azure, DigitalOcean, Hetzner, Linode, Vultr, and Oracle all serve
+ * instance metadata at this address. A plain TCP connect skips HTTP proxies,
+ * which would otherwise answer for a machine that is not in a cloud.
+ */
+const CLOUD_METADATA_ADDRESS = "169.254.169.254";
+const CLOUD_METADATA_TIMEOUT_MS = 300;
+
+const probeCloudMetadata = Effect.callback<boolean>((resume) => {
+ const socket = NodeNet.connect({
+ host: CLOUD_METADATA_ADDRESS,
+ port: 80,
+ timeout: CLOUD_METADATA_TIMEOUT_MS,
+ });
+ let settled = false;
+ const settle = (found: boolean) => {
+ if (settled) return;
+ settled = true;
+ socket.destroy();
+ resume(Effect.succeed(found));
+ };
+ socket.once("connect", () => settle(true));
+ socket.once("timeout", () => settle(false));
+ socket.once("error", () => settle(false));
+ return Effect.sync(() => socket.destroy());
+});
+
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
+ // Only the service default listens on every interface without being asked,
+ // so only it checks once whether it runs in a cloud. The check starts now so
+ // the first client does not wait for its timeout.
+ const onCloudVm = config.privateNetworkOnly
+ ? yield* Effect.cached(probeCloudMetadata)
+ : Effect.succeed(false);
+ yield* Effect.forkDetach(onCloudVm);
const resolve = Effect.gen(function* () {
const endpoints = [
@@ -105,6 +137,7 @@ export const make = Effect.gen(function* () {
host: config.host,
port: config.port,
interfaces: NodeOS.networkInterfaces(),
+ onCloudVm: yield* onCloudVm,
}),
];
// Tailscale Serve terminates HTTPS on the tailnet name and forwards to
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index a93d661dd8a..c88a42bd12b 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -186,7 +186,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 { acceptsPrivateNetworkConnection, 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";
@@ -300,7 +300,19 @@ const layerHttpServer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
return NodeHttpServer.layer(
- () => rejectRequestsUntilServing(guardHttpResponseWriteErrors(NodeHttp.createServer())),
+ () => {
+ const server = rejectRequestsUntilServing(
+ guardHttpResponseWriteErrors(NodeHttp.createServer()),
+ );
+ if (config.privateNetworkOnly) {
+ server.on("connection", (socket) => {
+ if (!acceptsPrivateNetworkConnection(socket)) {
+ socket.destroy();
+ }
+ });
+ }
+ return server;
+ },
{
host: config.host ?? "127.0.0.1",
port: config.port,
diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts
index abc16c16016..0a9bcaca805 100644
--- a/apps/server/src/serverRuntimeState.ts
+++ b/apps/server/src/serverRuntimeState.ts
@@ -14,6 +14,7 @@ export const PersistedServerRuntimeState = Schema.Struct({
pid: Schema.Int,
ownerId: Schema.optional(Schema.String),
host: Schema.optional(Schema.String),
+ privateNetworkOnly: Schema.optional(Schema.Boolean),
port: Schema.Int,
origin: Schema.String,
// Dev is single-origin: browsers must pair through this URL, not `origin`.
@@ -51,7 +52,10 @@ const runtimeOriginForConfig = (
};
export const makePersistedServerRuntimeState = (input: {
- readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
+ readonly config: Pick<
+ ServerConfig.ServerConfig["Service"],
+ "host" | "privateNetworkOnly" | "devUrl"
+ >;
readonly port: number;
readonly serviceManaged?: boolean;
}): Effect.Effect<PersistedServerRuntimeState> =>
@@ -59,6 +63,7 @@ export const makePersistedServerRuntimeState = (input: {
version: 1,
pid: process.pid,
...(input.config.host ? { host: input.config.host } : {}),
+ ...(input.config.privateNetworkOnly ? { privateNetworkOnly: true } : {}),
port: input.port,
origin: runtimeOriginForConfig(input.config, input.port),
...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts
index 1b411c93cf6..fd56b4a4c86 100644
--- a/apps/server/src/startupAccess.test.ts
+++ b/apps/server/src/startupAccess.test.ts
@@ -1,30 +1,75 @@
-import { expect, it } from "@effect/vitest";
+import type * as NodeOS from "node:os";
-import { resolveHeadlessConnectionString } from "./startupAccess.ts";
+import { describe, expect, it } from "@effect/vitest";
+
+import {
+ acceptsPrivateNetworkConnection,
+ resolveHeadlessConnectionString,
+} from "./startupAccess.ts";
+
+const ipv4 = (address: string, internal = false): NodeOS.NetworkInterfaceInfo => ({
+ address,
+ netmask: "255.255.255.0",
+ family: "IPv4",
+ mac: "00:00:00:00:00:00",
+ internal,
+ cidr: `${address}/24`,
+});
it("resolves wildcard hosts to a concrete external interface when one is available", () => {
const connectionString = resolveHeadlessConnectionString("0.0.0.0", 3773, {
- en0: [
- {
- address: "192.168.1.42",
- netmask: "255.255.255.0",
- family: "IPv4",
- mac: "00:00:00:00:00:00",
- internal: false,
- cidr: "192.168.1.42/24",
- },
- ],
- lo0: [
- {
- address: "127.0.0.1",
- netmask: "255.0.0.0",
- family: "IPv4",
- mac: "00:00:00:00:00:00",
- internal: true,
- cidr: "127.0.0.1/8",
- },
- ],
+ interfaces: { en0: [ipv4("192.168.1.42")], lo0: [ipv4("127.0.0.1", true)] },
});
expect(connectionString).toBe("http://192.168.1.42:3773");
});
+
+it("skips public and container addresses for a private-network listener", () => {
+ const interfaces = {
+ eth0: [ipv4("203.0.113.7")],
+ docker0: [ipv4("172.17.0.1")],
+ bridge200: [ipv4("192.168.64.1")],
+ eth1: [ipv4("10.0.0.5")],
+ };
+
+ expect(resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces })).toBe(
+ "http://203.0.113.7:3773",
+ );
+ expect(
+ resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces, privateNetworkOnly: true }),
+ ).toBe("http://10.0.0.5:3773");
+ expect(
+ resolveHeadlessConnectionString("0.0.0.0", 3773, {
+ interfaces: { eth0: [ipv4("203.0.113.7")] },
+ privateNetworkOnly: true,
+ }),
+ ).toBe("http://localhost:3773");
+});
+
+it("prefers a LAN address over a tailnet one for a private-network pairing URL", () => {
+ expect(
+ resolveHeadlessConnectionString("0.0.0.0", 3773, {
+ interfaces: { tailscale0: [ipv4("100.101.102.103")], en0: [ipv4("192.168.1.42")] },
+ privateNetworkOnly: true,
+ }),
+ ).toBe("http://192.168.1.42:3773");
+});
+
+describe("acceptsPrivateNetworkConnection", () => {
+ const accepts = (localAddress: string | undefined, remoteAddress: string | undefined) =>
+ acceptsPrivateNetworkConnection({ localAddress, remoteAddress });
+
+ it("serves loopback, LAN, and tailnet clients", () => {
+ expect(accepts("127.0.0.1", "127.0.0.1")).toBe(true);
+ expect(accepts("::ffff:192.168.1.20", "::ffff:192.168.1.31")).toBe(true);
+ expect(accepts("100.101.102.103", "100.90.1.2")).toBe(true);
+ });
+
+ it("closes connections from or to a public address", () => {
+ // A cloud VM's public address is NATed to a private interface address.
+ expect(accepts("172.31.4.10", "203.0.113.7")).toBe(false);
+ expect(accepts("203.0.113.7", "192.168.1.31")).toBe(false);
+ expect(accepts("169.254.10.1", "169.254.10.2")).toBe(false);
+ expect(accepts(undefined, "192.168.1.31")).toBe(false);
+ });
+});
diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts
index 6f5db469b91..cd2815931e3 100644
--- a/apps/server/src/startupAccess.ts
+++ b/apps/server/src/startupAccess.ts
@@ -1,5 +1,7 @@
+import * as NodeNet from "node:net";
import * as NodeOS from "node:os";
+import { isPrivateNetworkHost, isSharedAddressSpaceHost } from "@t3tools/shared/hostClassification";
import { QrCode } from "@t3tools/shared/qrCode";
import * as Effect from "effect/Effect";
import { HttpServer } from "effect/http";
@@ -36,6 +38,38 @@ export const isWildcardHost = (host: string | undefined): boolean =>
export const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
+/**
+ * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and
+ * macOS's `bridge100`+) have private addresses only this machine reaches. A
+ * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so
+ * it stays listed.
+ */
+export const VIRTUAL_INTERFACE =
+ /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/;
+
+/**
+ * Loopback or private-range IPv4 (LAN, tailnet, CGNAT), not link-local, in
+ * plain or IPv4-mapped IPv6 form.
+ */
+export const isPrivateNetworkAddress = (address: string): boolean => {
+ const ipv4 = address.replace(/^::ffff:/i, "");
+ return NodeNet.isIPv4(ipv4) && !ipv4.startsWith("169.254.") && isPrivateNetworkHost(ipv4);
+};
+
+/**
+ * A private-network listener binds every interface but serves only
+ * connections that stay on loopback, a LAN, or the tailnet. Both ends must be
+ * private: a cloud VM or a router port forward hands public clients to a
+ * private local address.
+ */
+export const acceptsPrivateNetworkConnection = (socket: {
+ readonly localAddress?: string | undefined;
+ readonly remoteAddress?: string | undefined;
+}): boolean =>
+ [socket.localAddress, socket.remoteAddress].every(
+ (address) => address !== undefined && isPrivateNetworkAddress(address),
+ );
+
export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string =>
address._tag === "InetAddressV6" && NetAddress.isLoopback(address.address)
? "[::1]"
@@ -50,7 +84,8 @@ const isIpv6Family = (family: string | number): boolean => family === "IPv6" ||
const resolveHeadlessConnectionHost = (
host: string | undefined,
- interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),
+ interfaces: NetworkInterfacesMap,
+ privateNetworkOnly: boolean,
): string => {
if (!host) {
return "localhost";
@@ -60,13 +95,26 @@ const resolveHeadlessConnectionHost = (
return normalizeHost(host);
}
- const interfaceEntries = Object.values(interfaces).flatMap((entries) => entries ?? []);
- const externalIpv4 = interfaceEntries.find(
- (entry) => !entry.internal && isIpv4Family(entry.family),
+ const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) =>
+ privateNetworkOnly && VIRTUAL_INTERFACE.test(name) ? [] : (entries ?? []),
);
+ const externalIpv4Entries = interfaceEntries.filter(
+ (entry) =>
+ !entry.internal &&
+ isIpv4Family(entry.family) &&
+ (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)),
+ );
+ // A tailnet or other CGNAT address reaches fewer devices than the LAN one.
+ const externalIpv4 = privateNetworkOnly
+ ? (externalIpv4Entries.find((entry) => !isSharedAddressSpaceHost(entry.address)) ??
+ externalIpv4Entries[0])
+ : externalIpv4Entries[0];
if (externalIpv4) {
return externalIpv4.address;
}
+ if (privateNetworkOnly) {
+ return "localhost";
+ }
const externalIpv6 = interfaceEntries.find(
(entry) => !entry.internal && isIpv6Family(entry.family),
@@ -77,9 +125,16 @@ const resolveHeadlessConnectionHost = (
export const resolveHeadlessConnectionString = (
host: string | undefined,
port: number,
- interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),
+ options: {
+ readonly interfaces?: NetworkInterfacesMap;
+ readonly privateNetworkOnly?: boolean | undefined;
+ } = {},
): string => {
- const connectionHost = resolveHeadlessConnectionHost(host, interfaces);
+ const connectionHost = resolveHeadlessConnectionHost(
+ host,
+ options.interfaces ?? NodeOS.networkInterfaces(),
+ options.privateNetworkOnly === true,
+ );
return `http://${formatHostForUrl(connectionHost)}:${port}`;
};
@@ -143,6 +198,7 @@ export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessI
const connectionString = resolveHeadlessConnectionString(
serverConfig.host,
resolveListeningPort(httpServer.address, serverConfig.port),
+ { privateNetworkOnly: serverConfig.privateNetworkOnly },
);
const issued = yield* serverAuth.issueStartupPairingCredential();
diff --git a/docs/internals/remote.md b/docs/internals/remote.md
index b581e1be1d5..3bd10a63882 100644
--- a/docs/internals/remote.md
+++ b/docs/internals/remote.md
@@ -54,6 +54,15 @@ dropped, which is how a changed LAN address replaces the old one; routes the
user saved are never touched. The reported addresses are hints like any advertised endpoint, so a
learned route still has to answer as this environment before it is used.
+A background service with no configured host is what makes this work for
+headless machines. It listens on every IPv4 interface and closes each
+connection unless both addresses of the direct peer are loopback, private, or
+tailnet IPv4. That keeps a VPS's public address closed, including a cloud VM
+whose public address is NATed to a private interface. It is not a firewall:
+T3 Connect and Tailscale Serve reach the server over loopback by design, and a
+proxy that rewrites the source address looks private. One listener per address would
+miss a DHCP change, and the wildcard keeps the reported addresses current.
+
Pull request routing trust covers the whole route list. Adding or changing a route
revokes it; reordering does not, because the same addresses remain trusted.
diff --git a/docs/user/background-service.md b/docs/user/background-service.md
index 9310b3fecb2..e93cf7a0d96 100644
--- a/docs/user/background-service.md
+++ b/docs/user/background-service.md
@@ -40,6 +40,16 @@ downloaded versions after showing you the list and asking once. Your projects,
threads, and settings under `~/.t3/userdata` are kept, along with `service.env`
under T3 home. Pass `--yes` from a script.
+## Local network access
+
+The service listens on your local network and Tailscale addresses, so the
+desktop and mobile apps on the same network connect directly instead of through
+T3 Connect. The hosted web app at app.t3.codes stays on T3 Connect, because
+browsers block plain HTTP from an HTTPS page. The service does not answer on
+public addresses, and every device still needs to pair or sign in. To keep the service reachable from this machine only, set
+`T3CODE_HOST=127.0.0.1` in `service.env` (below). Any `T3CODE_HOST` value
+replaces this default.
+
## Configure the service environment
Put custom environment variables in `service.env` under the service's T3 home
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 493a580d14c..fbda09d6af4 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -80,7 +80,8 @@ machine's current LAN and Tailscale addresses and adds them as routes, so
pairing once through T3 Connect is enough to use the LAN at home. When the
machine's LAN address changes, for example after it joins another Wi-Fi network,
the learned route follows it. The machine must allow network access for its LAN
-address to be learned. You can reorder a learned route, but not remove it; it
+address to be learned. The [background service](./background-service.md#local-network-access)
+allows it on private networks by default. You can reorder a learned route, but not remove it; it
goes away with the route it was learned through, or when the machine stops
reporting that address.
diff --git a/packages/client-runtime/src/connection/driver.ts b/packages/client-runtime/src/connection/driver.ts
index c4e6486da2f..0dc3c8a1a58 100644
--- a/packages/client-runtime/src/connection/driver.ts
+++ b/packages/client-runtime/src/connection/driver.ts
@@ -41,6 +41,10 @@ export interface EnvironmentConnectionLease {
export type RouteCheck = "answered" | "silent" | "unchecked";
const ROUTE_CHECK_TIMEOUT_MS = 2_500;
+// Preferred direct routes share one head start, so a relay connection does not
+// wait the full probe timeout for a LAN the device has already left. A route
+// that misses it connects over relay, then upgrades with a second reconnect.
+const ROUTE_CHECK_HEAD_START_MS = 500;
export class ConnectionDriver extends Context.Service<
ConnectionDriver,
@@ -72,6 +76,7 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
routes.length === 1
? []
: yield* Effect.forEach(routes, (route) => Effect.forkChild(checkRoute(route)));
+ const headStart = yield* Effect.forkChild(Effect.sleep(ROUTE_CHECK_HEAD_START_MS));
const attemptScope = yield* Scope.Scope;
let transient: ConnectionAttemptError | undefined;
let blocked: ConnectionAttemptError | undefined;
@@ -89,11 +94,17 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
}
return result;
});
- const silent: Array<ConnectionRoute> = [];
+ const silent: Array<{ readonly route: ConnectionRoute; readonly index: number }> = [];
for (const [index, route] of routes.entries()) {
- const check = checks.length === 0 ? "unchecked" : yield* Fiber.join(checks[index]!);
+ const check =
+ checks.length === 0
+ ? "unchecked"
+ : yield* Effect.raceFirst(
+ Fiber.join(checks[index]!),
+ Fiber.join(headStart).pipe(Effect.as<RouteCheck>("silent")),
+ );
if (check === "silent") {
- silent.push(route);
+ silent.push({ route, index });
continue;
}
const result = yield* attempt(route);
@@ -101,7 +112,16 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes")
// An incompatible server is the same server on every route.
if (result.failure.reason === "unsupported") return yield* result.failure;
}
- for (const route of silent) {
+ // A slow route that answered after the head start goes before one that is
+ // still dead, which can hold an attempt open far longer than its probe.
+ const late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), {
+ concurrency: "unbounded",
+ });
+ const retry = [
+ ...silent.filter((_, position) => late[position] !== "silent"),
+ ...silent.filter((_, position) => late[position] === "silent"),
+ ];
+ for (const { route } of retry) {
const result = yield* attempt(route);
if (result._tag === "Success") return result.success;
if (result.failure.reason === "unsupported") return yield* result.failure;
diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts
index be04d9308bb..0306a86ef49 100644
--- a/packages/client-runtime/src/connection/supervisor.test.ts
+++ b/packages/client-runtime/src/connection/supervisor.test.ts
@@ -1022,6 +1022,205 @@ describe("EnvironmentSupervisor", () => {
});
describe("EnvironmentSupervisor routes", () => {
+ it.effect("connects over relay before a slow LAN reachability check times out", () =>
+ Effect.gen(function* () {
+ const checkingLan = yield* Deferred.make<void>();
+ const harness = yield* makeHarness({
+ checkRoute: (route) =>
+ route.target._tag === "BearerConnectionTarget"
+ ? Deferred.succeed(checkingLan, undefined).pipe(
+ Effect.andThen(Effect.sleep("2500 millis")),
+ Effect.as("silent" as const),
+ )
+ : Effect.succeed("unchecked"),
+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
+ });
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
+ initiallyDesired: true,
+ }).pipe(Effect.provide(harness.dependencies));
+
+ yield* Deferred.await(checkingLan);
+ yield* TestClock.adjust("500 millis");
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
+ expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
+ "RelayConnectionTarget",
+ );
+ expect(yield* Ref.get(harness.prepareCount)).toBe(1);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
+ it.effect("shares one head start across several slow LAN routes", () =>
+ Effect.gen(function* () {
+ const secondLanTarget = new BearerConnectionTarget({
+ environmentId: TARGET.environmentId,
+ label: TARGET.label,
+ connectionId: "bearer:second-lan",
+ });
+ const entry: ConnectionCatalogEntry = {
+ ...LAN_THEN_RELAY_ENTRY,
+ alternateRoutes: [
+ {
+ target: secondLanTarget,
+ profile: Option.some(
+ new BearerConnectionProfile({
+ connectionId: secondLanTarget.connectionId,
+ environmentId: TARGET.environmentId,
+ label: TARGET.label,
+ httpBaseUrl: "http://192.168.56.1:3773/",
+ wsBaseUrl: "ws://192.168.56.1:3773/",
+ }),
+ ),
+ },
+ { target: RELAY_TARGET, profile: Option.none() },
+ ],
+ };
+ const checking = yield* Ref.make(0);
+ const checkingLans = yield* Deferred.make<void>();
+ const harness = yield* makeHarness({
+ checkRoute: (route) =>
+ route.target._tag === "BearerConnectionTarget"
+ ? Ref.updateAndGet(checking, (count) => count + 1).pipe(
+ Effect.flatMap((count) =>
+ count === 2 ? Deferred.succeed(checkingLans, undefined) : Effect.void,
+ ),
+ Effect.andThen(Effect.sleep("2500 millis")),
+ Effect.as("silent" as const),
+ )
+ : Effect.succeed("unchecked"),
+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
+ });
+ const supervisor = yield* EnvironmentSupervisor.make(entry, {
+ initiallyDesired: true,
+ }).pipe(Effect.provide(harness.dependencies));
+
+ yield* Deferred.await(checkingLans);
+ yield* TestClock.adjust("500 millis");
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
+ expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
+ "RelayConnectionTarget",
+ );
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
+ it.effect("still prefers a LAN route that responds within its head start", () =>
+ Effect.gen(function* () {
+ const checkingLan = yield* Deferred.make<void>();
+ const harness = yield* makeHarness({
+ checkRoute: (route) =>
+ route.target._tag === "BearerConnectionTarget"
+ ? Deferred.succeed(checkingLan, undefined).pipe(
+ Effect.andThen(Effect.sleep("100 millis")),
+ Effect.as("answered" as const),
+ )
+ : Effect.succeed("unchecked"),
+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),
+ });
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
+ initiallyDesired: true,
+ }).pipe(Effect.provide(harness.dependencies));
+
+ yield* Deferred.await(checkingLan);
+ yield* TestClock.adjust("100 millis");
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
+ expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(
+ "BearerConnectionTarget",
+ );
+ expect(yield* Ref.get(harness.prepareCount)).toBe(1);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
+ it.effect("tries a slow tailnet route that answered before a dead LAN route", () =>
+ Effect.gen(function* () {
+ const tailnetTarget = new BearerConnectionTarget({
+ environmentId: TARGET.environmentId,
+ label: TARGET.label,
+ connectionId: "bearer:tailnet",
+ });
+ // No relay: a Tailscale-only client away from the LAN.
+ const entry: ConnectionCatalogEntry = {
+ ...LAN_THEN_RELAY_ENTRY,
+ alternateRoutes: [
+ {
+ target: tailnetTarget,
+ profile: Option.some(
+ new BearerConnectionProfile({
+ connectionId: tailnetTarget.connectionId,
+ environmentId: TARGET.environmentId,
+ label: TARGET.label,
+ httpBaseUrl: "http://100.100.1.2:3773/",
+ wsBaseUrl: "ws://100.100.1.2:3773/",
+ network: "tailscale",
+ }),
+ ),
+ },
+ ],
+ };
+ const checking = yield* Ref.make(0);
+ const checkingBoth = yield* Deferred.make<void>();
+ const harness = yield* makeHarness({
+ checkRoute: (route) =>
+ Ref.updateAndGet(checking, (count) => count + 1).pipe(
+ Effect.flatMap((count) =>
+ count === 2 ? Deferred.succeed(checkingBoth, undefined) : Effect.void,
+ ),
+ Effect.andThen(
+ connectionRouteId(route.target) === LAN_TARGET.connectionId
+ ? Effect.sleep("2500 millis").pipe(Effect.as("silent" as const))
+ : Effect.sleep("700 millis").pipe(Effect.as("answered" as const)),
+ ),
+ ),
+ // The dead LAN address never answers the connection itself either.
+ prepare: (_attempt, target) =>
+ target._tag === "BearerConnectionTarget" &&
+ target.connectionId === LAN_TARGET.connectionId
+ ? Effect.never
+ : Effect.succeed(preparedFor(target)),
+ });
+ const supervisor = yield* EnvironmentSupervisor.make(entry, {
+ initiallyDesired: true,
+ }).pipe(Effect.provide(harness.dependencies));
+
+ yield* Deferred.await(checkingBoth);
+ yield* TestClock.adjust("2500 millis");
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
+ expect(
+ connectionRouteId(
+ Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target,
+ ),
+ ).toBe("bearer:tailnet");
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
+ it.effect("still tries a slow LAN route when relay fails", () =>
+ Effect.gen(function* () {
+ const checkingLan = yield* Deferred.make<void>();
+ const attempted: string[] = [];
+ const harness = yield* makeHarness({
+ checkRoute: (route) =>
+ route.target._tag === "BearerConnectionTarget"
+ ? Deferred.succeed(checkingLan, undefined).pipe(
+ Effect.andThen(Effect.sleep("2500 millis")),
+ Effect.as("answered" as const),
+ )
+ : Effect.succeed("unchecked"),
+ prepare: (_attempt, target) => {
+ attempted.push(target._tag);
+ return target._tag === "RelayConnectionTarget"
+ ? Effect.fail(blocked("Sign in to T3 Connect."))
+ : Effect.succeed(preparedFor(target));
+ },
+ });
+ const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {
+ initiallyDesired: true,
+ }).pipe(Effect.provide(harness.dependencies));
+
+ yield* Deferred.await(checkingLan);
+ yield* TestClock.adjust("2500 millis");
+ yield* awaitState(supervisor.state, (state) => state.phase === "connected");
+ expect(attempted).toEqual(["RelayConnectionTarget", "BearerConnectionTarget"]);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
it.effect("skips a silent LAN route and connects over T3 Connect", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({