diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts index d40e0d97e4842..a27027c6076d1 100644 --- a/apps/server/src/cli/pair.ts +++ b/apps/server/src/cli/pair.ts @@ -31,15 +31,11 @@ import * as Option from "effect/Option"; import * as References from "effect/References"; import * as Schema from "effect/Schema"; import { Command, Flag, GlobalFlag } from "effect/unstable/cli"; -import { - FetchHttpClient, - HttpClient, - HttpClientRequest, - HttpClientResponse, -} from "effect/unstable/http"; +import { FetchHttpClient } from "effect/unstable/http"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerConfig from "../config.ts"; +import { type EnvironmentProbeResult, probeEnvironmentDescriptor } from "../environmentProbe.ts"; import { resolveBaseDir } from "../os-jank.ts"; import { type PersistedServerRuntimeState, @@ -56,8 +52,6 @@ import { } from "../startupAccess.ts"; import { baseDirFlag, DurationFromString } from "./config.ts"; -const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment"; -const PAIR_PROBE_TIMEOUT = Duration.millis(2_500); // Tailscale provisions an HTTPS certificate on the first request to a fresh // serve mapping, which can take a few seconds. const TAILSCALE_PROBE_ATTEMPTS = 5; @@ -193,43 +187,6 @@ export const formatPairOutput = (input: { "", ].join("\n"); -/** - * Three outcomes, because they drive different decisions: a T3 descriptor - * (pair with it), nothing answering (safe to configure Tailscale Serve), or - * something answering that is not a T3 server (do NOT overwrite its mapping). - */ -type EnvironmentProbeResult = - | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor } - | { readonly _tag: "unreachable" } - | { readonly _tag: "not-a-t3-server" }; - -const probeEnvironmentDescriptor = ( - baseUrl: string, -): Effect.Effect => - Effect.gen(function* () { - const client = yield* HttpClient.HttpClient; - const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString()); - const response = yield* client.execute(request).pipe( - Effect.timeout(PAIR_PROBE_TIMEOUT), - // Transport failure or timeout: nothing (reachable) is listening there. - Effect.mapError(() => ({ _tag: "unreachable" }) as const), - ); - // Bad-gateway family means a proxy (Tailscale Serve) answered for a - // backend that is gone — a stale mapping, not a live occupant. Treating - // it as unreachable lets `t3 pair --tailscale` repair its own mapping - // after the server's port changed. - if (response.status === 502 || response.status === 503 || response.status === 504) { - return { _tag: "unreachable" } as const; - } - // Anything else that answered HTTP but not with a valid descriptor is - // some other service. - const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe( - Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)), - Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const), - ); - return { _tag: "descriptor", descriptor } as const; - }).pipe(Effect.catch((outcome) => Effect.succeed(outcome))); - interface DiscoveredPairTarget { readonly baseDir: string; readonly variant: PairStateVariant; diff --git a/apps/server/src/environmentProbe.ts b/apps/server/src/environmentProbe.ts new file mode 100644 index 0000000000000..26da0eae3191c --- /dev/null +++ b/apps/server/src/environmentProbe.ts @@ -0,0 +1,50 @@ +/** + * "Is a T3 Code server answering at this origin?" — shared by `t3 pair` + * discovery and by the Tailscale Serve ownership check, which both have to + * decide whether an endpoint is safe to take over. + */ +import { ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"; + +const WELL_KNOWN_ENVIRONMENT_PATH = "/.well-known/t3/environment"; +const ENVIRONMENT_PROBE_TIMEOUT = Duration.millis(2_500); + +/** + * Three outcomes, because they drive different decisions: a T3 descriptor + * (pair with it, or leave its serve mapping alone), nothing answering (safe to + * configure Tailscale Serve), or something answering that is not a T3 server + * (do NOT overwrite its mapping). + */ +export type EnvironmentProbeResult = + | { readonly _tag: "descriptor"; readonly descriptor: ExecutionEnvironmentDescriptor } + | { readonly _tag: "unreachable" } + | { readonly _tag: "not-a-t3-server" }; + +export const probeEnvironmentDescriptor = ( + baseUrl: string, +): Effect.Effect => + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString()); + const response = yield* client.execute(request).pipe( + Effect.timeout(ENVIRONMENT_PROBE_TIMEOUT), + // Transport failure or timeout: nothing (reachable) is listening there. + Effect.mapError(() => ({ _tag: "unreachable" }) as const), + ); + // Bad-gateway family means a proxy (Tailscale Serve) answered for a + // backend that is gone — a stale mapping, not a live occupant. Treating + // it as unreachable lets a server repair its own mapping after the + // previous owner's port went away. + if (response.status === 502 || response.status === 503 || response.status === 504) { + return { _tag: "unreachable" } as const; + } + // Anything else that answered HTTP but not with a valid descriptor is + // some other service. + const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe( + Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)), + Effect.mapError(() => ({ _tag: "not-a-t3-server" }) as const), + ); + return { _tag: "descriptor", descriptor } as const; + }).pipe(Effect.catch((outcome) => Effect.succeed(outcome))); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 696210b36b86a..4b2afb0839460 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -135,8 +135,8 @@ import { import { orchestrationHttpApiLayer } from "./orchestration/http.ts"; import * as NetService from "@t3tools/shared/Net"; import * as RelayClient from "@t3tools/shared/relayClient"; -import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale"; import { forkParked, ServerActivation } from "./serverActivation.ts"; +import { acquireTailscaleServe, releaseTailscaleServe } from "./tailscaleServe.ts"; // MCP handoff thread IDs include escaped provenance and can exceed find-my-way's // 100-character default for one path segment. @@ -628,44 +628,12 @@ export const makeServerLayer = Layer.unwrap( return null; } - const localPort = address.port; - return yield* ensureTailscaleServe({ - localPort, + return yield* acquireTailscaleServe({ + localPort: address.port, servePort: config.tailscaleServePort, - localHost: "127.0.0.1", - }).pipe( - Effect.as({ localPort, servePort: config.tailscaleServePort }), - Effect.tap(() => - Effect.logInfo("Tailscale Serve configured", { - localPort, - servePort: config.tailscaleServePort, - }), - ), - Effect.catch((cause) => - Effect.logWarning("Failed to configure Tailscale Serve", { - cause, - localPort, - servePort: config.tailscaleServePort, - }).pipe(Effect.as(null)), - ), - ); + }); }), - (configured) => - configured - ? disableTailscaleServe({ servePort: configured.servePort }).pipe( - Effect.tap(() => - Effect.logInfo("Tailscale Serve disabled", { - servePort: configured.servePort, - }), - ), - Effect.catch((cause) => - Effect.logWarning("Failed to disable Tailscale Serve", { - cause, - servePort: configured.servePort, - }), - ), - ) - : Effect.void, + releaseTailscaleServe, ), ) : Layer.empty; diff --git a/apps/server/src/tailscaleServe.test.ts b/apps/server/src/tailscaleServe.test.ts new file mode 100644 index 0000000000000..3dbb139043dce --- /dev/null +++ b/apps/server/src/tailscaleServe.test.ts @@ -0,0 +1,177 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import { HttpClient, HttpClientError, HttpClientResponse } from "effect/unstable/http"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { acquireTailscaleServe, releaseTailscaleServe } from "./tailscaleServe.ts"; + +const encoder = new TextEncoder(); + +const descriptorJson = JSON.stringify({ + environmentId: "environment-primary", + label: "primary", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.38", + capabilities: {}, +}); + +const serveStatusJson = (localPort: number) => + JSON.stringify({ + TCP: { "10010": { HTTPS: true } }, + Web: { + "host.tail.ts.net:10010": { + Handlers: { "/": { Proxy: `http://127.0.0.1:${String(localPort)}` } }, + }, + }, + }); + +function mockHandle(stdout: string) { + return 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(encoder.encode(stdout)), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); +} + +/** Records every tailscale invocation and answers `serve status` with `status`. */ +function spawnerLayer(status: string) { + const commands: Array> = []; + const layer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + const args = (command as unknown as { readonly args: ReadonlyArray }).args; + commands.push(args); + return Effect.succeed(mockHandle(args[1] === "status" ? status : "")); + }), + ); + return { commands, layer }; +} + +/** Answers the local descriptor probe: a live T3 server, or nothing listening. */ +function httpClientLayer(alive: boolean) { + const probed: Array = []; + const layer = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => { + probed.push(request.url); + return alive + ? Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(descriptorJson, { + status: 200, + headers: { "content-type": "application/json" }, + }), + ), + ) + : Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request, + description: "connection refused", + cause: new Error("ECONNREFUSED"), + }), + }), + ); + }), + ); + return { probed, layer }; +} + +const serveWrites = (commands: ReadonlyArray>) => + commands.filter((args) => args[1] === "--bg"); + +describe("tailscaleServe", () => { + it.effect("writes the mapping when the serve port is free", () => { + const spawner = spawnerLayer("{}"); + const http = httpClientLayer(false); + + return Effect.gen(function* () { + const owned = yield* acquireTailscaleServe({ localPort: 3773, servePort: 10010 }); + + assert.deepEqual(owned, { localPort: 3773, servePort: 10010 }); + assert.deepEqual(serveWrites(spawner.commands), [ + ["serve", "--bg", "--https=10010", "http://127.0.0.1:3773"], + ]); + assert.deepEqual(http.probed, []); + }).pipe(Effect.provide(Layer.merge(spawner.layer, http.layer))); + }); + + it.effect("keeps a mapping that already fronts a live server on another port", () => { + const spawner = spawnerLayer(serveStatusJson(3773)); + const http = httpClientLayer(true); + + return Effect.gen(function* () { + // The second desktop instance: same environment, next free backend port. + const owned = yield* acquireTailscaleServe({ localPort: 3774, servePort: 10010 }); + + assert.equal(owned, null); + assert.deepEqual(serveWrites(spawner.commands), []); + assert.deepEqual(http.probed, ["http://127.0.0.1:3773/.well-known/t3/environment"]); + }).pipe(Effect.provide(Layer.merge(spawner.layer, http.layer))); + }); + + it.effect("reclaims a mapping whose target no longer answers", () => { + const spawner = spawnerLayer(serveStatusJson(3774)); + const http = httpClientLayer(false); + + return Effect.gen(function* () { + const owned = yield* acquireTailscaleServe({ localPort: 3773, servePort: 10010 }); + + assert.deepEqual(owned, { localPort: 3773, servePort: 10010 }); + assert.deepEqual(serveWrites(spawner.commands), [ + ["serve", "--bg", "--https=10010", "http://127.0.0.1:3773"], + ]); + }).pipe(Effect.provide(Layer.merge(spawner.layer, http.layer))); + }); + + it.effect("adopts a mapping that already points at this server", () => { + const spawner = spawnerLayer(serveStatusJson(3773)); + const http = httpClientLayer(true); + + return Effect.gen(function* () { + const owned = yield* acquireTailscaleServe({ localPort: 3773, servePort: 10010 }); + + assert.deepEqual(owned, { localPort: 3773, servePort: 10010 }); + assert.deepEqual(serveWrites(spawner.commands), []); + assert.deepEqual(http.probed, []); + }).pipe(Effect.provide(Layer.merge(spawner.layer, http.layer))); + }); + + it.effect("removes the mapping on shutdown while it still points here", () => { + const spawner = spawnerLayer(serveStatusJson(3773)); + + return Effect.gen(function* () { + yield* releaseTailscaleServe({ localPort: 3773, servePort: 10010 }); + + assert.deepEqual( + spawner.commands.filter((args) => args.includes("off")), + [["serve", "--https=10010", "off"]], + ); + }).pipe(Effect.provide(spawner.layer)); + }); + + it.effect("leaves a mapping another server has taken over", () => { + const spawner = spawnerLayer(serveStatusJson(3775)); + + return Effect.gen(function* () { + yield* releaseTailscaleServe({ localPort: 3773, servePort: 10010 }); + + assert.deepEqual( + spawner.commands.filter((args) => args.includes("off")), + [], + ); + }).pipe(Effect.provide(spawner.layer)); + }); +}); diff --git a/apps/server/src/tailscaleServe.ts b/apps/server/src/tailscaleServe.ts new file mode 100644 index 0000000000000..edbfd940f4dbf --- /dev/null +++ b/apps/server/src/tailscaleServe.ts @@ -0,0 +1,139 @@ +/** + * Ownership rules for the Tailscale Serve mapping a server publishes. + * + * The mapping is tailnet-wide state keyed only by HTTPS port, so every server + * that starts with `tailscaleServeEnabled` competes for the same slot — a + * second desktop instance lands on the next free backend port and would + * otherwise repoint the tailnet URL away from the healthy first one. The rule + * is therefore: claim the mapping when it is free, ours, or stale, and never + * when it still reaches a live server. + */ +import { + disableTailscaleServe, + ensureTailscaleServe, + readTailscaleServeTarget, + type TailscaleServeTarget, +} from "@t3tools/tailscale"; +import * as Effect from "effect/Effect"; +import { HttpClient } from "effect/unstable/http"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { probeEnvironmentDescriptor } from "./environmentProbe.ts"; +import { formatHostForUrl, isLoopbackHost } from "./startupAccess.ts"; + +/** A mapping this server wrote, and is therefore allowed to remove again. */ +export interface OwnedTailscaleServeMapping { + readonly servePort: number; + readonly localPort: number; +} + +// The server always publishes itself on loopback, so a loopback target on our +// port is our own mapping - persisted by tailscale across a restart, or just +// written by us. +const isOwnMapping = (target: TailscaleServeTarget, localPort: number): boolean => + target.localPort === localPort && isLoopbackHost(target.localHost); + +const targetOrigin = (target: TailscaleServeTarget): string => + `http://${formatHostForUrl(target.localHost)}:${String(target.localPort)}`; + +/** + * Points the serve mapping at this server unless something live already holds + * it. Returns the mapping to remove on shutdown, or null when this server does + * not own one. + */ +export const acquireTailscaleServe = Effect.fn("server.tailscaleServe.acquire")(function* (input: { + readonly localPort: number; + readonly servePort: number; +}): Effect.fn.Return< + OwnedTailscaleServeMapping | null, + never, + ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient +> { + const { localPort, servePort } = input; + const existing = yield* readTailscaleServeTarget({ servePort }).pipe( + // An unreadable mapping is treated as unclaimed, which is what this did + // before there was a check at all. + Effect.catch((cause) => + Effect.logWarning("Could not read the Tailscale Serve mapping; treating it as unclaimed", { + cause, + servePort, + }).pipe(Effect.as(null)), + ), + ); + + if (existing !== null) { + if (isOwnMapping(existing, localPort)) { + yield* Effect.logInfo("Tailscale Serve already maps to this server", { + localPort, + servePort, + }); + return { localPort, servePort }; + } + const occupant = yield* probeEnvironmentDescriptor(targetOrigin(existing)); + if (occupant._tag !== "unreachable") { + yield* Effect.logWarning( + "Tailscale Serve already fronts a live server on another port; leaving it in place", + { + localPort, + servePort, + existingLocalPort: existing.localPort, + ...(occupant._tag === "descriptor" + ? { existingEnvironmentId: occupant.descriptor.environmentId } + : {}), + }, + ); + return null; + } + yield* Effect.logInfo("Reclaiming a Tailscale Serve mapping whose target is gone", { + localPort, + servePort, + staleLocalPort: existing.localPort, + }); + } + + return yield* ensureTailscaleServe({ localPort, servePort, localHost: "127.0.0.1" }).pipe( + Effect.as({ localPort, servePort }), + Effect.tap(() => Effect.logInfo("Tailscale Serve configured", { localPort, servePort })), + Effect.catch((cause) => + Effect.logWarning("Failed to configure Tailscale Serve", { + cause, + localPort, + servePort, + }).pipe(Effect.as(null)), + ), + ); +}); + +/** + * Removes the mapping on shutdown, but only while it still points at us: a + * server that started later may have taken it over legitimately, and tearing + * that down would strand the tailnet URL. + */ +export const releaseTailscaleServe = ( + owned: OwnedTailscaleServeMapping | null, +): Effect.Effect => { + if (owned === null) { + return Effect.void; + } + return Effect.gen(function* () { + const current = yield* readTailscaleServeTarget({ servePort: owned.servePort }).pipe( + Effect.orElseSucceed(() => null), + ); + if (current !== null && !isOwnMapping(current, owned.localPort)) { + yield* Effect.logInfo("Tailscale Serve now points elsewhere; leaving it in place", { + servePort: owned.servePort, + currentLocalPort: current.localPort, + }); + return; + } + yield* disableTailscaleServe({ servePort: owned.servePort }).pipe( + Effect.tap(() => Effect.logInfo("Tailscale Serve disabled", { servePort: owned.servePort })), + Effect.catch((cause) => + Effect.logWarning("Failed to disable Tailscale Serve", { + cause, + servePort: owned.servePort, + }), + ), + ); + }); +}; diff --git a/packages/tailscale/src/tailscale.test.ts b/packages/tailscale/src/tailscale.test.ts index 102153f6e2046..7ea89d7df8c56 100644 --- a/packages/tailscale/src/tailscale.test.ts +++ b/packages/tailscale/src/tailscale.test.ts @@ -16,7 +16,9 @@ import { ensureTailscaleServe, isTailscaleIpv4Address, parseTailscaleMagicDnsName, + parseTailscaleServeTarget, parseTailscaleStatus, + readTailscaleServeTarget, readTailscaleStatus, TAILSCALE_STATUS_TIMEOUT, TailscaleCommandExitError, @@ -67,6 +69,18 @@ function assertCarriesNoSecret(error: object, secret: string): void { const tailscaleStatusJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.100.100.100","fd7a:115c:a1e0::1","192.168.1.20"]}}`; const tailscaleStatusWithSingleIpJson = `{"Self":{"DNSName":"desktop.tail.ts.net.","TailscaleIPs":["100.90.1.2"]}}`; +const tailscaleServeStatusJson = JSON.stringify({ + TCP: { "10010": { HTTPS: true } }, + Web: { + "desktop.tail.ts.net:10010": { + Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } }, + }, + "desktop.tail.ts.net:443": { + Handlers: { "/": { Proxy: "http://127.0.0.1:5173" } }, + }, + }, +}); + function mockHandle(result: { stdout?: string; stderr?: string; code?: number }) { return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), @@ -378,4 +392,38 @@ describe("tailscale", () => { ]); }); }); + + it.effect("reads the serve mapping's local target", () => { + const layer = mockSpawnerLayer((command, args) => { + assert.equal(command, "tailscale"); + assert.deepEqual(args, ["serve", "status", "--json"]); + return { stdout: tailscaleServeStatusJson }; + }); + + return Effect.gen(function* () { + assert.deepEqual( + yield* readTailscaleServeTarget({ servePort: 10010 }).pipe(Effect.provide(layer)), + { + localHost: "127.0.0.1", + localPort: 3773, + }, + ); + // A serve port with no mapping must read as unclaimed, not as the + // mapping that happens to sit on another port. + assert.equal( + yield* readTailscaleServeTarget({ servePort: 8443 }).pipe(Effect.provide(layer)), + null, + ); + }); + }); + + it.effect("defaults the serve port to HTTPS", () => + Effect.gen(function* () { + assert.deepEqual(yield* parseTailscaleServeTarget(tailscaleServeStatusJson), { + localHost: "127.0.0.1", + localPort: 5173, + }); + assert.equal(yield* parseTailscaleServeTarget("{}", { servePort: 10010 }), null); + }), + ); }); diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.ts index 7f1cf41661fba..353f79b52320d 100644 --- a/packages/tailscale/src/tailscale.ts +++ b/packages/tailscale/src/tailscale.ts @@ -157,6 +157,18 @@ const collectStderr = collectStdout; const decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson)); +// `tailscale serve status --json` nests the mapping under +// Web[":"].Handlers["/"].Proxy. Only that leaf is needed and the +// surrounding shape moves between tailscale releases, so it is walked as +// unknown rather than modelled. +const TailscaleServeStatusJson = Schema.Struct({ + Web: Schema.optional(Schema.Unknown), +}); + +const decodeTailscaleServeStatusJson = Schema.decodeEffect( + Schema.fromJsonString(TailscaleServeStatusJson), +); + function normalizeMagicDnsName(status: TailscaleStatusJson): string | null { const dnsName = status.Self?.DNSName; if (typeof dnsName !== "string") { @@ -216,100 +228,42 @@ export const parseTailscaleStatus = ( }), ); -export const readTailscaleStatus = Effect.gen(function* () { - const args = ["status", "--json"]; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const hostPlatform = yield* HostProcessPlatform; - const executable = tailscaleCommandForPlatform(hostPlatform); - const commandContext = { - executable, - subcommand: "status" as const, - argumentCount: args.length, - }; - return yield* Effect.gen(function* () { - const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe( - Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })), - // Spawning can also fail as a defect rather than a typed error - a - // non-directory entry on PATH makes node throw ENOTDIR synchronously. - // `mapError` never sees that, so it would escape as an uncaught error. - Effect.catchDefect((cause) => - Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })), - ), - ); - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - collectStdout(child.stdout), - collectStderr(child.stderr), - child.exitCode.pipe(Effect.map(Number)), - ], - { concurrency: "unbounded" }, - ).pipe( - Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })), - ); - if (exitCode !== 0) { - return yield* new TailscaleCommandExitError({ - ...commandContext, - exitCode, - stdoutLength: stdout.length, - stderrLength: stderr.length, - ...(stderrDiagnosticOf(stderr) !== undefined - ? { stderrDiagnostic: stderrDiagnosticOf(stderr) } - : {}), - }); - } - return yield* parseTailscaleStatus(stdout); - }).pipe( - Effect.scoped, - Effect.timeout(TAILSCALE_STATUS_TIMEOUT), - Effect.catchTags({ - TimeoutError: (cause) => - Effect.fail( - new TailscaleCommandTimeoutError({ - ...commandContext, - timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT), - cause, - }), - ), - }), - ); -}); - -export function buildTailscaleHttpsBaseUrl(input: { - readonly magicDnsName: string; - readonly servePort?: number; -}): string { - const url = new URL(`https://${input.magicDnsName}`); - const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT; - if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) { - url.port = String(servePort); - } - url.pathname = "/"; - return url.toString(); -} - -const runTailscaleCommand = ( +/** + * Runs a tailscale subcommand and returns its stdout. Shared by every reader + * here so the scoped spawn, the timeout, and the redacted error shape stay + * identical across `status` and `serve status`. + */ +const captureTailscaleCommand = ( args: readonly string[], + subcommand: "status" | "serve", timeoutInput: Duration.Input, -): Effect.Effect => +): Effect.Effect => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const hostPlatform = yield* HostProcessPlatform; const executable = tailscaleCommandForPlatform(hostPlatform); const commandContext = { executable, - subcommand: "serve" as const, + subcommand, argumentCount: args.length, }; const timeout = Duration.fromInputUnsafe(timeoutInput); return yield* Effect.gen(function* () { const child = yield* spawner.spawn(ChildProcess.make(executable, args)).pipe( Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })), + // Spawning can also fail as a defect rather than a typed error - a + // non-directory entry on PATH makes node throw ENOTDIR synchronously. + // `mapError` never sees that, so it would escape as an uncaught error. Effect.catchDefect((cause) => Effect.fail(new TailscaleCommandSpawnError({ ...commandContext, cause })), ), ); - const [stderr, exitCode] = yield* Effect.all( - [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))], + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectStdout(child.stdout), + collectStderr(child.stderr), + child.exitCode.pipe(Effect.map(Number)), + ], { concurrency: "unbounded" }, ).pipe( Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })), @@ -318,12 +272,14 @@ const runTailscaleCommand = ( return yield* new TailscaleCommandExitError({ ...commandContext, exitCode, + stdoutLength: stdout.length, stderrLength: stderr.length, ...(stderrDiagnosticOf(stderr) !== undefined ? { stderrDiagnostic: stderrDiagnosticOf(stderr) } : {}), }); } + return stdout; }).pipe( Effect.scoped, Effect.timeout(timeout), @@ -340,6 +296,31 @@ const runTailscaleCommand = ( ); }); +export const readTailscaleStatus = captureTailscaleCommand( + ["status", "--json"], + "status", + TAILSCALE_STATUS_TIMEOUT, +).pipe(Effect.flatMap(parseTailscaleStatus)); + +export function buildTailscaleHttpsBaseUrl(input: { + readonly magicDnsName: string; + readonly servePort?: number; +}): string { + const url = new URL(`https://${input.magicDnsName}`); + const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT; + if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) { + url.port = String(servePort); + } + url.pathname = "/"; + return url.toString(); +} + +const runTailscaleCommand = ( + args: readonly string[], + timeoutInput: Duration.Input, +): Effect.Effect => + captureTailscaleCommand(args, "serve", timeoutInput).pipe(Effect.asVoid); + export const ensureTailscaleServe = (input: { readonly localPort: number; readonly servePort?: number; @@ -381,3 +362,103 @@ export const probeTailscaleHttpsEndpoint = (input: { onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300, }); }).pipe(Effect.orElseSucceed(() => false)); + +/** Where a serve mapping points: the local origin Tailscale proxies to. */ +export interface TailscaleServeTarget { + readonly localHost: string; + readonly localPort: number; +} + +/** + * The Web section is keyed by ":"; a key without a port is the + * implicit HTTPS default. + */ +const servePortOfWebKey = (hostPort: string): number => { + const separator = hostPort.lastIndexOf(":"); + if (separator === -1) { + return DEFAULT_TAILSCALE_SERVE_PORT; + } + const port = Number.parseInt(hostPort.slice(separator + 1), 10); + return Number.isInteger(port) ? port : DEFAULT_TAILSCALE_SERVE_PORT; +}; + +const rootProxyOfWebEntry = (entry: unknown): string | undefined => { + if (typeof entry !== "object" || entry === null) { + return undefined; + } + const handlers = (entry as { readonly Handlers?: unknown }).Handlers; + if (typeof handlers !== "object" || handlers === null) { + return undefined; + } + const root = (handlers as Record)["/"]; + if (typeof root !== "object" || root === null) { + return undefined; + } + const proxy = (root as { readonly Proxy?: unknown }).Proxy; + return typeof proxy === "string" && proxy.length > 0 ? proxy : undefined; +}; + +const parseProxyTarget = (proxy: string): TailscaleServeTarget | null => { + // Tailscale writes a full URL, but a bare host:port is tolerated so a + // hand-written mapping classifies as occupied instead of as absent. + for (const candidate of [proxy, `http://${proxy}`]) { + let url: URL; + try { + url = new URL(candidate); + } catch { + continue; + } + const port = + url.port.length > 0 ? Number.parseInt(url.port, 10) : url.protocol === "https:" ? 443 : 80; + if (!Number.isInteger(port) || url.hostname.length === 0) { + continue; + } + return { localHost: url.hostname, localPort: port }; + } + return null; +}; + +/** + * The local target of the serve mapping on `servePort`, or null when that port + * carries no mapping this can read as a proxy. + */ +export const parseTailscaleServeTarget = ( + rawServeStatusJson: string, + input: { readonly servePort?: number } = {}, +): Effect.Effect => + decodeTailscaleServeStatusJson(rawServeStatusJson).pipe( + Effect.mapError((cause) => new TailscaleStatusParseError({ cause })), + Effect.map((parsed) => { + const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT; + const web = parsed.Web; + if (typeof web !== "object" || web === null) { + return null; + } + for (const [hostPort, entry] of Object.entries(web as Record)) { + if (servePortOfWebKey(hostPort) !== servePort) { + continue; + } + const proxy = rootProxyOfWebEntry(entry); + if (proxy === undefined) { + continue; + } + return parseProxyTarget(proxy); + } + return null; + }), + ); + +/** + * Reads who currently owns the serve mapping. Callers use this to avoid + * repointing a mapping that already fronts a live server. + */ +export const readTailscaleServeTarget = ( + input: { readonly servePort?: number } = {}, +): Effect.Effect< + TailscaleServeTarget | null, + TailscaleCommandError | TailscaleStatusParseError, + ChildProcessSpawner.ChildProcessSpawner +> => + captureTailscaleCommand(["serve", "status", "--json"], "serve", TAILSCALE_STATUS_TIMEOUT).pipe( + Effect.flatMap((stdout) => parseTailscaleServeTarget(stdout, input)), + );