garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

cartopolis-agent · 2026-11-28T18:15:51Z

feat(app): contact, invite and guest links name the server they came from

Every link the app made said https://cartopolis.org whatever server it
was signed in to, so a link shared by an organiser on a server of their
own sent people to the wrong one. The origin is now the signed-in
server's (place_link::link_origin, from ConnectAddr through
model_assets::derive_api_base); a self-hosted server's web UI answers
/go itself. Loopback, tcp://, ws:// and the web build's empty address
keep cartopolis.org, since they have no address worth sharing.

Reading back, the host now counts for a contact link: one from another
server gives name@that-server, which the simulator already forwards
with its link code, and open_card_for_name turns a link from one's own
server back into the bare name, because the server looks a local person
up by name only (remote::Link::elsewhere would not strip it). Before,
a link from rug.example read on cartopolis.org asked for whoever had
that name here.
crates/cartopolis/src/systems/gui/communities.rs   |   8 ++
 crates/cartopolis/src/systems/gui/contacts.rs      |  15 +-
 .../cartopolis/src/systems/gui/lib_communities.rs  |   5 +-
 crates/cartopolis/src/systems/nav/place_link.rs    | 158 +++++++++++++++++++--
 crates/cartopolis/src/systems/net/calls.rs         |  23 +--
 5 files changed, 181 insertions(+), 28 deletions(-)

diff --git a/crates/cartopolis/src/systems/gui/communities.rs b/crates/cartopolis/src/systems/gui/communities.rs
index fe1a0191..345db87b 100644
--- a/crates/cartopolis/src/systems/gui/communities.rs
+++ b/crates/cartopolis/src/systems/gui/communities.rs
@@ -187,6 +187,9 @@ pub struct Communities {
     muted_loaded: bool,
     /// The last invite link a moderator made here, for the community it is to.
     pub invite: Option<(Uuid, String)>,
+    /// The address this app is signed in to (`ConnectAddr`), which an invite
+    /// link names (`place_link::link_origin`).
+    pub server: Option<String>,
     /// A code or link typed into Find.
     pub(crate) invite_input: String,
     /// An invite this launch was opened with, until the session is up.
@@ -391,12 +394,17 @@ pub fn sync_device(
     cameras: crate::grid::AnchoredCamera,
     online: Option<Res<crate::resources::OnlineSession>>,
     mut new_link: ResMut<crate::systems::place_link::NewLink>,
+    addr: Option<Res<crate::resources::ConnectAddr>>,
     mut launched: Local<bool>,
 ) {
     if !*launched {
         *launched = true;
         cs.pending_invite = launch_invite();
     }
+    let server = addr.as_deref().map(|a| a.0.as_str());
+    if cs.server.as_deref() != server {
+        cs.server = server.map(str::to_string);
+    }
     // A link tapped while the app already runs (`place_link::take_new_link`):
     // shown over whatever screen was open, because the person just asked for it.
     if let Some(code) = new_link.invite.take() {
diff --git a/crates/cartopolis/src/systems/gui/contacts.rs b/crates/cartopolis/src/systems/gui/contacts.rs
index 314833aa..299a13b4 100644
--- a/crates/cartopolis/src/systems/gui/contacts.rs
+++ b/crates/cartopolis/src/systems/gui/contacts.rs
@@ -229,6 +229,9 @@ pub struct Contacts {
     pub error: Option<String>,
     /// A contact link this launch was opened with: (username, code).
     pub pending_link: Option<(String, String)>,
+    /// The address this app is signed in to (`ConnectAddr`), which the
+    /// contact link names (`place_link::link_origin`).
+    pub server: Option<String>,
     /// Set by a screen each frame it wants [`Self::nearby`] kept fresh.
     pub want_nearby: bool,
     /// Where the people in the chat whose World view is open are, for their
@@ -454,6 +457,10 @@ impl Contacts {
 
     /// Open the person card for a username (a contact link, a nearby row).
     pub fn open_card_for_name(&mut self, username: &str, link_code: Option<String>) {
+        // A link names its server (`sanne@rug.example`); a person on this one
+        // is asked for by name, as the server knows them.
+        let home = crate::systems::place_link::link_home(self.server.as_deref());
+        let username = cartopolis_core::address::display(username, &home);
         let request_id = self.request_id();
         self.card_request = Some(request_id);
         self.card = Some(Card {
@@ -533,7 +540,8 @@ impl Contacts {
     /// This account's contact link.
     #[must_use]
     pub fn my_link(&self, me: &str) -> String {
-        crate::systems::place_link::contact_link(me, &self.settings.link_code)
+        let origin = crate::systems::place_link::link_origin(self.server.as_deref());
+        crate::systems::place_link::contact_link(&origin, me, &self.settings.link_code)
     }
 }
 
@@ -619,6 +627,7 @@ pub fn drive_contacts(
     private: Res<crate::systems::private_chat::PrivateChats>,
     layers: Res<crate::systems::layer_state::DataLayers>,
     mut new_link: ResMut<crate::systems::place_link::NewLink>,
+    addr: Option<Res<crate::resources::ConnectAddr>>,
     mut launched: Local<bool>,
 ) {
     if !*launched {
@@ -641,6 +650,10 @@ pub fn drive_contacts(
         }
         return;
     };
+    let server = addr.as_deref().map(|a| a.0.as_str());
+    if contacts.server.as_deref() != server {
+        contacts.server = server.map(str::to_string);
+    }
     for msg in inbox.0.drain(..) {
         match msg {
             NetMessage::ContactsState {
diff --git a/crates/cartopolis/src/systems/gui/lib_communities.rs b/crates/cartopolis/src/systems/gui/lib_communities.rs
index 1614269d..61a7369b 100644
--- a/crates/cartopolis/src/systems/gui/lib_communities.rs
+++ b/crates/cartopolis/src/systems/gui/lib_communities.rs
@@ -758,7 +758,10 @@ fn fields(f: &Fields, route: &Route, cs: &Communities) {
         cs.invite
             .as_ref()
             .filter(|(i, _)| Some(*i) == shown)
-            .map(|(_, code)| crate::systems::place_link::invite_link(code)),
+            .map(|(_, code)| {
+                let origin = crate::systems::place_link::link_origin(cs.server.as_deref());
+                crate::systems::place_link::invite_link(&origin, code)
+            }),
     );
     let draft = p.draft.as_ref();
     put(
diff --git a/crates/cartopolis/src/systems/nav/place_link.rs b/crates/cartopolis/src/systems/nav/place_link.rs
index d838dd34..47f19ab9 100644
--- a/crates/cartopolis/src/systems/nav/place_link.rs
+++ b/crates/cartopolis/src/systems/nav/place_link.rs
@@ -67,22 +67,80 @@ pub fn web_link(lat: f64, lng: f64, alt: f64, look: Option<(f32, f32)>) -> Strin
     )
 }
 
+/// The origin a contact or invite link made here carries: the server this app
+/// is signed in to (`server`, its `ConnectAddr`), as `https://<its name>`.
+///
+/// A self-hosted server's web UI answers `/go` itself (`static_files`), so a
+/// link naming it opens that server, where one naming cartopolis.org sent
+/// people to the wrong one. A server with no address worth sharing — none yet,
+/// a development simulator on loopback or plain `tcp://`/`ws://`, the web
+/// build's page-relative empty address — keeps [`WEB_ORIGIN`], as every link
+/// did before.
+pub fn link_origin(server: Option<&str>) -> String {
+    server
+        .and_then(crate::systems::model_assets::derive_api_base)
+        .and_then(|base| {
+            let rest = base.strip_prefix("https://")?;
+            let authority = rest.split(['/', '?', '#']).next()?;
+            (!authority.is_empty()).then(|| format!("https://{authority}"))
+        })
+        .unwrap_or_else(|| WEB_ORIGIN.to_string())
+}
+
+/// The server name links made here carry (`cartopolis.org`), for reading a
+/// link back: a person on it is a bare name, anyone else a full address.
+pub fn link_home(server: Option<&str>) -> String {
+    let origin = link_origin(server);
+    url_host(&origin)
+}
+
+/// The server a hosted link names: the host of an `https://` or `http://`
+/// link, unless it is this machine (`trunk serve`, a development page). `None`
+/// for the custom scheme, which names no server.
+fn link_server(input: &str) -> Option<String> {
+    let lower = input.trim().to_ascii_lowercase();
+    if !(lower.starts_with("https://") || lower.starts_with("http://")) {
+        return None;
+    }
+    let host = url_host(&lower);
+    (cartopolis_core::address::is_server_name(&host)
+        && !crate::platform::http::is_loopback_host(&host))
+    .then_some(host)
+}
+
+/// The host of a URL, lowercased, without a port or a `user@`.
+fn url_host(url: &str) -> String {
+    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
+    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
+    let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
+    let host = match authority.rsplit_once(':') {
+        Some((host, port)) if port.chars().all(|c| c.is_ascii_digit()) => host,
+        _ => authority,
+    };
+    host.to_ascii_lowercase()
+}
+
 /// The query key a contact link carries (`systems::contacts`).
 pub const CONTACT_KEY: &str = "contact";
 
-/// A person's contact link: `https://cartopolis.org/go?contact=jeroen~3f9a1c7e22b0`.
+/// A person's contact link on the server `origin` ([`link_origin`]):
+/// `https://cartopolis.org/go?contact=jeroen~3f9a1c7e22b0`.
 ///
 /// On the `/go` path for the reason a place link is (it is the one path the
 /// app claims on Android, and the web client serves it), with the name and the
 /// code joined by `~`, which is not in any username and needs no escaping.
 /// Whoever holds it may send a request whatever the person's setting says;
 /// resetting the code in Contacts ▸ Add is how old copies stop working.
-pub fn contact_link(username: &str, code: &str) -> String {
-    format!("{WEB_ORIGIN}/{LINK_PATH}?{CONTACT_KEY}={username}~{code}")
+pub fn contact_link(origin: &str, username: &str, code: &str) -> String {
+    format!("{origin}/{LINK_PATH}?{CONTACT_KEY}={username}~{code}")
 }
 
-/// The (username, code) a contact link carries, from either scheme and any
-/// host (see [`link_place`] for why the host is not checked).
+/// The (person, code) a contact link carries, from either scheme and any
+/// host. The person is a full address on the server the link names
+/// (`sanne@rug.example`), so somebody signed in elsewhere asks for the right
+/// one; a link with no server in it (the custom scheme, a development page)
+/// gives the bare name. [`cartopolis_core::address::display`] against the
+/// reader's own server turns a link from there back into a bare name.
 pub fn contact_from_link(input: &str) -> Option<(String, String)> {
     if !is_link(input.trim()) {
         return None;
@@ -96,19 +154,29 @@ pub fn contact_from_link(input: &str) -> Option<(String, String)> {
         .map(|(_, v)| percent_decode(v))?;
     let (user, code) = value.split_once('~')?;
     let (user, code) = (user.trim(), code.trim());
-    (!user.is_empty() && !code.is_empty()).then(|| (user.to_string(), code.to_string()))
+    if user.is_empty() || code.is_empty() {
+        return None;
+    }
+    let who = match link_server(input) {
+        Some(server) if cartopolis_core::address::split(user).is_none() => {
+            cartopolis_core::address::person(user, &server)
+        }
+        _ => user.to_string(),
+    };
+    Some((who, code.to_string()))
 }
 
 /// The query key a community invite carries (`systems::communities`).
 pub const COMMUNITY_KEY: &str = "community";
 
-/// A community's invite link: `https://cartopolis.org/go?community=3f9a1c7e22b0`.
+/// A community's invite link on the server `origin` ([`link_origin`]):
+/// `https://cartopolis.org/go?community=3f9a1c7e22b0`.
 ///
 /// On `/go` for the reason a contact link is: it is the one path the app claims
 /// on Android, and the web client serves it, so the link opens whichever of the
 /// two the person has.
-pub fn invite_link(code: &str) -> String {
-    format!("{WEB_ORIGIN}/{LINK_PATH}?{COMMUNITY_KEY}={code}")
+pub fn invite_link(origin: &str, code: &str) -> String {
+    format!("{origin}/{LINK_PATH}?{COMMUNITY_KEY}={code}")
 }
 
 /// The code an invite link carries, from either scheme and any host; a bare
@@ -417,7 +485,7 @@ mod tests {
 
     #[test]
     fn an_invite_link_round_trips() {
-        let link = invite_link("3f9a1c7e22b0");
+        let link = invite_link(WEB_ORIGIN, "3f9a1c7e22b0");
         assert_eq!(link, "https://cartopolis.org/go?community=3f9a1c7e22b0");
         assert_eq!(invite_from_link(&link).as_deref(), Some("3f9a1c7e22b0"));
         assert_eq!(
@@ -434,11 +502,12 @@ mod tests {
 
     #[test]
     fn a_contact_link_reads_back_as_the_name_and_code_it_was_made_from() {
-        let link = contact_link("sanne_k", "3f9a1c7e22b0");
+        let link = contact_link(WEB_ORIGIN, "sanne_k", "3f9a1c7e22b0");
         assert_eq!(
             contact_from_link(&link),
-            Some(("sanne_k".into(), "3f9a1c7e22b0".into()))
+            Some(("sanne_k@cartopolis.org".into(), "3f9a1c7e22b0".into()))
         );
+        // The custom scheme names no server: the reader's own.
         assert_eq!(
             contact_from_link("cartopolis://go?contact=eva~abc#x"),
             Some(("eva".into(), "abc".into()))
@@ -448,6 +517,62 @@ mod tests {
         assert_eq!(contact_from_link("eva~abc"), None);
     }
 
+    /// The tech this exists for: a link made while signed in to a server of
+    /// one's own names that server, and somebody signed in anywhere else reads
+    /// it as the person there.
+    #[test]
+    fn links_name_the_server_they_were_made_on() {
+        let origin = link_origin(Some("rug.example"));
+        assert_eq!(origin, "https://rug.example");
+        assert_eq!(
+            invite_link(&origin, "abc123"),
+            "https://rug.example/go?community=abc123"
+        );
+        let link = contact_link(&origin, "sanne", "c0de");
+        assert_eq!(link, "https://rug.example/go?contact=sanne~c0de");
+        let (who, code) = contact_from_link(&link).unwrap();
+        assert_eq!((who.as_str(), code.as_str()), ("sanne@rug.example", "c0de"));
+        // Read on cartopolis.org it is somebody elsewhere; on rug.example, there.
+        let display = cartopolis_core::address::display;
+        assert_eq!(display(&who, &link_home(Some("cartopolis.org"))), who);
+        assert_eq!(display(&who, &link_home(Some("rug.example"))), "sanne");
+
+        // Every spelling of the address a person signs in with.
+        for addr in [
+            "wss://rug.example/ws",
+            "rug.example:443",
+            "https://rug.example/x",
+        ] {
+            assert_eq!(link_origin(Some(addr)), "https://rug.example", "{addr}");
+        }
+        assert_eq!(
+            link_origin(Some("wss://rug.example:8443/ws")),
+            "https://rug.example:8443"
+        );
+        assert_eq!(link_home(Some("wss://rug.example:8443/ws")), "rug.example");
+        // Nothing worth sharing: the links name cartopolis.org as before.
+        for addr in [
+            "127.0.0.1:4747",
+            "localhost",
+            "tcp://10.0.0.2:4747",
+            "ws://x.test/ws",
+            "",
+        ] {
+            assert_eq!(link_origin(Some(addr)), WEB_ORIGIN, "{addr:?}");
+        }
+        assert_eq!(link_origin(None), WEB_ORIGIN);
+        // A link from a development page names no server.
+        assert_eq!(
+            contact_from_link("http://localhost:8080/go?contact=eva~abc"),
+            Some(("eva".into(), "abc".into()))
+        );
+        // An address in the link is kept, not wrapped twice.
+        assert_eq!(
+            contact_from_link("https://rug.example/go?contact=bob@elders.example~abc"),
+            Some(("bob@elders.example".into(), "abc".into()))
+        );
+    }
+
     fn fix(input: &str) -> LocationFix {
         place_from_link(input).unwrap_or_else(|| panic!("{input} should name a place"))
     }
@@ -560,7 +685,7 @@ mod tests {
     #[test]
     fn a_tapped_link_is_sorted_by_what_it_names() {
         assert_eq!(
-            followed(&invite_link("3f9a1c7e22b0")),
+            followed(&invite_link(WEB_ORIGIN, "3f9a1c7e22b0")),
             Some(Followed::Invite("3f9a1c7e22b0".into()))
         );
         assert_eq!(
@@ -568,8 +693,11 @@ mod tests {
             Some(Followed::Contact("sanne_k".into(), "3f9a1c7e22b0".into()))
         );
         assert_eq!(
-            followed(&contact_link("sanne_k", "3f9a1c7e22b0")),
-            Some(Followed::Contact("sanne_k".into(), "3f9a1c7e22b0".into()))
+            followed(&contact_link(WEB_ORIGIN, "sanne_k", "3f9a1c7e22b0")),
+            Some(Followed::Contact(
+                "sanne_k@cartopolis.org".into(),
+                "3f9a1c7e22b0".into()
+            ))
         );
         match followed("https://cartopolis.org/go?place=53.21940,6.56650,120m,-12.5,45") {
             Some(Followed::Place(f)) => assert_groningen(&f),
diff --git a/crates/cartopolis/src/systems/net/calls.rs b/crates/cartopolis/src/systems/net/calls.rs
index b01fa928..42302ffb 100644
--- a/crates/cartopolis/src/systems/net/calls.rs
+++ b/crates/cartopolis/src/systems/net/calls.rs
@@ -117,13 +117,11 @@ pub enum CallRequest {
 
 /// A guest link's address: the web page a guest opens, which handles `meet`.
 /// Not the `/go` path, which the app claims on Android: a guest has no app.
+/// On the server `origin` (`place_link::link_origin`), whose page joins its
+/// calls.
 #[must_use]
-pub fn guest_link(code: &str, secret: &[u8]) -> String {
-    format!(
-        "{}/?meet={code}#{}",
-        crate::systems::place_link::WEB_ORIGIN,
-        b64url(secret)
-    )
+pub fn guest_link(origin: &str, code: &str, secret: &[u8]) -> String {
+    format!("{origin}/?meet={code}#{}", b64url(secret))
 }
 
 /// A guest link's code and secret, from a link or a chat line that holds one
@@ -1162,7 +1160,10 @@ pub fn drive_calls(
             NetMessage::CallInvited { group, code, .. } if !code.is_empty() => {
                 if let Some((asked, secret)) = calls.invite_secret.take() {
                     if asked == group {
-                        let link = guest_link(&code, &secret);
+                        let origin = crate::systems::place_link::link_origin(
+                            addr.as_deref().map(|a| a.0.as_str()),
+                        );
+                        let link = guest_link(&origin, &code, &secret);
                         calls.guest_links.insert(group.clone(), secret);
                         calls.invited = Some(link.clone());
                         calls.link_to_post = Some((group, link));
@@ -2079,10 +2080,10 @@ mod tests {
     #[test]
     fn a_guest_link_carries_its_code_and_secret() {
         let secret: Vec<u8> = (0u8..16).collect();
-        let link = guest_link("k7q2m9x4ab", &secret);
-        assert!(
-            link.ends_with("/?meet=k7q2m9x4ab#AAECAwQFBgcICQoLDA0ODw"),
-            "{link}"
+        let link = guest_link("https://rug.example", "k7q2m9x4ab", &secret);
+        assert_eq!(
+            link,
+            "https://rug.example/?meet=k7q2m9x4ab#AAECAwQFBgcICQoLDA0ODw"
         );
         let line = format!("Guest link for the call, good for a day: {link}");
         assert_eq!(read_guest_link(&line), Some(("k7q2m9x4ab".into(), secret)));