feat: first-class Tailcat networking #9525
ClosedBearHuddleston(GitHub profile, opens in a new tab)wants to merge 25 commits into
main fromrefs/pull/9525/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/desktop/src/tailcat/DesktopTailcatEnvironment.ts line 144Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +158,21 @@158+ const net = yield* NetService.NetService;159+ const httpClient = yield* HttpClient.HttpClient;160+ const serviceScope = yield* Scope.Scope;161+ const entries = yield* Ref.make<ReadonlyMap<string, ForwardEntry>>(new Map());162+ const locks = yield* Ref.make<ReadonlyMap<string, Semaphore.Semaphore>>(new Map());163+164+ const nowIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));165+166+ const lockFor = (connectionId: string) =>167+ Effect.gen(function* () {168+ const current = (yield* Ref.get(locks)).get(connectionId);169+ if (current !== undefined) {170+ return current;171+ }172+ const created = yield* Semaphore.make(1);173+ yield* Ref.update(locks, (map) => new Map(map).set(connectionId, created));174+ return created;175+ });176+177+ const withLock = <A, E>(connectionId: string, effect: Effect.Effect<A, E>) =>178+ lockFor(connectionId).pipe(Effect.flatMap((lock) => lock.withPermits(1)(effect)));apps/server/src/federation/FederationService.ts line 351OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +331,21 @@331+ error._tag === "ExpiredBootstrapCredentialError"332+ ? "This peer code has expired. Create a new one on the other machine."333+ : "This peer code is not valid or was already used.",334+ })335+ : internalError(`Could not validate the peer code: ${error.message}`),336+ ),337+ );338+ if (grant.subject !== FEDERATION_PEER_CODE_PAIRING_SUBJECT) {339+ return yield* new FederationError({340+ code: "code-invalid",341+ message: "This code is a device pairing code, not a federation peer code.",342+ });343+ }344+ const offered =345+ grant.id === undefined ? undefined : (yield* Ref.get(pendingPeerCodes)).get(grant.id);346+ if (offered === undefined) {347+ return yield* new FederationError({348+ code: "code-expired",349+ message: "This peer code is no longer offered by this environment. Create a new one.",350+ });351+ }
- apps/server/src/federation/FederationTransport.ts line 241OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +221,21 @@221+222+ const isActive: FederationTransport["Service"]["isActive"] = (peerId) =>223+ Ref.get(forwards).pipe(224+ Effect.flatMap((current) => {225+ const existing = current.get(peerId);226+ return existing === undefined ? Effect.succeed(false) : existing.handle.isRunning;227+ }),228+ );229+230+ // Idle forwards are child processes with keepalive traffic; close the ones231+ // nobody has called through recently.232+ const sweepIdle = Effect.gen(function* () {233+ const cutoff = (yield* nowMs) - Duration.toMillis(FORWARD_IDLE_TTL);234+ const current = yield* Ref.get(forwards);235+ for (const [peerId, forward] of current) {236+ if (forward.lastUsedAtMs < cutoff) {237+ yield* drop(peerId);238+ yield* Effect.logInfo("Federation transport closed after idling.", { peerId });239+ }240+ }241+ });apps/server/src/federation/FederationTransport.ts line 95OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +75,21 @@75+76+export const make = Effect.gen(function* () {77+ const config = yield* ServerConfig.ServerConfig;78+ const runtime = yield* TailcatRuntime.TailcatRuntime;79+ const net = yield* NetService.NetService;80+ const httpClient = yield* HttpClient.HttpClient;81+ const fileSystem = yield* FileSystem.FileSystem;82+ const path = yield* Path.Path;83+ const serviceScope = yield* Scope.Scope;84+ const identityPath = path.join(config.secretsDir, TAILCAT_CLIENT_IDENTITY_FILE);85+ const forwards = yield* Ref.make<ReadonlyMap<EnvironmentId, ActiveForward>>(new Map());86+ // One lock per peer: a slow or unreachable peer must not stall the others.87+ const locks = yield* Ref.make<ReadonlyMap<EnvironmentId, Semaphore.Semaphore>>(new Map());88+ const lockFor = (peerId: EnvironmentId) =>89+ Effect.gen(function* () {90+ const existing = (yield* Ref.get(locks)).get(peerId);91+ if (existing !== undefined) return existing;92+ const created = yield* Semaphore.make(1);93+ yield* Ref.update(locks, (current) => new Map(current).set(peerId, created));94+ return created;95+ });
- apps/server/src/auth/http.ts lines 390 to 398Resolvedby BearHuddleston(GitHub profile, opens in a new tab)@@ -351,2 +355,21 @@351355 proofKeyThumbprint ? { proofKeyThumbprint } : undefined,352356 );357+ // A Tailcat connection code binds the pairing to the client's node358+ // key: only a grant minted as such may extend the transport359+ // allowlist, so a LAN pairing link cannot smuggle a key in.360+ const tailcatNodeKey = args.payload.client_tailcat_node_key?.trim();361+ if (362+ tailcatNodeKey !== undefined &&363+ exchange.grant.subject === TAILCAT_CONNECTION_CODE_PAIRING_SUBJECT &&364+ isTailcatNodeKey(tailcatNodeKey)365+ ) {366+ yield* tailcatRemoteAccess367+ .recordTrustedPeer({368+ nodeKey: tailcatNodeKey,369+ label: args.payload.client_label,370+ sessionId: exchange.sessionId,371+ })372+ .pipe(373+ Effect.catch((error) =>374+ Effect.logWarning("Could not record the paired Tailcat peer.", { error }),375+ ),apps/server/src/federation/FederationPeerStore.ts line 82OutdatedResolvedby BearHuddleston(GitHub profile, opens in a new tab)@@ -0,0 +62,21 @@62+/**63+ * A run this environment started on a peer. Event tails and sync bookkeeping64+ * are re-fetchable, so they stay in memory; only identity and the last known65+ * projection are written to disk.66+ */67+export const PersistedRemoteRun = Schema.Struct({68+ peerId: EnvironmentId,69+ peerLabel: TrimmedNonEmptyString,70+ run: FederationRun,71+});72+export type PersistedRemoteRun = typeof PersistedRemoteRun.Type;73+74+/**75+ * A peer code this environment offered and has not yet seen redeemed. The76+ * pairing token itself lives in the pairing-link store; this records which77+ * federation scopes the code promises, so a restart cannot orphan a live code.78+ */79+export const PersistedPendingPeerCode = Schema.Struct({80+ linkId: Schema.String,81+ scopes: Schema.Array(FederationScope),82+ expiresAt: Schema.String,apps/server/src/federation/FederationTransport.ts lines 100 to 106OutdatedResolvedby BearHuddleston(GitHub profile, opens in a new tab)@@ -0,0 +86,21 @@86+ // One lock per peer: a slow or unreachable peer must not stall the others.87+ const locks = yield* Ref.make<ReadonlyMap<EnvironmentId, Semaphore.Semaphore>>(new Map());88+ // Created and published in one modify, so concurrent first callers share a lock.89+ const lockFor = (peerId: EnvironmentId) =>90+ Ref.modify(locks, (current) => {91+ const existing = current.get(peerId);92+ if (existing !== undefined) return [existing, current] as const;93+ const created = Semaphore.makeUnsafe(1);94+ return [created, new Map(current).set(peerId, created)] as const;95+ });96+ const withPeerLock = <A, E>(peerId: EnvironmentId, effect: Effect.Effect<A, E>) =>97+ lockFor(peerId).pipe(Effect.flatMap((lock) => lock.withPermits(1)(effect)));98+ const nowMs = DateTime.now.pipe(Effect.map(DateTime.toEpochMillis));99+100+ const clientNodeKey: FederationTransport["Service"]["clientNodeKey"] = Effect.gen(function* () {101+ const exists = yield* fileSystem.exists(identityPath).pipe(Effect.orElseSucceed(() => false));102+ if (!exists) {103+ const created = yield* runtime.generateClientIdentity({ keyPath: identityPath });104+ return created.nodeKey;105+ }106+ return yield* runtime.readClientPublicKey({ keyPath: identityPath });apps/server/src/tailcat/TailcatRemoteAccess.ts lines 216 to 225Resolvedby BearHuddleston(GitHub profile, opens in a new tab)@@ -0,0 +226,21 @@226+ const runtimeState = yield* Ref.make<RuntimeState>(INITIAL_RUNTIME_STATE);227+ const signals = yield* Queue.unbounded<"reconcile">();228+ const expiryTimer = yield* Ref.make<Option.Option<Fiber.Fiber<void>>>(Option.none());229+ const retryTimer = yield* Ref.make<Option.Option<Fiber.Fiber<void>>>(Option.none());230+231+ const persistError = (cause: unknown) =>232+ new TailcatRemoteAccessError({233+ code: "unknown",234+ message: `Could not save Tailcat remote access settings: ${String(cause)}`,235+ });236+237+ const writePersisted = (next: PersistedTailcatRemoteAccess) =>238+ encodePersistedState(next).pipe(239+ Effect.flatMap((contents) =>240+ writeFileStringAtomically({ filePath: statePath, contents: `${contents}\n` }),241+ ),242+ Effect.mapError(persistError),243+ Effect.andThen(Ref.set(persisted, next)),244+ Effect.provideService(FileSystem.FileSystem, fileSystem),245+ Effect.provideService(Path.Path, path),246+ );native/tailcat/README.md lines 5 to 6OutdatedResolvedby BearHuddleston(GitHub profile, opens in a new tab)@@ -0,0 +1,6 @@1+# Tailcat runtime2+3+T3 Code bundles the upstream [Tailcat](https://github.com/tailscale/tailcat) CLI as the transport4+behind Tailcat environments and federation. The binary is pinned by `manifest.json` in this5+directory and verified by SHA-256 before it is staged into any artifact. Nothing downloads a6+"latest" binary at runtime; the runtime only ever runs the executable this manifest describes.packages/client-runtime/src/connection/onboarding.ts line 339Resolvedby BearHuddleston(GitHub profile, opens in a new tab)@@ -244,0 +315,21 @@315+ environmentId: provisioned.environmentId,316+ label,317+ connectionId,318+ }),319+ profile: new TailcatConnectionProfile({320+ connectionId,321+ environmentId: provisioned.environmentId,322+ label,323+ address: payload.address,324+ remotePort: payload.port,325+ }),326+ credential: new BearerConnectionCredential({ token: provisioned.bearerToken }),327+ });328+});329+330+const registerTailcatConnection = Effect.fn(331+ "clientRuntime.connection.onboarding.registerTailcatConnection",332+)(function* (input: TailcatConnectionInput) {333+ const registration = yield* prepareTailcatRegistration(input);334+ const registry = yield* EnvironmentRegistry.EnvironmentRegistry;335+ yield* registry.register(registration);packages/tailcat/src/runtime.ts line 523OutdatedResolvedby BearHuddleston(GitHub profile, opens in a new tab)@@ -0,0 +503,21 @@503+ // address stays stable across restarts instead of changing with whichever504+ // relay happens to be nearest at each start.505+ const result = yield* runCommand({506+ executablePath: runtime.executablePath,507+ args: ["genkey", `--key=${keyPath}`, "--fixed-region", "--force"],508+ subcommand: "genkey",509+ timeout: TAILCAT_SERVE_READY_TIMEOUT,510+ });511+ const lines = result.stdout512+ .split(/\r?\n/u)513+ .map((line) => line.trim())514+ .filter(Boolean);515+ const address = lines.find((line) => line.startsWith("tc"));516+ if (result.exitCode !== 0 || address === undefined) {517+ return yield* new TailcatCommandError({518+ subcommand: "genkey",519+ exitCode: result.exitCode,520+ detail: `Could not create a Tailcat identity: ${redactTailcatOutputLine(result.stderr.trim()) || "tailcat genkey failed"}.`,521+ });522+ }523+ yield* fileSystem.chmod(keyPath, 0o600).pipe(Effect.ignore);
- @@ -0,0 +176,21 @@176+ code: "peer-unreachable",177+ message:178+ "The peer did not answer through Tailcat. It may be offline, or this environment may no longer be trusted by it.",179+ })180+ : error._tag === "TailcatBinaryMissingError" ||181+ error._tag === "TailcatBinaryNotExecutableError" ||182+ error._tag === "TailcatVersionIncompatibleError"183+ ? transportUnavailable(error.message)184+ : new FederationError({ code: "peer-unreachable", message: error.message }),185+ ),186+ );187+ const touchedAt = yield* nowMs;188+ yield* Ref.update(forwards, (current) =>189+ new Map(current).set(peerId, {190+ scope,191+ handle,192+ address: transport.tailcat.address,193+ port: transport.tailcat.port,194+ lastUsedAtMs: touchedAt,195+ }),196+ );@@ -0,0 +270,21 @@270+ remoteProtocolVersion: Schema.NullOr(PositiveInt),271+ remoteCapabilities: Schema.Array(FederationCapability),272+ status: FederationPeerStatus,273+ lastSeenAt: Schema.NullOr(IsoDateTime),274+ lastError: Schema.NullOr(Schema.String),275+ createdAt: IsoDateTime,276+});277+export type FederationPeer = typeof FederationPeer.Type;278+279+export const FederationSnapshot = Schema.Struct({280+ environmentId: EnvironmentId,281+ publicKeyFingerprint: TrimmedNonEmptyString,282+ protocolVersion: PositiveInt,283+ peers: Schema.Array(FederationPeer),284+ updatedAt: IsoDateTime,285+});286+export type FederationSnapshot = typeof FederationSnapshot.Type;287+288+export const FederationCreatePeerCodeInput = Schema.Struct({289+ scopes: FederationScopes,290+ ttlSeconds: Schema.optionalKey(PositiveInt),@@ -0,0 +654,21 @@654+ cause: Cause.squash(cause),655+ }),656+ ),657+ ),658+ );659+ const exited = yield* Deferred.make<Option.Option<number>>();660+ yield* lineStream(handle.stderr).pipe(661+ Stream.runForEach(output.push),662+ Effect.ignore,663+ Effect.forkScoped,664+ );665+ yield* handle.exitCode.pipe(666+ Effect.map((code) => Option.some(Number(code))),667+ Effect.orElseSucceed(() => Option.none<number>()),668+ Effect.flatMap((code) => Deferred.succeed(exited, code)),669+ Effect.forkScoped,670+ );671+ const stdoutLines = lineStream(handle.stdout).pipe(672+ Stream.tap(output.push),673+ Stream.catch(() => Stream.empty),674+ );@@ -0,0 +309,21 @@309+ readonly distRoot: string;310+ readonly verbose: boolean;311+}) {312+ const fs = yield* FileSystem.FileSystem;313+ const path = yield* Path.Path;314+ const { manifest, platformKey } = input;315+ const goTarget = goTargetForPlatformKey(platformKey);316+ const tag = `v${manifest.version}`;317+ const fail = (reason: TailcatSourceBuildError["reason"], detail: string) =>318+ new TailcatSourceBuildError({ platformKey, reason, detail });319+ const git = (args: ReadonlyArray<string>, verbose: boolean) =>320+ runCommand({ command: "git", args, verbose }).pipe(321+ Effect.mapError(() => fail("tool-missing", "git")),322+ );323+324+ const goVersion = yield* runCommand({ command: "go", args: ["version"], verbose: false }).pipe(325+ Effect.mapError(() => fail("tool-missing", "go")),326+ );327+ if (goVersion.exitCode !== 0) {328+ return yield* fail("tool-missing", "go");329+ }@@ -0,0 +475,21 @@475+const selectPlatformKeys = Effect.fn("selectPlatformKeys")(function* (476+ manifest: TailcatManifest,477+ flags: { readonly platform: Option.Option<string>; readonly all: boolean },478+) {479+ const pinned = tailcatManifestPlatformKeys(manifest);480+ if (flags.all) {481+ return pinned;482+ }483+ if (Option.isSome(flags.platform)) {484+ const requested = flags.platform.value;485+ if (!isTailcatPlatformKey(requested)) {486+ return yield* new TailcatPlatformSelectionError({487+ reason: "unknown-platform",488+ detail: requested,489+ });490+ }491+ if (!pinned.includes(requested)) {492+ return yield* new TailcatPlatformSelectionError({ reason: "not-pinned", detail: requested });493+ }494+ return [requested];495+ }
- @@ -0,0 +265,21 @@265+ generation: number,266+ exitCode: Option.Option<number>,267+ ) =>268+ Effect.gen(function* () {269+ const current = yield* getEntry(connectionId);270+ if (Option.isNone(current) || current.value.generation !== generation) {271+ return;272+ }273+ const recorded = yield* failure(274+ "process-exited",275+ `The Tailcat forwarder exited${Option.isSome(exitCode) ? ` with code ${exitCode.value}` : ""}.`,276+ );277+ // This exit is the connection's next consecutive failure (1 = first).278+ const failures = current.value.consecutiveFailures + 1;279+ yield* patchEntry(connectionId, (entry) => ({280+ ...entry,281+ status: "failed",282+ running: null,283+ consecutiveFailures: failures,284+ lastError: recorded,285+ }));@@ -0,0 +213,21 @@213+/**214+ * Follow one remote run through the remote-runs subscription, printing each215+ * event once as it lands, until the run reaches a terminal status. Resolves216+ * with the last snapshot of the run, or none if the server stopped tracking it.217+ */218+const followRemoteRun = Effect.fn("peer.followRemoteRun")(function* (219+ client: WsRpcClient,220+ started: FederationRemoteRun,221+ options: { readonly json: boolean },222+) {223+ const printedThrough = yield* Ref.make(-1);224+ const latest = yield* Ref.make(Option.none<FederationRemoteRun>());225+ yield* client[WS_METHODS.federationSubscribeRemoteRuns]({}).pipe(226+ Stream.map((snapshot) =>227+ snapshot.runs.find(228+ (candidate) =>229+ candidate.peerId === started.peerId && candidate.run.threadId === started.run.threadId,230+ ),231+ ),232+ Stream.filter(Predicate.isNotUndefined),233+ Stream.takeUntil((remoteRun) => isTerminalRunStatus(remoteRun.run.status)),@@ -0,0 +941,21 @@941+ const client = yield* clientFor(endpoint.httpBaseUrl).pipe(942+ Effect.mapError((cause) => internalError(describeCause(cause))),943+ );944+ const attempt = Effect.gen(function* () {945+ const token = yield* sessionFor(peer, client);946+ return yield* call(client, { authorization: `Bearer ${token}` });947+ });948+ return yield* attempt.pipe(949+ Effect.catch((cause) =>950+ // One retry after a session refresh covers a revoked or expired951+ // token; anything else is a real failure.952+ isAuthRejection(cause)953+ ? Ref.update(peerSessions, (current) => withoutKey(current, peer.peerId)).pipe(954+ Effect.andThen(attempt),955+ )956+ : Effect.fail(cause),957+ ),958+ peerTimeout(`${peer.label} did not answer in time.`),959+ Effect.catch((cause) => mapPeerCallError(peer.peerId)(cause)),960+ Effect.tap(() => peers.setPeerStatus(peer.peerId, { status: "online", lastError: null })),961+ );@@ -0,0 +1313,21 @@1313+ return yield* callPeer(peer, (client, headers) =>1314+ client.federation.fetchArtifact({1315+ headers,1316+ params: { threadId: input.threadId, turnId: input.turnId },1317+ }),1318+ );1319+ });1320+1321+ const syncRemoteRun = (record: FederationRemoteRun) =>1322+ Effect.gen(function* () {1323+ const peer = yield* peers.getPeer(record.peerId);1324+ if (Option.isNone(peer)) {1325+ return;1326+ }1327+ const afterSequence = record.events.at(-1)?.sequence ?? 0;1328+ const response = yield* callPeer(peer.value, (client, headers) =>1329+ client.federation.runEvents({1330+ headers,1331+ params: { threadId: record.run.threadId },1332+ payload: { afterSequence },1333+ }),@@ -0,0 +709,21 @@709+ yield* stopRunning;710+ yield* fileSystem.remove(identityPath, { force: true }).pipe(711+ Effect.mapError(712+ (cause) =>713+ new TailcatRemoteAccessError({714+ code: "identity-failed",715+ message: `Could not remove the previous Tailcat identity: ${String(cause)}`,716+ }),717+ ),718+ );719+ yield* Ref.update(runtimeState, (state) => ({720+ ...state,721+ address: null,722+ failures: 0,723+ lastError: null,724+ }));725+ yield* Effect.logInfo("Tailcat identity regenerated; connected devices must re-pair.");726+ yield* signalReconcile;727+ return yield* publish;728+ },729+ ).pipe(Effect.withSpan("TailcatRemoteAccess.regenerateIdentity"));@@ -10,11 +10,20 @@1010 size?: "sm" | "default" | "lg" | number;11+ /** Monospace, for codes and other machine-readable text. */12+ font?: "default" | "mono";1113 unstyled?: boolean;1214 };131514-function Textarea({ className, size = "default", unstyled = false, ...props }: TextareaProps) {16+function Textarea({17+ className,18+ size = "default",19+ font = "default",20+ unstyled = false,21+ ...props22+}: TextareaProps) {1523 return (1624 <span1725 className={1826 cn(1927 !unstyled &&2028 "relative inline-flex w-full rounded-lg border border-input bg-background not-dark:bg-clip-padding text-base text-foreground shadow-xs/5 ring-ring/24 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] has-focus-visible:has-aria-invalid:border-destructive/64 has-focus-visible:has-aria-invalid:ring-destructive/16 has-aria-invalid:border-destructive/36 has-focus-visible:border-ring has-disabled:opacity-64 has-[:disabled,:focus-visible,[aria-invalid]]:shadow-none has-focus-visible:ring-[3px] not-has-disabled:has-not-focus-visible:not-has-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] sm:text-sm dark:bg-input/32 dark:has-aria-invalid:ring-destructive/24 dark:not-has-disabled:has-not-focus-visible:not-has-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)]",29+ font === "mono" && "font-mono",@@ -0,0 +1,4 @@1+# Tailcat Remote Access2+3+Tailcat connects two machines directly through an encrypted tunnel without a VPN, a4+tailnet, port forwarding, or a public address. T3 Code ships Tailcat built in, so a@@ -131,3 +139,17 @@131139 return platform === "win" ? "t3-resource-monitor.exe" : "t3-resource-monitor";132140 }133141142+/**143+ * Tailcat runtime directories a build ships. The runtime resolves144+ * `resources/tailcat/<platform-key>/` by the running process's arch, so a145+ * universal macOS app carries both darwin keys instead of a lipo'd binary.146+ */147+export function resolveTailcatPlatformKeys(148+ platform: typeof BuildPlatform.Type,149+ arch: typeof BuildArch.Type,150+): ReadonlyArray<TailcatPlatformKey> {151+ if (platform === "mac") {152+ if (arch === "universal") {153+ return ["darwin-arm64", "darwin-x64"];154+ }155+ return [arch === "arm64" ? "darwin-arm64" : "darwin-x64"];
BearHuddleston(GitHub profile, opens in a new tab) changed the title
juliusmarminge closed this
Sign in to join this conversation.


Macroscope skipped reviewing this pull request. Per-review cost limit exceeded (workspace setting).
This review would cost an estimated $31.41, which exceeds your per-review limit of $10.00.
The top 3 files driving up this estimate:
apps/server/src/federation/FederationService.tsapps/web/src/components/settings/FederationSection.tsxpackages/tailcat/src/runtime.tsTip
To get this pull request reviewed, you can:
@macroscope-appon this PR to request a manual review (monthly spend limits still apply)..macroscope/ignore.md— note that creating this file replaces Macroscope's built-in default ignores rather than extending them.