gent-link 0.2.0

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
use crate::{board::Boards, protocol};
use serde_json::Value;
use std::{
    process::{Command, Stdio},
    sync::Mutex,
};
use tauri::{Manager, Url, WebviewWindow};
use uuid::Uuid;

pub(crate) struct Shell {
    // Injected into a closure in the trusted main frame. Never serialized in a
    // page, URL, supervisor message or return value accessible to a board.
    key: String,
    // Keep the first supervisor snapshot even when the webview has not installed
    // its listener yet. Once ready, all subsequent messages go straight to it.
    initial: Mutex<Option<Vec<Value>>>,
}

impl Shell {
    pub(crate) fn new() -> Self {
        Self {
            key: Uuid::new_v4().simple().to_string(),
            initial: Mutex::new(Some(Vec::new())),
        }
    }
    pub(crate) fn script(&self) -> String {
        include_str!("bridge.js").replace("__GENT_SHELL_KEY__", &self.key)
    }

    fn authorize(&self, label: &str, url: Option<&Url>, key: &str) -> Result<(), &'static str> {
        if label == "main" && key == self.key && url.is_some_and(trusted) {
            Ok(())
        } else {
            Err("This page cannot control Gent Desktop")
        }
    }

    pub(crate) fn deliver(&self, window: &WebviewWindow, value: Value) {
        let mut initial = self.initial.lock().expect("desktop queue lock");
        if let Some(queue) = initial.as_mut() {
            queue.push(value);
        } else {
            dispatch(window, &value);
        }
    }
}

fn dispatch(window: &WebviewWindow, value: &Value) {
    if !window.url().is_ok_and(|url| trusted(&url)) {
        return;
    }
    // Parse data as JSON in the trusted frame. Author text is never evaluated.
    let encoded = serde_json::to_string(&value.to_string()).expect("JSON string");
    if window
        .eval(format!(
            "if (location.protocol==='tauri:' && location.hostname==='localhost' && ['/','/index.html'].includes(location.pathname)) window.dispatchEvent(new CustomEvent('gent-message',{{detail:JSON.parse({encoded})}}))"
        ))
        .is_err()
    {
        window.app_handle().exit(1);
    }
}

pub(crate) fn trusted(url: &Url) -> bool {
    url.scheme() == "tauri"
        && url.host_str() == Some("localhost")
        && url.username().is_empty()
        && url.password().is_none()
        && url.port().is_none()
        && matches!(url.path(), "/" | "/index.html")
        && url.query().is_none()
}

fn public_link(url: &str) -> bool {
    if matches!(
        url,
        "https://gent.link"
            | "https://gent.link/"
            | "https://gent.link/support"
            | "https://gent.link/pricing"
    ) {
        return true;
    }
    let Some(path) = url.strip_prefix("https://github.com/sam0x17/gent/") else {
        return false;
    };
    if let Some(sha) = path.strip_prefix("commit/") {
        return sha.len() == 40 && sha.bytes().all(|b| b.is_ascii_hexdigit());
    }
    path.strip_prefix("releases/tag/v").is_some_and(|version| {
        version.len() <= 128
            && version.starts_with(|c: char| c.is_ascii_digit())
            && version
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b".+-".contains(&b))
    })
}

#[tauri::command]
pub(crate) async fn gent_board(
    window: WebviewWindow,
    shell: tauri::State<'_, Shell>,
    key: String,
    value: crate::board::Document,
) -> Result<String, &'static str> {
    shell.authorize(window.label(), window.url().ok().as_ref(), &key)?;
    let scripts = crate::protection::scripts().await?;
    window.state::<Boards>().prepare(value, scripts)
}

#[tauri::command]
pub(crate) fn gent_bridge(
    window: WebviewWindow,
    shell: tauri::State<'_, Shell>,
    key: String,
    action: String,
    value: Value,
) -> Result<Option<String>, &'static str> {
    shell.authorize(window.label(), window.url().ok().as_ref(), &key)?;
    match action.as_str() {
        "ready" => {
            let mut initial = shell.initial.lock().expect("desktop queue lock");
            for message in initial.take().unwrap_or_default() {
                dispatch(&window, &message);
            }
            Ok(None)
        }
        "send" => protocol::send(&value).map(|()| None),
        "release_board" => {
            window
                .state::<Boards>()
                .release(value.as_str().ok_or("Invalid board URL")?);
            Ok(None)
        }
        "open" => {
            let url = value
                .as_str()
                .filter(|url| public_link(url))
                .ok_or("Unsupported public link")?;
            let opener = if cfg!(target_os = "macos") {
                "/usr/bin/open"
            } else {
                "/usr/bin/xdg-open"
            };
            let mut child = Command::new(opener)
                .arg(url)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .map_err(|_| "Could not open the link")?;
            std::thread::spawn(move || {
                let _ = child.wait();
            });
            Ok(None)
        }
        _ => Err("Unknown desktop request"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn supervisor_commands_require_the_current_shell_window_and_its_key() {
        let shell = Shell::new();
        let fresh = Shell::new();
        let main = Url::parse("tauri://localhost/index.html").unwrap();
        let board = Url::parse("gent-board://localhost/document").unwrap();
        assert!(shell.authorize("main", Some(&main), &shell.key).is_ok());
        assert!(shell.authorize("main", Some(&main), &fresh.key).is_err());
        assert!(shell.authorize("main", Some(&board), &shell.key).is_err());
        assert!(shell.authorize("other", Some(&main), &shell.key).is_err());
        assert!(shell.authorize("main", None, &shell.key).is_err());
    }

    #[test]
    fn shell_and_external_links_have_separate_destinations() {
        assert!(trusted(
            &Url::parse("tauri://localhost/index.html").unwrap()
        ));
        for other in [
            "tauri://other/index.html",
            "tauri://localhost/board",
            "https://gent.link",
        ] {
            assert!(!trusted(&Url::parse(other).unwrap()));
        }
        assert!(public_link(
            "https://github.com/sam0x17/gent/releases/tag/v0.1.8"
        ));
        assert!(public_link("https://gent.link/support"));
        assert!(!public_link("https://gent.link/support?next=elsewhere"));
        assert!(!public_link(
            "https://github.com/sam0x17/gent/releases/tag/v1/other"
        ));
    }
}