Skip to main content

tailscale/
lib.rs

1//! A work-in-progress [Tailscale](https://tailscale.com/blog/how-tailscale-works) library.
2//!
3//! `tailscale` allows Rust programs to connect to a tailnet and exchange traffic with peers over
4//! TCP and UDP. It can communicate with other `tailscale`-based peers, `tailscaled` (the Tailscale
5//! Go client), `tsnet`, and `libtailscale` via public DERP servers.
6//!
7//! <div class="warning">
8//! `tailscale` is unstable and insecure.
9//!
10//! We welcome enthusiasm and interest, but please **do not** build production software using these
11//! libraries or rely on it for data privacy until we have a chance to batten down some hatches and
12//! complete a third-party audit.
13//!
14//! See the [Caveats section](#caveats) for more details.
15//! </div>
16//!
17//! For language bindings, see the following crates:
18//!
19//! - C: [ts_ffi](https://docs.rs/ts_ffi)
20//! - Python: [ts_python](https://docs.rs/ts_python)
21//! - Elixir: [ts_elixir](https://docs.rs/ts_elixir)
22//!
23//! For instructions on how to run tests, lints, etc., see [CONTRIBUTING.md]. For the high-level
24//! architecture and repository layout, see [ARCHITECTURE.md].
25//!
26//! ## Code Sample
27//!
28//! A simple UDP client that periodically sends messages to a tailnet peer at `100.64.0.1:5678`:
29//!
30//! ```no_run
31//! # use std::{
32//! #     time::Duration,
33//! #     net::Ipv4Addr,
34//! #     error::Error,
35//! # };
36//! #
37//! # #[tokio::main]
38//! # async fn main() -> Result<(), Box<dyn Error>> {
39//! // Open a new connection to the tailnet
40//! let dev = tailscale::Device::new(
41//!     &tailscale::Config::default_with_key_file("tsrs_keys.json").await?,
42//!     Some("YOUR_AUTH_KEY_HERE".to_owned()),
43//! ).await?;
44//!
45//! // Bind a UDP socket on our tailnet IP, port 1234
46//! let sock = dev.udp_bind((dev.ipv4_addr().await?, 1234).into()).await?;
47//!
48//! // Send a packet containing "hello, world!" to 100.64.0.1:5678 once per second
49//! loop {
50//!     sock.send_to((Ipv4Addr::new(100, 64, 0, 1), 5678).into(), b"hello, world!").await?;
51//!     tokio::time::sleep(Duration::from_secs(1)).await;
52//! }
53//! # }
54//! ```
55//!
56//! Additional examples of using the `tailscale` crate can be found in the [`examples/`] directory.
57//!
58//! ## Using `tailscale`
59//!
60//! To use this crate or the language bindings, you will need to set the `TS_RS_EXPERIMENT` env var
61//! to `this_is_unstable_software`. We'll remove this requirement after a third-party code/cryptography
62//! audit and any necessary fixes.
63//!
64//! Under the hood, we use Tokio for our async runtime. You must also use Tokio, any kind and most
65//! configurations of Tokio runtimes should work, but there must be one available when you call any
66//! async API functions. The easiest way to do this is to use `#[tokio::main]`, see the
67//! [Tokio docs](https://docs.rs/tokio) for more information. In the future, we would like to limit
68//! our reliance on Tokio so that there are alternatives for users of other async runtimes.
69//!
70//! ## Caveats
71//!
72//! This software is still a work-in-progress! We are providing it in the open at this stage out of
73//! a belief in open-source and to see where the community runs with it, but please be aware of a
74//! few important considerations:
75//!
76//! - This implementation contains unaudited cryptography and hasn't undergone a comprehensive
77//!   security analysis. Conservatively, assume there could be a critical security hole meaning
78//!   anything you send or receive could be in the clear on the public Internet.
79//! - There are no compatibility guarantees at the moment. This is early-days software - we may
80//!   break dependent code in order to get things right.
81//! - Direct peer-to-peer connections via NAT traversal are implemented (STUN-discovered endpoints
82//!   and Disco, with `CallMeMaybe` hole-punching over DERP), with DERP relays as the fallback when
83//!   no direct path is available. Hard/symmetric NATs get the same single fixed-local-port candidate
84//!   (`EndpointSTUN4LocalPort`) Go Tailscale uses; behind a NAT with no static port mapping a flow
85//!   may still stay relayed through DERP, which caps its throughput. (Upstream Go does **not** do a
86//!   "256-port birthday-paradox spray" — that is a common misconception; the single-candidate guess
87//!   is the actual behavior, and this fork matches it.)
88//!
89//! ## Feature Flags
90//!
91//! - `axum`: enables the `axum` module, which enables you to run an `axum` HTTP server on top
92//!   of a [`netstack::TcpListener`].
93//!
94//! ## Platform Support
95//!
96//! `tailscale` currently supports the following platforms:
97//!
98//! - Linux (x86_64 and ARM64)
99//! - macOS (ARM64)
100//!
101//! ## Component crates
102//!
103//! The following crates are part of the tailscale-rs project and are dependencies of this one. For
104//! many tasks, just this crate should be sufficient and these other crates are an implementation detail.
105//! There are other crates too, see [ARCHITECTURE.md]
106//! or the [GitHub repo](https://github.com/tailscale/tailscale-rs).
107//!
108//! - [ts_runtime](https://docs.rs/ts_runtime): for each API-level `Device`, the runtime uses an actor
109//!   architecture to manage the lifecycle of the control client, data plane components, netstack, etc.
110//!   A message bus passes updates and communications between these top-level actors.
111//! - [ts_netcheck](https://docs.rs/ts_netcheck): checks network availability and reports latency to
112//!   DERP servers in different regions.
113//! - [ts_netstack_smoltcp](https://docs.rs/ts_netstack_smoltcp): a [smoltcp](https://docs.rs/smoltcp)-based
114//!   network stack that processes Layer 3+ packets to/from the overlay network.
115//! - [ts_control](https://docs.rs/ts_control): control plane client that handles registration,
116//!   authorization/authentication, configuration, and streaming updates.
117//! - [ts_dataplane](https://docs.rs/ts_dataplane): wires all the individual data plane functions together,
118//!   flowing inbound and outbound packets through the components in the correct order.
119//! - [ts_tunnel](https://docs.rs/ts_tunnel): a partial implementation of the WireGuard specification
120//!   that protects all data plane traffic, and is interoperable with other WireGuard clients, including Tailscale clients.
121//! - [ts_cli_util](https://docs.rs/ts_cli_util): helpers for writing command line tools and initializing
122//!   logging, used in examples.
123//! - [ts_disco_protocol](https://docs.rs/ts_disco_protocol): incomplete implementation of Tailscale's
124//!   discovery protocol (disco).
125//!
126//! [ARCHITECTURE.md]: https://github.com/tailscale/tailscale-rs/blob/main/ARCHITECTURE.md
127//! [CONTRIBUTING.md]: https://github.com/tailscale/tailscale-rs/blob/main/CONTRIBUTING.md
128//! [`examples/`]: https://github.com/tailscale/tailscale-rs/blob/main/examples/README.md
129//! [open an issue]: https://github.com/tailscale/tailscale-rs/issues
130//! [`axum` HTTP server]: https://docs.rs/axum/latest/axum/
131
132use std::{
133    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
134    time::Duration,
135};
136
137#[doc(inline)]
138pub use config::Config;
139#[doc(inline)]
140pub use error::{Error, InternalErrorKind};
141// Re-exported so a downstream crate depending only on `tailscale` can name the auth-key secret type
142// for [`Device::new_with_secret`] without taking a separate, version-pinned dependency on `secrecy`
143// (which would risk a `SecretString`-type mismatch if the two `secrecy` majors diverged). Callers
144// pass `tailscale::SecretString`; `secrecy` is a pure-Rust wrapper (no aws-lc/openssl/ring).
145pub use secrecy::SecretString;
146#[doc(inline)]
147pub use ts_control::ExitNodeSelector;
148#[doc(inline)]
149pub use ts_control::Node as NodeInfo;
150#[doc(inline)]
151pub use ts_control::tls::{CertifiedKey, TlsAcceptor, TlsStream};
152#[doc(inline)]
153pub use ts_control::{CertError, MISSING_CERT_RPC, ServeConfig, ServeState, ServeTarget};
154/// The netmap DNS configuration returned by [`Device::dns_config`] (Go `netmap.NetworkMap.DNS`).
155#[doc(inline)]
156pub use ts_control::{DnsConfig, DnsResolver, ExtraRecord};
157#[doc(inline)]
158pub use ts_control::{ExitProxyConfig, ExitProxyScheme};
159pub use ts_control::{
160    IdTokenError, LogoutError, ServiceError, ServiceMode, SetDnsError, SetDnsInternalErrorKind,
161    SshAccept, SshAction, SshConnIdentity, SshDecision, SshDenyReason, SshPolicy, SshPrincipal,
162    SshRule, StableNodeId,
163};
164// Re-exported so the application data-path transport can be selected through the `tailscale`
165// facade alone: `Config::transport_mode` is `TransportMode` (default `Netstack`; `Tun(TunConfig {
166// name, mtu })` for a real kernel TUN interface). Both are `pub` in `ts_control` but were not
167// reachable through this facade, forcing downstream crates to depend on `ts_control` directly just
168// to name them.
169pub use ts_control::{TransportMode, TunConfig};
170#[doc(inline)]
171pub use ts_netstack_smoltcp::PingError;
172use ts_netstack_smoltcp::{CreateSocket, netcore::Channel};
173#[doc(inline)]
174pub use ts_runtime::fallback_tcp::{
175    FallbackConnFuture, FallbackConnHandler, FallbackDecision, FallbackTcpHandle,
176};
177#[doc(inline)]
178pub use ts_runtime::taildrop::WaitingFile;
179#[doc(inline)]
180pub use ts_runtime::{
181    DeviceState, DnsQueryResult, FileTarget, IpnBusWatcher, NetcheckReport, Notify, NotifyWatchOpt,
182    RegionLatency, RegistrationError, Status, StatusNode, WhoIs,
183};
184/// The interactive-login URL type returned by [`Device::pop_browser_url`].
185#[doc(inline)]
186pub use url::Url;
187
188#[cfg(feature = "axum")]
189pub mod axum;
190pub mod config;
191mod dial;
192mod error;
193mod loopback;
194#[cfg(feature = "ssh")]
195pub mod ssh;
196
197#[doc(inline)]
198pub use dial::{ConnectedUdpSocket, DialConn};
199#[doc(inline)]
200pub use loopback::LoopbackHandle;
201
202/// How a program connects to a tailnet and communicates with peers.
203///
204/// The `Device` connects to the control plane, registers itself with the tailnet, and communicates
205/// with tailnet peers. Its tailnet identity is determined by the key state provided at
206/// construction-time.
207pub struct Device {
208    runtime: ts_runtime::Runtime,
209    /// Command channel to the application netstack. `None` in TUN transport mode, where there is
210    /// no userspace application netstack; the channel-driven socket APIs ([`Device::udp_bind`],
211    /// [`Device::tcp_listen`], [`Device::tcp_connect`], [`Device::ping`]) are unsupported there.
212    channel: Option<Channel>,
213    /// Whether IPv6 is enabled on the tailnet overlay (the `Config::enable_ipv6` gate, default
214    /// `false`). Captured at construction; used by [`Device::listen_service`] to decide whether an
215    /// IPv6 VIP-service address is bindable (the netstack only accepts IPv6 overlay addresses when
216    /// this is set).
217    enable_ipv6: bool,
218    /// The stored Serve config + its live per-port accept loops (`tsnet`'s `Get/SetServeConfig` +
219    /// serving runtime). Built lazily on the first [`Device::set_serve_config`] (it needs this
220    /// node's overlay IPv4, only known after registration). Held here so its accept loops abort when
221    /// the `Device` drops; `None` (empty config) until the first `set`.
222    serve: std::sync::Mutex<Option<ts_runtime::serve::ServeManager>>,
223    /// The live Funnel ingress manager (`tsnet`'s `ListenFunnel` data path), built on
224    /// [`Device::listen_funnel`](crate::Device::listen_funnel). Held here so its TLS-termination pump and the installed peerAPI
225    /// ingress sink stay alive for the device's life (and tear down when a new `listen_funnel`
226    /// replaces it, or the `Device` drops). `None` until the first `listen_funnel`.
227    funnel: std::sync::Mutex<Option<ts_runtime::funnel::FunnelManager>>,
228}
229
230/// Map a [`ts_runtime::taildrop::TaildropError`] to the device-facing [`Error`]. `Error` is a
231/// `Copy` enum with no payload, so the I/O detail string is dropped, but the *kind* is preserved so
232/// a caller can still distinguish the actionable cases: an invalid name →
233/// [`InternalErrorKind::BadRequest`], an in-progress conflict → [`InternalErrorKind::AlreadyExists`],
234/// a missing file → [`InternalErrorKind::NotFound`], and any other filesystem failure →
235/// [`InternalErrorKind::Io`].
236fn taildrop_err(e: ts_runtime::taildrop::TaildropError) -> Error {
237    use ts_runtime::taildrop::TaildropError;
238    match e {
239        TaildropError::InvalidFileName => Error::Internal(InternalErrorKind::BadRequest),
240        TaildropError::FileExists => Error::Internal(InternalErrorKind::AlreadyExists),
241        TaildropError::Io(io) if io.kind() == std::io::ErrorKind::NotFound => {
242            Error::Internal(InternalErrorKind::NotFound)
243        }
244        TaildropError::Io(_) => Error::Internal(InternalErrorKind::Io),
245    }
246}
247
248/// Map a [`ts_runtime::taildrop_send::TaildropSendError`] (the Taildrop *sender*) to the
249/// device-facing [`Error`]. The send-side conflict/forbidden/unexpected-status cases all reduce to
250/// `BadRequest` (the peer refused the transfer for a request-level reason), a dial failure or
251/// timeout to `Timeout`, an invalid name to `BadRequest`, and any stream I/O failure to `Io`.
252fn taildrop_send_err(e: ts_runtime::taildrop_send::TaildropSendError) -> Error {
253    use ts_runtime::taildrop_send::TaildropSendError;
254    match e {
255        TaildropSendError::Connect | TaildropSendError::Timeout => Error::Timeout,
256        TaildropSendError::InvalidName
257        | TaildropSendError::Forbidden
258        | TaildropSendError::Conflict
259        | TaildropSendError::UnexpectedStatus(_) => Error::Internal(InternalErrorKind::BadRequest),
260        TaildropSendError::Io => Error::Internal(InternalErrorKind::Io),
261    }
262}
263
264/// Resolve the effective registration auth key from `auth_key` plus the config's
265/// workload-identity-federation (WIF) / OAuth-client fields.
266///
267/// With the `identity-federation` feature enabled, an OAuth client secret (`tskey-client-…`) or a
268/// `client_id` + (`id_token` | `audience`) is exchanged for a Tailscale auth key against the SaaS
269/// admin API before registration (Go `tsnet.Server`'s `resolveAuthKey`). Without the feature this is
270/// a pure pass-through: `auth_key` is returned unchanged and the WIF config fields are ignored, so
271/// the default build is byte-identical to before.
272#[cfg(feature = "identity-federation")]
273async fn resolve_auth_key(
274    config: &Config,
275    auth_key: Option<String>,
276) -> Result<Option<String>, Error> {
277    let wif = ts_control::WifConfig {
278        auth_key,
279        client_id: config.client_id.clone(),
280        client_secret: config.client_secret.clone(),
281        id_token: config.id_token.clone(),
282        audience: config.audience.clone(),
283        tags: config.requested_tags.clone(),
284    };
285    ts_control::resolve_auth_key(&wif, &config.control_server_url)
286        .await
287        .map_err(|e| {
288            tracing::error!(error = %e, "resolving auth key via workload-identity federation");
289            Error::Internal(InternalErrorKind::BadRequest)
290        })
291}
292
293/// Pass-through when the `identity-federation` feature is disabled: the auth key is used as-is and
294/// the WIF config fields have no effect (matching Go, where the federation path is compiled out
295/// unless its optional feature is linked).
296#[cfg(not(feature = "identity-federation"))]
297async fn resolve_auth_key(
298    _config: &Config,
299    auth_key: Option<String>,
300) -> Result<Option<String>, Error> {
301    Ok(auth_key)
302}
303
304impl Device {
305    /// Create a device from the given [`Config`] and auth key.
306    ///
307    /// Internally, this will spawn multiple asynchronous actors onto a Tokio runtime.
308    ///
309    /// # Example
310    ///
311    /// ```rust,no_run
312    /// # #[tokio::main]
313    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
314    /// # use tailscale::*;
315    /// let dev = Device::new(
316    ///     &Config::default_with_key_file("tsrs_keys.json").await?,
317    ///     Some("MY_AUTH_KEY".to_string()),
318    /// ).await?;
319    /// # Ok(()) }
320    /// ```
321    pub async fn new(config: &Config, auth_key: Option<String>) -> Result<Self, Error> {
322        check_magic_env()?;
323
324        // Resolve the effective registration auth key. The explicit `auth_key` argument wins; if it
325        // is `None`, fall back to `config.auth_key` (Go `tsnet.Server.AuthKey`). When the
326        // `identity-federation` feature is enabled, the resolved key is further passed through the
327        // WIF / OAuth-client bootstrap, which exchanges an OAuth client secret (`tskey-client-…`) or
328        // an IdP-issued OIDC token for a Tailscale auth key before registration (SaaS-only).
329        let auth_key = auth_key.or_else(|| config.auth_key.clone());
330        let auth_key = resolve_auth_key(config, auth_key).await?;
331
332        let rt =
333            ts_runtime::Runtime::spawn(config.into(), auth_key, (&config.key_state).into()).await?;
334        // In TUN transport mode there is no application netstack, so the runtime has no command
335        // channel: that surfaces as `UnsupportedInTunMode`, which we map to a `None` channel rather
336        // than an error (the device is still usable for control-plane and peer-lookup APIs).
337        let channel = match rt.channel().await {
338            Ok(c) => Some(c),
339            Err(e) if e.kind == ts_runtime::ErrorKind::UnsupportedInTunMode => None,
340            Err(e) => return Err(e.into()),
341        };
342
343        Ok(Self {
344            runtime: rt,
345            channel,
346            enable_ipv6: config.enable_ipv6,
347            serve: std::sync::Mutex::new(None),
348            funnel: std::sync::Mutex::new(None),
349        })
350    }
351
352    /// Create a device from the given [`Config`] and a [`SecretString`] auth key.
353    ///
354    /// This is a back-compat-preserving convenience over [`new`](Self::new) for callers that already
355    /// hold the registration auth key as a [`secrecy::SecretString`] (e.g. a daemon that keeps the
356    /// pre-auth key wrapped end-to-end). It lets the caller avoid materializing a plain `String` at
357    /// the engine boundary: the secret is exposed only on the last inch, immediately before being
358    /// handed to [`new`](Self::new).
359    ///
360    /// # Honesty about the plaintext window
361    ///
362    /// This closes the *caller's* boundary, **not** the engine's internal handling. The engine still
363    /// resolves the auth key to a plain `String` internally for registration (the plaintext `String`
364    /// window inside the engine is identical to calling [`new`](Self::new) directly) — this method
365    /// does not make the engine itself secret-clean. If you call [`new`](Self::new) you create that
366    /// `String` yourself; if you call this you do not, but the engine creates one either way.
367    ///
368    /// Passing `None` is equivalent to `new(config, None)` (falls back to `config.auth_key`).
369    ///
370    /// # Example
371    ///
372    /// ```rust,no_run
373    /// # #[tokio::main]
374    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
375    /// # use tailscale::*;
376    /// let dev = Device::new_with_secret(
377    ///     &Config::default_with_key_file("tsrs_keys.json").await?,
378    ///     Some(SecretString::from("MY_AUTH_KEY")),
379    /// ).await?;
380    /// # Ok(()) }
381    /// ```
382    pub async fn new_with_secret(
383        config: &Config,
384        auth_key: Option<SecretString>,
385    ) -> Result<Self, Error> {
386        use secrecy::ExposeSecret as _;
387
388        // Expose the secret on the last inch and delegate to `new`, so the spawn/registration path
389        // is shared verbatim (no duplicated runtime-spawn logic) and the engine-internal plaintext
390        // window is byte-for-byte identical to a direct `new` call.
391        let plain = auth_key.map(|s| s.expose_secret().to_string());
392        Self::new(config, plain).await
393    }
394
395    /// The application netstack command channel, or an error in TUN transport mode (no application
396    /// netstack exists).
397    fn channel(&self) -> Result<&Channel, Error> {
398        self.channel
399            .as_ref()
400            .ok_or(Error::Internal(InternalErrorKind::UnsupportedInTunMode))
401    }
402
403    /// Get this [`Device`]'s IPv4 tailnet address.
404    pub async fn ipv4_addr(&self) -> Result<Ipv4Addr, Error> {
405        self.runtime
406            .control
407            .ask(ts_runtime::control_runner::Ipv4)
408            .await
409            .map_err(ts_runtime::Error::from)?
410            .ok_or(Error::Internal(InternalErrorKind::Actor))
411    }
412
413    /// Get this [`Device`]'s IPv6 tailnet address.
414    pub async fn ipv6_addr(&self) -> Result<Ipv6Addr, Error> {
415        self.runtime
416            .control
417            .ask(ts_runtime::control_runner::Ipv6)
418            .await
419            .map_err(ts_runtime::Error::from)?
420            .ok_or(Error::Internal(InternalErrorKind::Actor))
421    }
422
423    /// This node's tailnet IPv4 and (when provisioned) IPv6 addresses as a pair — the Rust analog of
424    /// Go `tsnet.Server.TailscaleIPs() (ip4, ip6 netip.Addr)`.
425    ///
426    /// Reads the self node's assigned addresses (the same source Go splits by family). The tailnet
427    /// is IPv4-only unless [`Config::enable_ipv6`](crate::config::Config) is set, so the IPv6 half is
428    /// `None` when no v6 address is assigned — the Rust shape for Go returning the zero `netip.Addr`
429    /// in that case (Go's IPv6-absent sentinel). Errors until the first netmap is received (no self
430    /// node yet), matching Go returning invalid addresses before the node has joined.
431    pub async fn tailscale_ips(&self) -> Result<(Ipv4Addr, Option<Ipv6Addr>), Error> {
432        let me = self.self_node().await?;
433        let v4 = me.tailnet_address.ipv4.addr();
434        let v6 = me.tailnet_address.ipv6.addr();
435        // The decoder synthesizes the unspecified `::` placeholder on an IPv4-only tailnet; surface
436        // a real v6 only when IPv6 is enabled AND a non-placeholder address was assigned.
437        let v6 = (self.enable_ipv6 && !v6.is_unspecified()).then_some(v6);
438        Ok((v4, v6))
439    }
440
441    /// Bind a UDP socket to the specified [`SocketAddr`].
442    ///
443    /// Returns an error in TUN transport mode (there is no application netstack to bind on).
444    pub async fn udp_bind(&self, socket_addr: SocketAddr) -> Result<netstack::UdpSocket, Error> {
445        self.channel()?
446            .udp_bind(socket_addr)
447            .await
448            .map_err(Into::into)
449    }
450
451    /// Bind a TCP listener to the specified [`SocketAddr`].
452    ///
453    /// Returns an error in TUN transport mode (there is no application netstack to listen on).
454    pub async fn tcp_listen(
455        &self,
456        socket_addr: SocketAddr,
457    ) -> Result<netstack::TcpListener, Error> {
458        self.channel()?
459            .tcp_listen(socket_addr)
460            .await
461            .map_err(Into::into)
462    }
463
464    /// Register a fallback TCP handler (like `tsnet`'s `RegisterFallbackTCPHandler`).
465    ///
466    /// The callback is consulted for every inbound TCP flow that matches **no** explicit
467    /// [`Device::tcp_listen`] listener, with the flow's `(src, dst)` addresses. It returns
468    /// `(handler, intercept)`:
469    /// - `(_, false)` — decline; the next registered callback is tried.
470    /// - `(Some(h), true)` — claim the flow; `h` is handed the accepted [`netstack::TcpStream`].
471    /// - `(None, true)` — claim and reject the flow (the connection is closed).
472    ///
473    /// Multiple handlers may be registered; they are consulted in registration order and the first
474    /// to intercept wins. The returned [`FallbackTcpHandle`] deregisters the handler when dropped.
475    ///
476    /// Handlers serve flows over the overlay netstack only — never a host socket — and a flow no
477    /// handler claims is closed (fail-closed), never direct-dialed.
478    ///
479    /// Returns an error in TUN transport mode (there is no application netstack to attach to).
480    pub fn register_fallback_tcp_handler<F>(&self, cb: F) -> Result<FallbackTcpHandle, Error>
481    where
482        F: Fn(SocketAddr, SocketAddr) -> FallbackDecision + Send + Sync + 'static,
483    {
484        self.runtime
485            .register_fallback_tcp_handler(std::sync::Arc::new(cb))
486            .map_err(Into::into)
487    }
488
489    /// Resolve a tailnet peer (or this node) by MagicDNS name to its tailnet IPv4 address.
490    ///
491    /// This is an in-process lookup against the netmap we already hold — like `tsnet`'s in-memory
492    /// `dnsMap`, it does not query any DNS server (there is no `100.100.100.100` resolver). The
493    /// `name` may be a bare hostname or a fully-qualified MagicDNS name, with or without a trailing
494    /// dot, in any case (matching is case-insensitive). Returns `Ok(None)` if no tailnet node has
495    /// that name.
496    ///
497    /// Only MagicDNS names are resolved; names outside the tailnet are not looked up here, so the
498    /// caller's system resolver remains responsible for them. IPv6 is intentionally not resolved —
499    /// this fork operates IPv4-only on the tailnet.
500    pub async fn resolve(&self, name: &str) -> Result<Option<Ipv4Addr>, Error> {
501        if let Some(peer) = self.peer_by_name(name).await? {
502            return Ok(Some(peer.tailnet_address.ipv4.addr()));
503        }
504
505        // tsnet's dnsMap also resolves our own name; fall back to self when no peer matches.
506        let me = self.self_node().await?;
507        if me.matches_name(name) {
508            return Ok(Some(me.tailnet_address.ipv4.addr()));
509        }
510
511        Ok(None)
512    }
513
514    /// Run a real DNS query through the tailnet's MagicDNS responder (the `100.100.100.100`
515    /// forward path), returning the raw response, RCODE, and resolver(s) consulted — the analogue of
516    /// Go `LocalClient.QueryDNS`.
517    ///
518    /// Unlike [`resolve`](Self::resolve) (an in-memory netmap lookup that answers only MagicDNS
519    /// A-records), this issues an actual query of any [`qtype`] and runs it through the live
520    /// responder: an authoritative tailnet name is answered locally, anything else is forwarded to
521    /// the configured split-DNS / recursive upstreams (or delegated to the active exit node's DoH).
522    /// The response is returned as raw bytes (matching Go's `QueryDNS`), since this fork's DNS wire
523    /// codec has no answer-record decoder; the caller parses records itself if needed.
524    ///
525    /// `qtype` is the raw RFC 1035 TYPE value (`1`=A, `28`=AAAA, `12`=PTR, `16`=TXT, `33`=SRV,
526    /// `65`=HTTPS/SVCB, …). Anti-leak is inherited from the responder: a tailnet-suffix name never
527    /// egresses, recursive forwards delegate to the exit node when one is active, and only IPv4
528    /// upstreams are dialed.
529    ///
530    /// Returns [`ErrorKind::UnsupportedInTunMode`](crate::ErrorKind::UnsupportedInTunMode) in TUN
531    /// transport mode (MagicDNS there is an in-packet intercept, not a queryable responder).
532    pub async fn query_dns(&self, name: &str, qtype: u16) -> Result<DnsQueryResult, Error> {
533        self.runtime
534            .query_dns(name, qtype)
535            .await
536            .map_err(Into::into)
537    }
538
539    /// Connect to a tailnet peer by MagicDNS name and port over TCP.
540    ///
541    /// Resolves `name` via [`Device::resolve`] (an in-process netmap lookup, no DNS server), then
542    /// dials the resulting tailnet IPv4 address. Returns [`InternalErrorKind::BadRequest`] if the
543    /// name does not resolve to a tailnet node.
544    pub async fn connect_by_name(
545        &self,
546        name: &str,
547        port: u16,
548    ) -> Result<netstack::TcpStream, Error> {
549        let addr = self
550            .resolve(name)
551            .await?
552            .ok_or(Error::Internal(InternalErrorKind::BadRequest))?;
553
554        self.tcp_connect((addr, port).into()).await
555    }
556
557    /// Resolve a `host:port` string to a tailnet [`SocketAddr`], honoring the family forced by a
558    /// `network` suffix. The host may be an IP literal (parsed directly) or a MagicDNS name
559    /// (resolved via [`Device::resolve`], which yields a tailnet IPv4). Shared by [`Device::dial`]
560    /// and [`Device::dial_tcp`]. The IPv4-only invariant is enforced here: a `…6` network, or any v6
561    /// destination, requires `Config::enable_ipv6` and otherwise returns
562    /// [`InternalErrorKind::BadRequest`] (a clean typed error rather than a downstream actor error).
563    async fn resolve_dial_addr(
564        &self,
565        network: dial::Network,
566        addr: &str,
567    ) -> Result<SocketAddr, Error> {
568        let (host, port) = dial::split_host_port(addr)?;
569
570        // An IP literal is used directly; otherwise resolve the MagicDNS name (IPv4 only).
571        let ip: IpAddr = if let Ok(ip) = host.parse::<IpAddr>() {
572            ip
573        } else {
574            self.resolve(host)
575                .await?
576                .ok_or(Error::Internal(InternalErrorKind::BadRequest))?
577                .into()
578        };
579
580        dial::check_family(network.family, ip)?;
581
582        // IPv4-only invariant: a v6 destination is only reachable when IPv6 is provisioned.
583        if ip.is_ipv6() && !self.enable_ipv6 {
584            return Err(Error::Internal(InternalErrorKind::BadRequest));
585        }
586
587        Ok((ip, port).into())
588    }
589
590    /// Connect to a tailnet address over TCP or UDP, the Rust analog of Go
591    /// `tsnet.Server.Dial(ctx, network, address)`.
592    ///
593    /// `network` is one of `"tcp"`, `"tcp4"`, `"tcp6"`, `"udp"`, `"udp4"`, `"udp6"`; `addr` is a
594    /// `host:port` string where `host` is a MagicDNS name, an IPv4 literal, or a bracketed IPv6
595    /// literal (`[2001:db8::1]:443`). The host is resolved in-process via [`Device::resolve`] (no DNS
596    /// server). Returns a [`DialConn`] whose arm matches the transport — use [`Device::dial_tcp`]
597    /// when you want the TCP stream directly.
598    ///
599    /// Differences from Go (documented for parity): ports must be **numeric** (Go's `LookupPort`
600    /// also resolves named ports like `"http"`; this fork avoids a services-file dependency), and
601    /// `…6`/v6 destinations require `Config::enable_ipv6` (the tailnet is IPv4-only by default).
602    ///
603    /// # Errors
604    /// [`InternalErrorKind::BadRequest`] for an unsupported `network`, a malformed/portless `addr`,
605    /// an unresolvable name, or a v6 destination while IPv6 is disabled; otherwise the transport's
606    /// own connect error.
607    pub async fn dial(&self, network: &str, addr: &str) -> Result<DialConn, Error> {
608        let net = dial::parse_network(network)?;
609        let remote = self.resolve_dial_addr(net, addr).await?;
610
611        match net.transport {
612            dial::Transport::Tcp => Ok(DialConn::Tcp(self.tcp_connect(remote).await?)),
613            dial::Transport::Udp => {
614                // Bind an ephemeral local UDP socket on this node's tailnet address of the SAME
615                // family as the remote, then connect it (Go's `Dial("udp", …)` returns a connected
616                // UDP `net.Conn`, with the local source picked by `IfElse(dst.Is6(), v6, v4)`). A v4
617                // local socket cannot send to a v6 peer, so the family must match `remote`. (TCP gets
618                // this for free: `tcp_connect` already picks the source family from `remote`.)
619                let local_ip: IpAddr = if remote.is_ipv6() {
620                    self.ipv6_addr().await?.into()
621                } else {
622                    self.ipv4_addr().await?.into()
623                };
624                let sock = self.udp_bind((local_ip, 0).into()).await?;
625                Ok(DialConn::Udp(ConnectedUdpSocket::new(sock, remote)))
626            }
627        }
628    }
629
630    /// Connect to a tailnet address over TCP, returning the stream directly — the common case of
631    /// [`Device::dial`] for `"tcp"`. `addr` is a `host:port` string (MagicDNS name or IP literal).
632    /// This is the building block for HTTP-over-tailnet: an embedder's `hyper`/`reqwest` client can
633    /// route requests by calling `dial_tcp(&format!("{host}:{port}"))` from its connector, mirroring
634    /// how Go `tsnet.Server.HTTPClient` sets `http.Transport.DialContext = Server.Dial`.
635    ///
636    /// # Errors
637    /// As [`Device::dial`] for the `"tcp"` network.
638    pub async fn dial_tcp(&self, addr: &str) -> Result<netstack::TcpStream, Error> {
639        let remote = self
640            .resolve_dial_addr(
641                dial::Network {
642                    transport: dial::Transport::Tcp,
643                    family: dial::Family::Any,
644                },
645                addr,
646            )
647            .await?;
648        self.tcp_connect(remote).await
649    }
650
651    /// Connect to a tailnet address over UDP, returning a connected socket directly — the `"udp"`
652    /// sibling of [`dial_tcp`](Device::dial_tcp) and the common case of [`Device::dial`] for
653    /// `"udp"`. `addr` is a `host:port` string (MagicDNS name or IP literal).
654    ///
655    /// Returns a [`ConnectedUdpSocket`] (`send`/`recv` against a fixed peer), the connected
656    /// UDP-`net.Conn` shape Go's `tsnet.Server.Dial("udp", …)` returns — as opposed to
657    /// [`listen_packet`](Device::listen_packet), which yields an unconnected `net.PacketConn`. An
658    /// ephemeral local UDP socket is bound on this node's tailnet address of the same family as the
659    /// resolved remote (a v4 local socket cannot send to a v6 peer).
660    ///
661    /// # Errors
662    /// As [`Device::dial`] for the `"udp"` network (name resolution, the IPv4-only / `enable_ipv6`
663    /// family invariant, or TUN transport mode having no application netstack to bind on).
664    pub async fn dial_udp(&self, addr: &str) -> Result<ConnectedUdpSocket, Error> {
665        let remote = self
666            .resolve_dial_addr(
667                dial::Network {
668                    transport: dial::Transport::Udp,
669                    family: dial::Family::Any,
670                },
671                addr,
672            )
673            .await?;
674        let local_ip: IpAddr = if remote.is_ipv6() {
675            self.ipv6_addr().await?.into()
676        } else {
677            self.ipv4_addr().await?.into()
678        };
679        let sock = self.udp_bind((local_ip, 0).into()).await?;
680        Ok(ConnectedUdpSocket::new(sock, remote))
681    }
682
683    /// Bind a UDP socket from a `host:port` string, the Rust analog of Go
684    /// `tsnet.Server.ListenPacket(network, addr)`.
685    ///
686    /// `network` is one of `"udp"`, `"udp4"`, `"udp6"`; `addr` must be a **valid IP literal**
687    /// `host:port` (Go's `ListenPacket` rejects a name or empty host — unlike `Listen`). An
688    /// unspecified host (`0.0.0.0`/`[::]`) binds on this node's tailnet address. Returns the
689    /// unconnected [`netstack::UdpSocket`] (a `net.PacketConn`).
690    ///
691    /// # Errors
692    /// [`InternalErrorKind::BadRequest`] for a non-UDP/unsupported `network`, a malformed addr, a
693    /// non-IP host, a family mismatch, or a v6 bind while IPv6 is disabled.
694    pub async fn listen_packet(
695        &self,
696        network: &str,
697        addr: &str,
698    ) -> Result<netstack::UdpSocket, Error> {
699        let net = dial::parse_network(network)?;
700        if net.transport != dial::Transport::Udp {
701            return Err(Error::Internal(InternalErrorKind::BadRequest));
702        }
703        let (host, port) = dial::split_host_port(addr)?;
704
705        // ListenPacket requires a valid IP host (Go rejects a name here).
706        let ip: IpAddr = host
707            .parse()
708            .map_err(|_| Error::Internal(InternalErrorKind::BadRequest))?;
709        dial::check_family(net.family, ip)?;
710
711        // A v6 bind (whether an explicit literal or an unspecified `[::]`) requires IPv6 to be
712        // provisioned — enforce the gate for BOTH cases (the unspecified `[::]` path used to skip it).
713        if ip.is_ipv6() && !self.enable_ipv6 {
714            return Err(Error::Internal(InternalErrorKind::BadRequest));
715        }
716
717        // An unspecified bind host (`0.0.0.0` / `[::]`) means "this node's tailnet address" — of the
718        // SAME family as the requested address, so a `udp6` `[::]:0` binds a v6 socket (it used to
719        // fall through to the v4 address regardless, silently yielding an IPv4 socket for a v6 listen).
720        let bind_ip: IpAddr = if ip.is_unspecified() {
721            if ip.is_ipv6() {
722                self.ipv6_addr().await?.into()
723            } else {
724                self.ipv4_addr().await?.into()
725            }
726        } else {
727            ip
728        };
729
730        self.udp_bind((bind_ip, port).into()).await
731    }
732
733    /// Connect to a TCP socket at the remote address.
734    ///
735    /// Returns an error in TUN transport mode (there is no application netstack to dial from).
736    pub async fn tcp_connect(&self, remote: SocketAddr) -> Result<netstack::TcpStream, Error> {
737        let channel = self.channel()?;
738
739        let ip: IpAddr = match remote.is_ipv4() {
740            true => self.ipv4_addr().await?.into(),
741            false => self.ipv6_addr().await?.into(),
742        };
743
744        // TODO(npry): collision checking
745        let ephemeral_port = rand::random_range(49152..=u16::MAX);
746
747        channel
748            .tcp_connect((ip, ephemeral_port).into(), remote)
749            .await
750            .map_err(Into::into)
751    }
752
753    /// Start a SOCKS5 proxy on a host loopback address that dials into the tailnet (Go
754    /// `tsnet.Server.Loopback`, SOCKS5 half).
755    ///
756    /// Binds a TCP listener on `127.0.0.1:0` (host loopback only — never an external interface) and
757    /// serves SOCKS5 (RFC 1928) with required username/password auth (RFC 1929): username `tsnet`,
758    /// password = the returned `proxy_cred`. Each `CONNECT` is dialed INTO the overlay via
759    /// [`Device::connect_by_name`] / [`Device::tcp_connect`] and spliced to the accepted host socket, so
760    /// a non-Rust host process can reach tailnet peers through the proxy. Returns the bound address, the
761    /// proxy credential, and a [`LoopbackHandle`] whose drop stops the listener.
762    ///
763    /// Anti-leak: the listener is loopback-only and every connection egresses over the overlay, never a
764    /// host socket — the host's real origin IP is never used to reach the destination. Unlike Go, the
765    /// LocalAPI HTTP surface is not served (this fork exposes status/whois/id-token natively on
766    /// `Device`); only the SOCKS5 proxy is provided.
767    ///
768    /// Returns an error in TUN transport mode (no application netstack to dial from).
769    pub async fn loopback(&self) -> Result<(std::net::SocketAddr, String, LoopbackHandle), Error> {
770        // Capture only cloneable pieces — never `&self` — for the spawned accept loop: a clone of the
771        // netstack command channel, this device's own overlay IPv4 (fetched once), and a boxed
772        // resolver closure over clones of the control + peer-tracker actor refs. The resolver
773        // replicates `Device::resolve` (peer-by-name, falling back to this node's own name).
774        let channel = self.channel()?.clone();
775        let self_ipv4 = self.ipv4_addr().await?;
776
777        let control = self.runtime.control.clone();
778        let peer_tracker = self.runtime.peer_tracker.clone();
779        let resolve: loopback::Resolver = std::sync::Arc::new(move |name: String| {
780            let control = control.clone();
781            let peer_tracker = peer_tracker.clone();
782            Box::pin(async move {
783                let pt = peer_tracker
784                    .upgrade()
785                    .ok_or(Error::Internal(InternalErrorKind::Actor))?;
786                let peer = pt
787                    .ask(ts_runtime::peer_tracker::PeerByName { name: name.clone() })
788                    .await
789                    .map_err(ts_runtime::Error::from)?;
790                if let Some(peer) = peer {
791                    return Ok(Some(peer.tailnet_address.ipv4.addr()));
792                }
793                // tsnet's dnsMap also resolves our own name; fall back to self.
794                let me = control
795                    .ask(ts_runtime::control_runner::SelfNode)
796                    .await
797                    .map_err(ts_runtime::Error::from)?
798                    .ok_or(Error::Internal(InternalErrorKind::Actor))?;
799                if me.matches_name(&name) {
800                    Ok(Some(me.tailnet_address.ipv4.addr()))
801                } else {
802                    Ok(None)
803                }
804            }) as std::pin::Pin<Box<dyn std::future::Future<Output = _> + Send>>
805        });
806
807        let dialer = loopback::OverlayDialer::new(channel, self_ipv4, resolve);
808        loopback::start(dialer).await
809    }
810
811    /// Get our node info.
812    pub async fn self_node(&self) -> Result<NodeInfo, Error> {
813        self.runtime
814            .control
815            .ask(ts_runtime::control_runner::SelfNode)
816            .await
817            .map_err(ts_runtime::Error::from)?
818            .ok_or(Error::Internal(InternalErrorKind::Actor))
819    }
820
821    /// The DNS names this node can obtain TLS certificates for — Go `tsnet.Server.CertDomains()`.
822    ///
823    /// These are the `CertDomains` control pushed in the netmap DNS config: the names a TLS-serving
824    /// consumer (e.g. a `ListenTLS`/`GetCertificate`-style caller) should request a cert for. Returns
825    /// an empty `Vec` before the first netmap, or when control granted none — mirroring Go returning a
826    /// clone of `nm.DNS.CertDomains` (empty/`nil` when absent).
827    pub async fn cert_domains(&self) -> Result<Vec<String>, Error> {
828        self.runtime
829            .control
830            .ask(ts_runtime::control_runner::CertDomains)
831            .await
832            .map_err(ts_runtime::Error::from)
833            .map_err(Into::into)
834    }
835
836    /// The DNS configuration control pushed in the latest netmap — Go `tsnet`'s view of
837    /// `netmap.NetworkMap.DNS` (what `tailscale dns status` reports).
838    ///
839    /// Returns the full [`DnsConfig`] — MagicDNS on/off, search domains, global + fallback resolvers,
840    /// split-DNS routes, extra records, cert domains — or `None` before the first netmap / when
841    /// control has sent no DNS config. A superset of [`cert_domains`](Device::cert_domains), which
842    /// remains a separate narrower accessor for the TLS-cert use. Mirrors Go reading a clone of
843    /// `nm.DNS` (absent ⇒ `None`).
844    pub async fn dns_config(&self) -> Result<Option<DnsConfig>, Error> {
845        self.runtime
846            .control
847            .ask(ts_runtime::control_runner::DnsConfig)
848            .await
849            .map_err(ts_runtime::Error::from)
850            .map_err(Into::into)
851    }
852
853    /// The URL control last asked this node to open in a browser (`MapResponse.PopBrowserURL`), or
854    /// `None` if control has never sent one.
855    ///
856    /// This is the interactive-login / consent URL an embedder driving a non-authkey (interactive)
857    /// login must surface to the user — the Rust analog of Go `ipn` delivering `BrowseToURL` through
858    /// the notification bus. A daemon polls this after starting an interactive login to obtain the
859    /// auth URL to present.
860    ///
861    /// **Sticky semantics** (Go `controlclient`'s `sess.lastPopBrowserURL`): once control sends a
862    /// URL it remains the returned value until control sends a *different* non-empty one — it is
863    /// **never cleared back to `None`** (control sends `PopBrowserURL` empty on nearly every netmap
864    /// tick; those empty updates are ignored, not treated as "clear"). So a non-`None` result does
865    /// **not** signal "control is asking *right now*" vs. "already handled" — it is the last URL
866    /// seen this session. A consumer that acts on it should de-duplicate on the URL value rather than
867    /// re-acting on every poll. For a push stream of *new* consent URLs (rather than polling this
868    /// sticky value), subscribe to [`watch_ipn_bus`](Self::watch_ipn_bus) and react to
869    /// [`Notify::browse_to_url`](crate::Notify::browse_to_url).
870    pub async fn pop_browser_url(&self) -> Result<Option<Url>, Error> {
871        self.runtime
872            .control
873            .ask(ts_runtime::control_runner::PopBrowserUrl)
874            .await
875            .map_err(ts_runtime::Error::from)
876            .map_err(Into::into)
877    }
878
879    /// This node's latest network-conditions report — the Rust analog of Go's `netcheck.Report` as
880    /// `tailscale netcheck` surfaces it.
881    ///
882    /// Returns the [`NetcheckReport`]: the preferred (lowest-latency) DERP region and the per-region
883    /// latency map this node last measured. Empty (default) before the first measurement. This fork's
884    /// net-report path measures only DERP-region latency, so the report carries that subset rather
885    /// than fabricating the UDP/port-mapping fields Go also reports (see [`NetcheckReport`]).
886    pub async fn netcheck(&self) -> Result<NetcheckReport, Error> {
887        self.runtime
888            .control
889            .ask(ts_runtime::control_runner::Netcheck)
890            .await
891            .map_err(ts_runtime::Error::from)
892            .map_err(Into::into)
893    }
894
895    /// This node's key-expiry instant as Unix seconds (`Node.KeyExpiry` in Go), or `Ok(None)` if
896    /// the key never expires.
897    ///
898    /// Like Go, this fork is **reactive** about key expiry — it reports it rather than rotating the
899    /// node key in the background. A caller can schedule re-authentication around this time; on
900    /// expiry, re-create the [`Device`] (which re-registers), supplying a fresh node key + the prior
901    /// `old_node_key` to rotate, or the same key to refresh.
902    pub async fn self_key_expiry_unix(&self) -> Result<Option<i64>, Error> {
903        Ok(self.self_node().await?.key_expiry_unix())
904    }
905
906    /// Whether this node's key has expired as of now (`!KeyExpiry.IsZero() && KeyExpiry.Before(now)`
907    /// in Go). A key with no expiry is never expired. See [`Device::self_key_expiry_unix`] for the
908    /// reactive-rotation note.
909    pub async fn self_key_expired(&self) -> Result<bool, Error> {
910        let now = std::time::SystemTime::now()
911            .duration_since(std::time::UNIX_EPOCH)
912            .map(|d| d.as_secs() as i64)
913            // An unreadable clock (pre-epoch) is treated as the far future so a time-limited key
914            // looks expired — fail-safe toward prompting re-auth rather than trusting a stale key.
915            .unwrap_or(i64::MAX);
916        Ok(self.self_node().await?.key_expired_at_unix(now))
917    }
918
919    /// Fetch the current Tailscale SSH policy pushed by control, if any.
920    ///
921    /// Returns `Ok(None)` when control has not sent an SSH policy. The SSH server treats an absent
922    /// or empty policy as **deny-all** (fail-closed). Used by the SSH auth path
923    /// ([`SshPolicy::evaluate`][ts_control::SshPolicy::evaluate]) to authorize incoming
924    /// connections.
925    pub async fn ssh_policy(&self) -> Result<Option<ts_control::SshPolicy>, Error> {
926        self.runtime
927            .control
928            .ask(ts_runtime::control_runner::CurrentSshPolicy)
929            .await
930            .map_err(ts_runtime::Error::from)
931            .map_err(Into::into)
932    }
933
934    /// Look up a peer by name.
935    pub async fn peer_by_name(&self, name: &str) -> Result<Option<NodeInfo>, Error> {
936        let pt = self
937            .runtime
938            .peer_tracker
939            .upgrade()
940            .ok_or(Error::Internal(InternalErrorKind::Actor))?;
941
942        pt.ask(ts_runtime::peer_tracker::PeerByName {
943            name: name.to_string(),
944        })
945        .await
946        .map_err(ts_runtime::Error::from)
947        .map_err(Into::into)
948    }
949
950    /// Look up a peer by ip.
951    pub async fn peer_by_tailnet_ip(&self, ip: IpAddr) -> Result<Option<NodeInfo>, Error> {
952        let pt = self
953            .runtime
954            .peer_tracker
955            .upgrade()
956            .ok_or(Error::Internal(InternalErrorKind::Actor))?;
957
958        pt.ask(ts_runtime::peer_tracker::PeerByTailnetIp { ip })
959            .await
960            .map_err(ts_runtime::Error::from)
961            .map_err(Into::into)
962    }
963
964    /// Look up the peer(s) with the most-specific route matches for `ip`.
965    ///
966    /// This reports which peers *advertise* a route covering `ip`, independent of this device's
967    /// `accept_routes` setting — analogous to the Go client's informational `PrimaryRoutes`. It is
968    /// not a reachability oracle: with `accept_routes` off, the dataplane will not actually route
969    /// to (or accept return traffic from) advertised subnet routes even if this returns a peer.
970    pub async fn peers_with_route(&self, ip: IpAddr) -> Result<Vec<NodeInfo>, Error> {
971        let pt = self
972            .runtime
973            .peer_tracker
974            .upgrade()
975            .ok_or(Error::Internal(InternalErrorKind::Actor))?;
976
977        pt.ask(ts_runtime::peer_tracker::PeerByAcceptedRoute { ip })
978            .await
979            .map_err(ts_runtime::Error::from)
980            .map_err(Into::into)
981    }
982
983    /// List the Taildrop files this device has fully received and not yet consumed (Go LocalAPI
984    /// `WaitingFiles`).
985    ///
986    /// Returns the files waiting under the configured `taildrop_dir`, sorted by name. Returns an
987    /// empty list when Taildrop is disabled (`Config::taildrop_dir` unset) — fail-closed, never an
988    /// error for the disabled case. A filesystem error while listing surfaces as
989    /// [`InternalErrorKind::Actor`].
990    pub fn taildrop_waiting_files(&self) -> Result<Vec<WaitingFile>, Error> {
991        let Some(store) = self.runtime.taildrop_store() else {
992            return Ok(Vec::new());
993        };
994        store
995            .waiting_files()
996            .map_err(|_| Error::Internal(InternalErrorKind::Actor))
997    }
998
999    /// Open a received Taildrop file by name for reading, returning the handle and its size (Go
1000    /// LocalAPI `OpenFile`).
1001    ///
1002    /// The `name` is validated (path-traversal-safe) inside the store before any path is built.
1003    /// Returns [`InternalErrorKind::BadRequest`] when Taildrop is disabled or the name is invalid,
1004    /// and [`InternalErrorKind::Actor`] for a filesystem error (e.g. the file does not exist).
1005    pub fn taildrop_open_file(&self, name: &str) -> Result<(std::fs::File, u64), Error> {
1006        let store = self
1007            .runtime
1008            .taildrop_store()
1009            .ok_or(Error::Internal(InternalErrorKind::BadRequest))?;
1010        store.open_file(name).map_err(taildrop_err)
1011    }
1012
1013    /// Delete a received Taildrop file by name (Go LocalAPI `DeleteFile`).
1014    ///
1015    /// The `name` is validated (path-traversal-safe) inside the store before any path is built.
1016    /// Returns [`InternalErrorKind::BadRequest`] when Taildrop is disabled or the name is invalid,
1017    /// and [`InternalErrorKind::Actor`] for a filesystem error (e.g. the file does not exist).
1018    pub fn taildrop_delete_file(&self, name: &str) -> Result<(), Error> {
1019        let store = self
1020            .runtime
1021            .taildrop_store()
1022            .ok_or(Error::Internal(InternalErrorKind::BadRequest))?;
1023        store.delete_file(name).map_err(taildrop_err)
1024    }
1025
1026    /// Send a local file to a tailnet `peer` via Taildrop (Go `PushFile` / `tailscale file cp`).
1027    ///
1028    /// Pushes `content_length` bytes from `reader` to the peer's peerAPI as
1029    /// `PUT /v0/put/<name>` over the overlay netstack — the sending counterpart to the receive store
1030    /// surfaced by [`Device::taildrop_waiting_files`]. The transfer rides the encrypted WireGuard
1031    /// overlay, never a host socket. The body is streamed from offset 0 (no resume).
1032    ///
1033    /// The destination is derived **solely from `peer`'s own node record**
1034    /// ([`NodeInfo::peerapi_addr`][ts_control::Node::peerapi_addr]): its advertised tailnet IPv4 and
1035    /// `peerapi4` port. The caller obtains `peer` from [`Device::peer_by_name`] /
1036    /// [`Device::peer_by_tailnet_ip`], so it is always a current netmap peer — a raw control-supplied
1037    /// or attacker-chosen address can never be targeted. As defense in depth, the resolved address is
1038    /// additionally asserted to be a Tailscale CGNAT IP before dialing.
1039    ///
1040    /// Returns [`InternalErrorKind::BadRequest`] when the peer advertises no IPv4 peerAPI (so it
1041    /// cannot receive files), when the name is invalid, or when the peer refuses the transfer
1042    /// (`403`/`409`/unexpected status); [`Error::Timeout`] on a dial failure or timeout; and
1043    /// [`InternalErrorKind::Io`] on a mid-transfer stream error.
1044    pub async fn send_file<R>(
1045        &self,
1046        peer: &NodeInfo,
1047        name: &str,
1048        content_length: u64,
1049        reader: R,
1050    ) -> Result<(), Error>
1051    where
1052        R: tokio::io::AsyncRead + Unpin,
1053    {
1054        let channel = self.channel()?;
1055
1056        // Destination comes only from the peer's own node record — never an arbitrary address.
1057        let dst = peer
1058            .peerapi_addr()
1059            .ok_or(Error::Internal(InternalErrorKind::BadRequest))?;
1060        // Defense in depth: refuse to dial anything outside the Tailscale CGNAT range, so a
1061        // malformed node record can't steer the PUT at a non-tailnet host.
1062        if !ts_control::is_tailscale_ip(dst.ip()) {
1063            return Err(Error::Internal(InternalErrorKind::BadRequest));
1064        }
1065
1066        let self_ipv4 = self.ipv4_addr().await?;
1067
1068        ts_runtime::taildrop_send::send_file(channel, self_ipv4, dst, name, content_length, reader)
1069            .await
1070            .map_err(taildrop_send_err)
1071    }
1072
1073    /// List the tailnet peers this node can Taildrop a file *to* — the Rust analog of Go's LocalAPI
1074    /// `FileTargets`.
1075    ///
1076    /// Each [`FileTarget`] pairs a peer's node record with the `http://ip:port` base of its peerAPI;
1077    /// pass `target.node` straight to [`Device::send_file`]. A peer qualifies when it advertises a
1078    /// reachable IPv4 peerAPI **and** is either owned by the same user as this node **or** explicitly
1079    /// granted the file-sharing-target capability — mirroring upstream's send-path filter. The list is
1080    /// gated on this node holding the file-sharing capability (control grants it when the admin
1081    /// enables Taildrop); absent that, the result is empty (fail-closed, not an error). Sorted by the
1082    /// peer's MagicDNS name. Targets are listed regardless of online state (matching upstream — an
1083    /// offline target's [`send_file`](Device::send_file) simply times out). Empty before the first
1084    /// netmap.
1085    pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
1086        self.runtime.file_targets().await.map_err(Into::into)
1087    }
1088
1089    /// Begin a debug packet capture, streaming a pcap of every packet crossing the dataplane to
1090    /// `writer` (Go `tsnet.Server.CapturePcap`).
1091    ///
1092    /// Installs a capture hook on the running dataplane: from now until [`Device::stop_capture`] is
1093    /// called (or another capture replaces this one), a copy of every plaintext IP packet on the
1094    /// datapath — outbound (pre-encrypt) and inbound (post-decrypt) — is framed and written to
1095    /// `writer`. The 24-byte pcap global header is written immediately on success.
1096    ///
1097    /// The format is byte-faithful classic pcap with Tailscale's `LINKTYPE_USER0` + 4-byte path
1098    /// preamble per record (see [`ts_runtime::capture`]); a resulting file opens in Wireshark, and
1099    /// with Tailscale's `ts-dissector.lua` the direction/path of each packet decodes.
1100    ///
1101    /// The hook runs **inline on the single-threaded dataplane step**, so `writer` must not block for
1102    /// long — a slow writer back-pressures the datapath. Records are **not** flushed per packet (that
1103    /// would be a syscall on every packet on the dataplane thread); buffered bytes are flushed when
1104    /// the writer is dropped on [`Device::stop_capture`]. Wrap `writer` in a [`std::io::BufWriter`] if
1105    /// you want buffering. A write error is swallowed per-packet (the capture silently drops that
1106    /// record) rather than tearing down the datapath; call [`Device::stop_capture`] to end it. Returns
1107    /// an error only if the dataplane actor is unreachable or the initial global-header write fails.
1108    pub async fn capture_pcap<W>(&self, writer: W) -> Result<(), Error>
1109    where
1110        W: std::io::Write + Send + 'static,
1111    {
1112        let sink = std::sync::Arc::new(std::sync::Mutex::new(
1113            ts_runtime::capture::PcapSink::new(writer)
1114                .map_err(|_| Error::Internal(InternalErrorKind::Io))?,
1115        ));
1116        let hook: ts_runtime::CaptureHook = std::sync::Arc::new(move |path, pkt: &[u8]| {
1117            if let Ok(mut sink) = sink.lock() {
1118                // A per-packet write failure (e.g. a closed pipe) silently drops that record rather
1119                // than tearing down the datapath; the caller ends capture via `stop_capture`.
1120                drop(sink.log_packet(path.code(), pkt));
1121            }
1122        });
1123        self.runtime.install_capture(Some(hook)).await?;
1124        Ok(())
1125    }
1126
1127    /// Stop a debug packet capture started by [`Device::capture_pcap`] (Go `ClearCaptureSink`).
1128    ///
1129    /// Clears the dataplane capture hook; the writer is dropped (its remaining buffered bytes are
1130    /// flushed by its own `Drop`). Idempotent — clearing when no capture is installed is a no-op.
1131    /// Returns an error only if the dataplane actor is unreachable.
1132    pub async fn stop_capture(&self) -> Result<(), Error> {
1133        self.runtime.install_capture(None).await?;
1134        Ok(())
1135    }
1136
1137    /// Snapshot of this device and its tailnet peers (like `tailscale status`).
1138    ///
1139    /// Combines this node's self info with the current peer set: each [`StatusNode`] reports the
1140    /// stable id, display name, tailnet IPs, advertised routes, and exit-node flag. (Per-peer
1141    /// `online`/user/capabilities are honestly `None`/empty in this fork — the domain node model
1142    /// does not yet carry the wire-level liveness/login fields; see `ts_runtime::status` docs.)
1143    pub async fn status(&self) -> Result<Status, Error> {
1144        self.runtime.status().await.map_err(Into::into)
1145    }
1146
1147    /// Fetch the current Tailnet Lock (TKA) status pushed by control, if any.
1148    ///
1149    /// Returns `Ok(None)` when control has sent no `TKAInfo` (tailnet lock not in use, or no change
1150    /// observed yet). The returned [`TkaStatus`][ts_control::TkaStatus] carries the authority head
1151    /// (a base32 `AUMHash`, decode with [`tka::AumHash::from_base32`][ts_tka::AumHash::from_base32])
1152    /// and the disablement signal. Signature verification of a peer's node-key signature against the
1153    /// authority is performed with the [`tka`] module's [`tka::Authority`][ts_tka::Authority].
1154    pub async fn tka_status(&self) -> Result<Option<ts_control::TkaStatus>, Error> {
1155        self.runtime
1156            .control
1157            .ask(ts_runtime::control_runner::CurrentTkaStatus)
1158            .await
1159            .map_err(ts_runtime::Error::from)
1160            .map_err(Into::into)
1161    }
1162
1163    /// Request an OIDC **ID token** from control for this node, scoped to `audience` (workload-
1164    /// identity federation, like `tailscale`'s `id-token` LocalAPI).
1165    ///
1166    /// Returns a signed JWT whose `sub` claim is this node's MagicDNS name and whose `aud` claim is
1167    /// `audience`, suitable for presenting to a third-party relying party (e.g. AWS/GCP
1168    /// workload-identity federation). The node is the token *subject*, not the authenticator — this
1169    /// is token issuance over the Noise transport (`POST /machine/id-token`), not a login path.
1170    /// Requires the control plane to support capability version ≥ 30.
1171    pub async fn fetch_id_token(&self, audience: &str) -> Result<String, ts_control::IdTokenError> {
1172        self.runtime.fetch_id_token(audience.to_string()).await
1173    }
1174
1175    /// Publish a `TXT` DNS record for this node into the tailnet's `ts.net` zone via control's
1176    /// `/machine/set-dns` RPC — the Rust analog of Go `tailscale.com/client/tailscale`'s
1177    /// `LocalClient.SetDNS(ctx, name, value)`.
1178    ///
1179    /// `name` is the full record name (e.g. `_acme-challenge.host.tailnet.ts.net`) and `value` is
1180    /// the record value (e.g. the base64url DNS-01 digest). Like Go's `SetDNS`, this publishes a
1181    /// `TXT` record specifically — its canonical use is satisfying an ACME DNS-01 challenge so a CA
1182    /// can verify control of a `*.ts.net` name. Issuance over the Noise transport (`POST
1183    /// /machine/set-dns`), not a login path.
1184    pub async fn set_dns(&self, name: &str, value: &str) -> Result<(), ts_control::SetDnsError> {
1185        self.runtime
1186            .set_dns(name.to_string(), value.to_string())
1187            .await
1188    }
1189
1190    /// Log this node out of the tailnet — deregister it from the control plane (the equivalent of
1191    /// Go `tsnet`'s `LocalClient.Logout`).
1192    ///
1193    /// Re-`POST`s `/machine/register` with this node's current node key and a past expiry, which the
1194    /// control plane honors by **expiring the node now**: it drops out of every peer's netmap and
1195    /// must re-register (re-authenticate) to rejoin.
1196    ///
1197    /// This is primarily for **non-ephemeral** nodes. An ephemeral node is garbage-collected by
1198    /// control shortly after it disconnects, but a persistent node lingers in the tailnet
1199    /// (visible to peers, counting against the machine limit) for up to ~24h after the process exits
1200    /// unless explicitly logged out. Call this before [`shutdown`](Self::shutdown) to deregister
1201    /// immediately. Calling it on an ephemeral node simply brings the GC forward; it is idempotent,
1202    /// so logging out an already-gone node is not an error.
1203    ///
1204    /// This is a **control-plane state change only**: it does not tear down the local datapath (do
1205    /// that via [`shutdown`](Self::shutdown)), and it does not delete or rotate the on-disk node key
1206    /// — re-registering with the same key (a fresh [`Device::new`]) is the re-login path.
1207    pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
1208        self.runtime.logout().await
1209    }
1210
1211    /// Snapshot this node's client metrics in Prometheus text exposition format.
1212    ///
1213    /// Mirrors Go Tailscale's `clientmetric` registry: process-global counters/gauges incremented
1214    /// on the datapath hot loops (e.g. `magicsock_send_udp`, `magicsock_recv_data_bytes_udp`),
1215    /// rendered as `# TYPE <name> <kind>\n<name> <value>\n` per metric, sorted by name. (Go `tsnet`
1216    /// exposes no metrics method of its own, so this is the fork's clean public surface.) The
1217    /// registry is process-global, so the output covers every `Device` in the process.
1218    pub fn metrics(&self) -> String {
1219        ts_metrics::write_prometheus()
1220    }
1221
1222    /// Map a tailnet source `addr` to the node that owns its IP (like `tsnet`'s `WhoIs`).
1223    ///
1224    /// Only the IP of `addr` is used; the port is ignored. Returns `Ok(None)` if no tailnet node
1225    /// owns that address.
1226    pub async fn whois(&self, addr: SocketAddr) -> Result<Option<WhoIs>, Error> {
1227        self.runtime.whois(addr).await.map_err(Into::into)
1228    }
1229
1230    /// Change the selected exit node at runtime, without recreating the [`Device`] — the equivalent
1231    /// of Go `tsnet`'s `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`.
1232    ///
1233    /// The peer may be named by stable node ID, tailnet IP, or MagicDNS name via
1234    /// [`ExitNodeSelector`] (a bare IP or name parses with `selector.parse()`); this is the same
1235    /// selector type as [`Config::exit_node`](crate::Config::exit_node), so the construction-time
1236    /// and runtime paths are identical. Passing `None` clears the exit node — internet-bound traffic
1237    /// is then dropped (fail-closed) unless this node egresses directly.
1238    ///
1239    /// The change is applied immediately: the new selector is re-resolved against the live peer set
1240    /// and the outbound route + inbound source filter are recomputed at once. A selector for a peer
1241    /// not yet in the netmap simply takes effect once that peer appears.
1242    ///
1243    /// Only NEW flows use the changed exit; in-flight connections are not torn down and continue
1244    /// egressing via the previously-selected exit until they close.
1245    pub async fn set_exit_node(&self, exit_node: Option<ExitNodeSelector>) -> Result<(), Error> {
1246        self.runtime
1247            .set_exit_node(exit_node)
1248            .await
1249            .map_err(Into::into)
1250    }
1251
1252    /// The currently-selected exit node, or `None` if none is selected.
1253    pub fn exit_node(&self) -> Option<ExitNodeSelector> {
1254        self.runtime.exit_node()
1255    }
1256
1257    /// Toggle whether this node accepts peer-advertised subnet routes at runtime, without recreating
1258    /// the [`Device`] — the equivalent of Go `tsnet`'s `LocalClient.EditPrefs(RouteAll)` /
1259    /// `tailscale set --accept-routes`.
1260    ///
1261    /// This is a purely **local** preference: unlike [`set_advertise_routes`](Self::set_advertise_routes)
1262    /// it is never reported to control, so it only changes which peer-advertised subnet routes *this*
1263    /// node installs. The change is applied immediately — the outbound route table and the inbound
1264    /// source filter are recomputed together against the live peer set, so turning it on installs (and
1265    /// accepts traffic from) newly-accepted subnets and turning it off removes them from both in
1266    /// lock-step. A peer's own tailnet address is always reachable regardless; the exit-node default
1267    /// route is governed by [`set_exit_node`](Self::set_exit_node), not this flag.
1268    ///
1269    /// Only NEW flows are affected; in-flight connections are not torn down. In TUN transport mode the
1270    /// netstack data path honors the toggle immediately, but the host routing table is not re-steered
1271    /// until the device is rebuilt.
1272    pub async fn set_accept_routes(&self, accept: bool) -> Result<(), Error> {
1273        self.runtime
1274            .set_accept_routes(accept)
1275            .await
1276            .map_err(Into::into)
1277    }
1278
1279    /// Whether this node currently accepts peer-advertised subnet routes (`--accept-routes`).
1280    pub fn accept_routes(&self) -> bool {
1281        self.runtime.accept_routes()
1282    }
1283
1284    /// Toggle whether this node accepts the tailnet's DNS configuration at runtime, without
1285    /// recreating the [`Device`] — the equivalent of Go `tsnet`'s `LocalClient.EditPrefs(CorpDNS)` /
1286    /// `tailscale set --accept-dns`.
1287    ///
1288    /// Like [`set_accept_routes`](Self::set_accept_routes) this is a purely **local** preference,
1289    /// never reported to control. When `false`, the MagicDNS responder ignores the control-pushed DNS
1290    /// configuration and answers every query `REFUSED` (mirroring Go applying an empty `dns.Config`
1291    /// when `CorpDNS` is off), so the node can join the tailnet for connectivity without taking over
1292    /// its DNS. The change is applied immediately to the netstack responder and the peerAPI DoH server
1293    /// that shares its view; flipping it back to `true` restores serving from the still-current config
1294    /// (the config is only gated at the read site, never destroyed), so the OFF→ON restore is
1295    /// automatic.
1296    ///
1297    /// In TUN transport mode the in-datapath responder honors the toggle immediately, but the host
1298    /// resolver/route programming (which points the host at `100.100.100.100`) is applied once at
1299    /// device build and is not re-steered until the device is rebuilt.
1300    pub async fn set_accept_dns(&self, accept: bool) -> Result<(), Error> {
1301        self.runtime
1302            .set_accept_dns(accept)
1303            .await
1304            .map_err(Into::into)
1305    }
1306
1307    /// Whether this node currently accepts the tailnet's DNS configuration (`--accept-dns` / `CorpDNS`).
1308    pub fn accept_dns(&self) -> bool {
1309        self.runtime.accept_dns()
1310    }
1311
1312    /// Change the subnet routes this node advertises at runtime — Go `tailscale set
1313    /// --advertise-routes`. This is the runtime equivalent of
1314    /// [`Config::advertise_routes`](crate::Config::advertise_routes): the node re-advertises the
1315    /// prefixes to control (so it is granted the subnet-router role for them) AND starts forwarding
1316    /// them on the data path, applied together so the two never disagree.
1317    ///
1318    /// `routes` is filtered to the IPv4-only, deduplicated set this fork honors (IPv6 prefixes are
1319    /// dropped under the IPv6-off posture). This sets the explicit subnet prefixes only; it does not
1320    /// affect the exit-node `0.0.0.0/0` advertisement. Only NEW forwarded flows use the changed set;
1321    /// in-flight flows keep their existing routing until they close.
1322    pub async fn set_advertise_routes(&self, routes: Vec<ipnet::IpNet>) -> Result<(), Error> {
1323        self.runtime
1324            .set_advertise_routes(routes)
1325            .await
1326            .map_err(Into::into)
1327    }
1328
1329    /// Advertise (or stop advertising) this node as an **exit node** at runtime — Go `tailscale set
1330    /// --advertise-exit-node`. The runtime equivalent of
1331    /// [`Config::advertise_exit_node`](crate::Config::advertise_exit_node): when `enable` it adds the
1332    /// `0.0.0.0/0` default route to what this node advertises (and forwards), when `false` it removes
1333    /// it.
1334    ///
1335    /// Composes with [`set_advertise_routes`](Device::set_advertise_routes): the explicit subnet
1336    /// routes and the exit-node advertisement are independent — toggling one preserves the other.
1337    /// Advertising an exit node only makes this node *eligible*; control + the peer still decide
1338    /// whether to route through it. Only NEW forwarded flows see the change; in-flight flows keep
1339    /// their routing.
1340    pub async fn set_advertise_exit_node(&self, enable: bool) -> Result<(), Error> {
1341        self.runtime
1342            .set_advertise_exit_node(enable)
1343            .await
1344            .map_err(Into::into)
1345    }
1346
1347    /// Change this node's hostname at runtime — Go `tailscale set --hostname`. Re-reports
1348    /// `Hostinfo.Hostname` to control on the live connection (no rebuild, no reconnect); control
1349    /// reflects the new name in the netmap (it drives the node's MagicDNS name / `tailscale status`
1350    /// display). Hostname is display metadata, so there is no data-path effect. The new value also
1351    /// persists across a later re-registration.
1352    pub async fn set_hostname(&self, hostname: String) -> Result<(), Error> {
1353        self.runtime
1354            .set_hostname(hostname)
1355            .await
1356            .map_err(Into::into)
1357    }
1358
1359    /// Re-bind the underlay UDP socket after a **network/link change** — Wi-Fi switch, sleep/wake,
1360    /// or any event that invalidates the device's local address/NAT mapping. This is the Rust
1361    /// analog of Go magicsock's `Conn.Rebind()`.
1362    ///
1363    /// The embedder owns deciding *when* to call this (it watches the OS for link changes — there is
1364    /// no built-in network monitor); `rebind` is the engine half that does the socket work:
1365    /// - Re-binds the underlay UDP socket, preferring the same local port (so the advertised
1366    ///   endpoint stays stable) and falling back to an ephemeral port. The IPv4-only-by-default
1367    ///   invariant is preserved.
1368    /// - Invalidates the now-stale local mapping: learned reflexive (STUN) addresses and every
1369    ///   peer's *confirmed* direct path are cleared, while candidate endpoints are kept — so peers
1370    ///   are re-probed over the new socket and **relay over DERP (never a direct host dial) until a
1371    ///   path re-confirms**. Endpoint discovery re-runs on its normal cadence.
1372    /// - Leaves peers, control, the netmap, disco keys, and DERP connections untouched; existing
1373    ///   WireGuard sessions survive (they ride whatever underlay carries them).
1374    ///
1375    /// A no-op if the underlay socket failed to bind at startup (the device is DERP-only). Existing
1376    /// connectivity is preserved on a re-bind error (the old socket is kept; the error is returned).
1377    pub async fn rebind(&self) -> Result<(), Error> {
1378        self.runtime.rebind().await.map_err(Into::into)
1379    }
1380
1381    /// The stable id of the exit node traffic is **currently** egressing through, or `None` if none
1382    /// is engaged (the equivalent of Go `tsnet`'s `Status.ExitNodeStatus.ID`).
1383    ///
1384    /// This differs from [`exit_node`](Self::exit_node), which returns the *configured* selector:
1385    /// the active exit node is the route updater's resolved, fail-closed answer. It is `None` when
1386    /// no exit node is configured, the configured selector matches no current peer, or the matched
1387    /// peer no longer advertises a default route (egress is then dropped, fail-closed). Match the id
1388    /// against [`Status::peers`](crate::Status::peers) (via [`status`](Self::status)) for details.
1389    pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
1390        self.runtime.active_exit_node()
1391    }
1392
1393    /// Watch for netmap changes: the returned receiver's value is the current set of peer
1394    /// [`StatusNode`]s and updates on every netmap change. This is the narrow peer-only view; for
1395    /// the unified Go-`WatchIPNBus` feed (peers + device-state + login URL in one stream) use
1396    /// [`watch_ipn_bus`](Self::watch_ipn_bus).
1397    pub async fn watch_netmap(
1398        &self,
1399    ) -> Result<tokio::sync::watch::Receiver<Vec<StatusNode>>, Error> {
1400        self.runtime.watch_netmap().await.map_err(Into::into)
1401    }
1402
1403    /// The current device connection-[`DeviceState`] (`Connecting` / `Running` / `NeedsLogin` /
1404    /// `Expired` / `Failed`).
1405    pub fn device_state(&self) -> DeviceState {
1406        self.runtime.device_state()
1407    }
1408
1409    /// Watch the device connection-[`DeviceState`], reacting push-style to control connection
1410    /// transitions instead of polling [`status`](Self::status).
1411    ///
1412    /// Returns a [`tokio::sync::watch::Receiver`]; await its
1413    /// [`changed`](tokio::sync::watch::Receiver::changed) to be woken on each transition. The
1414    /// initial value is the current state.
1415    pub fn watch_state(&self) -> tokio::sync::watch::Receiver<DeviceState> {
1416        self.runtime.watch_state()
1417    }
1418
1419    /// Subscribe to the unified IPN notification bus (Go `ipn`'s `WatchIPNBus`).
1420    ///
1421    /// Returns an [`IpnBusWatcher`]; await [`next`](IpnBusWatcher::next) to receive [`Notify`]
1422    /// events that merge device-[`DeviceState`] transitions (with the interactive-login URL surfaced
1423    /// as [`Notify::browse_to_url`]) and netmap peer-set changes into one feed — the single stream a
1424    /// consumer porting from Go's `WatchNotifications` expects, instead of composing
1425    /// [`watch_state`](Self::watch_state) and [`watch_netmap`](Self::watch_netmap) by hand. `mask`
1426    /// ([`NotifyWatchOpt`]) front-loads the current state as an initial snapshot on subscribe
1427    /// (`INITIAL_STATE` / `INITIAL_NETMAP`), mirroring Go's `NotifyInitialState` /
1428    /// `NotifyInitialNetMap`. Delivery is best-effort (a slow consumer drops notifications rather
1429    /// than stalling the runtime); the stream ends when the device shuts down.
1430    pub async fn watch_ipn_bus(&self, mask: NotifyWatchOpt) -> Result<IpnBusWatcher, Error> {
1431        self.runtime.watch_ipn_bus(mask).await.map_err(Into::into)
1432    }
1433
1434    /// Wait until the device finishes registering, returning a typed outcome — the clean
1435    /// replacement for polling [`ipv4_addr`](Self::ipv4_addr) in a loop.
1436    ///
1437    /// Resolves `Ok(())` once the device is [`DeviceState::Running`]. On a non-running outcome it
1438    /// returns a typed [`RegistrationError`]:
1439    /// - [`AuthRejected`](RegistrationError::AuthRejected) — bad/expired/unknown auth key;
1440    ///   **permanent** (re-pair).
1441    /// - [`NeedsLogin`](RegistrationError::NeedsLogin) — interactive authorization required;
1442    ///   **not permanent** (the runtime keeps retrying and reaches `Running` once the user
1443    ///   authorizes). Auth-key callers treat this as failure; interactive callers should ignore it
1444    ///   and drive the flow via [`watch_state`](Self::watch_state).
1445    /// - [`NetworkUnreachable`](RegistrationError::NetworkUnreachable) — **transient** (retry).
1446    /// - [`Timeout`](RegistrationError::Timeout) — no settled state within `timeout` (`None` waits
1447    ///   indefinitely).
1448    ///
1449    /// [`KeyExpired`](RegistrationError::KeyExpired) is not produced here (a key expires only after
1450    /// the node is up); observe it via [`watch_state`](Self::watch_state). Use
1451    /// [`RegistrationError::is_permanent`] to branch "re-pair" vs. "retry / drive login".
1452    pub async fn wait_until_running(
1453        &self,
1454        timeout: Option<Duration>,
1455    ) -> Result<(), RegistrationError> {
1456        self.runtime.wait_until_running(timeout).await
1457    }
1458
1459    /// Ping a tailnet peer over the overlay with an ICMPv4 echo, returning the round-trip time
1460    /// (like `tailscale ping`).
1461    ///
1462    /// The echo is sent from this device's own tailnet IPv4 over the overlay netstack — never a
1463    /// host socket. IPv6 destinations return [`PingError::Ipv6Unsupported`] (this fork is
1464    /// IPv4-only on the tailnet). A peer answers from its own OS stack; this netstack does not
1465    /// auto-reply to echo requests.
1466    ///
1467    /// In TUN transport mode there is no application netstack to ping from; this surfaces as
1468    /// [`PingError::Timeout`] (the same error this method already uses for an unavailable source
1469    /// address — `PingError` carries no dedicated "unsupported" variant).
1470    pub async fn ping(&self, dst: IpAddr, timeout: Duration) -> Result<Duration, PingError> {
1471        let channel = self.channel().map_err(|_| PingError::Timeout)?;
1472        let src = self.ipv4_addr().await.map_err(|_| PingError::Timeout)?;
1473        ts_netstack_smoltcp::ping(channel, src, dst, timeout).await
1474    }
1475
1476    /// The current **direct path** to the peer at tailnet IP `dst`: its confirmed direct UDP
1477    /// endpoint and that path's last-measured round-trip latency, or `None` when traffic to the peer
1478    /// is **relayed via DERP** (no trusted direct path right now), the peer is unknown, or it has no
1479    /// disco key.
1480    ///
1481    /// This is the direct-path analog of Go's `tailscale ping`/`PeerStatus` connectivity: a present
1482    /// result means packets reach the peer directly at the returned address, with roughly the
1483    /// returned RTT. The latency is a live snapshot taken from the most recent disco ping/pong that
1484    /// confirmed the path (up to one probe interval stale) — not a fresh on-demand round-trip. Unlike
1485    /// [`ping`](Device::ping) (an ICMP echo over the netstack), this reports the *underlay* path the
1486    /// data plane actually uses, distinguishing a direct connection from a DERP-relayed one.
1487    pub async fn direct_path(&self, dst: IpAddr) -> Result<Option<(SocketAddr, Duration)>, Error> {
1488        self.runtime.direct_path(dst).await.map_err(Into::into)
1489    }
1490
1491    /// Send a disco ping to the peer at tailnet IP `dst` **now** and await the pong — a fresh,
1492    /// on-demand round-trip measurement (Go's `tailscale ping`, `PingType::Disco`). Returns the
1493    /// endpoint that answered and the measured RTT, or `None` if no pong arrives within `timeout`
1494    /// (or the peer is unknown / has no candidate direct path).
1495    ///
1496    /// Unlike [`direct_path`](Device::direct_path) — which reports the *last periodic probe's* RTT
1497    /// from cache — this actively sends a ping and waits for the reply, so the latency is current. A
1498    /// `None` here means "no direct path confirmed within the timeout" (the peer may still be
1499    /// reachable via DERP). Unlike [`ping`](Device::ping) (an ICMP echo over the netstack), this
1500    /// measures the disco/underlay path the data plane uses for direct connections.
1501    pub async fn ping_disco(
1502        &self,
1503        dst: IpAddr,
1504        timeout: Duration,
1505    ) -> Result<Option<(SocketAddr, Duration)>, Error> {
1506        self.runtime
1507            .ping_disco(dst, timeout)
1508            .await
1509            .map_err(Into::into)
1510    }
1511
1512    /// Obtain a TLS certificate for a node's MagicDNS `name` (like `tsnet`'s `GetCertificate`).
1513    ///
1514    /// **Fail-closed without the `acme` feature.** By default this fork has no client-side ACME
1515    /// engine wired in, so this returns [`ts_control::CertError::Unimplemented`] (after a
1516    /// tailnet-name check) — it NEVER self-signs and NEVER returns a placeholder certificate
1517    /// ([`ts_control::MISSING_CERT_RPC`] names what is missing).
1518    ///
1519    /// **With the `acme` feature** this instead drives the client-side ACME DNS-01 engine to issue a
1520    /// real Let's Encrypt certificate for `name`, publishing the challenge TXT via the node's
1521    /// `POST /machine/set-dns` RPC (routed through the control runner). SaaS-only: a self-hosted
1522    /// control plane may 501 on set-dns, surfaced as [`ts_control::CertError::Acme`].
1523    #[cfg(not(feature = "acme"))]
1524    pub async fn get_certificate(&self, name: &str) -> Result<CertifiedKey, ts_control::CertError> {
1525        ts_control::get_certificate(name).await
1526    }
1527
1528    /// See the no-`acme` variant for the contract; with `acme` this issues a real cert via the
1529    /// runtime's ACME engine (`Device → Runtime → ControlRunner → issue_certificate_via_setdns`).
1530    #[cfg(feature = "acme")]
1531    pub async fn get_certificate(&self, name: &str) -> Result<CertifiedKey, ts_control::CertError> {
1532        self.runtime.get_certificate(name.to_string()).await
1533    }
1534
1535    /// Issue a real Let's Encrypt certificate for a node's MagicDNS `name` and return the **PEM
1536    /// pair** `(cert_chain_pem, key_pem)` — the analog of Go's `LocalClient.CertPairWithValidity`,
1537    /// for writing the daemon's on-disk `.crt` + `.key` (`tnet cert`). **`acme` feature only.**
1538    ///
1539    /// This drives the same client-side ACME DNS-01 issuance as [`Device::get_certificate`] (one
1540    /// order, the challenge TXT published via the node's `POST /machine/set-dns` RPC, routed through
1541    /// the runtime → control runner); it differs only in returning the raw leaf+chain PEM and the
1542    /// leaf private-key PEM instead of the opaque [`CertifiedKey`]. The second tuple element is
1543    /// **secret key material**: it is never logged anywhere on this path — persist it to a `0600`
1544    /// file and never trace it.
1545    ///
1546    /// **`min_validity` (honest "always fresh").** Go's `CertPairWithValidity` reuses a cached cert
1547    /// when it has at least `min_validity` of its lifetime remaining, re-issuing otherwise. This
1548    /// fork keeps **no cert cache** — every call issues fresh — so `min_validity` is accepted for
1549    /// signature compatibility but does not alter behavior: a freshly issued (full-lifetime) cert
1550    /// satisfies any `min_validity`. A reuse cache is separate future work; this does NOT fake one.
1551    ///
1552    /// Fail-closed: returns a [`ts_control::CertError`] (never a self-signed or partial pair) on any
1553    /// ACME/HTTP failure. SaaS-only: a self-hosted control plane may 501 on set-dns, surfaced as
1554    /// [`ts_control::CertError::Acme`].
1555    #[cfg(feature = "acme")]
1556    pub async fn cert_pair(
1557        &self,
1558        name: &str,
1559        min_validity: Option<Duration>,
1560    ) -> Result<(String, String), ts_control::CertError> {
1561        self.runtime.cert_pair(name.to_string(), min_validity).await
1562    }
1563
1564    /// Build a [`TlsAcceptor`] terminating TLS for `cfg.name` on the overlay (like `tsnet`'s
1565    /// `ListenTLS`).
1566    ///
1567    /// Obtains the certificate via [`Device::get_certificate`] — so with the `acme` feature this
1568    /// issues a real Let's Encrypt cert (when the control plane answers `set-dns`), and without it
1569    /// (or when issuance is unavailable) it surfaces the same fail-closed
1570    /// [`ts_control::CertError`] rather than ever serving a self-signed cert or downgrading to
1571    /// plaintext. Terminate accepted overlay streams with [`ts_control::accept_tls`].
1572    pub async fn listen_tls(
1573        &self,
1574        cfg: &ts_control::ServeConfig,
1575    ) -> Result<TlsAcceptor, ts_control::CertError> {
1576        // Route through Device::get_certificate (the acme-aware issuance path) rather than
1577        // ts_control::listen_tls, which only knows the non-acme stub. Validate the serve config
1578        // first (same fail-closed checks ts_control::listen_tls applies), then assemble the acceptor.
1579        cfg.validate()?;
1580        let cert = self.get_certificate(&cfg.name).await?;
1581        ts_control::tls_acceptor(cert)
1582    }
1583
1584    /// The currently-stored Serve config (like `tsnet`'s `GetServeConfig`).
1585    ///
1586    /// Returns the config last passed to [`Device::set_serve_config`], or an empty
1587    /// [`ts_control::ServeState`] (no ports) if none was ever set. Pure read — does not touch the
1588    /// network.
1589    pub fn get_serve_config(&self) -> ts_control::ServeState {
1590        match &*self.serve.lock().unwrap_or_else(|e| e.into_inner()) {
1591            Some(mgr) => mgr.get(),
1592            None => ts_control::ServeState::default(),
1593        }
1594    }
1595
1596    /// Replace this node's Serve config and (re)bind its tailnet ports (like `tsnet`'s
1597    /// `SetServeConfig`, REPLACE semantics).
1598    ///
1599    /// `state` becomes the **whole** config (full-replace reconcile: every previously-bound serve
1600    /// port's accept loop is torn down and the new config's ports are bound from scratch). For each
1601    /// configured port the manager binds an overlay listener on this node's tailnet IPv4 and
1602    /// dispatches per [`ts_control::ServeTarget`]:
1603    /// - [`Accept`](ts_control::ServeTarget::Accept) — the TLS-terminated stream is handed back over
1604    ///   the returned [`ServeAcceptedReceiver`](ts_runtime::serve::ServeAcceptedReceiver) (the
1605    ///   in-process stand-in for `ListenTLS`'s `net.Listener`).
1606    /// - [`Proxy`](ts_control::ServeTarget::Proxy) — reverse-proxy the decrypted stream to a local
1607    ///   host backend.
1608    /// - [`Text`](ts_control::ServeTarget::Text) — write a fixed body and close.
1609    /// - [`TcpForward`](ts_control::ServeTarget::TcpForward) — forward the **raw** (non-TLS) stream
1610    ///   to a local host backend.
1611    ///
1612    /// **Fail-closed.** `state.validate()` runs first. Every TLS-terminating port's acceptor is
1613    /// obtained up-front via [`Device::listen_tls`] (the ACME-aware cert path); if any cert cannot be
1614    /// issued the whole call fails with that [`ts_control::CertError`] and **nothing is bound** — a
1615    /// TLS port never downgrades to plaintext.
1616    ///
1617    /// **Anti-leak.** Listeners bind the overlay netstack only (never a host socket). The
1618    /// `Proxy`/`TcpForward` backend dial is a local host socket to the embedder's own backend (like
1619    /// Go's reverse-proxy to `127.0.0.1`), intentionally NOT routed through the exit-egress
1620    /// forwarder. A backend dial failure drops that connection; it never falls back.
1621    ///
1622    /// Returns an error in TUN transport mode (there is no application netstack to bind on). The
1623    /// previous config's accept loops (and any earlier `ServeAcceptedReceiver`) stop when this
1624    /// returns; the new receiver delivers every `Accept`-port connection.
1625    pub async fn set_serve_config(
1626        &self,
1627        state: ts_control::ServeState,
1628    ) -> Result<ts_runtime::serve::ServeAcceptedReceiver, Error> {
1629        state
1630            .validate()
1631            .map_err(|_| Error::Internal(InternalErrorKind::BadRequest))?;
1632
1633        // Fail-closed: build every TLS-terminating port's acceptor up-front via the ACME-aware cert
1634        // path. If any cert can't be issued, return before binding anything (no plaintext downgrade).
1635        let mut resolved = std::collections::BTreeMap::new();
1636        for (port, target) in &state.ports {
1637            let acceptor = if target.terminates_tls() {
1638                let cfg = ts_control::ServeConfig {
1639                    name: state.name.clone(),
1640                    port: *port,
1641                    target: target.clone(),
1642                };
1643                Some(self.listen_tls(&cfg).await.map_err(|_| {
1644                    // Cert issuance is fail-closed in this fork; surface as a request error rather
1645                    // than ever binding a plaintext TLS port.
1646                    Error::Internal(InternalErrorKind::BadRequest)
1647                })?)
1648            } else {
1649                None
1650            };
1651            resolved.insert(
1652                *port,
1653                ts_runtime::serve::ResolvedPort {
1654                    target: target.clone(),
1655                    acceptor,
1656                },
1657            );
1658        }
1659
1660        // The manager binds the OVERLAY netstack on this node's own tailnet IPv4.
1661        let self_ipv4 = self.ipv4_addr().await?;
1662        let channel = self.channel()?.clone();
1663
1664        let mut slot = self.serve.lock().unwrap_or_else(|e| e.into_inner());
1665        let mgr =
1666            slot.get_or_insert_with(|| ts_runtime::serve::ServeManager::new(channel, self_ipv4));
1667        Ok(mgr.set(state, resolved))
1668    }
1669
1670    /// Expose a tailnet TLS service to the public internet via Tailscale Funnel (like `tsnet`'s
1671    /// `ListenFunnel`), returning a [`FunnelAcceptedReceiver`](ts_runtime::funnel::FunnelAcceptedReceiver)
1672    /// that delivers each TLS-terminated public connection.
1673    ///
1674    /// **Two fail-closed gates, then the live ingress listener.** First the node-attribute gate is
1675    /// fully enforced from this node's own capability map (mirroring Go `ipn.NodeCanFunnel` +
1676    /// `ipn.CheckFunnelPort`): the tailnet admin must have enabled HTTPS and granted the `funnel`
1677    /// node attribute, and `cfg.port` must be in the set the `funnel-ports` capability allows —
1678    /// otherwise this returns [`ts_control::FunnelError::NotAllowed`] /
1679    /// [`ts_control::FunnelError::PortNotAllowed`] before touching any cert or network. Then the
1680    /// node's `*.ts.net` certificate is obtained via the ACME-aware [`Device::get_certificate`] (the
1681    /// Funnel hostname *is* the node's MagicDNS name, so its DNS-01 cert matches); fail-closed on
1682    /// [`ts_control::FunnelError::Cert`] — no self-signed or plaintext fallback.
1683    ///
1684    /// On success a [`FunnelManager`](ts_runtime::funnel::FunnelManager) is registered: its ingress
1685    /// sink is installed into the runtime's peerAPI `/v0/ingress` slot (making that route live without
1686    /// restarting the peerAPI server), and the `HostInfo.IngressEnabled` map-request signal is set so
1687    /// control routes Funnel traffic to this node. Public Funnel bytes arrive as a relay POST to
1688    /// `/v0/ingress`, are membership-gated + `101`-hijacked into a raw stream, TLS-terminated by the
1689    /// manager, and delivered over the returned receiver.
1690    ///
1691    /// **Where the relay comes from.** The public ingress **relay + DNS mapping** that feed
1692    /// `/v0/ingress` are Tailscale infrastructure ([`ts_control::MISSING_FUNNEL_RELAY`]), provisioned
1693    /// automatically against real Tailscale SaaS with a Funnel-enabled ACL; against a self-hosted
1694    /// control plane no relay exists, so the listener is correct but never fed.
1695    ///
1696    /// Anti-leak: Funnel TLS terminates only on the overlay netstack (the hijacked ingress stream
1697    /// arrives on the overlay peerAPI listener), never a host socket; there is no self-signed or
1698    /// plaintext fallback. A new `listen_funnel` replaces the previous manager (its pump + sink tear
1699    /// down); dropping the `Device` tears it down too.
1700    pub async fn listen_funnel(
1701        &self,
1702        cfg: &ts_control::ServeConfig,
1703        opts: ts_control::FunnelOptions,
1704    ) -> Result<ts_runtime::funnel::FunnelAcceptedReceiver, ts_control::FunnelError> {
1705        // Gate 1 (fail-closed, no network): node-attribute + funnel-port access from our cap map.
1706        let me = self
1707            .self_node()
1708            .await
1709            .map_err(|_| ts_control::FunnelError::NotAllowed)?;
1710        cfg.validate()?;
1711        ts_control::funnel_access(&me, cfg.port)?;
1712
1713        // Gate 2 (fail-closed): obtain the node's `*.ts.net` cert via the ACME-aware path and build
1714        // the TLS acceptor. A cert failure surfaces as FunnelError::Cert — never a plaintext listener.
1715        let cert = self
1716            .get_certificate(&cfg.name)
1717            .await
1718            .map_err(ts_control::FunnelError::Cert)?;
1719        let acceptor = ts_control::tls_acceptor(cert).map_err(ts_control::FunnelError::Cert)?;
1720
1721        // `opts.funnel_only` (reject tailnet-internal connections) is accepted for surface stability;
1722        // the ingress data path only ever carries relay-delivered public traffic, so there is no
1723        // tailnet-internal leg on this listener to reject. Documented as a no-op here for now.
1724        let _ = opts;
1725
1726        // Build the funnel manager + its ingress sink + the hand-back receiver, install the sink into
1727        // the runtime's shared peerAPI `/v0/ingress` slot (making the route live), and flip the
1728        // IngressEnabled map signal. Hold the manager on the device so its pump/sink live as long as
1729        // the listener; replacing a prior manager tears the old one down on drop at end of scope.
1730        let (manager, sink, receiver) = ts_runtime::funnel::FunnelManager::new(acceptor);
1731        {
1732            let slot = self.runtime.funnel_ingress_slot();
1733            *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(sink);
1734        }
1735        self.runtime
1736            .ingress_active_flag()
1737            .store(true, std::sync::atomic::Ordering::Relaxed);
1738
1739        let old = {
1740            let mut held = self.funnel.lock().unwrap_or_else(|e| e.into_inner());
1741            held.replace(manager)
1742        };
1743        drop(old);
1744
1745        Ok(receiver)
1746    }
1747
1748    /// Host a Tailscale **VIP service** (`svc:<label>`) by binding an overlay listener on the
1749    /// service's control-assigned virtual IP (like `tsnet`'s `ListenService`).
1750    ///
1751    /// **Fail-closed.** Mirrors Go `tsnet.Server.ListenService`'s preconditions, enforced from this
1752    /// node's own netmap state ([`ts_control::resolve_service_listen`]): the `name` must be a valid
1753    /// `svc:<dns-label>`, this node must be **tagged** (Go `ErrUntaggedServiceHost`), and control
1754    /// must have assigned the service a VIP address on this node (delivered via the `service-host`
1755    /// node-capability — see [`ts_control::Node::service_addresses`]). Any unmet precondition
1756    /// returns a typed [`ts_control::ServiceError`] before binding anything.
1757    ///
1758    /// When all hold, this binds a [`tcp_listen`][Device::tcp_listen] on the service VIP and the
1759    /// configured `mode` port over the **overlay netstack** (never a host socket) and returns the
1760    /// listener. The netstack already accepts packets for control-assigned VIPs (they are injected
1761    /// alongside the node's own tailnet address), so the listener is reachable by tailnet peers.
1762    ///
1763    /// The `Tun`/L3 service mode is unsupported (a TODO in upstream tsnet); only TCP/HTTP modes
1764    /// (which bind the same VIP:port at the listen layer) are offered. Returns an error in TUN
1765    /// transport mode (there is no application netstack to bind on).
1766    pub async fn listen_service(
1767        &self,
1768        name: &str,
1769        mode: ts_control::ServiceMode,
1770    ) -> Result<netstack::TcpListener, ts_control::ServiceError> {
1771        let me = self
1772            .self_node()
1773            .await
1774            .map_err(|e| ts_control::ServiceError::Listen(e.to_string()))?;
1775        let listen_addr = ts_control::resolve_service_listen(&me, name, mode, self.enable_ipv6)?;
1776        self.tcp_listen(listen_addr)
1777            .await
1778            .map_err(|e| ts_control::ServiceError::Listen(e.to_string()))
1779    }
1780
1781    /// Attempt to gracefully shut down this device's runtime.
1782    ///
1783    /// Reports whether the device was fully shut down before the timeout. It is still shut
1784    /// down if it timed out, just more violently and with potential resource leaks.
1785    ///
1786    /// If `timeout` is `None`, then shutdown will never time-out.
1787    pub async fn shutdown(self, timeout: Option<Duration>) -> bool {
1788        self.runtime.graceful_shutdown(timeout).await
1789    }
1790}
1791
1792/// Command-channel-driven userspace network stack.
1793///
1794/// This is an opinionated wrapper around [smoltcp](https://docs.rs/smoltcp) that provides an
1795/// easier-to-integrate, more-portable API.
1796pub mod netstack {
1797    #[doc(inline)]
1798    pub use ts_netstack_smoltcp::netcore::Error;
1799    #[doc(inline)]
1800    pub use ts_netstack_smoltcp::netcore::InternalErrorKind;
1801    #[doc(inline)]
1802    pub use ts_netstack_smoltcp::netsock::{TcpListener, TcpStream, UdpSocket};
1803}
1804
1805/// Geneve (RFC 8926) framing for Tailscale **peer-relay** traffic. A peer that advertises
1806/// [`NodeInfo::is_peer_relay`] runs a UDP relay server; relayed disco + WireGuard frames are
1807/// Geneve-encapsulated with a VNI. This module exposes the header codec so the framing is
1808/// recognizable. NOTE: the active relay *data path* (the relay-allocation handshake +
1809/// magicsock integration) is **not yet implemented** in this fork — this is the wire-aware slice.
1810pub mod geneve {
1811    #[doc(inline)]
1812    pub use ts_packet::geneve::{
1813        GENEVE_FIXED_HEADER_LEN, GENEVE_PROTOCOL_DISCO, GENEVE_PROTOCOL_WIREGUARD, GeneveError,
1814        GeneveHeader,
1815    };
1816}
1817
1818/// Tailnet Lock (TKA) verification: the [`tka::Authority`] checks a peer's node-key signature
1819/// against the trusted-key state, mirroring Go's `tka` package. Pair with [`Device::tka_status`]
1820/// (the control-pushed head/disablement signal).
1821pub mod tka {
1822    #[doc(inline)]
1823    pub use ts_tka::{
1824        AumHash, AumKind, Authority, Key, KeyKind, NodeKeySignature, SigKind, State, TkaError,
1825        aum_hash,
1826    };
1827}
1828
1829/// Tailscale cryptographic key types.
1830pub mod keys {
1831    #[doc(inline)]
1832    pub use ts_keys::{
1833        DiscoKeyPair, DiscoPrivateKey, DiscoPublicKey, MachineKeyPair, MachinePrivateKey,
1834        MachinePublicKey, NetworkLockKeyPair, NetworkLockPrivateKey, NetworkLockPublicKey,
1835        NodeKeyPair, NodePrivateKey, NodePublicKey, NodeState, PersistState,
1836    };
1837}
1838
1839const ENV_MAGIC_VAR: &str = "TS_RS_EXPERIMENT";
1840const ENV_MAGIC_VALUE: &str = "this_is_unstable_software";
1841
1842fn check_magic_env() -> Result<(), Error> {
1843    if std::env::var(ENV_MAGIC_VAR).as_deref() != Ok(ENV_MAGIC_VALUE) {
1844        let warning = format!(
1845            "
1846check failed: set {ENV_MAGIC_VAR}={ENV_MAGIC_VALUE} to acknowledge that tailscale-rs is early-days
1847experimental software containing bugs, unvalidated cryptography, and no stability or compatibility
1848guarantees.
1849            "
1850        );
1851
1852        eprintln!("{}", warning.trim());
1853
1854        return Err(Error::UnstableEnvVar);
1855    };
1856
1857    Ok(())
1858}
1859
1860#[cfg(test)]
1861mod tests {
1862    use secrecy::ExposeSecret as _;
1863
1864    use super::*;
1865
1866    // `Device::new`/`new_with_secret` cannot be unit-tested end-to-end without a live control
1867    // server (registration). The only behavioral difference `new_with_secret` introduces over `new`
1868    // is exposing the `SecretString` to a plain `String` on the last inch; everything after is the
1869    // shared `new` path. So we assert that equivalence at the auth-key-resolution level: the secret
1870    // path must resolve to the exact same key the plain path feeds into `resolve_auth_key`.
1871    const SAMPLE_KEY: &str = "tskey-auth-koCgSLP5R811CNTRL-EXAMPLEEXAMPLEEXAMPLEEXAMPLE";
1872
1873    // The mapping `new_with_secret` applies (`Option<SecretString>` -> `Option<String>`) must be a
1874    // byte-for-byte round-trip, so the spawn arg is identical to a direct `new(config, Some(..))`.
1875    #[test]
1876    fn secret_exposes_to_identical_string() {
1877        let plain = Some(SAMPLE_KEY.to_string());
1878        let from_secret =
1879            Some(SecretString::from(SAMPLE_KEY)).map(|s| s.expose_secret().to_string());
1880        assert_eq!(from_secret, plain);
1881
1882        // `None` must pass through unchanged (so it falls back to `config.auth_key` exactly as `new`).
1883        let none_secret: Option<SecretString> = None;
1884        assert_eq!(
1885            none_secret.map(|s| s.expose_secret().to_string()),
1886            None::<String>
1887        );
1888    }
1889
1890    // End-to-end equivalence at the resolve layer: feeding the exposed secret through
1891    // `resolve_auth_key` yields the same `Option<String>` as feeding the plain string — i.e. both
1892    // constructors reach the same spawn argument, without registering against a control server.
1893    #[tokio::test]
1894    async fn new_with_secret_resolves_same_as_new() {
1895        let config = Config::default();
1896
1897        let via_plain = resolve_auth_key(&config, Some(SAMPLE_KEY.to_string()))
1898            .await
1899            .expect("plain auth key resolves");
1900
1901        let exposed = Some(SecretString::from(SAMPLE_KEY)).map(|s| s.expose_secret().to_string());
1902        let via_secret = resolve_auth_key(&config, exposed)
1903            .await
1904            .expect("secret-derived auth key resolves");
1905
1906        assert_eq!(via_plain, via_secret);
1907        // Without the `identity-federation` feature `resolve_auth_key` is a pass-through, so the
1908        // resolved key is the input verbatim; assert that too to pin the default-build behavior.
1909        #[cfg(not(feature = "identity-federation"))]
1910        assert_eq!(via_secret, Some(SAMPLE_KEY.to_string()));
1911    }
1912}