rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Bearer tokens accepted by `rho daemon serve --http`, kept in rho's
//! credential store under a dedicated account separate from MCP server tokens.
//!
//! Because raw `rho-protocol` gives full user-level control over the daemon
//! (opening sessions in any workspace, answering approvals, changing config,
//! and stopping/restarting the daemon), daemon HTTP tokens are completely
//! distinct from workspace-scoped `rho mcp token` credentials.

use anyhow::Context as _;
use rho_protocol::BridgeToken;
use rho_providers::credentials::CredentialStore;
use serde::{Deserialize, Serialize};

use crate::app::{
    http_guard::{find_by_secret, new_secret, sha256_hex, validate_name},
    mcp_server::token_store::{self, StoredSet},
};

/// Credential-store account for daemon HTTP bearer tokens.
pub(crate) const ACCOUNT: &str = "daemon-http-tokens";

/// Cross-process lock file for daemon HTTP token updates.
const LOCK_FILE: &str = ".rho-daemon-tokens.lock";

/// Every bearer token `rho daemon serve --http` accepts.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DaemonTokenSet {
    pub(crate) tokens: Vec<DaemonTokenRecord>,
}

/// One daemon HTTP token: its name and the hex SHA-256 of its secret, and
/// what is known of the device holding it (`rho/device/list`). Each field
/// after the hash is optional, so a record an earlier rho saved loads, and
/// describes the token's current secret: a rotation clears what was known
/// of the device that held the last one.
//
// P4 adds the device's push registration here, optional like these: its
// APNs token and environment, and the public key notification titles are
// sealed to.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct DaemonTokenRecord {
    pub(crate) name: String,
    sha256: String,
    /// What the device said it runs when it redeemed a pairing code.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) platform: Option<String>,
    /// Unix seconds when the token got its secret.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) paired_at: Option<u64>,
    /// Unix seconds when the bridge last saw the token, at most about once
    /// a minute ([`DaemonTokenSet::mark_seen`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) last_seen: Option<u64>,
}

impl StoredSet for DaemonTokenSet {
    const ACCOUNT: &'static str = ACCOUNT;
    const WHAT: &'static str = "daemon HTTP tokens";
    const LOCK_FILE: &'static str = LOCK_FILE;
    const GUARDED: &'static str = "daemon HTTP tokens";
}

impl DaemonTokenSet {
    /// Loads the saved token set from `store`; empty when none exists.
    pub(crate) fn load(store: &dyn CredentialStore) -> anyhow::Result<Self> {
        token_store::load(store)
    }

    /// Gives token `name` a fresh 256-bit secret, creating it if needed, and
    /// returns the secret once. Any previous secret stops working immediately.
    /// The secret is a [`BridgeToken`], the shape a pairing string carries,
    /// whose `rho_daemon_` prefix makes a leak recognizable and distinct
    /// from `rho_mcp_` tokens.
    pub(crate) fn rotate(&mut self, name: &str) -> anyhow::Result<BridgeToken> {
        self.rotate_at(name, unix_now())
    }

    /// [`Self::rotate`], at `now`, in Unix seconds, which the token's
    /// record keeps as when it was paired. What was known of the device
    /// that held the token before is cleared.
    pub(crate) fn rotate_at(&mut self, name: &str, now: u64) -> anyhow::Result<BridgeToken> {
        validate_name("token", name)?;
        let secret: BridgeToken = new_secret(BridgeToken::PREFIX)
            .parse()
            .context("minted a daemon token clients would refuse")?;
        let record = DaemonTokenRecord {
            name: name.to_owned(),
            sha256: sha256_hex(secret.secret()),
            platform: None,
            paired_at: Some(now),
            last_seen: None,
        };
        match self.tokens.iter_mut().find(|token| token.name == name) {
            Some(token) => *token = record,
            None => self.tokens.push(record),
        }
        Ok(secret)
    }

    /// Records that the device holding token `name` runs `platform`.
    pub(crate) fn set_platform(&mut self, name: &str, platform: Option<String>) {
        if let Some(token) = self.tokens.iter_mut().find(|token| token.name == name) {
            token.platform = platform;
        }
    }

    /// Records that the token whose secret is `presented` was seen at
    /// `now`. Matched by secret, not name, so a socket of a token rotated
    /// meanwhile stamps nothing on its new holder; returns whether one
    /// matched.
    pub(crate) fn mark_seen(&mut self, presented: &str, now: u64) -> bool {
        let Some(name) = self.authenticate(presented).map(|token| token.name.clone()) else {
            return false;
        };
        if let Some(token) = self.tokens.iter_mut().find(|token| token.name == name) {
            token.last_seen = Some(now);
        }
        true
    }

    /// Whether token `name` exists.
    pub(crate) fn contains(&self, name: &str) -> bool {
        self.tokens.iter().any(|token| token.name == name)
    }

    /// Removes token `name`; returns whether it existed.
    pub(crate) fn revoke(&mut self, name: &str) -> bool {
        let before = self.tokens.len();
        self.tokens.retain(|token| token.name != name);
        self.tokens.len() != before
    }

    /// Returns the matching token record in constant time across all tokens.
    pub(crate) fn authenticate(&self, presented: &str) -> Option<&DaemonTokenRecord> {
        find_by_secret(&self.tokens, presented, |token| &token.sha256)
    }
}

/// Now, in Unix seconds.
pub(super) fn unix_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs())
        .unwrap_or_default()
}

#[cfg(test)]
#[path = "tokens_tests.rs"]
mod tests;