Skip to main content

ts_runtime/
lib.rs

1#![doc = include_str!("../README.md")]
2
3extern crate ts_netstack_smoltcp as netstack;
4
5use core::time::Duration;
6use std::sync::Arc;
7
8use kameo::{
9    actor::{ActorRef, Spawn, WeakActorRef},
10    mailbox::Signal,
11};
12use netstack::netcore::Channel;
13use tokio::sync::watch;
14
15use crate::{
16    control_runner::ControlRunner, dataplane::DataplaneActor, direct::DirectManager,
17    forwarder_actor::ForwarderActor, multiderp::Multiderp, netstack_actor::NetstackActor,
18};
19
20/// Pcap stream framer for debug packet capture (`CapturePcap`).
21pub mod capture;
22/// Control runner.
23pub mod control_runner;
24mod dataplane;
25mod derp_latency;
26/// Device connection-state tracking ([`DeviceState`]) and typed registration outcome
27/// ([`RegistrationError`]).
28pub mod device_state;
29mod direct;
30/// DNS over TCP for the MagicDNS service IP: the transport a stub resolver retries on when a UDP
31/// answer comes back truncated. Only the TUN application data path serves it today, so it is
32/// compiled with `tun`.
33#[cfg(feature = "tun")]
34mod dns_over_tcp;
35mod env;
36mod error;
37/// Exit-node suggestion algorithm (the classic DERP-region-latency path, Go
38/// `suggestExitNodeUsingDERP`) and its result/error types.
39pub mod exit_node_suggest;
40/// Fallback TCP handler registry (`tsnet.Server.RegisterFallbackTCPHandler` parity).
41pub mod fallback_tcp;
42mod forwarder_actor;
43/// Client-side Funnel ingress termination (`tsnet`'s `ListenFunnel` data path).
44pub mod funnel;
45/// Unified IPN notification bus ([`Notify`] / [`watch_ipn_bus`](Runtime::watch_ipn_bus)), mirroring
46/// Go `ipn` `LocalBackend.WatchNotifications` / the `WatchIPNBus` LocalAPI.
47pub mod ipn_bus;
48mod magic_dns;
49pub use magic_dns::DnsQueryResult;
50mod multiderp;
51/// OS network-link-change supervisor (opt-in `network-monitor` feature): re-binds + re-probes
52/// connectivity on a link change. Compiled out entirely when the feature is off.
53#[cfg(feature = "network-monitor")]
54mod netmon;
55mod netstack_actor;
56mod packetfilter;
57pub mod peer_tracker;
58mod peerapi;
59mod peerapi_doh;
60mod route_updater;
61mod security;
62/// Stored Serve config + accept-loop runtime (`tsnet`'s `Get/SetServeConfig` + serving runtime).
63pub mod serve;
64mod src_filter;
65/// Netmap status snapshot, WhoIs, and watcher types.
66pub mod status;
67/// Taildrop peer-to-peer file transfer store.
68pub mod taildrop;
69pub mod taildrop_send;
70/// Tailnet-Lock (TKA) chain-sync orchestration: bootstrap + offer/send driver (the runtime layer
71/// that bridges the `ts_control` sync RPCs and the `ts_tka` chain logic).
72mod tka_sync;
73#[cfg(feature = "tun")]
74mod tun_actor;
75
76pub use device_state::{DeviceState, RegistrationError};
77pub(crate) use env::Env;
78pub use error::{Error, ErrorKind};
79pub use exit_node_suggest::{ExitNodeSuggestion, SuggestExitNodeError};
80pub use ipn_bus::{IpnBusWatcher, Notify, NotifyWatchOpt};
81pub use status::{FileTarget, NetcheckReport, RegionLatency, Status, StatusNode, WhoIs};
82pub use tka_sync::TkaLogEntry;
83pub use ts_dataplane::{CaptureHook, CapturePath};
84
85use crate::peer_tracker::PeerTracker;
86
87/// The runtime for a tailscale device.
88pub struct Runtime {
89    /// Reference to the control actor.
90    pub control: ActorRef<ControlRunner>,
91    dataplane: ActorRef<DataplaneActor>,
92    /// Reference to the direct (disco/UDP underlay) manager, retained so [`Runtime::rebind`] can
93    /// ask it to re-bind the underlay socket on a network/link change.
94    direct: ActorRef<DirectManager>,
95    /// Reference to the application netstack actor. `None` in TUN transport mode, where there is
96    /// no userspace application netstack (the application data path is a real kernel TUN device).
97    netstack: Option<WeakActorRef<NetstackActor>>,
98    /// Reference to the peer tracker for peer lookups.
99    pub peer_tracker: WeakActorRef<PeerTracker>,
100    /// Fallback TCP handler registry, bound to the application netstack. `None` in TUN transport
101    /// mode (no application netstack exists to attach it to).
102    fallback_tcp: Option<fallback_tcp::FallbackTcpManager>,
103    /// Reference to the MagicDNS responder, retained so [`Runtime::query_dns`] can run a query
104    /// through the live `100.100.100.100` forward path. `None` in TUN transport mode (no
105    /// `MagicDnsActor` is spawned there — TUN-mode MagicDNS is an in-packet intercept, not an actor).
106    magic_dns: Option<ActorRef<magic_dns::MagicDnsActor>>,
107    /// Reference to the forwarder actor, retained so [`Runtime::set_advertise_routes`] can push a
108    /// new accept/dial route table onto the running forwarder (the local half of advertising
109    /// routes). Without this the strong ref would drop after the startup `GetChannel` and the
110    /// forwarder would be reachable only via the message bus.
111    forwarder: ActorRef<ForwarderActor>,
112    /// Reference to the multiderp manager, retained so [`Runtime::status`] can resolve each
113    /// relayed peer's DERP region id to its region **code** (`ipnstate.PeerStatus.Relay`). Without
114    /// this the strong ref would drop after startup (it is cloned into the direct manager + route
115    /// updater) and the region-code map would be unreachable.
116    multiderp: ActorRef<Multiderp>,
117    env: Env,
118    shutdown: watch::Sender<bool>,
119    _security: security::SecurityGuard,
120    /// Sender side of the exit-node selector `watch` cell. Held privately here (not on the cloned
121    /// `Env`, which keeps only the read side) so that only `Runtime::set_exit_node` can mutate the
122    /// selection; the route updater and source filter re-read it via [`Env::exit_node`].
123    exit_node_tx: watch::Sender<Option<ts_control::ExitNodeSelector>>,
124    /// Sender side of the accept-routes preference `watch` cell. Held privately here (same rationale
125    /// as [`exit_node_tx`](Self::exit_node_tx)) so that only [`Runtime::set_accept_routes`] can
126    /// toggle it; the route updater and source filter re-read it via [`Env::accept_routes`].
127    accept_routes_tx: watch::Sender<bool>,
128    /// Sender side of the accept-dns preference `watch` cell. Held privately here (same rationale as
129    /// [`accept_routes_tx`](Self::accept_routes_tx)) so that only [`Runtime::set_accept_dns`] can
130    /// toggle it; the MagicDNS responder re-reads it via [`Env::accept_dns`] when it rebuilds its
131    /// view (the republish that `set_accept_dns` triggers).
132    accept_dns_tx: watch::Sender<bool>,
133    /// Receiver mirroring the *active* (resolved + fail-closed) exit node's stable id, fed by the
134    /// route updater. Read by [`Runtime::status`] / [`Runtime::active_exit_node`] to report which
135    /// exit node traffic is actually egressing through (vs. the merely-configured selector).
136    active_exit_rx: watch::Receiver<Option<ts_control::StableNodeId>>,
137    /// Receiver for the device connection-state cell, fed by the control runner. Read by
138    /// [`Runtime::watch_state`] and [`Runtime::wait_until_running`].
139    state_rx: watch::Receiver<DeviceState>,
140    /// Receiver for the retained peer-capability grants, fed by the packet-filter updater. Read by
141    /// [`Runtime::whois`] to resolve the flow-scoped cap map (Go `apitype.WhoIsResponse.CapMap`).
142    cap_grants_rx: watch::Receiver<packetfilter::CapGrants>,
143    /// Receiver for the invalid-packet-filter health flag, fed by the packet-filter updater. Read by
144    /// [`Runtime::status`] to fill [`Status::health`].
145    invalid_filter_rx: packetfilter::InvalidPacketFilterRx,
146    /// Live advertised-route preference (explicit subnet routes + the exit-node flag), seeded from
147    /// the startup config. [`Runtime::set_advertise_routes`] and [`set_advertise_exit_node`] each
148    /// mutate their part under this lock then re-send the composed set, so the two compose.
149    advertise: std::sync::Mutex<AdvertiseState>,
150    /// The most recent exit-node suggestion's stable id (Go `LocalBackend.lastSuggestedExitNode`),
151    /// remembered across calls so [`Runtime::suggest_exit_node`] can apply *stickiness* — if the
152    /// previously-suggested node is still an eligible candidate in the winning region it is kept, to
153    /// avoid the suggestion flapping between equally-good ties on each call. `None` until the first
154    /// suggestion. Held behind a `Mutex` (same rationale as [`advertise`](Self::advertise): a
155    /// cheap, infrequently-touched bit of mutable runtime state, not worth an actor round-trip).
156    prev_suggestion: std::sync::Mutex<Option<ts_control::StableNodeId>>,
157    /// Background task that periodically reaps abandoned taildrop `.partial` files (Go
158    /// `feature/taildrop/delete.go` `fileDeleter`). `None` when no taildrop store is configured.
159    /// Aborted on [`Drop`] so it cannot outlive the runtime (the `reauth_bridge` pattern).
160    taildrop_reaper: Option<tokio::task::JoinHandle<()>>,
161    /// The opt-in OS network-link-change supervisor (`network-monitor` feature + the
162    /// `Config::network_monitor` flag). Retained so the actor — and thus the
163    /// `LinkMonitorHandle` it holds, which aborts the monitor's watcher task on drop — lives for the
164    /// device's life and is torn down when the runtime drops. `None` when the flag is off. Only
165    /// present when built with the `network-monitor` feature.
166    #[cfg(feature = "network-monitor")]
167    #[allow(dead_code)]
168    netmon_supervisor: Option<ActorRef<netmon::NetmonSupervisor>>,
169}
170
171impl Runtime {
172    /// Spawn a new runtime with the given parameters for connecting to a tailnet.
173    pub async fn spawn(
174        config: ts_control::Config,
175        auth_key: Option<String>,
176        keys: ts_keys::NodeState,
177    ) -> Result<Self, Error> {
178        let (shutdown_tx, shutdown_rx) = watch::channel(false);
179
180        // The exit-node selector, accept-routes, and accept-dns preferences are live `watch` cells so
181        // `Device::set_exit_node` / `set_accept_routes` / `set_accept_dns` can change them at runtime.
182        // `new_with_runtime_txs` returns each `Sender` (mutation capability) grouped in `pref_cells`
183        // so they are retained privately on the `Runtime`, while only the `Receiver`s (the readers'
184        // contract) live on the cloned `Env`. Initial values come from `ForwarderConfig`.
185        let (env, pref_cells) = Env::new_with_runtime_txs(
186            keys,
187            shutdown_rx,
188            env::ForwarderConfig::from_control_config(&config),
189        );
190
191        let mut security = security::SecurityGuard::new(shutdown_tx.clone());
192        security.watch(&env.bus);
193        security.ready(&env.bus).await?;
194
195        // Both userspace netstacks (application + forwarder) share one netstack config. Honor the
196        // per-deployment TCP buffer knob, and set the netstack MTU to the overlay/tunnel MTU so the
197        // advertised MSS fits the tunnel — leaving it at the netstack's generic 1500 default would
198        // emit over-1280 segments into the WireGuard path. The MTU comes from a `Tun` transport's
199        // `TunConfig` when one is configured (so the netstack and the TUN agree), else the 1280
200        // overlay default (the `Netstack` userspace mode — the common case — has no per-OS MTU knob,
201        // but the tailnet overlay MTU is still 1280).
202        let configured_mtu = match &config.transport_mode {
203            ts_control::TransportMode::Tun(tun_cfg) => tun_cfg.mtu,
204            ts_control::TransportMode::Netstack => None,
205        };
206        let netstack_config = netstack_config_from(config.tcp_buffer_size, configured_mtu);
207
208        let dataplane = DataplaneActor::spawn(env.clone());
209        security.watch(&dataplane);
210        security.ready(&dataplane).await?;
211        security.packet_pump(dataplane.ask(dataplane::PacketPumpAbortHandle).await?);
212
213        let (netstack_id, netstack_up, netstack_down) =
214            dataplane.ask(dataplane::NewOverlayTransport).await?;
215
216        // A second overlay transport feeds the dedicated any-IP forwarder netstack. Inbound packets
217        // for advertised subnet routes / the exit-node default route are routed here (see
218        // `route_updater`), keeping forwarded flows off the application netstack.
219        let (forwarder_id, forwarder_up, forwarder_down) =
220            dataplane.ask(dataplane::NewOverlayTransport).await?;
221
222        // The selected DERP home region (Go `report.PreferredDERP`): the control runner is the sole
223        // writer (it applies the netcheck `bestRecent` + hysteresis smoothing), and `Multiderp`
224        // reads it to drive the local home relay — so the relay follows the SAME smoothed home the
225        // runner advertises to control, instead of picking it from the raw per-cycle latency minimum
226        // (which flapped on jitter and could disagree with the advertised home). Created here so it
227        // outlives both actors; `None` until the first home is chosen.
228        let (home_region_tx, home_region_rx) = watch::channel::<Option<ts_derp::RegionId>>(None);
229
230        let multiderp = Multiderp::spawn((env.clone(), dataplane.clone(), home_region_rx));
231        security.watch(&multiderp);
232        security.ready(&multiderp).await?;
233
234        // Spawn the direct (disco) underlay manager before the route updater. Its `on_start`
235        // binds the UDP socket and registers its transport synchronously, so by the time the
236        // route updater asks it for the direct transport id it is guaranteed to be available.
237        let direct = DirectManager::spawn((env.clone(), dataplane.clone(), multiderp.clone()));
238        security.watch(&direct);
239        security.ready(&direct).await?;
240
241        // Spawn the forwarder before the route updater. Its `on_start` builds the forwarder
242        // netstack, enables any-IP acceptance, and starts the per-port accept loops synchronously,
243        // so by the time the route updater begins delivering advertised prefixes to
244        // `forwarder_id` the netstack is already draining its transport.
245        let forwarder = ForwarderActor::spawn((
246            env.clone(),
247            netstack_config.clone(),
248            forwarder_up,
249            forwarder_down,
250        ));
251        security.watch(&forwarder);
252        security.ready(&forwarder).await?;
253        // Force `on_start` to finish (any-IP enabled, accept loops live) before the route updater
254        // can route the first inbound flow to `forwarder_id`: an `ask` blocks until the actor has
255        // started.
256        //
257        // The forwarder netstack's overlay `Channel` is reused by the TUN application path for
258        // recursive / exit-node-DoH MagicDNS forwarding (TUN mode has no application netstack of its
259        // own, but the forwarder netstack runs in both modes and egresses over the overlay — the
260        // anti-leak property `forward_query`/`forward_doh` require). Only the `tun` Tun arm consumes
261        // it, so it is unused when the `tun` feature is off — allow that without warn-as-error.
262        #[cfg_attr(not(feature = "tun"), allow(unused_variables))]
263        let (forwarder_channel,) = forwarder.ask(forwarder_actor::GetChannel).await?;
264
265        // The route updater is the single authoritative resolver of the active (resolved,
266        // fail-closed) exit node; it publishes the resolved stable id into this watch cell so
267        // `Runtime::status` can report which exit is actually engaged (not just configured).
268        let (active_exit_tx, active_exit_rx) = watch::channel(None);
269        let route_updater = route_updater::RouteUpdater::spawn((
270            multiderp.clone(),
271            direct.clone(),
272            env.clone(),
273            netstack_id,
274            forwarder_id,
275            active_exit_tx,
276        ));
277        security.watch(&route_updater);
278        security.ready(&route_updater).await?;
279        // The packet-filter updater also surfaces the retained cap-grants (for flow-scoped WhoIs)
280        // through a `watch` cell whose receiver the `Runtime` holds — the bus has no replay, so a
281        // `watch` is how `Runtime::whois` reads the current grants on demand.
282        let (cap_grants_tx, cap_grants_rx) = watch::channel(Default::default());
283        // The live compiled filter for the peerAPI DoH source gate. Created here — before either
284        // actor spawns — so the updater (sole writer) and the MagicDNS responder (reader, which
285        // hands the receiver to its peerAPI server task) share one cell no matter which `on_start`
286        // runs first. The gate is fail-closed, so a filter that never reaches it means refusing
287        // peers control's ACL admits. The bus has no replay for late readers (see
288        // `packetfilter::LiveFilterRx`).
289        let (live_filter_tx, live_filter_rx) = watch::channel(None);
290        let (invalid_filter_tx, invalid_filter_rx) = watch::channel(false);
291        let packetfilter = packetfilter::PacketfilterUpdater::spawn((
292            env.clone(),
293            cap_grants_tx,
294            live_filter_tx,
295            invalid_filter_tx,
296        ));
297        security.watch(&packetfilter);
298        security.ready(&packetfilter).await?;
299        let source_filter = src_filter::SourceFilterUpdater::spawn(env.clone());
300        security.watch(&source_filter);
301        security.ready(&source_filter).await?;
302        // TKA enforcement-authority cell (Go `tkaFilterNetmapLocked`). Created here — before both
303        // actors spawn — so the control runner (sole writer, `Sender`) and the peer tracker (reader,
304        // `Receiver`) share one `watch` cell. A `watch` (not a bus message) is the transport for this
305        // security-critical state: last-write-wins, never dropped under load, ordered by the control
306        // runner's writes, so a disable (`None`) can never be reordered behind or dropped before a
307        // stale `Some`. `None` = no lock synced / disabled (admit all).
308        let (tka_authority_tx, tka_authority_rx) =
309            watch::channel::<Option<std::sync::Arc<ts_tka::Authority>>>(None);
310        let peer_tracker = PeerTracker::spawn((env.clone(), tka_authority_rx));
311        security.watch(&peer_tracker);
312        security.ready(&peer_tracker).await?;
313
314        // Select the application data path from the transport mode. The forwarder/egress path
315        // above is UNCHANGED in both modes — TUN mode only swaps the application data path, never
316        // the forwarder. `config` is moved into `ControlRunner::spawn` below, so branch on a
317        // borrow and clone the small `TunConfig` where needed before the move.
318        //
319        // - Netstack (the default, and the only reachable arm when the `tun` feature is off):
320        //   spawn the application netstack + MagicDNS responder + fallback-TCP registry, all on
321        //   the `netstack_up`/`netstack_down` overlay seam.
322        // - Tun: spawn `TunActor` on that same overlay seam instead; no application netstack and
323        //   no MagicDNS responder exist, and `netstack`/`fallback_tcp` are `None`.
324        // - Tun requested but built without the `tun` feature: hard-error (a config/build
325        //   mismatch knowable at spawn time). NEVER silently fall back to netstack.
326        let (netstack, fallback_tcp, magic_dns) = match &config.transport_mode {
327            ts_control::TransportMode::Netstack => {
328                let netstack = NetstackActor::spawn((
329                    env.clone(),
330                    netstack_config,
331                    netstack_up,
332                    netstack_down,
333                ));
334
335                security.watch(&netstack);
336                security.ready(&netstack).await?;
337                // Fetch the netstack channel while we still hold the strong ActorRef, then spawn
338                // the MagicDNS responder on it. Its ActorRef is retained on `Runtime` so
339                // `query_dns` can drive the live forward path; the serve loop itself is owned by the
340                // actor's internal JoinSet.
341                let (channel,) = netstack.ask(netstack_actor::GetChannel).await?;
342                // The fallback-TCP registry attaches to the application netstack — the same one
343                // that carries the embedder's explicit `Device::tcp_listen` sockets — so a
344                // fallback handler sees exactly the inbound flows no explicit listener matched.
345                let fallback_tcp = fallback_tcp::FallbackTcpManager::new(channel.clone());
346                let magic_dns =
347                    magic_dns::MagicDnsActor::spawn((env.clone(), channel, live_filter_rx));
348                security.watch(&magic_dns);
349                security.ready(&magic_dns).await?;
350
351                (
352                    Some(netstack.downgrade()),
353                    Some(fallback_tcp),
354                    Some(magic_dns),
355                )
356            }
357
358            #[cfg(feature = "tun")]
359            ts_control::TransportMode::Tun(tun_cfg) => {
360                // Reuse the same `netstack_up`/`netstack_down` overlay-transport pair that would
361                // have fed the netstack — it is just the application-side overlay seam (the name
362                // is historical). No NetstackActor / MagicDnsActor is spawned.
363                let tun = tun_actor::TunActor::spawn((
364                    env.clone(),
365                    tun_cfg.clone(),
366                    netstack_up,
367                    netstack_down,
368                    // Reuse the forwarder netstack's overlay `Channel` for recursive / exit-node-DoH
369                    // MagicDNS forwarding in the TUN datapath (TUN mode has no application netstack
370                    // Channel of its own). Egresses over the overlay — anti-leak preserved.
371                    //
372                    // Host-route gating (subnet routes gated on `--accept-routes`, the host `/0` from
373                    // the selected exit peer) is no longer snapshotted here: `TunActor` reads the live
374                    // `Env` cells (`accept_routes`/`exit_node`) on every host-FIB apply — both the
375                    // device-build path and the `PeerState` re-apply path — and folds the union of
376                    // peers' AllowedIPs (see `tun_actor::host_routes_from_node`). A runtime
377                    // `set_accept_routes` / `set_exit_node` toggle re-broadcasts the peer state, so the
378                    // host routing table is re-steered live (no device rebuild needed).
379                    forwarder_channel.clone(),
380                ));
381                security.watch(&tun);
382                security.ready(&tun).await?;
383
384                (None, None, None)
385            }
386
387            #[cfg(not(feature = "tun"))]
388            ts_control::TransportMode::Tun(_) => {
389                return Err(Error {
390                    kind: ErrorKind::TunUnavailable,
391                    target_actor: None,
392                    message_ty: None,
393                });
394            }
395        };
396
397        // Device connection-state cell. Created here (not inside the actor) so the control runner's
398        // `on_start` can publish `Failed`/`NeedsLogin` and still return `Err` without the sender
399        // being tied to a `Self` that never gets constructed on a hard registration failure.
400        let (state_tx, state_rx) = watch::channel(DeviceState::Connecting);
401
402        // Seed the live advertised-route preference from the startup config before `config` moves
403        // into the control runner, so the runtime setters compose against the configured baseline.
404        let advertise = std::sync::Mutex::new(AdvertiseState {
405            routes: config.advertise_routes.clone(),
406            exit_node: config.advertise_exit_node,
407        });
408
409        // This telemetry subscriber also has a bounded mailbox and multiple subscriptions.
410        // Starting it after control publishes could deadlock its second Register behind
411        // delivery to its first subscription while on_start cannot drain its mailbox.
412        let latency = derp_latency::DerpLatencyMeasurer::spawn(env.clone());
413        security.watch(&latency);
414        security.ready(&latency).await?;
415
416        // Every security subscriber is now registered. Control on_start may replay a cached
417        // map immediately; spawning it earlier would lose state even with guaranteed delivery.
418        // Control self-messages (stream pump and TKA sync results), so keep its mailbox
419        // unbounded too. Publishers never wait for broker handling or subscriber capacity.
420        // A stalled handler can accumulate inputs; supervision covers death, not stalls.
421        let control = ControlRunner::spawn_with_mailbox(
422            control_runner::Params {
423                config,
424                auth_key,
425                env: env.clone(),
426                state_tx,
427                tka_authority: tka_authority_tx,
428                home_region: home_region_tx,
429            },
430            kameo::mailbox::unbounded(),
431        );
432
433        security.watch(&control);
434
435        // Spawn the taildrop partial-reaper if a store is configured; it sweeps abandoned `.partial`
436        // files every `DELETE_DELAY` and exits on shutdown (the handle is aborted in `Drop`).
437        let taildrop_reaper = env.taildrop_store.as_ref().map(|store| {
438            crate::taildrop::spawn_partial_reaper(store.clone(), shutdown_tx.subscribe())
439        });
440
441        // Opt-in OS network-link monitor (`Config::network_monitor`, default off). When enabled it
442        // spawns a `NetmonSupervisor` that, on a coalesced link change, asks the direct manager to
443        // rebind + re-probe and republishes `MeasureNow` for a re-netcheck — the auto-recovery a
444        // real `tailscaled` performs and the engine otherwise leaves to the embedder. When the flag
445        // is off this is a complete no-op: zero extra threads/sockets, byte-for-byte today's
446        // behavior. The manual `Device::rebind` path is unchanged either way.
447        //
448        // Feature gating is strict and never silent: with the `network-monitor` feature ON the
449        // supervisor (and its `ts_netmon` dep) compile in and spawn when the flag is set; with the
450        // feature OFF, setting the flag is a HARD error at spawn (mirrors the `TransportMode::Tun`
451        // without-`tun`-feature error above), so a build that cannot honor the request fails loudly
452        // rather than booting a node that silently won't auto-recover.
453        #[cfg(feature = "network-monitor")]
454        let netmon_supervisor = if env.network_monitor {
455            // Slice (a): no OS event-source backend is wired yet (the Linux netlink / macOS
456            // PF_ROUTE backends are later slices), so the supervisor runs against a `NoopLinkMonitor`
457            // — it is live and correctly shaped (it will react the moment a real backend feeds it),
458            // it just never sees a synthetic/OS event in this build. Production end-to-end reaction
459            // is proven in the integration test via a `ManualLinkMonitor`.
460            let monitor: std::sync::Arc<dyn ts_netmon::LinkMonitor> =
461                std::sync::Arc::new(ts_netmon::NoopLinkMonitor);
462            Some(netmon::NetmonSupervisor::spawn(
463                netmon::NetmonSupervisorArgs {
464                    monitor,
465                    direct: direct.clone(),
466                    env: env.clone(),
467                },
468            ))
469        } else {
470            None
471        };
472
473        #[cfg(not(feature = "network-monitor"))]
474        if env.network_monitor {
475            // The flag is set but this build cannot honor it. Fail loudly (never a silent no-op).
476            return Err(Error {
477                kind: ErrorKind::NetworkMonitorUnavailable,
478                target_actor: None,
479                message_ty: None,
480            });
481        }
482
483        Ok(Self {
484            control,
485            dataplane,
486            direct,
487            peer_tracker: peer_tracker.downgrade(),
488            fallback_tcp,
489            magic_dns,
490            forwarder,
491            multiderp,
492            netstack,
493            env,
494            shutdown: shutdown_tx,
495            _security: security,
496            exit_node_tx: pref_cells.exit_node,
497            accept_routes_tx: pref_cells.accept_routes,
498            accept_dns_tx: pref_cells.accept_dns,
499            active_exit_rx,
500            state_rx,
501            cap_grants_rx,
502            invalid_filter_rx,
503            advertise,
504            prev_suggestion: std::sync::Mutex::new(None),
505            taildrop_reaper,
506            #[cfg(feature = "network-monitor")]
507            netmon_supervisor,
508        })
509    }
510
511    /// Register a fallback TCP handler consulted for every inbound TCP flow that matches no
512    /// explicit listener (`tsnet.Server.RegisterFallbackTCPHandler` parity).
513    ///
514    /// The returned [`fallback_tcp::FallbackTcpHandle`] deregisters the handler when dropped. See
515    /// [`fallback_tcp`] for the dispatch contract and anti-leak guarantees.
516    ///
517    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
518    /// application netstack to attach a fallback handler to.
519    pub fn register_fallback_tcp_handler(
520        &self,
521        cb: Arc<
522            dyn Fn(core::net::SocketAddr, core::net::SocketAddr) -> fallback_tcp::FallbackDecision
523                + Send
524                + Sync,
525        >,
526    ) -> Result<fallback_tcp::FallbackTcpHandle, Error> {
527        Ok(self
528            .fallback_tcp
529            .as_ref()
530            .ok_or(Error {
531                kind: ErrorKind::UnsupportedInTunMode,
532                target_actor: None,
533                message_ty: None,
534            })?
535            .register(cb))
536    }
537
538    /// Get a channel to send commands to the netstack.
539    ///
540    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
541    /// application netstack.
542    pub async fn channel(&self) -> Result<Channel, Error> {
543        let (channel,) = self
544            .netstack
545            .as_ref()
546            .ok_or(Error {
547                kind: ErrorKind::UnsupportedInTunMode,
548                target_actor: None,
549                message_ty: None,
550            })?
551            .upgrade()
552            .ok_or(Error {
553                kind: ErrorKind::ActorGone,
554                target_actor: None,
555                message_ty: None,
556            })?
557            .ask(netstack_actor::GetChannel)
558            .await?;
559
560        Ok(channel)
561    }
562
563    /// Resolve `name` for `qtype` through the live MagicDNS responder (the `100.100.100.100`
564    /// forward path), returning the raw DNS response, its RCODE, and the upstream resolver(s)
565    /// consulted (analogue of Go `LocalClient.QueryDNS`).
566    ///
567    /// This drives the *real* responder — the same `decide`/forward logic an on-the-wire query
568    /// hits — so the answer and its anti-leak posture (a tailnet-suffix name never egresses; a
569    /// recursive forward delegates to the active exit node's DoH; only IPv4 upstreams are dialed)
570    /// match exactly what a tailnet client observes. `qtype` is the raw RFC 1035 TYPE (`1`=A,
571    /// `28`=AAAA, `12`=PTR, or any other).
572    ///
573    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where MagicDNS is an
574    /// in-packet intercept on the host's own resolver rather than an actor that can be queried, and
575    /// [`ErrorKind::ActorGone`] if the responder has shut down.
576    pub async fn query_dns(
577        &self,
578        name: &str,
579        qtype: u16,
580    ) -> Result<magic_dns::DnsQueryResult, Error> {
581        let result = self
582            .magic_dns
583            .as_ref()
584            .ok_or(Error {
585                kind: ErrorKind::UnsupportedInTunMode,
586                target_actor: None,
587                message_ty: None,
588            })?
589            .ask(magic_dns::Query {
590                name: name.to_owned(),
591                qtype,
592            })
593            .await?;
594
595        Ok(result)
596    }
597
598    /// The Taildrop file store, if Taildrop is enabled (`taildrop_dir` configured and the store
599    /// initialized). `None` when disabled — fail-closed. Shared with the peerAPI Taildrop server so
600    /// the embedder's read APIs and the receive path see the same on-disk store.
601    pub fn taildrop_store(&self) -> Option<Arc<crate::taildrop::TaildropStore>> {
602        self.env.taildrop_store.clone()
603    }
604
605    /// The shared Funnel ingress slot the peerAPI `/v0/ingress` route reads per connection.
606    ///
607    /// `Device::listen_funnel` installs a [`FunnelManager`](crate::funnel::FunnelManager)'s sink here
608    /// to make the route live (the peerAPI server is already running from startup). Returns a clone of
609    /// the runtime-lifetime `Arc` so the device can write the slot without restarting the server. See
610    /// [`crate::funnel`] for the ingress data path.
611    pub fn funnel_ingress_slot(&self) -> crate::funnel::FunnelIngressSlot {
612        self.env.funnel_ingress.clone()
613    }
614
615    /// The shared "Funnel ingress listener active" flag (the same `Arc` the control session reads to
616    /// set `HostInfo.IngressEnabled`). `Device::listen_funnel` flips it `true` while a funnel listener
617    /// is up so control routes Funnel traffic to this node; clearing it advertises no live endpoint.
618    pub fn ingress_active_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
619        self.env.ingress_active.clone()
620    }
621
622    /// Install (`Some`) or clear (`None`) the debug packet-capture hook on the running dataplane.
623    /// `Some(hook)` tees every plaintext packet crossing the datapath to `hook` until it is cleared;
624    /// `None` stops capture. Mirrors Go `tstun.Wrapper.InstallCaptureHook` / `ClearCaptureSink`.
625    pub async fn install_capture(
626        &self,
627        hook: Option<ts_dataplane::CaptureHook>,
628    ) -> Result<(), Error> {
629        self.dataplane
630            .ask(dataplane::InstallCapture { hook })
631            .await
632            .map_err(Into::into)
633    }
634
635    /// Re-bind the underlay UDP socket after a network/link change (Wi-Fi switch, sleep/wake). The
636    /// embedder's own link monitor calls this (the engine owns the socket re-bind; the embedder owns
637    /// OS netmon). Re-binds the socket (same-port-preferred, IPv4-only invariant preserved) and
638    /// resets the now-stale local NAT mapping — clearing learned reflexive addresses and every
639    /// confirmed direct path while keeping candidate endpoints, so peers re-probe over the new socket
640    /// and relay over DERP (never a direct host dial) until a path re-confirms. Peers, control, the
641    /// netmap, disco state, and DERP are untouched. A no-op when the underlay is inert (bind failed
642    /// at startup, DERP-only). Mirrors Go magicsock `Conn.Rebind` + `resetEndpointStates`.
643    pub async fn rebind(&self) -> Result<(), Error> {
644        self.direct.ask(direct::Rebind).await.map_err(Error::from)
645    }
646
647    /// Force an immediate STUN / endpoint re-probe **without** rebinding the underlay socket —
648    /// Go magicsock's `Conn.ReSTUN`. Asks the `DirectManager` to run one STUN sweep now (re-learn
649    /// our reflexive/public address) while leaving the socket, its NAT mapping, learned paths, peers,
650    /// control, and DERP untouched. Lighter than [`rebind`](Self::rebind): no socket swap, no
651    /// re-ping. A no-op when the underlay is inert (bind failed at startup, DERP-only). No control
652    /// round-trip.
653    pub async fn re_stun(&self) -> Result<(), Error> {
654        self.direct.ask(direct::ReStun).await.map_err(Error::from)
655    }
656
657    /// A snapshot of the local netmap: this node plus every known peer.
658    ///
659    /// Combines the self node held by the control runner with the peer set held by the peer
660    /// tracker. Mirrors tsnet's `LocalClient::Status`.
661    ///
662    /// `self_node` is `None` until the first netmap update has been received from control. Peer
663    /// entries carry no online/user/capability data (see the [`status`] module docs for that gap).
664    pub async fn status(&self) -> Result<Status, Error> {
665        let self_node_domain = self.control.ask(control_runner::SelfNode).await?;
666        // The MagicDNS suffix is the self node's FQDN minus its host label — already split into
667        // `Node.tailnet` at decode time (Go derives it the same way in `NetworkMap.MagicDNSSuffix`).
668        // Capture it before the domain `Node` is mapped away into a `StatusNode`.
669        let magic_dns_suffix = self_node_domain.as_ref().and_then(|n| n.tailnet.clone());
670        let self_node = self_node_domain.as_ref().map(StatusNode::from_node);
671
672        let peers_with_ids = self
673            .peer_tracker
674            .upgrade()
675            .ok_or(Error {
676                kind: ErrorKind::ActorGone,
677                target_actor: None,
678                message_ty: None,
679            })?
680            .ask(peer_tracker::GetStatus)
681            .await?;
682
683        // Join per-peer connectivity (Go `PeerStatus.CurAddr`): one batched query to the direct
684        // manager for every peer's current trusted direct endpoint, then fill `cur_addr` on each
685        // `StatusNode`. A peer absent from the map is relayed via DERP (`cur_addr = None`). This is a
686        // live snapshot — the direct path can expire/re-confirm between calls (matches Go's snapshot
687        // semantics). The `watch_netmap` stream intentionally carries no connectivity (it is a netmap
688        // watch, not a path-state watch, and does not re-fire on direct↔relay flips).
689        let ids: Vec<ts_transport::PeerId> = peers_with_ids.iter().map(|(id, _)| *id).collect();
690        let best_addrs = self
691            .direct
692            .ask(direct::BestAddrs { ids: ids.clone() })
693            .await
694            .unwrap_or_default();
695
696        // For the peers with NO direct path (relayed via DERP), resolve the region CODE they relay
697        // through (Go `PeerStatus.Relay`). One batched ask to multiderp; `cur_addr` and `relay` are
698        // mutually exclusive for a routed peer, mirroring Go's empty-vs-set strings.
699        let relay_ids: Vec<ts_transport::PeerId> = ids
700            .into_iter()
701            .filter(|id| !best_addrs.contains_key(id))
702            .collect();
703        let relay_codes = if relay_ids.is_empty() {
704            Default::default()
705        } else {
706            self.multiderp
707                .ask(multiderp::RelayCodesForPeers { ids: relay_ids })
708                .await
709                .unwrap_or_default()
710        };
711
712        let peers = peers_with_ids
713            .into_iter()
714            .map(|(id, mut node)| match best_addrs.get(&id).copied() {
715                Some(addr) => {
716                    node.cur_addr = Some(addr);
717                    node
718                }
719                None => {
720                    node.relay = relay_codes.get(&id).cloned();
721                    node
722                }
723            })
724            .collect();
725
726        Ok(Status {
727            self_node,
728            peers,
729            active_exit_node: self.active_exit_node(),
730            magic_dns_suffix,
731            health: packetfilter::health_warnings(*self.invalid_filter_rx.borrow()),
732        })
733    }
734
735    /// Suggest a reasonably good exit node to use, from the current netmap + recent DERP latency
736    /// (Go `LocalBackend.SuggestExitNode`). The Phase-1 classic DERP-region-latency path; see the
737    /// [`exit_node_suggest`] module for the algorithm, scope, and the IPv4-only parity deviation.
738    ///
739    /// Gathers the inputs the way [`status`](Self::status) and [`file_targets`](Self::file_targets)
740    /// do — from the control runner, the latest [`NetcheckReport`]'s preferred DERP region plus the
741    /// recent per-region latencies (both immediate, non-blocking borrows), and every peer
742    /// [`Node`](ts_control::Node) from the peer tracker — then runs the pure algorithm with the
743    /// production uniform-random selectors (`random_region` / `random_node`). The returned
744    /// suggestion's id is remembered in the runtime's `prev_suggestion` cell so the next call is
745    /// *sticky* (Go `lastSuggestedExitNode`).
746    ///
747    /// Returns `Ok(None)` when no peer is an eligible candidate (Go's empty response), and
748    /// `Err(`[`SuggestExitNodeError::NoPreferredDerp`]`)` when there is no netcheck report yet (Go's
749    /// `ErrNoPreferredDERP`, "try again later").
750    pub async fn suggest_exit_node(
751        &self,
752    ) -> Result<Result<Option<ExitNodeSuggestion>, SuggestExitNodeError>, Error> {
753        use ts_control::NODE_ATTR_SUGGEST_EXIT_NODE;
754
755        // The two netcheck inputs Go's `suggestExitNode` takes. First the preferred DERP region from
756        // the latest report (Go `MagicConn().GetLastNetcheckReport().PreferredDERP`): an immediate
757        // borrow of the control runner's published measurement (the value `Device::netcheck`
758        // surfaces), used only as the "have we netchecked at all yet" precondition.
759        let report = self.control.ask(control_runner::Netcheck).await?;
760
761        // Then the *ranking* input: the lowest latency seen per region over the retained measurement
762        // history (Go `netcheck.Client.RecentRegionLatency()`). Deliberately NOT the latest report's
763        // own latency list — every measurement this fork makes is partial (`complete_threshold`), so
764        // ranking on one report leaves a distant candidate's region unmeasured and collapses the
765        // suggestion to a uniform random pick. See `exit_node_suggest`'s module docs.
766        let region_latency = self
767            .control
768            .ask(control_runner::RecentRegionLatency)
769            .await?;
770
771        // Every known peer (Go reads the netmap peers via `AppendMatchingPeers`); the domain `Node`
772        // retains the cap map, home DERP region, online state, and accepted routes the predicate
773        // needs.
774        let peers = self
775            .peer_tracker
776            .upgrade()
777            .ok_or(Error {
778                kind: ErrorKind::ActorGone,
779                target_actor: None,
780                message_ty: None,
781            })?
782            .ask(peer_tracker::AllPeers)
783            .await?;
784
785        // Project each peer into the algorithm's candidate inputs. The eligibility predicate runs
786        // inside the pure function, so every peer is passed (self is naturally absent from the peer
787        // set). `derp_region`/`online`/`cap_map`/`accepted_routes` map straight off the domain node;
788        // the exit-route check is the fork's family-agnostic `prefix_len == 0` (IPv4-only parity —
789        // see `exit_node_suggest::suggest_exit_node`).
790        let candidates: Vec<exit_node_suggest::ExitNodeCandidate> = peers
791            .iter()
792            .map(|peer| exit_node_suggest::ExitNodeCandidate {
793                stable_id: peer.stable_id.clone(),
794                name: peer
795                    .fqdn_opt(false)
796                    .unwrap_or_else(|| peer.hostname.clone()),
797                derp_region: peer.derp_region,
798                online: peer.online,
799                advertises_exit_route: peer
800                    .accepted_routes
801                    .iter()
802                    .any(|route| route.prefix_len() == 0),
803                has_suggest_cap: peer.has_node_attr(NODE_ATTR_SUGGEST_EXIT_NODE),
804            })
805            .collect();
806
807        // Read the sticky previous suggestion, run the pure algorithm with the production
808        // uniform-random selectors, then update the sticky value to the new result. This mirrors Go
809        // `suggestExitNodeLocked` (`ipn/ipnlocal/local.go`), which assigns `b.lastSuggestedExitNode =
810        // res.ID` on **every** no-error return — INCLUDING the empty/no-candidate result, where it
811        // clears the sticky id to "". So a successful suggestion sets stickiness, an empty result
812        // CLEARS it (a peer that dropped out of candidacy stops being preferred), and only an `Err`
813        // (`NoPreferredDerp` — no netcheck yet) returns before the assignment and leaves it untouched.
814        let prev = self.prev_suggestion.lock().unwrap().clone();
815        let outcome = exit_node_suggest::suggest_exit_node(
816            report.preferred_derp,
817            &region_latency,
818            &candidates,
819            prev.as_ref(),
820            &exit_node_suggest::random_region,
821            &exit_node_suggest::random_node,
822        );
823        *self.prev_suggestion.lock().unwrap() = exit_node_suggest::next_sticky(prev, &outcome);
824        Ok(outcome)
825    }
826
827    /// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
828    ///
829    /// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
830    /// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
831    /// this node **or** explicitly granted the file-sharing-target capability. The whole list is
832    /// gated on this node holding the file-sharing capability (control sets it when the admin enables
833    /// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
834    /// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
835    ///
836    /// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
837    /// on online either; an offline target's send will simply time out). The self node is never
838    /// included. Returns empty before the first netmap.
839    ///
840    /// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
841    /// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
842    /// fail-closes if such a peer refused the transfer.
843    pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
844        // Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
845        // admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
846        let self_node = self.control.ask(control_runner::SelfNode).await?;
847        let Some(self_node) = self_node else {
848            return Ok(Vec::new()); // no netmap yet
849        };
850        if !self_node.can_share_files() {
851            return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
852        }
853        let self_user_id = self_node.user_id;
854
855        let peers = self
856            .peer_tracker
857            .upgrade()
858            .ok_or(Error {
859                kind: ErrorKind::ActorGone,
860                target_actor: None,
861                message_ty: None,
862            })?
863            .ask(peer_tracker::AllPeers)
864            .await?;
865
866        // Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
867        Ok(status::build_file_targets(peers, self_user_id))
868    }
869
870    /// The stable id of the exit node traffic is currently egressing through, or `None` if none is
871    /// engaged. This is the route updater's resolved + fail-closed answer (see
872    /// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
873    /// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
874    /// no longer advertising a default route (in which case egress is dropped and this returns
875    /// `None`).
876    pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
877        self.active_exit_rx.borrow().clone()
878    }
879
880    /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
881    ///
882    /// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
883    /// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
884    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
885    /// [`ts_control::IdTokenError::NetworkError`].
886    pub async fn fetch_id_token(
887        &self,
888        audience: String,
889    ) -> Result<String, ts_control::IdTokenError> {
890        self.control
891            .ask(control_runner::FetchIdToken { audience })
892            .await
893            .map_err(flatten_send_err)
894    }
895
896    /// Log this node out of the tailnet: deregister it by expiring its current node key.
897    ///
898    /// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
899    /// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
900    /// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
901    /// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
902    /// `fetch_id_token`: a handler error carries the real
903    /// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
904    /// surfaced as [`ts_control::LogoutError::NetworkError`].
905    pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
906        self.control
907            .ask(control_runner::Logout)
908            .await
909            .map_err(flatten_logout_send_err)
910    }
911
912    /// Publish a `TXT` DNS record for this node via control's `/machine/set-dns` (Go
913    /// `LocalClient.SetDNS`).
914    ///
915    /// Forwards to the control runner, which POSTs the record over a fresh Noise channel. The kameo
916    /// delegated-reply send error is flattened the same way as `fetch_id_token`:
917    /// a handler error carries the real [`ts_control::SetDnsError`]; any other send failure (actor
918    /// shutdown / mailbox closed) is surfaced as [`ts_control::SetDnsError::NetworkError`].
919    pub async fn set_dns(
920        &self,
921        name: String,
922        value: String,
923    ) -> Result<(), ts_control::SetDnsError> {
924        self.control
925            .ask(control_runner::SetDns { name, value })
926            .await
927            .map_err(flatten_set_dns_send_err)
928    }
929
930    /// Sign `node_key` with this node's network-lock key and submit the signature to control
931    /// (Go `tka.sign` Direct case → `/machine/tka/sign`).
932    ///
933    /// Submits only — the local [`Authority`](ts_tka::Authority) is **not** mutated here; it advances
934    /// via the existing verified-sync path. A handler error carries the real [`ts_control::TkaSyncError`];
935    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
936    /// [`ts_control::TkaSyncError::NetworkError`].
937    pub async fn tka_sign(&self, node_key: [u8; 32]) -> Result<(), ts_control::TkaSyncError> {
938        self.control
939            .ask(control_runner::TkaSign { node_key })
940            .await
941            .map_err(flatten_tka_send_err)
942    }
943
944    /// Disable Tailnet Lock by presenting the `disablement_secret` to control (Go `tka.disable` →
945    /// `/machine/tka/disable`), targeting the current authority head.
946    ///
947    /// Submits only — the local [`Authority`](ts_tka::Authority) is **not** mutated here. A handler
948    /// error carries the real [`ts_control::TkaSyncError`] (incl.
949    /// [`Unsupported`](ts_control::TkaSyncError::Unsupported) when there is no known TKA head to
950    /// disable); any other send failure collapses to
951    /// [`NetworkError`](ts_control::TkaSyncError::NetworkError).
952    pub async fn tka_disable(
953        &self,
954        disablement_secret: Vec<u8>,
955    ) -> Result<(), ts_control::TkaSyncError> {
956        self.control
957            .ask(control_runner::TkaDisable { disablement_secret })
958            .await
959            .map_err(flatten_tka_send_err)
960    }
961
962    /// Initialize Tailnet Lock with this node as the sole initial trusted key, gated by
963    /// `disablement_secret` (Go `tka` init → `/machine/tka/init/{begin,finish}`).
964    ///
965    /// Submits only — does not seed the local [`Authority`](ts_tka::Authority); the node picks up the
966    /// new lock via the existing verified netmap-sync. A handler error carries the real
967    /// [`ts_control::TkaSyncError`] ([`Unsupported`](ts_control::TkaSyncError::Unsupported) if
968    /// control needs other nodes re-signed — the single-node "lock yourself in" subset only); any
969    /// other send failure collapses to [`NetworkError`](ts_control::TkaSyncError::NetworkError).
970    pub async fn tka_init(
971        &self,
972        disablement_secret: Vec<u8>,
973    ) -> Result<(), ts_control::TkaSyncError> {
974        self.control
975            .ask(control_runner::TkaInit { disablement_secret })
976            .await
977            .map_err(flatten_tka_send_err)
978    }
979
980    /// Read up to `limit` entries of the Tailnet-Lock update-chain log, head-first (Go
981    /// `NetworkLockLog`). A **pure local read** of the synced AUM chain — no control round-trip — so
982    /// the only failure is a kameo send error (actor gone / mailbox), surfaced as a coarse [`Error`]
983    /// like the other local-read paths (`status`/`tka_status`), not a [`ts_control::TkaSyncError`].
984    /// Returns an empty `Vec` when no lock is synced.
985    pub async fn tka_log(&self, limit: usize) -> Result<Vec<TkaLogEntry>, Error> {
986        self.control
987            .ask(control_runner::TkaLog { limit })
988            .await
989            .map_err(Error::from)
990    }
991
992    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` (`acme` feature).
993    ///
994    /// Mirrors `fetch_id_token`: forwards to the control runner, which runs
995    /// the client-side ACME DNS-01 flow on a spawned task and publishes the challenge TXT via the
996    /// node's set-dns RPC. The kameo delegated-reply send error is flattened — a handler error
997    /// carries the real [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox
998    /// closed) is surfaced as a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control
999    /// plane 501s on set-dns.
1000    #[cfg(feature = "acme")]
1001    pub async fn get_certificate(
1002        &self,
1003        name: String,
1004    ) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
1005        self.control
1006            .ask(control_runner::GetCertificate { name })
1007            .await
1008            .map_err(flatten_cert_send_err)
1009    }
1010
1011    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` and return the
1012    /// **PEM pair** `(cert_chain_pem, key_pem)` — the analog of Go's
1013    /// `LocalClient.CertPairWithValidity`, for writing the daemon's on-disk `.crt` + `.key`
1014    /// (`tnet cert`). `acme` feature.
1015    ///
1016    /// Same issuance as [`get_certificate`](Self::get_certificate) (one client-side ACME DNS-01
1017    /// order, challenge published via the node's set-dns RPC) — only the result shape differs: this
1018    /// returns the leaf+chain PEM and the leaf-key PEM instead of the opaque
1019    /// [`CertifiedKey`](ts_control::tls::CertifiedKey). The second element is the **leaf private
1020    /// key** PEM; it is never logged anywhere on this path.
1021    ///
1022    /// **`min_validity` (honest "always fresh").** Go's `CertPairWithValidity` reuses a cached cert
1023    /// when it has at least `min_validity` of its lifetime left, and re-issues otherwise. This fork
1024    /// has **no cert cache** — every call performs a fresh issuance — so `min_validity` is accepted
1025    /// for signature compatibility but does not change behavior: a freshly issued cert (full
1026    /// lifetime) trivially satisfies any `min_validity`. A reuse cache is separate future work; this
1027    /// does NOT fake one.
1028    ///
1029    /// Mirrors [`get_certificate`](Self::get_certificate)'s error handling: the kameo
1030    /// delegated-reply send error is flattened — a handler error carries the real
1031    /// [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox closed) collapses
1032    /// to a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control plane 501s on set-dns.
1033    #[cfg(feature = "acme")]
1034    pub async fn cert_pair(
1035        &self,
1036        name: String,
1037        min_validity: Option<Duration>,
1038    ) -> Result<(String, String), ts_control::CertError> {
1039        // No cert cache exists in this fork (every issuance is fresh), so `min_validity` is honored
1040        // trivially by always issuing a full-lifetime cert. Bound (unused beyond this contract) so
1041        // the parameter is explicitly accounted for rather than silently ignored.
1042        let _ = min_validity;
1043        self.control
1044            .ask(control_runner::GetCertPair { name })
1045            .await
1046            .map_err(flatten_cert_send_err)
1047    }
1048
1049    /// Resolve which node owns a tailnet source address.
1050    ///
1051    /// Maps the destination IP of `addr` to its owning node. Mirrors tsnet's `LocalClient::WhoIs`.
1052    /// Returns `None` if no peer holds that tailnet IP.
1053    ///
1054    /// The returned [`WhoIs`] additionally carries the **flow-scoped** peer-capability grants
1055    /// ([`WhoIs::cap_map`], Go `apitype.WhoIsResponse.CapMap`): the caps control's packet-filter
1056    /// application rules authorize for traffic from THIS node (the flow source) to `addr` (the
1057    /// destination). Empty when no grant matches. (The node-level cap map rides
1058    /// [`WhoIs::capabilities`].)
1059    pub async fn whois(&self, addr: core::net::SocketAddr) -> Result<Option<WhoIs>, Error> {
1060        let whois = self
1061            .peer_tracker
1062            .upgrade()
1063            .ok_or(Error {
1064                kind: ErrorKind::ActorGone,
1065                target_actor: None,
1066                message_ty: None,
1067            })?
1068            .ask(peer_tracker::Whois { addr })
1069            .await?;
1070
1071        let Some(mut whois) = whois else {
1072            return Ok(None);
1073        };
1074
1075        // Fill the flow-scoped cap map: src = this node's own tailnet IP (of the dst's family),
1076        // dst = the queried address. A grant applies when its source matches the flow source — `src`
1077        // ∈ its src prefixes OR this node holds one of its source node-caps — AND `dst` ∈ its dst
1078        // prefixes (Go `Filter.CapsWithValues`). Resolve our own IP + cap map from the self node; if
1079        // it isn't known yet, leave the map empty (no grants resolvable without a source).
1080        let dst = addr.ip();
1081        if let Some(self_node) = self.control.ask(control_runner::SelfNode).await? {
1082            let src: core::net::IpAddr = if dst.is_ipv6() {
1083                self_node.tailnet_address.ipv6.addr().into()
1084            } else {
1085                self_node.tailnet_address.ipv4.addr().into()
1086            };
1087            let grants = self.cap_grants_rx.borrow();
1088            whois.cap_map = ts_packetfilter_state::caps_for(&grants, src, dst, |cap| {
1089                self_node.has_node_attr(cap)
1090            });
1091        }
1092
1093        Ok(Some(whois))
1094    }
1095
1096    /// The current direct-path status to the peer holding tailnet IP `dst`: its confirmed direct UDP
1097    /// endpoint and that path's last-measured RTT, or `None` when there is no direct path right now
1098    /// (the peer is relayed via DERP, is unknown, or has no disco key).
1099    ///
1100    /// The latency is the RTT of the most recent disco ping/pong that confirmed the path — a live
1101    /// snapshot up to one probe interval stale, NOT a fresh on-demand round-trip (that is a separate,
1102    /// heavier capability). Mirrors the direct-path latency Go surfaces for `ipnstate.PeerStatus`.
1103    pub async fn direct_path(
1104        &self,
1105        dst: core::net::IpAddr,
1106    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
1107        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
1108            kind: ErrorKind::ActorGone,
1109            target_actor: None,
1110            message_ty: None,
1111        })?;
1112
1113        // Resolve the tailnet IP to its node, then to its disco key. No node / no disco key ⇒ no
1114        // direct path is possible (a peer with no disco key can only be reached via DERP).
1115        let Some(node) = peer_tracker
1116            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
1117            .await?
1118        else {
1119            return Ok(None);
1120        };
1121        let Some(disco) = node.disco_key else {
1122            return Ok(None);
1123        };
1124
1125        self.direct
1126            .ask(direct::DirectPathLatency { disco })
1127            .await
1128            .map_err(Into::into)
1129    }
1130
1131    /// Send a disco ping to the peer holding tailnet IP `dst` **now** and await the pong, returning
1132    /// the fresh round-trip latency and the endpoint that answered, or `None` if no pong arrives
1133    /// within `timeout` (or the peer is unknown / has no disco key / no candidate path). This is the
1134    /// true on-demand `PingType::Disco` (Go `tailscale ping`), as opposed to
1135    /// [`direct_path`](Self::direct_path) which reports the last periodic probe's RTT.
1136    ///
1137    /// The ping round-trip is awaited OFF the direct manager's mailbox (we take a `MagicSock` handle
1138    /// and await on it directly), so a slow/timing-out ping never blocks the actor.
1139    pub async fn ping_disco(
1140        &self,
1141        dst: core::net::IpAddr,
1142        timeout: Duration,
1143    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
1144        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
1145            kind: ErrorKind::ActorGone,
1146            target_actor: None,
1147            message_ty: None,
1148        })?;
1149
1150        let Some(node) = peer_tracker
1151            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
1152            .await?
1153        else {
1154            return Ok(None);
1155        };
1156        let Some(disco) = node.disco_key else {
1157            return Ok(None);
1158        };
1159
1160        // Cheap synchronous handle fetch, then await the ping OFF the actor mailbox.
1161        let Some(sock) = self.direct.ask(direct::SockHandle).await? else {
1162            return Ok(None);
1163        };
1164        // A `ping_now` error is an underlay UDP send failure (not an actor problem); surface it as a
1165        // reply-level error. A timed-out / unanswered ping is `Ok(None)`, not an error.
1166        sock.ping_now(&disco, timeout).await.map_err(|_| Error {
1167            kind: ErrorKind::ReplyErr,
1168            target_actor: None,
1169            message_ty: None,
1170        })
1171    }
1172
1173    /// Change the selected exit node at runtime (the equivalent of Go `tsnet`'s
1174    /// `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`), without recreating the device.
1175    ///
1176    /// Updates the live exit-node selector, then asks the peer tracker to re-broadcast the current
1177    /// peer set so the route updater and source filter re-resolve the new selector immediately.
1178    /// `None` clears the exit node (internet-bound traffic is then dropped, fail-closed, unless this
1179    /// node egresses directly). The selection is re-resolved against the live peer set, so passing a
1180    /// selector for a peer not yet in the netmap simply takes effect once that peer appears.
1181    pub async fn set_exit_node(
1182        &self,
1183        selector: Option<ts_control::ExitNodeSelector>,
1184    ) -> Result<(), Error> {
1185        // Update the live cell every reader borrows from. `send_replace` keeps the value current
1186        // even with no active receivers (none can have dropped while the runtime is up, but it is
1187        // the right non-failing primitive here).
1188        self.exit_node_tx.send_replace(selector);
1189
1190        // Trigger an immediate re-resolution: the route updater (outbound routes + DoH delegation)
1191        // and the source filter (inbound validation) both recompute on an `Arc<PeerState>`, so a
1192        // re-broadcast applies the new exit without waiting for the next netmap update.
1193        self.peer_tracker
1194            .upgrade()
1195            .ok_or(Error {
1196                kind: ErrorKind::ActorGone,
1197                target_actor: None,
1198                message_ty: None,
1199            })?
1200            .ask(peer_tracker::RepublishState)
1201            .await
1202            .map_err(Into::into)
1203    }
1204
1205    /// The currently-selected exit node, or `None` if none is selected.
1206    pub fn exit_node(&self) -> Option<ts_control::ExitNodeSelector> {
1207        self.env.exit_node()
1208    }
1209
1210    /// Toggle whether this node accepts peer-advertised subnet routes at runtime (the equivalent of
1211    /// Go `tsnet`'s `LocalClient.EditPrefs(RouteAll)` / `tailscale set --accept-routes`), without
1212    /// recreating the device.
1213    ///
1214    /// `accept-routes` is a purely **local** preference — unlike advertised routes it is never
1215    /// reported to control (no `Hostinfo` / MapRequest side), so this only re-runs the local
1216    /// route/source-filter recompute, mirroring [`set_exit_node`](Self::set_exit_node) rather than
1217    /// [`set_advertise_routes`](Self::set_advertise_routes). Updates the live cell, then asks the peer
1218    /// tracker to re-broadcast the current peer set so the route updater (outbound routes) and the
1219    /// source filter (inbound validation) re-filter against the new value immediately: turning it on
1220    /// installs newly-accepted subnet routes (and widens the source filter to match); turning it off
1221    /// removes them from BOTH in lock-step (never accepting a source for a route no longer installed).
1222    /// Self routes and the exit-node default `/0` are unaffected (the latter is gated by the exit-node
1223    /// selection, not this flag).
1224    ///
1225    /// In TUN transport mode the host routing table is also re-steered live: the `RepublishState`
1226    /// kicked below re-broadcasts the peer set to the `TunActor`, whose `PeerState` handler re-reads
1227    /// `accept_routes` (and the exit selection) from `Env` and re-applies the host routes — so the
1228    /// toggle takes effect without rebuilding the device (the apply is an idempotent add-new/
1229    /// remove-gone diff). The exit-node default `/0` is still keyed on the exit selection, not this flag.
1230    pub async fn set_accept_routes(&self, accept: bool) -> Result<(), Error> {
1231        // Update the live cell every reader borrows from (same primitive/rationale as set_exit_node).
1232        self.accept_routes_tx.send_replace(accept);
1233
1234        // Trigger an immediate re-filter: the route updater and source filter both recompute on an
1235        // `Arc<PeerState>`, so a re-broadcast applies the new preference without waiting for the next
1236        // netmap update. Both re-read the same live cell, so the outbound route set and the inbound
1237        // source filter stay coupled (the anti-leak invariant).
1238        self.peer_tracker
1239            .upgrade()
1240            .ok_or(Error {
1241                kind: ErrorKind::ActorGone,
1242                target_actor: None,
1243                message_ty: None,
1244            })?
1245            .ask(peer_tracker::RepublishState)
1246            .await
1247            .map_err(Into::into)
1248    }
1249
1250    /// Whether this node currently accepts peer-advertised subnet routes (`--accept-routes`).
1251    pub fn accept_routes(&self) -> bool {
1252        self.env.accept_routes()
1253    }
1254
1255    /// Toggle whether this node accepts the tailnet's DNS configuration at runtime (the equivalent of
1256    /// Go `tsnet`'s `LocalClient.EditPrefs(CorpDNS)` / `tailscale set --accept-dns`), without
1257    /// recreating the device.
1258    ///
1259    /// Like [`set_accept_routes`](Self::set_accept_routes), `accept-dns` is a purely **local**
1260    /// preference — it is never reported to control (no `Hostinfo` / MapRequest side), so this only
1261    /// re-runs the local MagicDNS view rebuild. Updates the live cell, then asks the peer tracker to
1262    /// re-broadcast the current peer set; the resulting `PeerState` rebuild re-applies the gate on the
1263    /// MagicDNS responder (and the peerAPI DoH server that shares its view). When `false`, the
1264    /// responder ignores the control-pushed DNS config and answers every query `REFUSED`, mirroring Go
1265    /// applying an empty `dns.Config` when `CorpDNS` is off; flipping it back to `true` restores
1266    /// serving from the still-current config (the real config is never destroyed — only gated at the
1267    /// read site), so the OFF→ON restore is automatic.
1268    pub async fn set_accept_dns(&self, accept: bool) -> Result<(), Error> {
1269        // Update the live cell every reader borrows from (same primitive/rationale as set_accept_routes).
1270        self.accept_dns_tx.send_replace(accept);
1271
1272        // Trigger an immediate view rebuild: the MagicDNS responder re-reads `Env::accept_dns()` when
1273        // it handles a `PeerState`, so a re-broadcast re-applies the gate on both the netstack
1274        // responder and the peerAPI DoH server (which share the view) without waiting for the next
1275        // control/peer update. Mirrors `set_accept_routes`'s republish.
1276        self.peer_tracker
1277            .upgrade()
1278            .ok_or(Error {
1279                kind: ErrorKind::ActorGone,
1280                target_actor: None,
1281                message_ty: None,
1282            })?
1283            .ask(peer_tracker::RepublishState)
1284            .await
1285            .map_err(Into::into)
1286    }
1287
1288    /// Whether this node currently accepts the tailnet's DNS configuration (`--accept-dns` / `CorpDNS`).
1289    pub fn accept_dns(&self) -> bool {
1290        self.env.accept_dns()
1291    }
1292
1293    /// Change the set of subnet routes this node advertises at runtime (Go `tailscale set
1294    /// --advertise-routes`). Applies BOTH halves together so the wire and the data path agree:
1295    ///
1296    /// 1. **Wire** — re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
1297    ///    (so control grants the node the subnet-router role for exactly these prefixes).
1298    /// 2. **Local** — swap the forwarder's accept/dial route table (so the node actually forwards the
1299    ///    prefixes it advertises). New flows see the new set; in-flight flows keep their routing.
1300    ///
1301    /// `routes` is filtered to the IPv4-only, deduplicated set this fork can honor (IPv6 prefixes are
1302    /// dropped under the IPv6-off posture — we never advertise a route we won't forward), so the wire
1303    /// and forwarder are fed the identical final set. This sets the explicit subnet prefixes only; it
1304    /// does NOT touch the exit-node `0.0.0.0/0` advertisement (a separate concern).
1305    pub async fn set_advertise_routes(&self, routes: Vec<ipnet::IpNet>) -> Result<(), Error> {
1306        // Update the explicit-subnet part of the live preference, keep the exit-node flag, and
1307        // re-send the composed set. Composes with `set_advertise_exit_node` (neither clobbers the
1308        // other's contribution to `Hostinfo.RoutableIPs`).
1309        let composed = {
1310            let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
1311            adv.routes = routes;
1312            compose_advertised_routes(adv.routes.clone(), adv.exit_node)
1313        };
1314        self.apply_advertised_routes(composed).await
1315    }
1316
1317    /// Advertise (or stop advertising) this node as an **exit node** — the `0.0.0.0/0` + `::/0`
1318    /// default-route pair (Go `tailscale set --advertise-exit-node`). Composes with
1319    /// [`set_advertise_routes`](Self::set_advertise_routes): toggling the exit node re-sends the
1320    /// explicit subnet routes plus (when `enable`) the default-route pair, so the two preferences are
1321    /// independent. Like `set_advertise_routes`, this both re-advertises `Hostinfo.RoutableIPs` to
1322    /// control AND updates the forwarder's accept/dial set, applied together. Control still gates
1323    /// whether the advertised exit node is actually *usable* by peers (this only advertises it).
1324    pub async fn set_advertise_exit_node(&self, enable: bool) -> Result<(), Error> {
1325        let composed = {
1326            let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
1327            adv.exit_node = enable;
1328            compose_advertised_routes(adv.routes.clone(), adv.exit_node)
1329        };
1330        self.apply_advertised_routes(composed).await
1331    }
1332
1333    /// Push a freshly-composed advertised-route set to BOTH halves: the forwarder's accept/dial
1334    /// table (local) FIRST — so the node forwards a prefix before control grants it, never the
1335    /// reverse — then re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
1336    /// (wire). `composed` is already filtered + exit-node-folded by [`compose_advertised_routes`].
1337    async fn apply_advertised_routes(&self, composed: Vec<ipnet::IpNet>) -> Result<(), Error> {
1338        self.forwarder
1339            .ask(forwarder_actor::UpdateRoutes {
1340                routes: composed.clone(),
1341            })
1342            .await?;
1343        self.control
1344            .ask(control_runner::SetAdvertiseRoutes { routes: composed })
1345            .await
1346            .map_err(Into::into)
1347    }
1348
1349    /// Change this node's hostname at runtime (Go `tailscale set --hostname`), re-reporting
1350    /// `Hostinfo.Hostname` to control on the live map-poll connection. Hostname is display-only
1351    /// (control reflects it in the netmap), so there is no dataplane half. The new value is also
1352    /// what a subsequent re-registration reports, so it persists across a reconnect.
1353    pub async fn set_hostname(&self, hostname: String) -> Result<(), Error> {
1354        self.control
1355            .ask(control_runner::SetHostname { hostname })
1356            .await
1357            .map_err(Into::into)
1358    }
1359
1360    /// Subscribe to netmap peer-change events: the **narrow** peer-set view.
1361    ///
1362    /// Returns a [`watch::Receiver`] whose value is the current set of peer [`StatusNode`]s,
1363    /// updated on every netmap state update from control. Await
1364    /// [`watch::Receiver::changed`](tokio::sync::watch::Receiver::changed) to react to peers
1365    /// joining, leaving, or changing. For the unified Go-`WatchIPNBus` feed that merges this with
1366    /// device-state and the interactive-login URL, see [`watch_ipn_bus`](Self::watch_ipn_bus); this
1367    /// method is the peer-only projection of the same underlying cell.
1368    pub async fn watch_netmap(&self) -> Result<watch::Receiver<Vec<StatusNode>>, Error> {
1369        self.peer_tracker
1370            .upgrade()
1371            .ok_or(Error {
1372                kind: ErrorKind::ActorGone,
1373                target_actor: None,
1374                message_ty: None,
1375            })?
1376            .ask(peer_tracker::WatchNetmap)
1377            .await
1378            .map_err(Into::into)
1379    }
1380
1381    /// The current device connection-[`DeviceState`].
1382    pub fn device_state(&self) -> DeviceState {
1383        self.state_rx.borrow().clone()
1384    }
1385
1386    /// Watch the device connection-[`DeviceState`] (`Connecting` → `Running` / `NeedsLogin` /
1387    /// `Expired` / `Failed`).
1388    ///
1389    /// Returns a [`watch::Receiver`]; await
1390    /// [`changed`](tokio::sync::watch::Receiver::changed) to react push-style to control connection
1391    /// transitions instead of polling [`status`](Self::status). The initial value is the current
1392    /// state. Note: a transient per-reconnect dip back to `Connecting` is **not** currently
1393    /// emitted (control transparently reconnects below this layer); the state reflects registration
1394    /// outcome and node-key expiry.
1395    pub fn watch_state(&self) -> watch::Receiver<DeviceState> {
1396        self.state_rx.clone()
1397    }
1398
1399    /// Wait until the device finishes registering, returning a typed outcome.
1400    ///
1401    /// Resolves `Ok(())` once the device reaches [`DeviceState::Running`]. Returns a typed
1402    /// [`RegistrationError`] otherwise — the actionable distinction between "retry", "re-pair", and
1403    /// "drive interactive login" that replaces polling the device's `ipv4_addr` in a loop:
1404    /// - `AuthRejected` — bad/expired/unknown auth key. **Permanent** (re-pair).
1405    /// - `NeedsLogin(url)` — interactive authorization required (no usable auth key). **Not
1406    ///   permanent**: the runtime keeps retrying and will reach `Running` once the user authorizes
1407    ///   the URL. An **auth-key** caller should treat this as a failure; an **interactive** caller
1408    ///   should ignore this return and instead drive the flow via [`watch_state`](Self::watch_state)
1409    ///   (this method returns the URL eagerly rather than blocking for the whole login).
1410    /// - `NetworkUnreachable` — control unreachable. **Transient** (retry).
1411    /// - `Timeout` — no settled state within `timeout`.
1412    ///
1413    /// `KeyExpired` is not produced by this initial wait (a node key expires only *after* it has
1414    /// come up); observe post-registration expiry via [`watch_state`](Self::watch_state).
1415    /// `timeout` of `None` waits indefinitely for a settled state.
1416    pub async fn wait_until_running(
1417        &self,
1418        timeout: Option<Duration>,
1419    ) -> Result<(), RegistrationError> {
1420        device_state::wait_for_running(self.state_rx.clone(), timeout).await
1421    }
1422
1423    /// Subscribe to the unified IPN notification bus (Go `ipn` `WatchIPNBus` /
1424    /// `LocalBackend.WatchNotifications`).
1425    ///
1426    /// Returns an [`IpnBusWatcher`]; await [`next`](IpnBusWatcher::next) to receive [`Notify`]
1427    /// events that coalesce device-[`DeviceState`] changes (including the interactive-login URL as
1428    /// `browse_to_url`) and netmap peer-set changes into one feed. `mask`
1429    /// ([`NotifyWatchOpt`]) selects which current-state fields are front-loaded as an initial
1430    /// snapshot on subscribe (`INITIAL_STATE` / `INITIAL_NETMAP`), exactly like Go's
1431    /// `NotifyInitialState` / `NotifyInitialNetMap`.
1432    ///
1433    /// This composes the same `watch` cells as [`watch_state`](Self::watch_state),
1434    /// [`watch_netmap`](Self::watch_netmap), and `pop_browser_url` — one source of truth, so the
1435    /// merged feed cannot diverge from those narrow views. Besides the registration-time login URL
1436    /// (carried by `NeedsLogin`), `browse_to_url` also streams the mid-session
1437    /// `MapResponse.PopBrowserURL` (re-auth / consent on an already-running node). Delivery is
1438    /// best-effort/lossy (a bounded per-watcher buffer; a notification is dropped rather than
1439    /// blocking the runtime if a slow consumer's buffer fills), matching Go's bus. The stream ends
1440    /// (`next` returns `None`) on runtime shutdown or when the watcher is dropped.
1441    pub async fn watch_ipn_bus(&self, mask: NotifyWatchOpt) -> Result<IpnBusWatcher, Error> {
1442        // The peer-set cell lives on the peer-tracker actor; obtain a receiver the same way
1443        // `watch_netmap` does. State + shutdown cells are held here.
1444        let peer_rx = self
1445            .peer_tracker
1446            .upgrade()
1447            .ok_or(Error {
1448                kind: ErrorKind::ActorGone,
1449                target_actor: None,
1450                message_ty: None,
1451            })?
1452            .ask(peer_tracker::WatchNetmap)
1453            .await?;
1454        // The running-node consent-URL cell lives on the control runner; obtain its receiver the
1455        // same way (the control actor ref is strong, so no upgrade needed).
1456        let browser_rx = self.control.ask(control_runner::WatchBrowserUrl).await?;
1457        Ok(ipn_bus::spawn_watcher(
1458            mask,
1459            self.state_rx.clone(),
1460            peer_rx,
1461            browser_rx,
1462            self.shutdown.subscribe(),
1463        ))
1464    }
1465
1466    /// Attempt to shut down the runtime gracefully.
1467    ///
1468    /// Returns false if the shutdown timed out. It is still shut down if it timed out, just
1469    /// more violently and with possible resource leaks.
1470    pub async fn graceful_shutdown(self, timeout: Option<Duration>) -> bool {
1471        self.shutdown.send_replace(true);
1472
1473        async fn _shutdown_all(runtime: Runtime) {
1474            // See the note in `Drop` for why we only need to stop these actors to bring down the
1475            // whole runtime.
1476
1477            let _ignore = runtime.control.stop_gracefully().await;
1478            let _ignore = runtime.dataplane.stop_gracefully().await;
1479            let _ignore = runtime.env.bus.stop_gracefully().await;
1480
1481            tokio::join![
1482                runtime.control.wait_for_shutdown(),
1483                runtime.dataplane.wait_for_shutdown(),
1484                runtime.env.bus.wait_for_shutdown(),
1485            ];
1486        }
1487
1488        let fut = _shutdown_all(self);
1489
1490        match timeout {
1491            Some(timeout) => tokio::time::timeout(timeout, fut).await.is_ok(),
1492            None => {
1493                fut.await;
1494                true
1495            }
1496        }
1497    }
1498}
1499
1500impl Drop for Runtime {
1501    fn drop(&mut self) {
1502        // Stop the taildrop reaper so it cannot outlive the runtime (the `reauth_bridge` pattern). It
1503        // also self-exits when `shutdown` flips below, but aborting is immediate and covers the
1504        // already-shutdown early-return path too.
1505        if let Some(reaper) = self.taildrop_reaper.take() {
1506            reaper.abort();
1507        }
1508
1509        // We must have already run `graceful_shutdown`: on the happy path, this does nothing, but
1510        // if it timed out, we need to make sure the actors are dead so we don't leak them and their
1511        // dependents.
1512        if *self.shutdown.borrow() {
1513            self.control.kill();
1514            self.dataplane.kill();
1515            self.env.bus.kill();
1516            return;
1517        }
1518
1519        self.shutdown.send_replace(true);
1520
1521        // The security guard retains supervised actors until it can kill them independently of
1522        // full mailboxes. Its Drop also aborts the packet pump and all remaining supervised actors.
1523        // Stop the control/dataplane/bus here for the graceful-shutdown path.
1524
1525        // First shut down the actors we have an ActorRef to:
1526        try_shutdown(&self.control);
1527        try_shutdown(&self.dataplane);
1528
1529        // Then shut down the message bus; the guard cancels its subscribers on Drop.
1530        try_shutdown(&self.env.bus);
1531    }
1532}
1533
1534fn try_shutdown(a: &ActorRef<impl kameo::Actor>) {
1535    if let Err(e) = a.mailbox_sender().try_send(Signal::Stop) {
1536        tracing::error!(error = %e, "graceful shutdown failed, killing actor");
1537        a.kill();
1538    }
1539}
1540
1541/// Tailscale's overlay MTU. The userspace netstacks MUST advertise an MSS that fits this so they
1542/// never hand the WireGuard encrypt path an IP packet larger than the tunnel can carry (the netstack
1543/// has no PMTU discovery and nothing re-segments between it and the 1280-MTU TUN). This is the same
1544/// default the TUN device uses (`tun_config_from_control`); both are derived from this value so the
1545/// netstack and the TUN always agree.
1546///
1547/// This is the **inner** IP-packet budget. The WireGuard transport header (a 16-byte
1548/// `TransportDataHeader` + the 16-byte AEAD tag = 32 bytes) is added by `TransmitSession::encrypt`
1549/// *after* the netstack produces the inner packet, and the outer UDP/IP headers ride on top of that.
1550/// So do NOT subtract the WireGuard overhead here — that would be a double-subtraction that
1551/// under-fills the tunnel and diverges from the TUN's MTU. The assert below documents that the outer
1552/// datagram still fits a conventional 1500-byte physical path with margin (1280 + 32 WG + 8 UDP +
1553/// 20 outer-IP = 1340).
1554const DEFAULT_OVERLAY_MTU: u16 = 1280;
1555
1556const _: () = assert!(
1557    DEFAULT_OVERLAY_MTU as usize + 32 + 8 + 20 <= 1500,
1558    "inner overlay MTU + WireGuard(32) + UDP(8) + outer-IP(20) must fit a 1500-byte physical path"
1559);
1560
1561/// Build the netstack config shared by both userspace netstacks (application + forwarder) from the
1562/// per-deployment `tcp_buffer_size` and `mtu` knobs.
1563///
1564/// `tcp_buffer_size`: `None` keeps the netstack default (256 KiB/direction); `Some(n)` overrides it
1565/// (e.g. a smaller window on a memory-constrained exit node forwarding many concurrent flows — see
1566/// [`netstack::netcore::Config::tcp_buffer_size`]).
1567///
1568/// `mtu`: the overlay/tunnel MTU. `None` (and a stray `0`) falls back to [`DEFAULT_OVERLAY_MTU`]
1569/// (1280), exactly as the TUN device does, so the netstack's advertised MSS fits the tunnel. Leaving
1570/// this at the netstack's generic 1500 default (the prior behavior) made smoltcp advertise MSS ~1460
1571/// and segment to ~1500 B, which then overflowed the 1280 TUN — a PMTU black-hole / throughput cliff.
1572///
1573/// Factored out of [`Runtime::spawn`] so the mapping is unit-testable without standing up the actors.
1574fn netstack_config_from(
1575    tcp_buffer_size: Option<usize>,
1576    mtu: Option<u16>,
1577) -> netstack::netcore::Config {
1578    let mut c = netstack::netcore::Config::default();
1579    if let Some(tcp_buffer_size) = tcp_buffer_size {
1580        c.tcp_buffer_size = tcp_buffer_size;
1581    }
1582    // `0` is not a usable MTU; treat it like `None` and fall back to the overlay default, mirroring
1583    // the TUN's `and_then(NonZeroU16::new).unwrap_or(1280)`.
1584    let mtu = mtu.filter(|&m| m != 0).unwrap_or(DEFAULT_OVERLAY_MTU);
1585    c.mtu = usize::from(mtu);
1586    c
1587}
1588
1589/// Filter a requested advertise-route set to the IPv4-only, deduplicated set this fork can honor,
1590/// mirroring [`ts_control::Config::advertised_routes`] so a runtime `set_advertise_routes` feeds the
1591/// wire (control grant) and the forwarder (accept/dial table) the identical final set. IPv6 prefixes
1592/// are dropped under the IPv6-off posture — we never advertise a route we won't forward. Order is
1593/// preserved (first occurrence wins). Factored out so the filter is unit-testable without an actor.
1594fn filter_advertise_routes(routes: Vec<ipnet::IpNet>) -> Vec<ipnet::IpNet> {
1595    let mut filtered: Vec<ipnet::IpNet> = Vec::new();
1596    for net in routes {
1597        if matches!(net, ipnet::IpNet::V4(_)) {
1598            if !filtered.contains(&net) {
1599                filtered.push(net);
1600            }
1601        } else {
1602            tracing::warn!(prefix = %net, "dropping IPv6 advertise route (IPv6-off posture)");
1603        }
1604    }
1605    filtered
1606}
1607
1608/// Compose the final advertised-route set from the explicit subnet `routes` and the exit-node flag,
1609/// mirroring [`ts_control::Config::advertised_routes`]: the IPv4-only, deduplicated subnet prefixes,
1610/// plus the exit-node pair `0.0.0.0/0` + `::/0` appended when `exit_node` is set. This is the
1611/// single source of truth both runtime advertise mutators (`set_advertise_routes`,
1612/// `set_advertise_exit_node`) feed, so the two compose instead of clobbering. Factored out so the composition is unit-testable without an actor.
1613fn compose_advertised_routes(routes: Vec<ipnet::IpNet>, exit_node: bool) -> Vec<ipnet::IpNet> {
1614    let mut filtered = filter_advertise_routes(routes);
1615    if exit_node {
1616        for net in ts_control::exit_node_routes() {
1617            if !filtered.contains(&net) {
1618                filtered.push(net);
1619            }
1620        }
1621    }
1622    filtered
1623}
1624
1625/// The runtime's live advertised-route preference: the explicit subnet routes plus whether this node
1626/// advertises itself as an exit node. Held behind a `Mutex` on the [`Runtime`] so
1627/// [`Runtime::set_advertise_routes`] and [`Runtime::set_advertise_exit_node`] each mutate their own
1628/// part and re-send the composed set — they compose rather than clobber (Go `EditPrefs` keeps
1629/// `AdvertiseRoutes` and the exit-node advertisement as independent prefs that both feed
1630/// `Hostinfo.RoutableIPs`).
1631#[derive(Debug, Default, Clone)]
1632struct AdvertiseState {
1633    /// The explicit subnet prefixes (pre-filter; the last value passed to `set_advertise_routes`).
1634    routes: Vec<ipnet::IpNet>,
1635    /// Whether this node advertises the exit-node default routes (`0.0.0.0/0` + `::/0`).
1636    exit_node: bool,
1637}
1638
1639/// Flatten a kameo delegated-reply [`SendError`] for the id-token RPC into the RPC's own
1640/// [`ts_control::IdTokenError`].
1641///
1642/// A [`SendError::HandlerError`](kameo::error::SendError::HandlerError) carries the real
1643/// `IdTokenError` produced by the handler and is surfaced verbatim. Any other send failure (actor
1644/// not running / stopped, mailbox full, send timeout) is a delivery problem rather than an RPC
1645/// result, so it collapses to a transient [`ts_control::IdTokenError::NetworkError`]. Factored out
1646/// of [`Runtime::fetch_id_token`] so this mapping is unit-testable without standing up an actor.
1647fn flatten_send_err<M>(
1648    e: kameo::error::SendError<M, ts_control::IdTokenError>,
1649) -> ts_control::IdTokenError {
1650    match e {
1651        kameo::error::SendError::HandlerError(err) => err,
1652        _ => ts_control::IdTokenError::NetworkError,
1653    }
1654}
1655
1656/// Flatten a kameo `SendError` from the `Logout` ask into a [`ts_control::LogoutError`].
1657///
1658/// A `HandlerError` carries the real `LogoutError` from the control RPC and is surfaced verbatim;
1659/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1660/// problem, not a logout result — collapses to the transient [`ts_control::LogoutError::NetworkError`]
1661/// (logout is idempotent, so a retry after a delivery failure is safe). Factored out of
1662/// [`Runtime::logout`] so the mapping is unit-testable without standing up an actor.
1663fn flatten_logout_send_err<M>(
1664    e: kameo::error::SendError<M, ts_control::LogoutError>,
1665) -> ts_control::LogoutError {
1666    match e {
1667        kameo::error::SendError::HandlerError(err) => err,
1668        _ => ts_control::LogoutError::NetworkError,
1669    }
1670}
1671
1672/// Flatten a kameo `SendError` from the `SetDns` ask into a [`ts_control::SetDnsError`].
1673///
1674/// A `HandlerError` carries the real `SetDnsError` from the set-dns RPC and is surfaced verbatim;
1675/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1676/// problem, not a publish result — collapses to the transient
1677/// [`ts_control::SetDnsError::NetworkError`]. Factored out of [`Runtime::set_dns`] so the mapping is
1678/// unit-testable without standing up an actor.
1679fn flatten_set_dns_send_err<M>(
1680    e: kameo::error::SendError<M, ts_control::SetDnsError>,
1681) -> ts_control::SetDnsError {
1682    match e {
1683        kameo::error::SendError::HandlerError(err) => err,
1684        _ => ts_control::SetDnsError::NetworkError,
1685    }
1686}
1687
1688/// Flatten a kameo `SendError` from a TKA mutation ask (`TkaSign`/`TkaDisable`) into a
1689/// [`ts_control::TkaSyncError`]. A `HandlerError` carries the real RPC error; any other send failure
1690/// (actor shutdown / mailbox closed) is surfaced as the transient
1691/// [`ts_control::TkaSyncError::NetworkError`]. Generic over the message type so both share it.
1692fn flatten_tka_send_err<M>(
1693    e: kameo::error::SendError<M, ts_control::TkaSyncError>,
1694) -> ts_control::TkaSyncError {
1695    match e {
1696        kameo::error::SendError::HandlerError(err) => err,
1697        _ => ts_control::TkaSyncError::NetworkError,
1698    }
1699}
1700
1701/// Flatten a kameo `SendError` from the `GetCertificate` / `GetCertPair` ask into a
1702/// [`ts_control::CertError`].
1703///
1704/// A `HandlerError` carries the real `CertError` produced by the ACME issuance and is surfaced
1705/// verbatim. `CertError` has no transient-network variant, so any other send failure (actor not
1706/// running / stopped, mailbox full, send timeout) — a delivery problem rather than an issuance
1707/// result — collapses to a [`ts_control::CertError::Io`]. Generic over the message type, so it
1708/// serves both [`Runtime::get_certificate`] and [`Runtime::cert_pair`]; factored out so the mapping
1709/// is unit-testable without standing up an actor.
1710#[cfg(feature = "acme")]
1711fn flatten_cert_send_err<M>(
1712    e: kameo::error::SendError<M, ts_control::CertError>,
1713) -> ts_control::CertError {
1714    match e {
1715        kameo::error::SendError::HandlerError(err) => err,
1716        _ => ts_control::CertError::Io(std::io::Error::other(
1717            "control runner unavailable for certificate issuance",
1718        )),
1719    }
1720}
1721
1722#[cfg(test)]
1723mod tests {
1724    use super::*;
1725
1726    /// `None` must leave the netstack's own default TCP window in place (the 256 KiB throughput
1727    /// default), and must not silently coerce to some other value.
1728    #[test]
1729    fn netstack_config_none_uses_netstack_default() {
1730        let default = netstack::netcore::Config::default();
1731        let built = netstack_config_from(None, None);
1732        assert_eq!(
1733            built.tcp_buffer_size, default.tcp_buffer_size,
1734            "None must inherit the netstack default TCP buffer size"
1735        );
1736    }
1737
1738    #[test]
1739    fn netstack_config_mtu_defaults_to_overlay_not_generic_1500() {
1740        // The crux of the fix: with no explicit MTU, the netstack must use the 1280 overlay MTU, NOT
1741        // smoltcp's generic 1500 default — otherwise it advertises an MSS that overflows the tunnel.
1742        let built = netstack_config_from(None, None);
1743        assert_eq!(
1744            built.mtu,
1745            usize::from(DEFAULT_OVERLAY_MTU),
1746            "netstack MTU must default to the 1280 overlay MTU, not the 1500 netstack default"
1747        );
1748        assert_ne!(built.mtu, 1500, "must not leave the generic 1500 default");
1749    }
1750
1751    #[test]
1752    fn netstack_config_honors_explicit_mtu_and_rejects_zero() {
1753        // An explicit (control-supplied) MTU is honored verbatim.
1754        assert_eq!(netstack_config_from(None, Some(1400)).mtu, 1400);
1755        // A stray 0 is not a usable MTU; fall back to the overlay default (mirrors the TUN).
1756        assert_eq!(
1757            netstack_config_from(None, Some(0)).mtu,
1758            usize::from(DEFAULT_OVERLAY_MTU)
1759        );
1760    }
1761
1762    #[test]
1763    fn netstack_config_overlay_mtu_matches_tun_default() {
1764        // The netstack MTU default and the TUN MTU default must be the same value, or the two
1765        // netstacks and the TUN would disagree on the segment size budget.
1766        assert_eq!(
1767            DEFAULT_OVERLAY_MTU, 1280,
1768            "overlay MTU must match the TUN device default (tun_config_from_control)"
1769        );
1770    }
1771
1772    /// `Some(n)` must override the TCP window (the memory-vs-throughput knob exit-node operators
1773    /// reach for), reaching the config that both netstacks are built from.
1774    #[test]
1775    fn netstack_config_some_overrides_buffer() {
1776        let built = netstack_config_from(Some(64 * 1024), None);
1777        assert_eq!(
1778            built.tcp_buffer_size,
1779            64 * 1024,
1780            "Some(n) must override the TCP buffer size that both netstacks use"
1781        );
1782    }
1783
1784    /// `set_advertise_routes` must feed the wire and the forwarder the IDENTICAL filtered set:
1785    /// IPv4-only (IPv6 dropped under the IPv6-off posture), deduplicated, order preserved.
1786    #[test]
1787    fn filter_advertise_routes_keeps_v4_dedups_drops_v6() {
1788        let v4a: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1789        let v4b: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
1790        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1791
1792        // Mixed input with a duplicate v4 and a v6 prefix.
1793        let out = filter_advertise_routes(vec![v4a, v6, v4b, v4a]);
1794
1795        assert_eq!(
1796            out,
1797            vec![v4a, v4b],
1798            "v6 dropped, duplicate v4 collapsed, first-occurrence order preserved"
1799        );
1800    }
1801
1802    /// An all-IPv6 request filters to empty (we never advertise a route we won't forward) rather
1803    /// than erroring — clearing the advertised set is a legitimate outcome.
1804    #[test]
1805    fn filter_advertise_routes_all_v6_is_empty() {
1806        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1807        assert!(filter_advertise_routes(vec![v6]).is_empty());
1808    }
1809
1810    /// `compose_advertised_routes` folds the exit-node default-route pair onto the filtered subnet routes
1811    /// when (and only when) the exit-node flag is set — so `set_advertise_routes` and
1812    /// `set_advertise_exit_node` compose. The two preferences are independent.
1813    #[test]
1814    fn compose_advertised_routes_folds_exit_node() {
1815        let subnet: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1816        let default_v4: ipnet::IpNet = "0.0.0.0/0".parse().unwrap();
1817        let default_v6: ipnet::IpNet = "::/0".parse().unwrap();
1818
1819        // Exit node off: just the (filtered) subnet routes.
1820        assert_eq!(
1821            compose_advertised_routes(vec![subnet], false),
1822            vec![subnet],
1823            "exit-node off ⇒ no default route"
1824        );
1825        // Exit node on: subnet routes PLUS the default-route pair.
1826        assert_eq!(
1827            compose_advertised_routes(vec![subnet], true),
1828            vec![subnet, default_v4, default_v6],
1829            "exit-node on ⇒ 0.0.0.0/0 + ::/0 appended"
1830        );
1831        // Exit node on with NO subnet routes: just the default route.
1832        assert_eq!(
1833            compose_advertised_routes(vec![], true),
1834            vec![default_v4, default_v6],
1835            "exit-node alone advertises only the default-route pair"
1836        );
1837        // Idempotent: an explicit 0.0.0.0/0 already in the routes isn't duplicated by the fold.
1838        assert_eq!(
1839            compose_advertised_routes(vec![default_v4], true),
1840            vec![default_v4, default_v6],
1841            "the exit-node fold dedups against an explicit default route"
1842        );
1843    }
1844
1845    /// A `HandlerError` carries the real `IdTokenError` from the RPC handler and must pass through
1846    /// verbatim, not be flattened to a generic network error. Using an `Internal(_)` payload (not
1847    /// `NetworkError`) makes the passthrough observable: a buggy flatten that always returned
1848    /// `NetworkError` would fail this assertion.
1849    #[test]
1850    fn flatten_send_err_handler_error_passes_through() {
1851        // Build an `Internal(_)` payload via the public `From<Utf8Error>` conversion (no extra
1852        // deps): it is distinct from the `_ => NetworkError` fallback, so a buggy flatten that
1853        // always returned `NetworkError` would fail this assertion.
1854        // Route the invalid bytes through a runtime Vec so the `invalid_from_utf8` lint (which only
1855        // fires on compile-time-known literals) doesn't flag this intentional bad input.
1856        let bytes = vec![0xffu8, 0xfe];
1857        let utf8_err = core::str::from_utf8(&bytes).unwrap_err();
1858        let inner = ts_control::IdTokenError::from(utf8_err);
1859        assert!(matches!(inner, ts_control::IdTokenError::Internal(_)));
1860        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1861            kameo::error::SendError::HandlerError(inner.clone());
1862        assert_eq!(flatten_send_err(e), inner);
1863    }
1864
1865    /// A non-handler send failure (actor stopped) is a delivery problem, not an RPC result, so it
1866    /// must collapse to a transient `NetworkError`.
1867    #[test]
1868    fn flatten_send_err_actor_stopped_is_network_error() {
1869        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1870            kameo::error::SendError::ActorStopped;
1871        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1872    }
1873
1874    /// `ActorNotRunning` (the message bounces back undelivered) is likewise a delivery failure and
1875    /// must map to a transient `NetworkError`.
1876    #[test]
1877    fn flatten_send_err_actor_not_running_is_network_error() {
1878        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1879            kameo::error::SendError::ActorNotRunning(control_runner::FetchIdToken {
1880                audience: "sts.amazonaws.com".to_string(),
1881            });
1882        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1883    }
1884
1885    /// A `HandlerError` from the logout RPC carries the real `LogoutError` and must pass through
1886    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1887    /// passthrough observable.
1888    #[test]
1889    fn flatten_logout_send_err_handler_error_passes_through() {
1890        let inner = ts_control::LogoutError::Internal(ts_control::LogoutInternalErrorKind::Http);
1891        assert!(matches!(inner, ts_control::LogoutError::Internal(_)));
1892        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1893            kameo::error::SendError::HandlerError(inner.clone());
1894        assert_eq!(flatten_logout_send_err(e), inner);
1895    }
1896
1897    /// A non-handler send failure (actor stopped) is a delivery problem, not a logout result, and
1898    /// collapses to a transient `NetworkError` (logout is idempotent, so a retry is safe).
1899    #[test]
1900    fn flatten_logout_send_err_actor_stopped_is_network_error() {
1901        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1902            kameo::error::SendError::ActorStopped;
1903        assert_eq!(
1904            flatten_logout_send_err(e),
1905            ts_control::LogoutError::NetworkError
1906        );
1907    }
1908
1909    /// A `HandlerError` from the set-dns RPC carries the real `SetDnsError` and must pass through
1910    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1911    /// passthrough observable.
1912    #[test]
1913    fn flatten_set_dns_send_err_handler_error_passes_through() {
1914        let inner = ts_control::SetDnsError::Internal(ts_control::SetDnsInternalErrorKind::Http);
1915        assert!(matches!(inner, ts_control::SetDnsError::Internal(_)));
1916        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1917            kameo::error::SendError::HandlerError(inner.clone());
1918        assert_eq!(flatten_set_dns_send_err(e), inner);
1919    }
1920
1921    /// A non-handler send failure (actor stopped) is a delivery problem, not a publish result, and
1922    /// collapses to a transient `NetworkError`.
1923    #[test]
1924    fn flatten_set_dns_send_err_actor_stopped_is_network_error() {
1925        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1926            kameo::error::SendError::ActorStopped;
1927        assert_eq!(
1928            flatten_set_dns_send_err(e),
1929            ts_control::SetDnsError::NetworkError
1930        );
1931    }
1932
1933    /// A `HandlerError` from a TKA mutation RPC carries the real `TkaSyncError` and must pass through
1934    /// verbatim (an `Unsupported` payload makes the passthrough observable, distinct from the
1935    /// `_ => NetworkError` fallback).
1936    #[test]
1937    fn flatten_tka_send_err_handler_error_passes_through() {
1938        let e: kameo::error::SendError<control_runner::TkaSign, ts_control::TkaSyncError> =
1939            kameo::error::SendError::HandlerError(ts_control::TkaSyncError::Unsupported);
1940        assert_eq!(
1941            flatten_tka_send_err(e),
1942            ts_control::TkaSyncError::Unsupported
1943        );
1944    }
1945
1946    /// A non-handler send failure (actor stopped) collapses to a transient `NetworkError`.
1947    #[test]
1948    fn flatten_tka_send_err_actor_stopped_is_network_error() {
1949        let e: kameo::error::SendError<control_runner::TkaSign, ts_control::TkaSyncError> =
1950            kameo::error::SendError::ActorStopped;
1951        assert_eq!(
1952            flatten_tka_send_err(e),
1953            ts_control::TkaSyncError::NetworkError
1954        );
1955    }
1956
1957    /// The same flatten works for the `TkaDisable` message type (the helper is generic over `M`).
1958    #[test]
1959    fn flatten_tka_send_err_works_for_disable() {
1960        let e: kameo::error::SendError<control_runner::TkaDisable, ts_control::TkaSyncError> =
1961            kameo::error::SendError::HandlerError(ts_control::TkaSyncError::Unsupported);
1962        assert_eq!(
1963            flatten_tka_send_err(e),
1964            ts_control::TkaSyncError::Unsupported
1965        );
1966    }
1967}