Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix: pair computers that have many networks

leepokai57537a1e5d52
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
index 8c6d330f..8fc6ff01 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
@@ -24,7 +24,7 @@ data class Computer(
fun validate() {
require(RelayCrypto.computerId(signKey.decodeBase64Url(32)) == id) { "This computer's identity changed. Pair it again." }
boxKey?.decodeBase64Url(32)
- require(urls.size <= 16 && urls.all(::isDirectUrl)) { "Invalid computer address" }
+ require(urls.size <= MAX_URLS && urls.all(::isDirectUrl)) { "Invalid computer address" }
require(cloud == null || isCloudUrl(cloud)) { "Invalid cloud address" }
}
}
@@ -35,6 +35,12 @@ fun Iterable<Computer>.currentId(last: String?): String? = last?.takeIf { id ->
@Serializable
enum class ConnectionRoute { Automatic, CloudflareFirst, DirectOnly }
+/** Phones keep at most this many direct addresses; a computer with many networks sends more, best first. */
+internal const val MAX_URLS = 16
+
+/** The direct addresses kept from a computer's list: valid ones, once each, the best [MAX_URLS]. */
+internal fun directUrls(urls: Iterable<String>): List<String> = urls.filter(::isDirectUrl).distinct().take(MAX_URLS)
+
internal fun isDirectUrl(value: String): Boolean {
val url = value.toHttpUrlOrNull() ?: return false
return url.username.isEmpty() && url.password.isEmpty() && url.fragment == null
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
index 0406744e..bd9348f2 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
@@ -113,7 +113,7 @@ object HostClient {
val updated = computer.copy(
name = hello.text("name")?.takeIf(String::isNotBlank) ?: computer.name,
boxKey = hello.text("boxKey") ?: computer.boxKey,
- urls = hello["urls"]?.jsonArray?.map { it.jsonPrimitive.content }?.filter(::isDirectUrl) ?: computer.urls,
+ urls = hello["urls"]?.jsonArray?.map { it.jsonPrimitive.content }?.let(::directUrls) ?: computer.urls,
cloud = hello.text("cloud"),
)
updated.validate()
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
index a8e797f9..b79396da 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt
@@ -39,7 +39,7 @@ data class Pairing(val computer: Computer, val code: String) {
name = params["name"]?.takeIf(String::isNotBlank) ?: "My computer",
signKey = requireNotNull(params["sk"]),
boxKey = requireNotNull(params["bk"]),
- urls = params["urls"].orEmpty().split(',').filter { it.isNotEmpty() && isDirectUrl(it) }.distinct(),
+ urls = directUrls(params["urls"].orEmpty().split(',')),
cloud = params["cloud"]?.takeIf(String::isNotEmpty),
)
computer.validate()
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
index 5ff3be29..55aa2d4a 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt
@@ -64,6 +64,12 @@ class PairingTest {
assertFails<IllegalArgumentException> { Pairing.parse(link(params + ("urls" to "ftp://host.test") - "cloud"), "codync") }
}
+ @Test fun `a computer with many networks pairs with its best sixteen addresses`() {
+ val urls = (1..30).map { "http://172.${it + 1}.0.1:19222" }
+ val pairing = Pairing.parse(link(params + ("urls" to urls.joinToString(","))), "codync")
+ assertEquals(urls.take(16), pairing.computer.urls)
+ }
+
@Test fun `strict base64url refuses padding noncanonical bits and wrong lengths`() {
for (value in listOf("AA=", "AB", "A", "+A", "AA ")) assertFails<IllegalArgumentException> { value.decodeBase64Url() }
assertFails<IllegalArgumentException> { "AA".decodeBase64Url(32) }
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index c180f206..0bbe9bac 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -134,7 +134,7 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair
| `id` | 是 | 必須等於 `computerId(sk)`,否則拒絕 |
| `sk`, `bk` | 是 | host 公鑰 |
| `code` | 是 | 16 random bytes,b64url;一次性、10 分鐘;host 最多同時 5 組(新的擠掉最舊的) |
-| `urls` | 否 | 直連候選(`service::addresses`):先 `CODYNC_EXTERNAL_URL` 設的網址(`https://host` 等,只能是 host 根路徑),再 Tailscale,再 LAN(`http://ip:port`);可為空 |
+| `urls` | 否 | 直連候選(`service::addresses`):先 `CODYNC_EXTERNAL_URL` 設的網址(`https://host` 等,只能是 host 根路徑),再 Tailscale,再 LAN(`http://ip:port`,略過 Docker、Podman、Kubernetes、libvirt、LXD 的容器橋接介面);最多 16 個(手機只留前 16 個);可為空 |
| `cloud` | 否 | host 使用的 cloud base URL(`https://…`;DEBUG build 另允許 `http://127.0.0.1:*`/`http://localhost:*`);缺 = host 關閉雲端 |
| `name` | 否 | 顯示名稱 |
diff --git a/host/src/service/addresses.rs b/host/src/service/addresses.rs
new file mode 100644
index 00000000..7055570c
--- /dev/null
+++ b/host/src/service/addresses.rs
@@ -0,0 +1,111 @@
+//! The addresses phones dial this host at, sent in the pairing link and every `hello`.
+
+use serde_json::Value;
+use std::process::Command;
+use std::sync::LazyLock;
+
+/// Phones keep at most this many addresses, best first (the Android app refuses a longer list).
+const MAX_ADDRESSES: usize = 16;
+
+/// Addresses the phone can try, best first: the ones set in `CODYNC_EXTERNAL_URL`, Tailscale, then LAN.
+pub fn addresses(port: u16) -> Vec<String> {
+ // Read once: every hello asks, and a bad entry warns once.
+ static EXTERNAL: LazyLock<Vec<String>> =
+ LazyLock::new(|| external_urls(&std::env::var("CODYNC_EXTERNAL_URL").unwrap_or_default()));
+ let mut tailscale = vec![];
+ let mut lan = vec![];
+ for iface in if_addrs::get_if_addrs().unwrap_or_default() {
+ if iface.is_loopback() || is_container_bridge(&iface.name) {
+ continue;
+ }
+ if let std::net::IpAddr::V4(ip) = iface.ip() {
+ let o = ip.octets();
+ // 100.64.0.0/10 is Tailscale's CGNAT range.
+ if o[0] == 100 && (64..128).contains(&o[1]) {
+ tailscale.push(format!("http://{ip}:{port}"));
+ } else if ip.is_private() {
+ lan.push(format!("http://{ip}:{port}"));
+ }
+ }
+ }
+ if let Ok(out) = Command::new("tailscale").args(["status", "--json"]).output()
+ && let Ok(v) = serde_json::from_slice::<Value>(&out.stdout)
+ && let Some(dns) = v["Self"]["DNSName"].as_str()
+ {
+ let dns = dns.trim_end_matches('.');
+ if !dns.is_empty() {
+ tailscale.insert(0, format!("http://{dns}:{port}"));
+ }
+ }
+ tailscale.sort();
+ tailscale.dedup();
+ lan.sort();
+ lan.dedup();
+ EXTERNAL.iter().cloned().chain(tailscale).chain(lan).take(MAX_ADDRESSES).collect()
+}
+
+/// A bridge that containers or VMs on this computer sit behind (Docker, Podman, Kubernetes, libvirt, LXD).
+/// No phone reaches the host through one, and a server with many Docker networks has dozens.
+fn is_container_bridge(name: &str) -> bool {
+ const PREFIXES: [&str; 12] =
+ ["docker", "br-", "veth", "virbr", "lxcbr", "lxdbr", "cni", "flannel", "cali", "weave", "podman", "kube"];
+ PREFIXES.iter().any(|prefix| name.starts_with(prefix))
+}
+
+/// Where phones reach this host besides its own interfaces, such as an HTTPS reverse proxy that forwards
+/// `/channel`: comma-separated `http(s)://` URLs at the root of a host (phones dial `<url>/channel`). The pairing
+/// link and every `hello` carry them, so a phone keeps them when it refreshes its addresses.
+fn external_urls(var: &str) -> Vec<String> {
+ var.split(',')
+ .map(str::trim)
+ .filter(|u| !u.is_empty())
+ .filter_map(|u| match reqwest::Url::parse(u) {
+ Ok(url)
+ if matches!(url.scheme(), "http" | "https")
+ && url.host().is_some()
+ && url.username().is_empty()
+ && url.password().is_none()
+ && url.path() == "/"
+ && url.query().is_none()
+ && url.fragment().is_none() =>
+ {
+ Some(url.as_str().trim_end_matches('/').to_owned())
+ }
+ _ => {
+ tracing::warn!(
+ url = u,
+ "CODYNC_EXTERNAL_URL entry isn't an http(s) URL at the root of a host (no user or password); ignored"
+ );
+ None
+ }
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn external_urls_keep_http_addresses_only() {
+ assert_eq!(
+ external_urls(
+ " https://codync.example.com/ , ftp://x, nonsense,http://10.0.0.2:8080,https://x.com/codync,https://x.com/?a,https://u:[email protected]"
+ ),
+ ["https://codync.example.com", "http://10.0.0.2:8080"]
+ );
+ assert_eq!(external_urls(""), [] as [String; 0]);
+ }
+
+ #[test]
+ fn container_bridges_are_not_addresses() {
+ for name in
+ ["docker0", "docker_gwbridge", "br-3f2a9c1d7e4b", "veth12ab", "virbr0", "lxdbr0", "cni0", "flannel.1"]
+ {
+ assert!(is_container_bridge(name), "{name}");
+ }
+ for name in ["eth0", "enp0s3", "en0", "wlan0", "br0", "bridge0", "tailscale0", "ens3"] {
+ assert!(!is_container_bridge(name), "{name}");
+ }
+ }
+}
diff --git a/host/src/service/mod.rs b/host/src/service/mod.rs
index da71ee2a..0d03acbf 100644
--- a/host/src/service/mod.rs
+++ b/host/src/service/mod.rs
@@ -13,9 +13,12 @@ use sha2::{Digest, Sha256};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
-use std::sync::{LazyLock, OnceLock};
+use std::sync::OnceLock;
use std::time::{Duration, Instant};
+mod addresses;
+pub use addresses::addresses;
+
#[cfg(unix)]
mod unix;
#[cfg(unix)]
@@ -169,73 +172,6 @@ impl KeepAwake {
}
}
-/// Addresses the phone can try, best first: the ones set in `CODYNC_EXTERNAL_URL`, Tailscale, then LAN.
-pub fn addresses(port: u16) -> Vec<String> {
- // Read once: every hello asks, and a bad entry warns once.
- static EXTERNAL: LazyLock<Vec<String>> =
- LazyLock::new(|| external_urls(&std::env::var("CODYNC_EXTERNAL_URL").unwrap_or_default()));
- let mut tailscale = vec![];
- let mut lan = vec![];
- for iface in if_addrs::get_if_addrs().unwrap_or_default() {
- if iface.is_loopback() {
- continue;
- }
- if let std::net::IpAddr::V4(ip) = iface.ip() {
- let o = ip.octets();
- // 100.64.0.0/10 is Tailscale's CGNAT range.
- if o[0] == 100 && (64..128).contains(&o[1]) {
- tailscale.push(format!("http://{ip}:{port}"));
- } else if ip.is_private() {
- lan.push(format!("http://{ip}:{port}"));
- }
- }
- }
- if let Ok(out) = Command::new("tailscale").args(["status", "--json"]).output()
- && let Ok(v) = serde_json::from_slice::<Value>(&out.stdout)
- && let Some(dns) = v["Self"]["DNSName"].as_str()
- {
- let dns = dns.trim_end_matches('.');
- if !dns.is_empty() {
- tailscale.insert(0, format!("http://{dns}:{port}"));
- }
- }
- tailscale.sort();
- tailscale.dedup();
- lan.sort();
- lan.dedup();
- EXTERNAL.iter().cloned().chain(tailscale).chain(lan).collect()
-}
-
-/// Where phones reach this host besides its own interfaces, such as an HTTPS reverse proxy that forwards
-/// `/channel`: comma-separated `http(s)://` URLs at the root of a host (phones dial `<url>/channel`). The pairing
-/// link and every `hello` carry them, so a phone keeps them when it refreshes its addresses.
-fn external_urls(var: &str) -> Vec<String> {
- var.split(',')
- .map(str::trim)
- .filter(|u| !u.is_empty())
- .filter_map(|u| match reqwest::Url::parse(u) {
- Ok(url)
- if matches!(url.scheme(), "http" | "https")
- && url.host().is_some()
- && url.username().is_empty()
- && url.password().is_none()
- && url.path() == "/"
- && url.query().is_none()
- && url.fragment().is_none() =>
- {
- Some(url.as_str().trim_end_matches('/').to_owned())
- }
- _ => {
- tracing::warn!(
- url = u,
- "CODYNC_EXTERNAL_URL entry isn't an http(s) URL at the root of a host (no user or password); ignored"
- );
- None
- }
- })
- .collect()
-}
-
pub fn host_name() -> String {
let n = gethostname::gethostname().to_string_lossy().into_owned();
n.trim_end_matches(".local").to_owned()
@@ -420,17 +356,6 @@ mod tests {
);
}
- #[test]
- fn external_urls_keep_http_addresses_only() {
- assert_eq!(
- external_urls(
- " https://codync.example.com/ , ftp://x, nonsense,http://10.0.0.2:8080,https://x.com/codync,https://x.com/?a,https://u:[email protected]"
- ),
- ["https://codync.example.com", "http://10.0.0.2:8080"]
- );
- assert_eq!(external_urls(""), [] as [String; 0]);
- }
-
#[test]
fn mac_models_map_to_devices() {
assert_eq!(mac_device("MacBook Pro"), Device::Laptop);