From 2feb3299b45a8fc7c03ee9816e1f10d40b9d1070 Mon Sep 17 00:00:00 2001 From: Tobias Kriebisch Date: Mon, 16 Nov 2026 13:24:28 +0100 Subject: [PATCH 1/6] fix(peer): Headscale tailnets can link environments over their 100.64.x addresses --- .../src/environment/DirectEndpoints.test.ts | 15 ++++++++++++++- apps/server/src/environment/DirectEndpoints.ts | 13 +++++++++++++ apps/server/src/peer/PeerLinks.ts | 12 ++++++++++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/apps/server/src/environment/DirectEndpoints.test.ts b/apps/server/src/environment/DirectEndpoints.test.ts index 09ecc1ee8c8c9..16a9f3fe31108 100644 --- a/apps/server/src/environment/DirectEndpoints.test.ts +++ b/apps/server/src/environment/DirectEndpoints.test.ts @@ -18,7 +18,7 @@ import { describe, expect, it } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import * as DirectEndpoints from "./DirectEndpoints.ts"; import * as ServerEnvironment from "./ServerEnvironment.ts"; -import { resolveBoundEndpoints } from "./DirectEndpoints.ts"; +import { isOnTailnetIpv4, resolveBoundEndpoints } from "./DirectEndpoints.ts"; const INTERFACES: ReturnType = { lo0: [ @@ -215,6 +215,19 @@ describe("resolveBoundEndpoints", () => { ]); }); + it("is on a tailnet by IPv4 only through Tailscale's interface, not other VPNs in its range", () => { + expect(isOnTailnetIpv4({ en0: INTERFACES.en0, tailscale0: vpnInterface("100.64.0.6") })).toBe( + true, + ); + expect( + isOnTailnetIpv4({ + en0: INTERFACES.en0, + CloudflareWARP: vpnInterface("100.96.0.1"), + utun7: vpnInterface("100.85.0.1"), + }), + ).toBe(false); + }); + it("never reports a host name, which can resolve to another machine per client", () => { for (const host of ["server.local", "devbox", "devbox.home.arpa"]) { expect( diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index c39ca1d85484e..b67dffa0d8b2a 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -18,6 +18,7 @@ import * as NodeOS from "node:os"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { formatHostForUrl, + isSharedAddressSpaceHost, isTailnetHost, isWildcardHost, } from "@t3tools/shared/hostClassification"; @@ -57,6 +58,18 @@ const isTailscaleInterface = ( /^tailscale/i.test(name) || entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address)); +/** + * Whether this machine holds a 100.64.0.0/10 address on Tailscale's interface. + * Control servers like Headscale give nodes no *.ts.net name or fd7a:115c:a1e0:: + * address to recognize, so their peers are reached by these IPv4 addresses. + */ +export const isOnTailnetIpv4 = (interfaces: NetworkInterfacesMap): boolean => + Object.entries(interfaces).some( + ([name, entries = []]) => + isTailscaleInterface(name, entries) && + entries.some((entry) => entry.family === "IPv4" && isSharedAddressSpaceHost(entry.address)), + ); + export function resolveBoundEndpoints(input: { readonly platform: NodeJS.Platform; readonly host: string | undefined; diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 859266c469c70..7bafac7252e69 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -35,9 +35,15 @@ import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientError from "effect/http/HttpClientError"; import * as HttpApi from "effect/http-api/HttpApi"; import * as HttpApiClient from "effect/http-api/HttpApiClient"; -import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification"; +import { + isLocalLoopbackHost, + isSharedAddressSpaceHost, + isTailnetHost, +} from "@t3tools/shared/hostClassification"; +import * as NodeOS from "node:os"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { isOnTailnetIpv4 } from "../environment/DirectEndpoints.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -173,6 +179,7 @@ const failStorage = (cause: unknown) => * The base URL a peer is reached at, normalised to its origin. The pairing * code and then the link's token travel to it, so plain http is accepted only * where the network already encrypts: this machine, or a Tailscale address. + * A 100.64.0.0/10 address counts only while this machine is on a tailnet too. */ const peerOrigin = (url: string) => { const parsed = URL.parse(url); @@ -188,7 +195,8 @@ const peerOrigin = (url: string) => { if ( parsed.protocol === "http:" && !isLocalLoopbackHost(parsed.hostname) && - !isTailnetHost(parsed.hostname) + !isTailnetHost(parsed.hostname) && + !(isSharedAddressSpaceHost(parsed.hostname) && isOnTailnetIpv4(NodeOS.networkInterfaces())) ) { return Effect.fail( new PeerLinkError({ From d44930110914bccf518a3a7865f38125fb3f9710 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 12:36:48 +0000 Subject: [PATCH 2/6] test(peer): fold the tailnet IPv4 check into the existing interface case Co-Authored-By: Claude Opus 5.5 --- .../src/environment/DirectEndpoints.test.ts | 16 +++------------- apps/server/src/environment/DirectEndpoints.ts | 7 ++----- 2 files changed, 5 insertions(+), 18 deletions(-) diff --git a/apps/server/src/environment/DirectEndpoints.test.ts b/apps/server/src/environment/DirectEndpoints.test.ts index 16a9f3fe31108..157479965bd7f 100644 --- a/apps/server/src/environment/DirectEndpoints.test.ts +++ b/apps/server/src/environment/DirectEndpoints.test.ts @@ -213,19 +213,9 @@ describe("resolveBoundEndpoints", () => { { kind: "lan", httpBaseUrl: "http://100.96.0.1:3773/" }, { kind: "lan", httpBaseUrl: "http://100.85.0.1:3773/" }, ]); - }); - - it("is on a tailnet by IPv4 only through Tailscale's interface, not other VPNs in its range", () => { - expect(isOnTailnetIpv4({ en0: INTERFACES.en0, tailscale0: vpnInterface("100.64.0.6") })).toBe( - true, - ); - expect( - isOnTailnetIpv4({ - en0: INTERFACES.en0, - CloudflareWARP: vpnInterface("100.96.0.1"), - utun7: vpnInterface("100.85.0.1"), - }), - ).toBe(false); + expect(isOnTailnetIpv4(interfaces)).toBe(true); + const { tailscale0: _, ...withoutTailscale } = interfaces; + expect(isOnTailnetIpv4(withoutTailscale)).toBe(false); }); it("never reports a host name, which can resolve to another machine per client", () => { diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index b67dffa0d8b2a..a13b0b93d100e 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -58,11 +58,8 @@ const isTailscaleInterface = ( /^tailscale/i.test(name) || entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address)); -/** - * Whether this machine holds a 100.64.0.0/10 address on Tailscale's interface. - * Control servers like Headscale give nodes no *.ts.net name or fd7a:115c:a1e0:: - * address to recognize, so their peers are reached by these IPv4 addresses. - */ +// Peers advertise their Tailscale IPv4 as a tailnet endpoint, and Headscale nodes +// may have no *.ts.net name or IPv6 address to reach them by instead. export const isOnTailnetIpv4 = (interfaces: NetworkInterfacesMap): boolean => Object.entries(interfaces).some( ([name, entries = []]) => From 0770a5b3c69a11e3fc3bc5680bcf49595c9d41d6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 12:51:12 +0000 Subject: [PATCH 3/6] fix(peer): plain http to a 100.64.x address requires Tailscale to list it as a peer The interface check trusted any 100.64.0.0/10 destination while this machine was on a tailnet, so a WARP or carrier-NAT address could receive the pairing code and the link's token in clear. Linking and resolving now accept such an address only while tailscale status --json runs with its TUN device and lists it for this machine or a peer, which also covers Headscale nodes. Ported from #26475. Co-authored-by: Julius Marminge Co-Authored-By: Claude Opus 5.5 --- .../src/environment/DirectEndpoints.test.ts | 5 +- .../server/src/environment/DirectEndpoints.ts | 10 -- apps/server/src/peer/PeerLinks.test.ts | 108 +++++++++++++++++- apps/server/src/peer/PeerLinks.testkit.ts | 5 +- apps/server/src/peer/PeerLinks.ts | 77 +++++++------ packages/tailscale/src/tailscale.ts | 58 ++++++++-- 6 files changed, 198 insertions(+), 65 deletions(-) diff --git a/apps/server/src/environment/DirectEndpoints.test.ts b/apps/server/src/environment/DirectEndpoints.test.ts index 157479965bd7f..09ecc1ee8c8c9 100644 --- a/apps/server/src/environment/DirectEndpoints.test.ts +++ b/apps/server/src/environment/DirectEndpoints.test.ts @@ -18,7 +18,7 @@ import { describe, expect, it } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import * as DirectEndpoints from "./DirectEndpoints.ts"; import * as ServerEnvironment from "./ServerEnvironment.ts"; -import { isOnTailnetIpv4, resolveBoundEndpoints } from "./DirectEndpoints.ts"; +import { resolveBoundEndpoints } from "./DirectEndpoints.ts"; const INTERFACES: ReturnType = { lo0: [ @@ -213,9 +213,6 @@ describe("resolveBoundEndpoints", () => { { kind: "lan", httpBaseUrl: "http://100.96.0.1:3773/" }, { kind: "lan", httpBaseUrl: "http://100.85.0.1:3773/" }, ]); - expect(isOnTailnetIpv4(interfaces)).toBe(true); - const { tailscale0: _, ...withoutTailscale } = interfaces; - expect(isOnTailnetIpv4(withoutTailscale)).toBe(false); }); it("never reports a host name, which can resolve to another machine per client", () => { diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index a13b0b93d100e..c39ca1d85484e 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -18,7 +18,6 @@ import * as NodeOS from "node:os"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { formatHostForUrl, - isSharedAddressSpaceHost, isTailnetHost, isWildcardHost, } from "@t3tools/shared/hostClassification"; @@ -58,15 +57,6 @@ const isTailscaleInterface = ( /^tailscale/i.test(name) || entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address)); -// Peers advertise their Tailscale IPv4 as a tailnet endpoint, and Headscale nodes -// may have no *.ts.net name or IPv6 address to reach them by instead. -export const isOnTailnetIpv4 = (interfaces: NetworkInterfacesMap): boolean => - Object.entries(interfaces).some( - ([name, entries = []]) => - isTailscaleInterface(name, entries) && - entries.some((entry) => entry.family === "IPv4" && isSharedAddressSpaceHost(entry.address)), - ); - export function resolveBoundEndpoints(input: { readonly platform: NodeJS.Platform; readonly host: string | undefined; diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 8f1d6cc381d63..71ea5bcc21234 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -2,7 +2,8 @@ import * as NodeFS from "node:fs"; // @effect-diagnostics-next-line nodeBuiltinImport:off - A peer with a certificate this machine does not trust. import * as NodeHttps from "node:https"; -import { NodeHttpServer } from "@effect/platform-node"; +import { NodeHttpClient, NodeHttpServer } from "@effect/platform-node"; +import * as Undici from "@effect/platform-node/Undici"; import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; import * as Context from "effect/Context"; @@ -17,7 +18,10 @@ import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as HttpRouter from "effect/http/HttpRouter"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as Sink from "effect/Sink"; import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { Tool, Toolkit } from "effect/ai"; import { @@ -89,8 +93,9 @@ const serveB = (descriptor: ExecutionEnvironmentDescriptor) => const makeA = ( descriptor: ExecutionEnvironmentDescriptor, secrets?: typeof ServerSecretStore.layer, + machine?: Layer.Layer, ) => - layerLinkingEnvironment(descriptor, secrets).pipe( + layerLinkingEnvironment(descriptor, secrets, undefined, machine).pipe( Layer.build, Effect.map((context) => ({ links: Context.get(context, PeerLinks.PeerLinks), @@ -346,6 +351,105 @@ const serveRaw = ( ), ); +/** `tailscale status --json` with `peerIps` as another machine on its tailnet. */ +const tailscaleStatus = (backendState: string, peerIps: ReadonlyArray, tun = true) => + JSON.stringify({ + BackendState: backendState, + TUN: tun, + Self: { TailscaleIPs: ["100.101.0.1"] }, + Peer: { "nodekey:box": { TailscaleIPs: peerIps } }, + }); + +/** A's `tailscale`, whose `status --json` prints what `status` holds at each run. */ +const layerTailscale = (status: Ref.Ref) => + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Ref.get(status).pipe( + Effect.map((json) => + 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(json)), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ), + ), + ); + +/** Connections to `host` reach 127.0.0.1 instead, as a tailnet route would reach the peer. */ +const layerRouteHostToLoopback = (host: string) => { + const connect = Undici.buildConnector({}); + return NodeHttpClient.layerUndiciOptions({ + connect: (options, callback) => + connect( + { ...options, hostname: options.hostname === host ? "127.0.0.1" : options.hostname }, + callback, + ), + }); +}; + +it.effect( + "links over plain http to a 100.64.0.0/10 address only while Tailscale routes to it as a peer", + () => + Effect.scoped( + Effect.gen(function* () { + const b = yield* serveB(box); + const port = new URL(b.url).port; + const status = yield* Ref.make(tailscaleStatus("Stopped", ["100.100.1.2"])); + const a = yield* makeA( + laptop, + undefined, + Layer.mergeAll(layerTailscale(status), layerRouteHostToLoopback("100.100.1.2")), + ); + const linkTo = (url: string) => + b.auth + .issuePairingCredential() + .pipe( + Effect.flatMap(({ credential }) => + a.links.link({ url, pairingCode: credential, access: "auto" }), + ), + ); + + // Stopped or in userspace networking, Tailscale still lists its peers, + // but the OS would not send traffic to them through it. + for (const refused of [ + tailscaleStatus("Stopped", ["100.100.1.2"]), + tailscaleStatus("Running", ["100.100.1.2"], false), + // WARP and carrier-grade NAT share the range: an address Tailscale does not list. + tailscaleStatus("Running", ["100.100.9.9"]), + ]) { + yield* Ref.set(status, refused); + const error = yield* linkTo(`http://100.100.1.2:${port}`).pipe(Effect.flip); + expect(error.message).toContain("plain http"); + } + expect(yield* linkedSessions(b)).toEqual([]); + + yield* Ref.set(status, tailscaleStatus("Running", ["100.100.1.2"])); + expect(yield* linkTo(`http://100.100.1.2:${port}/`)).toMatchObject({ + environmentId: box.environmentId, + urls: [`http://100.100.1.2:${port}`], + }); + yield* probe(a); + expect((yield* Ref.get(b.bearers)).length).toBeGreaterThan(0); + + // Once Tailscale stops, the link's token stays here. + yield* Ref.set(status, tailscaleStatus("NeedsLogin", ["100.100.1.2"])); + yield* Ref.set(b.bearers, []); + yield* probe(a).pipe(Effect.flip); + expect(yield* Ref.get(b.bearers)).toEqual([]); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("never follows a peer's redirect with the pairing code", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.ts index ff09db6cbdf7f..6f67f9d83109f 100644 --- a/apps/server/src/peer/PeerLinks.testkit.ts +++ b/apps/server/src/peer/PeerLinks.testkit.ts @@ -196,7 +196,8 @@ export type ServedPeer = Effect.Success>; /** * The environment that links: its own database and secret store, reaching - * peers over plain HTTP. Provide it to anything built on its links. + * peers over plain HTTP. Provide it to anything built on its links. `machine` + * replaces what this machine provides, such as its `tailscale` or its network. */ export const layerLinkingEnvironment = ( descriptor: ExecutionEnvironmentDescriptor, @@ -205,9 +206,11 @@ export const layerLinkingEnvironment = ( SqlClient.SqlClient, E | Layer.Error > = Sqlite.layerMemory, + machine: Layer.Layer = Layer.empty, ) => PeerMcpClient.layer.pipe( Layer.provideMerge(PeerLinks.layer), + Layer.provide(machine), Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })), Layer.provideMerge(database), Layer.provide(Layer.mergeAll(secrets, FetchHttpClient.layer)), diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 7bafac7252e69..9b8fb799a25f8 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -40,10 +40,10 @@ import { isSharedAddressSpaceHost, isTailnetHost, } from "@t3tools/shared/hostClassification"; -import * as NodeOS from "node:os"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { readTailnetAddresses } from "@t3tools/tailscale"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; -import { isOnTailnetIpv4 } from "../environment/DirectEndpoints.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -175,39 +175,6 @@ const failStorage = (cause: unknown) => ), ); -/** - * The base URL a peer is reached at, normalised to its origin. The pairing - * code and then the link's token travel to it, so plain http is accepted only - * where the network already encrypts: this machine, or a Tailscale address. - * A 100.64.0.0/10 address counts only while this machine is on a tailnet too. - */ -const peerOrigin = (url: string) => { - const parsed = URL.parse(url); - if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) { - return Effect.fail( - new PeerLinkError({ - reason: "unreachable", - // Never the address as given: it may hold a username, password or query. - message: "That address is not an http or https address.", - }), - ); - } - if ( - parsed.protocol === "http:" && - !isLocalLoopbackHost(parsed.hostname) && - !isTailnetHost(parsed.hostname) && - !(isSharedAddressSpaceHost(parsed.hostname) && isOnTailnetIpv4(NodeOS.networkInterfaces())) - ) { - return Effect.fail( - new PeerLinkError({ - reason: "unreachable", - message: `${parsed.origin} is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`, - }), - ); - } - return Effect.succeed(parsed.origin); -}; - /** The system error under a failed connection, such as ECONNREFUSED or ENOTFOUND. */ const connectionCode = (cause: unknown) => [cause, Predicate.hasProperty(cause, "cause") ? cause.cause : undefined] @@ -259,11 +226,47 @@ const make = Effect.gen(function* () { const environment = yield* ServerEnvironment.ServerEnvironment; const serverSettings = yield* ServerSettings.ServerSettingsService; const isOwnLoopback = yield* LoopbackHost; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const enabled = serverSettings.getSettings.pipe( Effect.map((settings) => settings.linkedEnvironmentsEnabled), Effect.orElseSucceed(() => false), ); + const isTailnetAddress = (host: string) => + readTailnetAddresses.pipe( + Effect.map((addresses) => addresses.has(host)), + Effect.orElseSucceed(() => false), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + /** + * A peer's base URL as its origin. Its pairing code and token travel there, so + * plain http only where the network encrypts: this machine, or Tailscale. WARP + * and CGNAT share 100.64.0.0/10, so those count only where Tailscale lists them. + */ + const peerOrigin = Effect.fn("PeerLinks.peerOrigin")(function* (url: string) { + const parsed = URL.parse(url); + if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) { + return yield* new PeerLinkError({ + reason: "unreachable", + // Never the address as given: it may hold a username, password or query. + message: "That address is not an http or https address.", + }); + } + if ( + parsed.protocol === "http:" && + !isLocalLoopbackHost(parsed.hostname) && + !isTailnetHost(parsed.hostname) && + !(isSharedAddressSpaceHost(parsed.hostname) && (yield* isTailnetAddress(parsed.hostname))) + ) { + return yield* new PeerLinkError({ + reason: "unreachable", + message: `${parsed.origin} is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`, + }); + } + return parsed.origin; + }); + /** A fresh name for one link's token; the row records it. */ const newSecretName = random.randomBytes(16).pipe( Effect.map((bytes) => `peer-link-${Hex.encode(bytes)}`), @@ -767,7 +770,9 @@ const make = Effect.gen(function* () { ? Option.none() : yield* Effect.raceAll( link.urls.map((url) => - answersAs(url, environmentId).pipe( + // A 100.x address is trusted only while Tailscale still lists it. + peerOrigin(url).pipe( + Effect.flatMap((origin) => answersAs(origin, environmentId)), Effect.flatMap(Effect.fromOption), Effect.map((peer) => ({ url, peer })), ), diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.ts index 0456f95ab4850..0dc63a79915fb 100644 --- a/packages/tailscale/src/tailscale.ts +++ b/packages/tailscale/src/tailscale.ts @@ -308,23 +308,30 @@ export const readTailscaleStatus = readTailscaleOutput("status", ["status", "--j Effect.flatMap(parseTailscaleStatus), ); -const TailscaleExitNodeJson = Schema.Struct({ +const TailscalePeersJson = Schema.Struct({ + BackendState: Schema.optional(Schema.Unknown), + TUN: Schema.optional(Schema.Unknown), + // Go prints a nil Self or Peer as null: logged out, or no other machines. + Self: Schema.optional( + Schema.NullOr(Schema.Struct({ TailscaleIPs: Schema.optional(Schema.Unknown) })), + ), ExitNodeStatus: Schema.optional(Schema.Struct({ Online: Schema.optional(Schema.Unknown) })), Peer: Schema.optional( - Schema.Record( - Schema.String, - Schema.Struct({ - ExitNode: Schema.optional(Schema.Unknown), - HostName: Schema.optional(Schema.Unknown), - DNSName: Schema.optional(Schema.Unknown), - }), + Schema.NullOr( + Schema.Record( + Schema.String, + Schema.Struct({ + ExitNode: Schema.optional(Schema.Unknown), + HostName: Schema.optional(Schema.Unknown), + DNSName: Schema.optional(Schema.Unknown), + TailscaleIPs: Schema.optional(Schema.Unknown), + }), + ), ), ), }); -const decodeTailscaleExitNodeJson = Schema.decodeEffect( - Schema.fromJsonString(TailscaleExitNodeJson), -); +const decodeTailscalePeersJson = Schema.decodeEffect(Schema.fromJsonString(TailscalePeersJson)); export interface TailscaleExitNode { readonly name: string | null; @@ -338,7 +345,7 @@ export interface TailscaleExitNode { export const parseTailscaleExitNode = ( rawStatusJson: string, ): Effect.Effect => - decodeTailscaleExitNodeJson(rawStatusJson).pipe( + decodeTailscalePeersJson(rawStatusJson).pipe( Effect.mapError((cause) => new TailscaleStatusParseError({ cause })), Effect.map((parsed) => { if (parsed.ExitNodeStatus === undefined) return null; @@ -359,6 +366,33 @@ export const readTailscaleExitNode = readTailscaleOutput("status", ["status", "- Effect.flatMap(parseTailscaleExitNode), ); +/** + * The addresses of this machine and every other machine on its tailnet. Empty + * unless Tailscale runs with its TUN device: stopped or in userspace networking, + * it still lists them, but the OS would send traffic to them unencrypted. + */ +const parseTailnetAddresses = ( + rawStatusJson: string, +): Effect.Effect, TailscaleStatusParseError> => + decodeTailscalePeersJson(rawStatusJson).pipe( + Effect.mapError((cause) => new TailscaleStatusParseError({ cause })), + Effect.map((parsed) => { + if (parsed.BackendState !== "Running" || parsed.TUN !== true) return new Set(); + const nodes = [...(parsed.Self ? [parsed.Self] : []), ...Object.values(parsed.Peer ?? {})]; + return new Set( + nodes.flatMap((node) => + Array.isArray(node.TailscaleIPs) + ? node.TailscaleIPs.filter((address): address is string => typeof address === "string") + : [], + ), + ); + }), + ); + +export const readTailnetAddresses = readTailscaleOutput("status", ["status", "--json"]).pipe( + Effect.flatMap(parseTailnetAddresses), +); + const TailscalePrefsJson = Schema.Struct({ RunSSH: Schema.optional(Schema.Unknown), WantRunning: Schema.optional(Schema.Unknown), From 312511c8e571266f97e05102f7b00e3341055eaf Mon Sep 17 00:00:00 2001 From: Tobias Kriebisch Date: Sat, 21 Nov 2026 12:04:17 +0100 Subject: [PATCH 4/6] fix(peer): a link resolve refuses is no longer listed as reachable --- apps/server/src/peer/PeerLinks.test.ts | 1 + apps/server/src/peer/PeerLinks.ts | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 71ea5bcc21234..49351f2e70666 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -446,6 +446,7 @@ it.effect( yield* Ref.set(b.bearers, []); yield* probe(a).pipe(Effect.flip); expect(yield* Ref.get(b.bearers)).toEqual([]); + expect((yield* a.links.list).map((link) => link.status)).toEqual(["unreachable"]); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 9b8fb799a25f8..20bbd58fc17e1 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -643,7 +643,11 @@ const make = Effect.gen(function* () { if (link.urls.length === 0) return { ...link, status: "unreachable" }; const answered = yield* Effect.raceAll( link.urls.map((url) => - answersAs(url, link.environmentId).pipe(Effect.flatMap(Effect.fromOption)), + // Listed as reachable only where resolve would still use it. + peerOrigin(url).pipe( + Effect.flatMap((origin) => answersAs(origin, link.environmentId)), + Effect.flatMap(Effect.fromOption), + ), ), ).pipe(Effect.timeoutOption(LIST_PROBE_TIMEOUT), Effect.orElseSucceed(Option.none)); if (Option.isNone(answered)) return { ...link, status: "unreachable" }; From 2a6a99e219564fc0b0ca04bbcaa0cd865a39de7b Mon Sep 17 00:00:00 2001 From: Tobias Kriebisch Date: Sat, 21 Nov 2026 12:12:48 +0100 Subject: [PATCH 5/6] fix(peer): the Tailscale lookup no longer spends a listed link's probe budget --- apps/server/src/peer/PeerLinks.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 20bbd58fc17e1..d451f4b746fca 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -639,15 +639,18 @@ const make = Effect.gen(function* () { now: DateTime.Utc, ): Effect.fn.Return { if (DateTime.isLessThanOrEqualTo(link.expiresAt, now)) return { ...link, status: "expired" }; + // Listed as reachable only where resolve would still use it. Checked before + // the probe budget starts: `tailscale status` alone can take most of it. + const origins = (yield* Effect.forEach( + link.urls, + (url) => peerOrigin(url).pipe(Effect.option), + { concurrency: "unbounded" }, + )).flatMap((origin) => (Option.isSome(origin) ? [origin.value] : [])); // A race over no addresses never settles. - if (link.urls.length === 0) return { ...link, status: "unreachable" }; + if (origins.length === 0) return { ...link, status: "unreachable" }; const answered = yield* Effect.raceAll( - link.urls.map((url) => - // Listed as reachable only where resolve would still use it. - peerOrigin(url).pipe( - Effect.flatMap((origin) => answersAs(origin, link.environmentId)), - Effect.flatMap(Effect.fromOption), - ), + origins.map((origin) => + answersAs(origin, link.environmentId).pipe(Effect.flatMap(Effect.fromOption)), ), ).pipe(Effect.timeoutOption(LIST_PROBE_TIMEOUT), Effect.orElseSucceed(Option.none)); if (Option.isNone(answered)) return { ...link, status: "unreachable" }; From f7f1dd229d752fc8c5436f2310e4d82e659597a8 Mon Sep 17 00:00:00 2001 From: Tobias Kriebisch Date: Mon, 23 Nov 2026 08:38:02 +0100 Subject: [PATCH 6/6] fix(peer): a slow Tailscale lookup no longer holds up a link's other addresses --- apps/server/src/peer/PeerLinks.ts | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index d451f4b746fca..e9986f2e59b76 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -639,20 +639,22 @@ const make = Effect.gen(function* () { now: DateTime.Utc, ): Effect.fn.Return { if (DateTime.isLessThanOrEqualTo(link.expiresAt, now)) return { ...link, status: "expired" }; - // Listed as reachable only where resolve would still use it. Checked before - // the probe budget starts: `tailscale status` alone can take most of it. - const origins = (yield* Effect.forEach( - link.urls, - (url) => peerOrigin(url).pipe(Effect.option), - { concurrency: "unbounded" }, - )).flatMap((origin) => (Option.isSome(origin) ? [origin.value] : [])); // A race over no addresses never settles. - if (origins.length === 0) return { ...link, status: "unreachable" }; + if (link.urls.length === 0) return { ...link, status: "unreachable" }; const answered = yield* Effect.raceAll( - origins.map((origin) => - answersAs(origin, link.environmentId).pipe(Effect.flatMap(Effect.fromOption)), + link.urls.map((url) => + // Listed as reachable only where resolve would still use it. The probe + // budget starts after that check: `tailscale status` can take most of it. + peerOrigin(url).pipe( + Effect.flatMap((origin) => + answersAs(origin, link.environmentId).pipe( + Effect.flatMap(Effect.fromOption), + Effect.timeout(LIST_PROBE_TIMEOUT), + ), + ), + ), ), - ).pipe(Effect.timeoutOption(LIST_PROBE_TIMEOUT), Effect.orElseSucceed(Option.none)); + ).pipe(Effect.option); if (Option.isNone(answered)) return { ...link, status: "unreachable" }; return { ...(yield* withLabel(link, answered.value.label)), status: "reachable" }; });