1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! TailscaleProvider — the public NetworkProvider implementation.
//!
//! Orchestrates the Go sidecar (Layer 1) and bridge (Layer 2) to provide
//! peer discovery, raw TCP connectivity, and diagnostics via the Tailscale
//! network.
use std::collections::HashMap;
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::sync::{broadcast, mpsc, oneshot, Mutex, RwLock};
use tokio::task::JoinHandle;
use super::bridge::{Bridge, DIAL_TIMEOUT};
use super::protocol::ProxyAddCommandData;
use super::sidecar::{GoSidecar, SidecarConfig, SidecarInternalEvent};
use crate::network::{
HealthInfo, IncomingConnection, NetworkError, NetworkPeer, NetworkPeerEvent,
NetworkTcpListener, NodeIdentity, PeerAddr, PingResult, ProxyAddParams, ProxyAddResult,
ProxyListEntry,
};
/// Configuration for creating a TailscaleProvider.
#[derive(Debug, Clone)]
pub struct TailscaleConfig {
/// Path to the Go sidecar binary.
pub binary_path: PathBuf,
/// Application identifier (RFC 017 §5.1). Stored as a plain `String`
/// because validation happens in `NodeBuilder::app_id`; by the time the
/// config is constructed the value is already a valid `AppId`.
pub app_id: String,
/// Stable per-device ULID (RFC 017 §5.4).
pub device_id: String,
/// Original (unsanitised) device name — retained for display and for
/// building the `NodeIdentity` returned from `local_identity()`.
pub device_name: String,
/// Final Tailscale hostname, already composed by the caller as
/// `truffle-{app_id}-{slug(device_name)}`. The provider does NOT rebuild
/// this — it trusts the builder has applied the RFC 017 derivation once.
pub hostname: String,
/// State directory for tsnet persistent state.
pub state_dir: String,
/// Optional Tailscale auth key for headless authentication.
pub auth_key: Option<String>,
/// Whether the node is ephemeral (removed when offline).
pub ephemeral: Option<bool>,
/// ACL tags to advertise (e.g., ["tag:truffle"]).
pub tags: Option<Vec<String>>,
}
/// State of the provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProviderState {
Stopped,
Starting,
Running,
Stopping,
}
/// Tailscale network provider implementing [`NetworkProvider`](crate::network::NetworkProvider).
///
/// Wraps the Go sidecar (tsnet) and local TCP bridge to provide:
/// - Peer discovery via WatchIPNBus events
/// - Raw TCP dial/listen over encrypted Tailscale tunnels
/// - Network-level ping and health monitoring
///
/// All bridge internals (pending_dials, session tokens, binary headers) are
/// completely hidden. Callers interact only with plain `TcpStream`s and
/// high-level types.
pub struct TailscaleProvider {
config: TailscaleConfig,
state: Arc<RwLock<ProviderState>>,
/// Local node identity (populated after start).
///
/// Uses `std::sync::RwLock` (not tokio) so the sync trait methods
/// `local_identity()` and `local_addr()` can read without `.await`.
identity: Arc<std::sync::RwLock<NodeIdentity>>,
/// Local node address (populated after start).
///
/// Uses `std::sync::RwLock` (not tokio) so the sync trait method
/// `local_addr()` can read without `.await`.
local_addr: Arc<std::sync::RwLock<PeerAddr>>,
/// Cached peer list.
peers: Arc<RwLock<HashMap<String, NetworkPeer>>>,
/// Broadcast channel for peer events.
peer_event_tx: broadcast::Sender<NetworkPeerEvent>,
/// Health info cache.
health: Arc<RwLock<HealthInfo>>,
/// Handle to the Go sidecar (set during start).
sidecar: Arc<Mutex<Option<GoSidecar>>>,
/// Handle to the bridge (set during start).
bridge: Arc<Mutex<Option<Arc<Bridge>>>>,
/// Bridge shutdown sender.
bridge_shutdown_tx: Arc<Mutex<Option<tokio::sync::watch::Sender<bool>>>>,
/// Session token (32 bytes, generated on start).
session_token: Arc<RwLock<[u8; 32]>>,
/// Local Tailscale stable ID, captured from the `tsnet:status` event
/// (netmap `self` entry). Used for self-filtering in the peer event
/// chain — we must filter by this, NOT by hostname, because hostname
/// collisions from crashed/restarted dev runs can cause the local
/// node to appear as its own peer under a different Tailscale ID.
local_tailscale_id: Arc<std::sync::RwLock<Option<String>>>,
}
impl TailscaleProvider {
/// Create a new TailscaleProvider with the given configuration.
///
/// Does not start the provider — call [`start()`](crate::network::NetworkProvider::start) to begin.
pub fn new(config: TailscaleConfig) -> Self {
let (peer_event_tx, _) = broadcast::channel(256);
// Seed the identity with the RFC 017 fields we already know from
// the config. `tailscale_id`, `dns_name`, and `ip` are filled in
// later when the sidecar reports `tsnet:status`.
let initial_identity = NodeIdentity {
app_id: config.app_id.clone(),
device_id: config.device_id.clone(),
device_name: config.device_name.clone(),
tailscale_hostname: config.hostname.clone(),
tailscale_id: String::new(),
dns_name: None,
ip: None,
};
Self {
config,
state: Arc::new(RwLock::new(ProviderState::Stopped)),
identity: Arc::new(std::sync::RwLock::new(initial_identity)),
local_addr: Arc::new(std::sync::RwLock::new(PeerAddr::default())),
peers: Arc::new(RwLock::new(HashMap::new())),
peer_event_tx,
health: Arc::new(RwLock::new(HealthInfo {
state: "stopped".to_string(),
healthy: false,
..Default::default()
})),
sidecar: Arc::new(Mutex::new(None)),
bridge: Arc::new(Mutex::new(None)),
bridge_shutdown_tx: Arc::new(Mutex::new(None)),
session_token: Arc::new(RwLock::new([0u8; 32])),
local_tailscale_id: Arc::new(std::sync::RwLock::new(None)),
}
}
/// Generate a random 32-byte session token.
fn generate_session_token() -> Result<[u8; 32], NetworkError> {
let mut token = [0u8; 32];
getrandom::getrandom(&mut token).map_err(|e| {
NetworkError::Internal(format!("failed to generate session token: {e}"))
})?;
Ok(token)
}
/// Convert a SidecarPeer to a NetworkPeer.
fn sidecar_peer_to_network_peer(peer: &super::protocol::SidecarPeer) -> NetworkPeer {
let ip = peer
.tailscale_ips
.first()
.and_then(|s| s.parse::<IpAddr>().ok())
.unwrap_or(IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED));
NetworkPeer {
id: peer.id.clone(),
hostname: peer.hostname.clone(),
ip,
online: peer.online,
cur_addr: if peer.cur_addr.is_empty() {
None
} else {
Some(peer.cur_addr.clone())
},
relay: if peer.relay.is_empty() {
None
} else {
Some(peer.relay.clone())
},
os: if peer.os.is_empty() {
None
} else {
Some(peer.os.clone())
},
last_seen: peer.last_seen.clone(),
key_expiry: peer.key_expiry.clone(),
dns_name: Some(peer.dns_name.clone()),
}
}
/// Spawn the background event processing loop that maps sidecar events
/// to peer events and updates cached state.
#[allow(clippy::too_many_arguments)]
fn spawn_event_processor(
mut sidecar_rx: broadcast::Receiver<SidecarInternalEvent>,
peers: Arc<RwLock<HashMap<String, NetworkPeer>>>,
peer_event_tx: broadcast::Sender<NetworkPeerEvent>,
health: Arc<RwLock<HealthInfo>>,
identity: Arc<std::sync::RwLock<NodeIdentity>>,
local_addr: Arc<std::sync::RwLock<PeerAddr>>,
local_tailscale_id: Arc<std::sync::RwLock<Option<String>>>,
state: Arc<RwLock<ProviderState>>,
started_tx: Option<oneshot::Sender<Result<(), NetworkError>>>,
app_id: String,
) {
tokio::spawn(async move {
let mut started_tx = started_tx;
loop {
match sidecar_rx.recv().await {
Ok(event) => {
match event {
SidecarInternalEvent::Started {
hostname,
dns_name,
tailscale_ip,
node_id,
} => {
let ip: Option<IpAddr> = tailscale_ip.parse().ok();
{
let mut id = identity.write().unwrap();
// `tailscale_hostname` is already populated
// from the config at construction time. We
// overwrite it with whatever the sidecar
// actually registered (Tailscale may append
// `-2`, `-3`, … for hostname collisions).
id.tailscale_hostname = hostname.clone();
id.dns_name = Some(dns_name.clone());
id.ip = ip;
if !node_id.is_empty() {
id.tailscale_id = node_id.clone();
}
}
// Capture the local Tailscale stable ID for
// self-filtering in the peer event chain.
if !node_id.is_empty() {
*local_tailscale_id.write().unwrap() = Some(node_id);
}
{
let mut addr = local_addr.write().unwrap();
addr.hostname = hostname;
addr.dns_name = Some(dns_name);
addr.ip = ip;
}
{
let mut h = health.write().await;
h.state = "running".to_string();
h.healthy = true;
}
*state.write().await = ProviderState::Running;
// Signal start() that we're ready
if let Some(tx) = started_tx.take() {
let _ = tx.send(Ok(()));
}
}
SidecarInternalEvent::AuthRequired { auth_url } => {
tracing::info!("tailscale auth required: {auth_url}");
// Emit auth URL via peer events so callers can display it.
// Do NOT consume started_tx — keep waiting for Running state.
let _ = peer_event_tx
.send(NetworkPeerEvent::AuthRequired { url: auth_url });
}
SidecarInternalEvent::Stopped => {
*state.write().await = ProviderState::Stopped;
let mut h = health.write().await;
h.state = "stopped".to_string();
h.healthy = false;
tracing::info!("tailscale provider stopped");
return;
}
SidecarInternalEvent::StateChange { state: new_state } => {
let mut h = health.write().await;
h.state = new_state;
}
SidecarInternalEvent::KeyExpiring { expires_at } => {
let mut h = health.write().await;
h.key_expiry = Some(expires_at);
}
SidecarInternalEvent::HealthWarning { warnings } => {
let mut h = health.write().await;
h.warnings = warnings;
h.healthy = h.warnings.is_empty();
}
SidecarInternalEvent::PeersReceived(sidecar_peers) => {
let mut peer_map = peers.write().await;
// Self-filter by Tailscale stable ID, not by
// hostname — hostname collisions from crashed/
// restarted dev runs can cause the local node
// to appear as its own peer under a different
// Tailscale ID.
let self_id = local_tailscale_id.read().unwrap().clone();
// Filter to peers that belong to our app AND
// are not ourselves.
let new_peers: HashMap<String, NetworkPeer> = sidecar_peers
.iter()
.filter(|p| {
if let Some(ref me) = self_id {
if p.id == *me {
return false;
}
}
is_app_peer(&p.hostname, &app_id)
})
.map(|p| {
let np = Self::sidecar_peer_to_network_peer(p);
(np.id.clone(), np)
})
.collect();
// Detect joins, leaves, and updates
for (id, new_peer) in &new_peers {
if let Some(_existing) = peer_map.get(id) {
let _ = peer_event_tx
.send(NetworkPeerEvent::Updated(new_peer.clone()));
} else {
let _ = peer_event_tx
.send(NetworkPeerEvent::Joined(new_peer.clone()));
}
}
for id in peer_map.keys() {
if !new_peers.contains_key(id) {
let _ =
peer_event_tx.send(NetworkPeerEvent::Left(id.clone()));
}
}
*peer_map = new_peers;
}
SidecarInternalEvent::PeerChanged(change) => {
let mut peer_map = peers.write().await;
// Self-filter by Tailscale stable ID, not
// by hostname — see comment in PeersReceived.
let self_id = local_tailscale_id.read().unwrap().clone();
match change.change_type.as_str() {
"joined" => {
if let Some(p) = change.peer {
if let Some(ref me) = self_id {
if p.id == *me {
continue;
}
}
if is_app_peer(&p.hostname, &app_id) {
let np = Self::sidecar_peer_to_network_peer(&p);
peer_map.insert(np.id.clone(), np.clone());
let _ = peer_event_tx
.send(NetworkPeerEvent::Joined(np));
}
}
}
"left" => {
if peer_map.remove(&change.peer_id).is_some() {
let _ = peer_event_tx
.send(NetworkPeerEvent::Left(change.peer_id));
}
}
"updated" => {
if let Some(p) = change.peer {
if let Some(ref me) = self_id {
if p.id == *me {
continue;
}
}
if is_app_peer(&p.hostname, &app_id) {
let np = Self::sidecar_peer_to_network_peer(&p);
peer_map.insert(np.id.clone(), np.clone());
let _ = peer_event_tx
.send(NetworkPeerEvent::Updated(np));
}
}
}
other => {
tracing::warn!("unknown peer change type: {other}");
}
}
}
SidecarInternalEvent::Error { code, message } => {
tracing::error!("sidecar error [{code}]: {message}");
// If start() is still waiting and this is a fatal error
if let Some(tx) = started_tx.take() {
let _ = tx.send(Err(NetworkError::SidecarError(format!(
"[{code}] {message}"
))));
}
}
SidecarInternalEvent::ProcessExited { exit_code } => {
tracing::error!("sidecar process exited: {exit_code:?}");
*state.write().await = ProviderState::Stopped;
let mut h = health.write().await;
h.state = "crashed".to_string();
h.healthy = false;
if let Some(tx) = started_tx.take() {
let _ = tx.send(Err(NetworkError::SidecarError(format!(
"process exited with code {exit_code:?}"
))));
}
return;
}
// Dial/Listen/Ping results are handled by the caller,
// not the background event processor
_ => {}
}
}
Err(broadcast::error::RecvError::Lagged(n)) => {
tracing::warn!("event processor lagged by {n} events");
}
Err(broadcast::error::RecvError::Closed) => {
tracing::info!("sidecar event channel closed, stopping event processor");
return;
}
}
}
});
}
}
/// Check if a hostname belongs to a truffle node in the given app.
///
/// RFC 017 §4: every truffle-managed Tailscale hostname has the shape
/// `truffle-{app_id}-{slug(device_name)}`. The prefix `truffle-{app_id}-`
/// is used to admit peers from our own application and reject peers from
/// other apps on the same tailnet. A hostname that matches the prefix but
/// has no trailing slug is rejected — we require at least one character
/// after the separator so that `truffle-playground-` (empty slug edge)
/// cannot masquerade as a real peer.
pub(crate) fn is_app_peer(hostname: &str, app_id: &str) -> bool {
let prefix = format!("truffle-{app_id}-");
hostname.len() > prefix.len() && hostname.starts_with(&prefix)
}
impl super::super::NetworkProvider for TailscaleProvider {
async fn start(&mut self) -> Result<(), NetworkError> {
{
let current_state = *self.state.read().await;
if current_state != ProviderState::Stopped {
return Err(NetworkError::AlreadyRunning);
}
}
*self.state.write().await = ProviderState::Starting;
// Generate session token
let token = Self::generate_session_token()?;
let token_hex = hex::encode(token);
*self.session_token.write().await = token;
// Start the bridge
let bridge = Bridge::bind(token).await?;
let bridge_port = bridge.local_port()?;
let bridge = Arc::new(bridge);
// Create bridge shutdown channel
let (bridge_shutdown_tx, bridge_shutdown_rx) = tokio::sync::watch::channel(false);
// Run bridge accept loop
{
let bridge_clone = bridge.clone();
tokio::spawn(async move {
bridge_clone.run(bridge_shutdown_rx).await;
});
}
*self.bridge.lock().await = Some(bridge.clone());
*self.bridge_shutdown_tx.lock().await = Some(bridge_shutdown_tx);
// Build sidecar config
let sidecar_config = SidecarConfig {
binary_path: self.config.binary_path.clone(),
hostname: self.config.hostname.clone(),
state_dir: self.config.state_dir.clone(),
auth_key: self.config.auth_key.clone(),
bridge_port,
session_token_hex: token_hex,
ephemeral: self.config.ephemeral,
tags: self.config.tags.clone(),
};
// Spawn the sidecar
let (sidecar, sidecar_rx) = GoSidecar::spawn(sidecar_config.clone()).await?;
// Create a channel for the event processor to signal when we're running
let (started_tx, started_rx) = oneshot::channel();
// Start event processor
Self::spawn_event_processor(
sidecar_rx,
self.peers.clone(),
self.peer_event_tx.clone(),
self.health.clone(),
self.identity.clone(),
self.local_addr.clone(),
self.local_tailscale_id.clone(),
self.state.clone(),
Some(started_tx),
self.config.app_id.clone(),
);
// Send start command to sidecar
sidecar.send_start(&sidecar_config).await?;
*self.sidecar.lock().await = Some(sidecar);
// Wait for the sidecar to reach "running" state.
// Use a generous timeout (5 min) because browser auth may take a while.
// Auth URLs are emitted via peer_events() so the caller can display them.
let auth_timeout = Duration::from_secs(300);
let result = tokio::time::timeout(auth_timeout, started_rx)
.await
.map_err(|_| {
NetworkError::StartFailed(
"timed out waiting for authentication (5 min). \
Subscribe to peer_events() to display auth URLs."
.into(),
)
})?
.map_err(|_| NetworkError::StartFailed("start signal channel dropped".into()))?;
match result {
Ok(()) => {
// Fetch initial peer list
if let Some(ref sidecar) = *self.sidecar.lock().await {
let _ = sidecar.send_get_peers().await;
// Also start WatchIPNBus for real-time peer events
let _ = sidecar.send_watch_peers().await;
}
tracing::info!("tailscale provider started successfully");
Ok(())
}
Err(e) => {
*self.state.write().await = ProviderState::Stopped;
Err(e)
}
}
}
async fn stop(&mut self) -> Result<(), NetworkError> {
*self.state.write().await = ProviderState::Stopping;
// Shut down sidecar
if let Some(sidecar) = self.sidecar.lock().await.take() {
sidecar.shutdown().await;
}
// Shut down bridge
if let Some(tx) = self.bridge_shutdown_tx.lock().await.take() {
let _ = tx.send(true);
}
*self.bridge.lock().await = None;
// Clear state
self.peers.write().await.clear();
*self.state.write().await = ProviderState::Stopped;
let mut h = self.health.write().await;
h.state = "stopped".to_string();
h.healthy = false;
tracing::info!("tailscale provider stopped");
Ok(())
}
fn local_identity(&self) -> NodeIdentity {
self.identity.read().unwrap().clone()
}
fn local_addr(&self) -> PeerAddr {
self.local_addr.read().unwrap().clone()
}
fn peer_events(&self) -> broadcast::Receiver<NetworkPeerEvent> {
self.peer_event_tx.subscribe()
}
async fn peers(&self) -> Vec<NetworkPeer> {
self.peers.read().await.values().cloned().collect()
}
async fn dial_tcp(&self, addr: &str, port: u16) -> Result<TcpStream, NetworkError> {
if *self.state.read().await != ProviderState::Running {
return Err(NetworkError::NotRunning);
}
let bridge = self
.bridge
.lock()
.await
.clone()
.ok_or(NetworkError::NotRunning)?;
// Generate a unique request ID
let request_id = uuid::Uuid::new_v4().to_string();
// Register the pending dial before sending the command
let dial_rx = bridge.register_dial(request_id.clone()).await;
// Scope the sidecar lock: subscribe + send, then release
let mut event_rx = {
let sidecar_guard = self.sidecar.lock().await;
let sidecar = sidecar_guard.as_ref().ok_or(NetworkError::NotRunning)?;
let event_rx = sidecar.subscribe();
sidecar
.send_dial(request_id.clone(), addr.to_string(), port)
.await?;
event_rx
};
// Wait for either:
// 1. Bridge delivers the TcpStream (success path)
// 2. Sidecar reports dial failure via event (error path)
// 3. Timeout
//
// The bridge delivers the TcpStream once the Go sidecar bridges the
// connection back. If the sidecar reports a failure, we get that via
// the event channel and abort early.
let result = tokio::time::timeout(DIAL_TIMEOUT, async {
// Spawn a task to watch for dial failure events.
// We keep the JoinHandle so we can abort it once the select resolves,
// preventing an orphaned task that would loop forever.
let fail_request_id = request_id.clone();
let (fail_tx, fail_rx) = oneshot::channel::<String>();
let fail_watcher: JoinHandle<()> = tokio::spawn(async move {
loop {
match event_rx.recv().await {
Ok(SidecarInternalEvent::DialFailed {
request_id: rid,
error,
}) if rid == fail_request_id => {
let _ = fail_tx.send(error);
return;
}
Err(broadcast::error::RecvError::Closed) => {
let _ = fail_tx.send("event channel closed".to_string());
return;
}
_ => continue,
}
}
});
let result = tokio::select! {
stream_result = dial_rx => {
stream_result.map_err(|_| NetworkError::DialFailed("dial cancelled".into()))
}
fail_result = fail_rx => {
let error = fail_result.unwrap_or_else(|_| "dial watcher dropped".to_string());
Err(NetworkError::DialFailed(error))
}
};
// Cancel the fail-watcher task so it doesn't leak
fail_watcher.abort();
result
})
.await
.map_err(|_| NetworkError::DialTimeout(DIAL_TIMEOUT))?;
// Clean up pending dial on any error
if result.is_err() {
bridge.remove_dial(&request_id).await;
}
result
}
async fn listen_tcp(&self, port: u16) -> Result<NetworkTcpListener, NetworkError> {
if *self.state.read().await != ProviderState::Running {
return Err(NetworkError::NotRunning);
}
let bridge = self
.bridge
.lock()
.await
.clone()
.ok_or(NetworkError::NotRunning)?;
// Create channel for incoming connections
let (tx, rx) = mpsc::channel::<IncomingConnection>(64);
// Scope the sidecar lock: subscribe + send listen, then release
let mut event_rx = {
let sidecar_guard = self.sidecar.lock().await;
let sidecar = sidecar_guard.as_ref().ok_or(NetworkError::NotRunning)?;
let event_rx = sidecar.subscribe();
sidecar.send_listen(port, None).await?;
event_rx
};
// Wait for confirmation or error.
// When port is 0, the sidecar assigns an ephemeral port and reports
// the actual port in the Listening event.
let actual_port = tokio::time::timeout(Duration::from_secs(10), async {
loop {
match event_rx.recv().await {
Ok(SidecarInternalEvent::Listening { port: p }) if port == 0 || p == port => {
return Ok(p);
}
Ok(SidecarInternalEvent::Error { code, message }) => {
return Err(NetworkError::ListenFailed(format!("[{code}] {message}")));
}
Err(broadcast::error::RecvError::Closed) => {
return Err(NetworkError::SidecarError("event channel closed".into()));
}
_ => continue,
}
}
})
.await
.map_err(|_| NetworkError::ListenFailed("listen confirmation timed out".into()))??;
// Register the channel with the bridge using the actual port
bridge.register_listener(actual_port, tx).await;
Ok(NetworkTcpListener {
port: actual_port,
incoming: rx,
})
}
async fn unlisten_tcp(&self, port: u16) -> Result<(), NetworkError> {
if *self.state.read().await != ProviderState::Running {
return Err(NetworkError::NotRunning);
}
let bridge = self
.bridge
.lock()
.await
.clone()
.ok_or(NetworkError::NotRunning)?;
// Remove bridge listener
bridge.remove_listener(port).await;
// Tell sidecar to stop listening
{
let sidecar_guard = self.sidecar.lock().await;
let sidecar = sidecar_guard.as_ref().ok_or(NetworkError::NotRunning)?;
sidecar.send_unlisten(port).await?;
}
Ok(())
}
async fn ping(&self, addr: &str) -> Result<PingResult, NetworkError> {
if *self.state.read().await != ProviderState::Running {
return Err(NetworkError::NotRunning);
}
let target = addr.to_string();
// Scope the sidecar lock: subscribe + send ping, then release
let mut event_rx = {
let sidecar_guard = self.sidecar.lock().await;
let sidecar = sidecar_guard.as_ref().ok_or(NetworkError::NotRunning)?;
let event_rx = sidecar.subscribe();
sidecar.send_ping(target.clone(), None).await?;
event_rx
};
// Wait for result
let result = tokio::time::timeout(Duration::from_secs(15), async {
loop {
match event_rx.recv().await {
Ok(SidecarInternalEvent::PingResult(data)) if data.target == target => {
if !data.error.is_empty() {
return Err(NetworkError::PingFailed(data.error));
}
let connection = if data.direct {
"direct".to_string()
} else if !data.relay.is_empty() {
format!("relay:{}", data.relay)
} else {
"unknown".to_string()
};
return Ok(PingResult {
latency: Duration::from_secs_f64(data.latency_ms / 1000.0),
connection,
peer_addr: if data.peer_addr.is_empty() {
None
} else {
Some(data.peer_addr)
},
});
}
Err(broadcast::error::RecvError::Closed) => {
return Err(NetworkError::SidecarError("event channel closed".into()));
}
_ => continue,
}
}
})
.await
.map_err(|_| NetworkError::PingFailed("ping timed out".into()))?;
result
}
async fn bind_udp(&self, port: u16) -> Result<super::super::NetworkUdpSocket, NetworkError> {
if *self.state.read().await != ProviderState::Running {
return Err(NetworkError::NotRunning);
}
// Scope the sidecar lock: subscribe + send listenPacket, then release
let mut event_rx = {
let sidecar_guard = self.sidecar.lock().await;
let sidecar = sidecar_guard.as_ref().ok_or(NetworkError::NotRunning)?;
let event_rx = sidecar.subscribe();
sidecar.send_listen_packet(port).await?;
event_rx
};
// Wait for the sidecar to report the local relay port
let local_port = tokio::time::timeout(Duration::from_secs(10), async {
loop {
match event_rx.recv().await {
Ok(SidecarInternalEvent::ListeningPacket {
port: p,
local_port,
}) if p == port => {
return Ok(local_port);
}
Ok(SidecarInternalEvent::Error { code, message }) => {
return Err(NetworkError::ListenFailed(format!(
"UDP bind failed [{code}] {message}"
)));
}
Err(broadcast::error::RecvError::Closed) => {
return Err(NetworkError::SidecarError("event channel closed".into()));
}
_ => continue,
}
}
})
.await
.map_err(|_| {
NetworkError::ListenFailed("UDP listenPacket confirmation timed out".into())
})??;
// Bind a local UDP socket and connect it to the relay
let local_socket = tokio::net::UdpSocket::bind("127.0.0.1:0")
.await
.map_err(|e| NetworkError::Internal(format!("failed to bind local UDP socket: {e}")))?;
local_socket
.connect(format!("127.0.0.1:{local_port}"))
.await
.map_err(|e| {
NetworkError::Internal(format!("failed to connect local UDP socket to relay: {e}"))
})?;
let rust_local_addr = local_socket
.local_addr()
.map_err(|e| NetworkError::Internal(format!("failed to get local UDP addr: {e}")))?;
// Send a registration packet so the relay learns our address.
// Without this, the relay drops inbound packets because it doesn't
// know where to forward them (it learns the Rust peer address from
// the first outbound packet).
local_socket
.send(b"TRUFFLE_UDP_REGISTER")
.await
.map_err(|e| NetworkError::Internal(format!("failed to send UDP registration: {e}")))?;
tracing::info!(
tsnet_port = port,
relay_port = local_port,
rust_local_addr = %rust_local_addr,
"UDP socket bound via tsnet relay (registered)"
);
Ok(super::super::NetworkUdpSocket::new(local_socket, port))
}
async fn health(&self) -> HealthInfo {
self.health.read().await.clone()
}
// ── Reverse proxy ─────────────────────────────────────────────────
async fn proxy_add(&self, config: ProxyAddParams) -> Result<ProxyAddResult, NetworkError> {
if *self.state.read().await != ProviderState::Running {
return Err(NetworkError::NotRunning);
}
// Scope the sidecar lock: subscribe + send command, then release
let mut event_rx = {
let sidecar_guard = self.sidecar.lock().await;
let sidecar = sidecar_guard.as_ref().ok_or(NetworkError::NotRunning)?;
let event_rx = sidecar.subscribe();
sidecar
.send_proxy_add(ProxyAddCommandData {
id: config.id.clone(),
name: config.name.clone(),
listen_port: config.listen_port,
target_host: config.target_host.clone(),
target_port: config.target_port,
target_scheme: config.target_scheme.clone(),
})
.await?;
event_rx
};
// Wait for confirmation or error
tokio::time::timeout(Duration::from_secs(10), async {
loop {
match event_rx.recv().await {
Ok(SidecarInternalEvent::ProxyAdded {
id,
listen_port,
url,
}) if id == config.id => {
return Ok(ProxyAddResult {
id,
listen_port,
url,
});
}
Ok(SidecarInternalEvent::ProxyError { id, code, message })
if id == config.id =>
{
return Err(NetworkError::ProxyError(format!("[{code}] {message}")));
}
Ok(SidecarInternalEvent::Error { code, message }) => {
return Err(NetworkError::ProxyError(format!("[{code}] {message}")));
}
Err(broadcast::error::RecvError::Closed) => {
return Err(NetworkError::SidecarError("event channel closed".into()));
}
Err(broadcast::error::RecvError::Lagged(_)) => {
return Err(NetworkError::SidecarError(
"event channel lagged: proxy confirmation may have been lost".into(),
));
}
Ok(_) => continue,
}
}
})
.await
.map_err(|_| NetworkError::ProxyError("proxy add timed out".into()))?
}
async fn proxy_remove(&self, id: &str) -> Result<(), NetworkError> {
if *self.state.read().await != ProviderState::Running {
return Err(NetworkError::NotRunning);
}
let target_id = id.to_string();
// Scope the sidecar lock: subscribe + send command, then release
let mut event_rx = {
let sidecar_guard = self.sidecar.lock().await;
let sidecar = sidecar_guard.as_ref().ok_or(NetworkError::NotRunning)?;
let event_rx = sidecar.subscribe();
sidecar.send_proxy_remove(id).await?;
event_rx
};
// Wait for confirmation or error
tokio::time::timeout(Duration::from_secs(10), async {
loop {
match event_rx.recv().await {
Ok(SidecarInternalEvent::ProxyRemoved { id }) if id == target_id => {
return Ok(());
}
Ok(SidecarInternalEvent::ProxyError { id, code, message })
if id == target_id =>
{
return Err(NetworkError::ProxyError(format!("[{code}] {message}")));
}
Ok(SidecarInternalEvent::Error { code, message }) => {
return Err(NetworkError::ProxyError(format!("[{code}] {message}")));
}
Err(broadcast::error::RecvError::Closed) => {
return Err(NetworkError::SidecarError("event channel closed".into()));
}
Err(broadcast::error::RecvError::Lagged(_)) => {
return Err(NetworkError::SidecarError(
"event channel lagged: proxy confirmation may have been lost".into(),
));
}
Ok(_) => continue,
}
}
})
.await
.map_err(|_| NetworkError::ProxyError("proxy remove timed out".into()))?
}
async fn proxy_list(&self) -> Result<Vec<ProxyListEntry>, NetworkError> {
if *self.state.read().await != ProviderState::Running {
return Err(NetworkError::NotRunning);
}
// Scope the sidecar lock: subscribe + send command, then release
let mut event_rx = {
let sidecar_guard = self.sidecar.lock().await;
let sidecar = sidecar_guard.as_ref().ok_or(NetworkError::NotRunning)?;
let event_rx = sidecar.subscribe();
sidecar.send_proxy_list().await?;
event_rx
};
// Wait for the list response
tokio::time::timeout(Duration::from_secs(10), async {
loop {
match event_rx.recv().await {
Ok(SidecarInternalEvent::ProxyList { proxies }) => {
return Ok(proxies
.into_iter()
.map(|p| ProxyListEntry {
id: p.id,
name: p.name,
listen_port: p.listen_port,
target_host: p.target_host,
target_port: p.target_port,
target_scheme: p.target_scheme,
url: p.url,
})
.collect());
}
Ok(SidecarInternalEvent::Error { code, message }) => {
return Err(NetworkError::ProxyError(format!("[{code}] {message}")));
}
Err(broadcast::error::RecvError::Closed) => {
return Err(NetworkError::SidecarError("event channel closed".into()));
}
Err(broadcast::error::RecvError::Lagged(_)) => {
return Err(NetworkError::SidecarError(
"event channel lagged: proxy confirmation may have been lost".into(),
));
}
Ok(_) => continue,
}
}
})
.await
.map_err(|_| NetworkError::ProxyError("proxy list timed out".into()))?
}
}
impl TailscaleProvider {
/// Get the local identity (convenience alias — same as the trait method).
///
/// Retained for backwards compatibility with existing callers that used
/// the old async version.
pub async fn local_identity_async(&self) -> NodeIdentity {
self.identity.read().unwrap().clone()
}
/// Get the local address (convenience alias — same as the trait method).
///
/// Retained for backwards compatibility with existing callers that used
/// the old async version.
pub async fn local_addr_async(&self) -> PeerAddr {
self.local_addr.read().unwrap().clone()
}
}