// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // The client side of one map long-poll (mapSession in tailscale.com's // controlclient): applies full and delta MapResponses to the state they // describe, and builds the network map the rest of the client works from. import type { DERPMap, DNSConfig, FilterRule, MapResponse, PeerChange, TailNode, UserProfile, WireNode } from "./control-types.ts"; /** The network as control last described it. */ export interface NetMap { /** This node. */ self: TailNode; /** This node's node key, "nodekey:". */ nodeKey: string; /** This node's Tailscale addresses as CIDR prefixes ("100.64.0.1/32", "fd7a:...:1/128"). */ addresses: string[]; /** When the node key expires, null if it does not. */ keyExpiry: Date | null; /** The node key has expired (by control's flag or the clock). */ expired: boolean; /** The MagicDNS name, without the trailing dot. */ name: string; /** Peers sorted by ID. */ peers: TailNode[]; /** DERP regions, or null before control has sent any. */ derpMap: DERPMap | null; /** DNS settings, or null if control has sent none. */ dns: DNSConfig | null; /** Packet filter: rules for traffic into this node (all named filters concatenated). */ packetFilter: FilterRule[]; /** Tailnet name. */ domain: string; /** Users of the nodes, by user ID. */ userProfiles: Record; /** Problems control sees with this node; empty when healthy. */ health: string[]; sshPolicy: unknown; /** Control's clock at the last response, if it said. */ controlTime: Date | null; } const ZERO_TIME = "0001-01-01T00:00:00Z"; /** Normalises a wire node: HomeDERP from the legacy "127.3.3.40:N", AllowedIPs from Addresses. */ export function normalizeNode(n: WireNode): TailNode { const out = { ...n } as TailNode; if (typeof n.DERP === "string" && n.DERP) { if (!out.HomeDERP) { const m = /^127\.3\.3\.40:(\d+)$/.exec(n.DERP); if (m) out.HomeDERP = Number(m[1]); } delete out.DERP; } out.HomeDERP ??= 0; out.Addresses = n.Addresses ?? []; out.Endpoints = n.Endpoints ?? []; if (n.AllowedIPs == null) out.AllowedIPs = [...out.Addresses]; // An unsigned peer may not route more than its own addresses. if (n.UnsignedPeerAPIOnly) out.AllowedIPs = [...out.Addresses]; return out; } /** Parses a Go time; null for absent or the zero time. */ export function parseTime(s: string | null | undefined): Date | null { if (!s || s === ZERO_TIME || s.startsWith("0001-01-01")) return null; const d = new Date(s); return Number.isNaN(d.getTime()) ? null : d; } /** State of one map session (one streaming /machine/map response). */ export class MapSession { readonly peers = new Map(); self: TailNode | null = null; derpMap: DERPMap | null = null; dns: DNSConfig | null = null; domain = ""; health: string[] = []; sshPolicy: unknown = null; controlTime: Date | null = null; readonly userProfiles = new Map(); /** Named packet filters ("base" for MapResponse.PacketFilter). */ readonly packetFilters = new Map(); /** From the first response, for resuming (unused by servers today). */ sessionHandle = ""; seq = 0; /** Non-keepalive responses applied. */ updates = 0; /** The clock, for PeerSeenChange and expiry (tests replace it). */ now: () => Date = () => new Date(); /** * Applies one response. Returns true when it changed the netmap (anything * but a keep-alive). */ apply(resp: MapResponse): boolean { if (resp.ControlTime) this.controlTime = parseTime(resp.ControlTime); if (resp.KeepAlive) return false; if (resp.MapSessionHandle) this.sessionHandle = resp.MapSessionHandle; if (resp.Seq) this.seq = resp.Seq; this.updates++; this.#applyPeers(resp); if (resp.Node) this.self = normalizeNode(resp.Node); for (const up of resp.UserProfiles ?? []) this.userProfiles.set(up.ID, up); if (resp.DERPMap) { const dm: DERPMap = { ...resp.DERPMap }; if (dm.Regions) { const regions: Record = {}; for (const [id, r] of Object.entries(dm.Regions)) if (r) regions[id] = r; dm.Regions = regions; } const last = this.derpMap; if (last) { if (!dm.Regions) { dm.Regions = last.Regions; if (last.omitDefaultRegions !== undefined) dm.omitDefaultRegions = last.omitDefaultRegions; } if (!dm.HomeParams) { if (last.HomeParams) dm.HomeParams = last.HomeParams; } else if (!dm.HomeParams.RegionScore && last.HomeParams?.RegionScore) { dm.HomeParams = { ...dm.HomeParams, RegionScore: last.HomeParams.RegionScore }; } } dm.Regions ??= {}; this.derpMap = dm; } if (resp.PacketFilter != null) this.packetFilters.set("base", resp.PacketFilter); if (resp.PacketFilters) { if ("*" in resp.PacketFilters && resp.PacketFilters["*"] == null) this.packetFilters.clear(); for (const [k, v] of Object.entries(resp.PacketFilters)) { if (k === "*") continue; if (v) this.packetFilters.set(k, v); else this.packetFilters.delete(k); } } if (resp.DNSConfig) this.dns = resp.DNSConfig; if (resp.Domain) this.domain = resp.Domain; if (resp.Health != null) this.health = resp.Health; if (resp.SSHPolicy != null) this.sshPolicy = resp.SSHPolicy; return true; } #applyPeers(resp: MapResponse): void { const peers = this.peers; if (resp.Peers && resp.Peers.length) { peers.clear(); for (const n of resp.Peers) peers.set(n.ID, normalizeNode(n)); return; } for (const id of resp.PeersRemoved ?? []) peers.delete(id); for (const n of resp.PeersChanged ?? []) peers.set(n.ID, normalizeNode(n)); for (const [id, seen] of Object.entries(resp.PeerSeenChange ?? {})) { const p = peers.get(Number(id)); if (!p) continue; peers.set(p.ID, { ...p, LastSeen: seen ? this.now().toISOString() : null }); } for (const [id, online] of Object.entries(resp.OnlineChange ?? {})) { const p = peers.get(Number(id)); if (p) peers.set(p.ID, { ...p, Online: online }); } for (const pc of resp.PeersChangedPatch ?? []) { const p = peers.get(pc.NodeID); if (p) peers.set(p.ID, applyPeerChange(p, pc)); } } /** The current netmap, or null until control has described this node. */ netmap(): NetMap | null { const self = this.self; if (!self) return null; const keyExpiry = parseTime(self.KeyExpiry); const now = this.controlTime ?? this.now(); const filterKeys = [...this.packetFilters.keys()].sort(); const userProfiles: Record = {}; for (const [id, up] of this.userProfiles) userProfiles[id] = up; return { self, nodeKey: self.Key, addresses: self.Addresses, keyExpiry, expired: Boolean(self.Expired) || (keyExpiry !== null && keyExpiry.getTime() <= now.getTime()), name: (self.Name ?? "").replace(/\.$/, ""), peers: [...this.peers.values()].sort((a, b) => a.ID - b.ID), derpMap: this.derpMap, dns: this.dns, packetFilter: filterKeys.flatMap((k) => this.packetFilters.get(k)!), domain: this.domain, userProfiles, health: this.health, sshPolicy: this.sshPolicy, controlTime: this.controlTime, }; } } function applyPeerChange(p: TailNode, pc: PeerChange): TailNode { const n: TailNode = { ...p }; if (pc.DERPRegion) n.HomeDERP = pc.DERPRegion; if (pc.Cap) n.Cap = pc.Cap; if (pc.Endpoints) n.Endpoints = pc.Endpoints; if (pc.Key) n.Key = pc.Key; if (pc.DiscoKey) n.DiscoKey = pc.DiscoKey; if (pc.Online != null) n.Online = pc.Online; if (pc.LastSeen) n.LastSeen = pc.LastSeen; if (pc.KeyExpiry) n.KeyExpiry = pc.KeyExpiry; if (pc.KeySignature) n.KeySignature = pc.KeySignature; if (pc.CapMap) n.CapMap = pc.CapMap; return n; }