gent-link 0.2.5

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
//! One private file per scheduled publisher. Credentials never enter CLI arguments or output.
use anyhow::{Context, Result, ensure};
use clap::Subcommand;
use gent_daemon::{config, request, store::grant_verifier};
use gent_protocol::{
    OwnerOp, Request,
    dashboard::{GrantAdmin, GrantOp, MAX_HTML_BYTES, valid_grant_key},
};
use rustix::fs::{Mode, OFlags, open};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
    fs::{self, File},
    io::{Read, Write},
    os::unix::fs::MetadataExt,
    path::{Path, PathBuf},
};
use uuid::Uuid;

#[derive(Subcommand)]
pub(crate) enum Command {
    /// Issue a scoped credential for a published dashboard, or migrate a legacy board.
    Grant {
        board: Uuid,
        #[arg(long)]
        expected_revision: u64,
        #[arg(long)]
        out: PathBuf,
        /// Convert a legacy board using this UTF-8 HTML file and keep its title and buttons.
        #[arg(long)]
        initial_html: Option<PathBuf>,
    },
    /// Read the current HTML publication using its grant.
    Get {
        board: Uuid,
        #[arg(long)]
        grant: PathBuf,
    },
    /// Replace only the document, preserving title and declared callbacks.
    Update {
        board: Uuid,
        #[arg(long)]
        expected_revision: u64,
        #[arg(long)]
        grant: PathBuf,
        #[arg(long)]
        html_file: PathBuf,
    },
    /// Invalidate this board's active credential.
    Revoke {
        board: Uuid,
        #[arg(long)]
        expected_revision: u64,
    },
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct GrantFile {
    version: u8,
    cluster: String,
    board: Uuid,
    secret: String,
}

fn read_file(path: &Path, cluster: &str, board: Uuid) -> Result<GrantFile> {
    let file = File::from(open(
        path,
        OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
        Mode::empty(),
    )?);
    let meta = file.metadata()?;
    ensure!(
        meta.is_file()
            && meta.nlink() == 1
            && meta.mode() & 0o077 == 0
            && meta.uid() == rustix::process::geteuid().as_raw(),
        "grant must be a private file owned by this user"
    );
    let mut bytes = Vec::new();
    file.take(1025).read_to_end(&mut bytes)?;
    ensure!(bytes.len() <= 1024, "invalid grant file");
    let grant: GrantFile =
        serde_json::from_slice(&bytes).map_err(|_| anyhow::anyhow!("invalid grant file"))?;
    ensure!(
        grant.version == 1
            && grant.board == board
            && grant.cluster == cluster
            && valid_grant_key(&grant.secret),
        "grant is invalid for this board or cluster"
    );
    Ok(grant)
}

// Install before issuing. Retrying after a lost RPC reply reuses the same verifier.
fn prepare(path: &Path, cluster: &str, board: Uuid) -> Result<GrantFile> {
    if path.try_exists()? {
        return read_file(path, cluster, board);
    }
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    match fs::symlink_metadata(parent) {
        Ok(meta) => ensure!(
            meta.is_dir()
                && meta.uid() == rustix::process::geteuid().as_raw()
                && meta.mode() & 0o022 == 0,
            "grant directory must be owned by this user and writable only by its owner"
        ),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => config::private_dir(parent)?,
        Err(e) => return Err(e.into()),
    }
    let mut bytes = [0u8; 32];
    getrandom::fill(&mut bytes).context("secure randomness unavailable")?;
    let secret = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
    let grant = GrantFile {
        version: 1,
        cluster: cluster.into(),
        board,
        secret,
    };
    let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
    tmp.write_all(&serde_json::to_vec(&grant)?)?;
    tmp.as_file().sync_all()?;
    match tmp.persist_noclobber(path) {
        Ok(_) => {
            File::open(parent)?.sync_all()?;
            Ok(grant)
        }
        Err(e) if e.error.kind() == std::io::ErrorKind::AlreadyExists => {
            read_file(path, cluster, board)
        }
        Err(e) => Err(e.error.into()),
    }
}

fn read_html(path: &Path) -> Result<String> {
    let mut html = String::new();
    File::open(path)?
        .take(MAX_HTML_BYTES as u64 + 1)
        .read_to_string(&mut html)?;
    ensure!(
        (1..=MAX_HTML_BYTES).contains(&html.len()),
        "publish 1–65536 UTF-8 bytes"
    );
    Ok(html)
}

pub(crate) async fn run(home: &Path, command: Command) -> Result<Value> {
    let cluster = config::load(home)?.cluster.id;
    let (board, path, action) = match command {
        Command::Grant {
            board,
            expected_revision,
            out,
            initial_html,
        } => {
            let html = initial_html.as_deref().map(read_html).transpose()?;
            let grant = prepare(&out, &cluster, board)?;
            let verifier = grant_verifier(&cluster, board, &grant.secret)?;
            let action = match html {
                Some(html) => GrantAdmin::MigrateAndIssue {
                    expected_revision,
                    verifier,
                    html,
                },
                None => GrantAdmin::Issue {
                    expected_revision,
                    verifier,
                },
            };
            return crate::owner(
                home,
                OwnerOp::DashboardGrant {
                    agent: board,
                    action,
                },
            )
            .await;
        }
        Command::Revoke {
            board,
            expected_revision,
        } => {
            return crate::owner(
                home,
                OwnerOp::DashboardGrant {
                    agent: board,
                    action: GrantAdmin::Revoke { expected_revision },
                },
            )
            .await;
        }
        Command::Get { board, grant } => (board, grant, GrantOp::Get),
        Command::Update {
            board,
            expected_revision,
            grant,
            html_file,
        } => {
            let html = read_html(&html_file)?;
            (
                board,
                grant,
                GrantOp::Update {
                    expected_revision,
                    html,
                },
            )
        }
    };
    let secret = read_file(&path, &cluster, board)?.secret;
    request(
        home,
        Request::DashboardDelegate {
            agent: board,
            secret,
            action,
        },
    )
    .await
}