Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

Direct connections through a forwarded port; Windows' listener starts hidden

Adib Hanna4bf286a1a7b0
diff --git a/README.md b/README.md
index a46697e..47ee00a 100644
--- a/README.md
+++ b/README.md
@@ -107,6 +107,7 @@ runners = ["mac-studio-01", "mac-studio-02"] # expected runners; missing ones
# user = "ci" port = 2222 ssh_options = ["-i", "~/.ssh/ci"]
# discover = false # don't list runners found but not declared
# notes = "Under the desk"
+# direct_address = "nas.example.com:47822" # where a direct connection reaches it (NAT, a forwarded port)
[[machine]]
name = "StudioNAS" # no runners: shown under "Other machines"
diff --git a/agent/src/direct.rs b/agent/src/direct.rs
index a98ace1..7e17c3b 100644
--- a/agent/src/direct.rs
+++ b/agent/src/direct.rs
@@ -477,11 +477,12 @@ fn install_service() -> (&'static str, Option<String>) {
#[cfg(windows)]
{
// A task at sign-in, in the user's own desktop session (where the
- // screen and clipboard are), started now too; and a way in through
+ // screen and clipboard are), through a windowless console (nothing
+ // shows on their screen), started now too; and a way in through
// Windows' firewall for the agent (administrators only).
let script = format!(
"$exe = {exe}\n\
- $action = New-ScheduledTaskAction -Execute $exe -Argument 'listen'\n\
+ $action = New-ScheduledTaskAction -Execute 'conhost.exe' -Argument ('--headless \"' + $exe + '\" listen')\n\
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME\n\
$principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited\n\
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew\n\
@@ -489,8 +490,8 @@ fn install_service() -> (&'static str, Option<String>) {
try {{ Remove-NetFirewallRule -DisplayName {task} -ErrorAction SilentlyContinue; New-NetFirewallRule -DisplayName {task} -Direction Inbound -Program $exe -Protocol UDP -Action Allow -Profile Any -ErrorAction Stop | Out-Null; $fw = 'yes' }} catch {{ $fw = 'no' }}\n\
Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object {{ $_.CommandLine -match ' listen' }} | ForEach-Object {{ Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }}\n\
Start-ScheduledTask -TaskName {task}\n\
- Start-Sleep -Milliseconds 800\n\
- $running = @(Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object {{ $_.CommandLine -match ' listen' }}).Count -gt 0\n\
+ $running = $false\n\
+ foreach ($i in 1..20) {{ Start-Sleep -Milliseconds 250; if (@(Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object {{ $_.CommandLine -match ' listen' }}).Count) {{ $running = $true; break }} }}\n\
\"fw=$fw running=$running\"",
exe = crate::win::quote(&exe()),
task = crate::win::quote(TASK)
diff --git a/src/config.rs b/src/config.rs
index 743b063..3fc4a14 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -298,6 +298,10 @@ pub struct MachineSpec {
/// at its sessions until it's connected again (its sessions go on there).
#[serde(default)]
pub disconnected: bool,
+ /// Where a direct connection reaches it ("host:port"), when its own
+ /// addresses don't: a VM behind its host's NAT, a router's forwarded port.
+ #[serde(default)]
+ pub direct_address: Option<String>,
}
/// Where a cloud machine lives, as config.toml records it:
diff --git a/src/fleet/connection.rs b/src/fleet/connection.rs
index 26b83f1..df66219 100644
--- a/src/fleet/connection.rs
+++ b/src/fleet/connection.rs
@@ -72,7 +72,10 @@ impl Engine {
machine_id: spec.id.clone(),
via: "none".into(),
direct: paired.is_some(),
- address: paired.as_ref().map(|p| format!("{}:{} (UDP)", p.host, p.port)),
+ address: paired.as_ref().map(|p| match spec.direct_address.as_deref().filter(|a| !a.trim().is_empty()) {
+ Some(a) => format!("{} (UDP, forwarded)", a.trim()),
+ None => format!("{}:{} (UDP)", p.host, p.port),
+ }),
latency_ms: None,
network: None,
peer: None,
@@ -111,7 +114,8 @@ impl Engine {
// Its local-network address didn't answer, so the connection took the
// long way. Away from home that's expected; but when Tailscale itself
// reaches the machine on this network, something here blocked us.
- let lan = paired.as_ref().map(|p| p.lan.clone()).unwrap_or_default();
+ // (A machine reached at an address of its own has no local way to look for.)
+ let lan = if spec.direct_address.is_some() { Vec::new() } else { paired.as_ref().map(|p| p.lan.clone()).unwrap_or_default() };
let long_way = out.via == "direct" && !lan.is_empty() && out.network.as_deref().is_some_and(|n| n != "Local network");
let here = out.tailnet.as_ref().is_some_and(|d| d.path == "direct" && same_network(d, &lan));
if long_way && (here || out.tailnet.is_none()) {
diff --git a/src/fleet/engine/roaming.rs b/src/fleet/engine/roaming.rs
index 5f1d684..f841571 100644
--- a/src/fleet/engine/roaming.rs
+++ b/src/fleet/engine/roaming.rs
@@ -211,6 +211,10 @@ impl Engine {
}
direct::retry_now(id);
}
+ // Reached at an address of its own (a forwarded port): no shorter way.
+ if self.machine(id).is_some_and(|(s, _)| s.direct_address.is_some()) {
+ return;
+ }
let Some(paired) = direct::paired(id).filter(|p| !p.lan.is_empty()) else { return };
if moves().lock().unwrap().get(id).is_some_and(|t| t.elapsed() < MOVE_HOME_PAUSE) {
return;
diff --git a/src/fleet/link.rs b/src/fleet/link.rs
index 04ccae0..3e72931 100644
--- a/src/fleet/link.rs
+++ b/src/fleet/link.rs
@@ -288,6 +288,17 @@ async fn connect(spec: &MachineSpec) -> Result<Arc<Link>, String> {
}
async fn connect_direct(spec: &MachineSpec, paired: &super::direct::Paired) -> Result<Arc<Link>, String> {
+ // Reached at an address of its own choosing (a forwarded port): that one only.
+ let mut paired = paired.clone();
+ if let Some(address) = spec.direct_address.as_deref().map(str::trim).filter(|a| !a.is_empty()) {
+ let (host, port) = match address.rsplit_once(':').map(|(h, p)| (h, p.parse::<u16>())) {
+ Some((h, Ok(p))) => (h.trim_matches(['[', ']']).to_string(), p),
+ _ => (address.to_string(), paired.port),
+ };
+ let ips: Vec<String> = tokio::net::lookup_host((host.as_str(), port)).await.map(|a| a.map(|s| s.ip().to_string()).collect()).unwrap_or_default();
+ paired = super::direct::Paired { lan: ips, tailnet: Vec::new(), host, port, ..paired };
+ }
+ let paired = &paired;
let conn = super::direct::connect(&spec.id, paired).await?;
let peer = conn.remote_address();
let (mut send, recv) = conn.open_bi().await.map_err(|e| e.to_string())?;