feat(clients): learn an environment's LAN and tailnet addresses #15468
Mergedjuliusmarmingemerged 9 commits into
t3code/connection-routes fromrefs/pull/15468/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
juliusmarminge removed labelssize:XL
juliusmarminge added labelsmacroscope-review
- apps/server/src/environment/DirectEndpoints.ts lines 52 to 52OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +32,21 @@32+>()("t3/environment/DirectEndpoints") {}33+34+const isUsableAddress = (address: string): boolean =>35+ !address.startsWith("127.") && !address.startsWith("169.254.") && !address.startsWith("fe80:");36+37+/**38+ * Plain HTTP endpoints for the addresses a server bound to `host` accepts.39+ * IPv4 only: link-local and temporary IPv6 addresses change too often to be40+ * worth saving.41+ */42+export function resolveBoundEndpoints(input: {43+ readonly host: string | undefined;44+ readonly port: number;45+ readonly interfaces: NetworkInterfacesMap;46+}): ReadonlyArray<ServerDirectEndpoint> {47+ if (isLoopbackHost(input.host)) return [];48+ const addresses = isWildcardHost(input.host)49+ ? Object.values(input.interfaces)50+ .flatMap((entries) => entries ?? [])51+ .filter(52+ (entry) => !entry.internal && entry.family === "IPv4" && isUsableAddress(entry.address),packages/client-runtime/src/connection/routes.ts lines 217 to 221OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -189,0 +201,21 @@201+ * an address already saved is not learned twice.202+ */203+export function mergeLearnedRoutes(input: {204+ readonly entry: ConnectionCatalogEntry;205+ readonly activeRoute: ConnectionRoute;206+ readonly reported: ReadonlyArray<{ readonly httpBaseUrl: string }>;207+ /** Plain HTTP routes are unusable from an HTTPS page (mixed content). */208+ readonly allowInsecure: boolean;209+}): ReadonlyArray<ConnectionRoute> | null {210+ const { entry } = input;211+ const active = input.activeRoute.target;212+ const saved = connectionRoutes(entry);213+ // The primary and SSH routes have no credential a learned route could reuse.214+ if (active._tag !== "RelayConnectionTarget" && active._tag !== "BearerConnectionTarget") {215+ return null;216+ }217+ const authorization = active._tag === "RelayConnectionTarget" ? "t3-connect" : undefined;218+ const sharedCredential =219+ active._tag === "BearerConnectionTarget"220+ ? credentialConnectionId(active.connectionId)221+ : undefined;packages/client-runtime/src/connection/routes.ts line 272OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -189,0 +252,21 @@252+ target: new BearerConnectionTarget({253+ environmentId: entry.target.environmentId,254+ label: entry.target.label,255+ connectionId,256+ }),257+ profile: Option.some(258+ new BearerConnectionProfile({259+ connectionId,260+ environmentId: entry.target.environmentId,261+ label: entry.target.label,262+ httpBaseUrl,263+ wsBaseUrl: `${url.protocol === "https:" ? "wss:" : "ws:"}//${url.host}/`,264+ learned: true,265+ ...(authorization === undefined ? {} : { authorization }),266+ }),267+ ),268+ });269+ }270+ const before = saved.map((route) => connectionRouteId(route.target)).join("\n");271+ const after = next.map((route) => connectionRouteId(route.target)).join("\n");272+ return before === after ? null : next;packages/client-runtime/src/connection/registry.ts line 886Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -830,0 +845,21 @@845+ readonly environmentId: EnvironmentId;846+ readonly activeRoute: ConnectionRoute;847+ readonly reported: ReadonlyArray<{ readonly httpBaseUrl: string }>;848+ }) {849+ return yield* withLeaseLock(850+ input.environmentId,851+ Effect.gen(function* () {852+ if ((yield* Ref.get(platformEnvironmentIds)).has(input.environmentId)) {853+ return Option.none<ConnectionCatalogEntry>();854+ }855+ const entry = (yield* SubscriptionRef.get(entries)).get(input.environmentId);856+ if (entry === undefined) return Option.none<ConnectionCatalogEntry>();857+ const routes = mergeLearnedRoutes({858+ entry,859+ activeRoute: input.activeRoute,860+ reported: input.reported,861+ allowInsecure: allowInsecureRoutes,862+ });863+ if (routes === null) return Option.none<ConnectionCatalogEntry>();864+ const next = entryWithRoutes(entry, routes);865+ yield* registrations.setRoutes(input.environmentId, persistedRoutes(next));packages/client-runtime/src/authorization/service.ts line 499OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -466,13 +480,20 @@480+ ...httpAuthorization(token, endpoint?.httpBaseUrl),481+ socketUrl,482+ });466483 let selected = yield* getDpopToken(input);467484 if (selected.fromCache) {468485 const cachedSocket = yield* createDpopSocketUrl(469486 selected.token,470487 CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,488+ endpoint,471489 ).pipe(Effect.result);472490 if (Result.isSuccess(cachedSocket)) {473491 yield* assertSession(selected.identity);474- return { ...httpAuthorization(selected.token), socketUrl: cachedSocket.success };492+ return authorized(selected.token, cachedSocket.success);475493 }476494 if (cachedSocket.failure._tag === "ConnectionBlockedError") {477495 return yield* mapDpopSocketError(cachedSocket.failure);478496 }497+ // An unreachable direct address says nothing about the token, so keep498+ // it for the T3 Connect route rather than forcing a relay round trip.499+ if (endpoint !== undefined) {
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- packages/client-runtime/src/connection/routes.ts lines 310 to 323Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -189,0 +267,21 @@267+ ),268+ });269+ }270+ const before = saved.map((route) => connectionRouteId(route.target)).join("\n");271+ const after = next.map((route) => connectionRouteId(route.target)).join("\n");272+ return before === after ? null : next;273+}274+275+/**276+ * A learned bearer route borrows the credential of the route it was learned277+ * from, so its id points back at that credential's owner.278+ */279+function learnedConnectionId(280+ environmentId: string,281+ host: string,282+ sharedCredential: string | undefined,283+): string {284+ return sharedCredential === undefined285+ ? `learned:${environmentId}:${host}`286+ : `learned:${environmentId}:${host}@${sharedCredential}`;287+}
- apps/server/src/environment/DirectEndpoints.ts line 88Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +45,21 @@45+46+/**47+ * Plain HTTP endpoints for the private addresses a server bound to `host`48+ * accepts. IPv4 only: link-local and temporary IPv6 addresses change too49+ * often to be worth saving.50+ */51+export function resolveBoundEndpoints(input: {52+ readonly host: string | undefined;53+ readonly port: number;54+ readonly interfaces: NetworkInterfacesMap;55+}): ReadonlyArray<ServerDirectEndpoint> {56+ if (isLoopbackHost(input.host)) return [];57+ const addresses = isWildcardHost(input.host)58+ ? Object.values(input.interfaces)59+ .flatMap((entries) => entries ?? [])60+ .filter(61+ (entry) =>62+ !entry.internal && entry.family === "IPv4" && isAdvertisableAddress(entry.address),63+ )64+ .map((entry) => entry.address)65+ : [input.host!].filter(isAdvertisableAddress);
- packages/client-runtime/src/authorization/service.ts lines 491 to 531Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -472,13 +490,19 @@472490 if (Result.isSuccess(cachedSocket)) {473491 yield* assertSession(selected.identity);474- return { ...httpAuthorization(selected.token), socketUrl: cachedSocket.success };492+ return authorized(selected.token, cachedSocket.success);475493 }476494 if (cachedSocket.failure._tag === "ConnectionBlockedError") {477495 return yield* mapDpopSocketError(cachedSocket.failure);478496 }497+ // An unreachable direct address says nothing about the token, so keep498+ // it for the T3 Connect route rather than forcing a relay round trip.499+ // A rejected token falls through and is replaced like on the tunnel.500+ if (endpoint !== undefined && cachedSocket.failure._tag !== "EnvironmentAuthInvalidError") {501+ return yield* mapDpopSocketError(cachedSocket.failure);502+ }479503 selected = yield* getDpopToken({480504 ...input,481505 rejectedAccessToken: selected.token.accessToken,482506 });483507 }484- const socket = yield* createDpopSocketUrl(selected.token).pipe(Effect.result);508+ const socket = yield* createDpopSocketUrl(selected.token, undefined, endpoint).pipe(
- apps/server/src/environment/DirectEndpoints.ts line 114Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +70,21 @@70+ kind: isTailscaleIpv4Address(address) ? "tailnet" : "lan",71+ httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,72+ }));73+}74+75+/** @public Service construction is part of the canonical Effect module API. */76+export const make = Effect.gen(function* () {77+ const config = yield* ServerConfig.ServerConfig;78+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;79+80+ const resolve = Effect.gen(function* () {81+ const endpoints = [82+ ...resolveBoundEndpoints({83+ host: config.host,84+ port: config.port,85+ interfaces: NodeOS.networkInterfaces(),86+ }),87+ ];88+ // Tailscale Serve terminates HTTPS on the tailnet name and forwards to89+ // loopback, so it works even for a loopback-only server.90+ if (config.tailscaleServeEnabled) {@@ -1689,3 +1691,4 @@16891691 remoteOpenTargets: yield* resolveAvailableEditorsForConfig(16901692 remoteOpenTargets.resolveTargets(),16911693 ),1694+ directEndpoints: yield* resolveAvailableEditorsForConfig(directEndpoints.resolve()),@@ -0,0 +64,21 @@64+ (entry) =>65+ !entry.internal && entry.family === "IPv4" && isAdvertisableAddress(entry.address),66+ )67+ .map((entry) => entry.address)68+ : [input.host!].filter(isAdvertisableAddress);69+ return [...new Set(addresses)].map((address) => ({70+ kind: isTailscaleIpv4Address(address) ? "tailnet" : "lan",71+ httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,72+ }));73+}74+75+/** @public Service construction is part of the canonical Effect module API. */76+export const make = Effect.gen(function* () {77+ const config = yield* ServerConfig.ServerConfig;78+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;79+80+ const resolve = Effect.gen(function* () {81+ const endpoints = [82+ ...resolveBoundEndpoints({83+ host: config.host,84+ port: config.port,
juliusmarminge added labels🚀 Mobile Continuous Deployment
juliusmarminge merged this745c225
juliusmarminge closed this
Sign in to join this conversation.

Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
9e84d92· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.