pitboard-core 0.22.0

The engine behind Pitboard: switches Claude Code, Codex and Claude Desktop between accounts by parking and restoring their logins. Its API serves Pitboard's own front ends.
Documentation
//! Antigravity's login as agy stores it (`agy_stored_token`): one JSON document, written whole
//! in one place or split between its keyring item and a token file (`agy_split_login`).

use crate::host::Os;
use crate::store::Error;
use base64::Engine as _;
use serde_json::{Map, Value};

/// What agy's own sign-in prints once it waits for the code the browser shows (`agy_sign_in`).
pub(crate) const ASKS_FOR_A_CODE: &str = "Enter the authorization code:";

// go-keyring's prefixes on macOS, where `security` passes text: base64, or hex from builds
// before it (`agy_login_item`).
const BASE64: &str = "go-keyring-base64:";
const HEX: &str = "go-keyring-encoded:";

/// The login in a keyring item, as go-keyring hands it to agy.
pub(crate) fn opened(stored: &str) -> Result<String, Error> {
    let bytes = if let Some(rest) = stored.strip_prefix(BASE64) {
        base64::engine::general_purpose::STANDARD
            .decode(rest.trim())
            .map_err(|e| Error::Malformed(format!("its keyring item is not base64: {e}")))?
    } else if let Some(rest) = stored.strip_prefix(HEX) {
        hex::decode(rest.trim())
            .map_err(|e| Error::Malformed(format!("its keyring item is not hex: {e}")))?
    } else {
        return Ok(stored.to_owned());
    };
    String::from_utf8(bytes).map_err(|_| Error::Malformed("its keyring item is not text".into()))
}

/// The login as go-keyring would keep it in a keyring item on `os`.
pub(crate) fn sealed(login: &str, os: Os) -> String {
    match os {
        Os::MacOs => format!(
            "{BASE64}{}",
            base64::engine::general_purpose::STANDARD.encode(login)
        ),
        Os::Linux | Os::Windows => login.to_owned(),
    }
}

fn token(login: &Value) -> Option<&Map<String, Value>> {
    login["token"].as_object().filter(|token| {
        ["access_token", "refresh_token"].into_iter().any(|key| {
            token
                .get(key)
                .and_then(Value::as_str)
                .is_some_and(|t| !t.is_empty())
        })
    })
}

/// Whether `login` holds tokens, rather than only the project and plan beside them.
pub(crate) fn has_token(login: &Value) -> bool {
    token(login).is_some()
}

pub(crate) fn refresh_token(login: &Value) -> Option<&str> {
    token(login)?
        .get("refresh_token")?
        .as_str()
        .filter(|t| !t.is_empty())
}

/// The account, as agy reads it from the login itself (`agy_identity`).
pub(crate) fn email(login: &Value) -> Option<&str> {
    login["id_token_email"].as_str().filter(|e| !e.is_empty())
}

/// When the access token stops working, in epoch seconds.
pub(crate) fn access_expiry(login: &Value) -> Option<i64> {
    token(login)?
        .get("expiry")?
        .as_str()
        .and_then(crate::time::parse)
}

pub(crate) fn plan(login: &Value) -> Option<String> {
    ["tier_display_name", "user_tier"]
        .into_iter()
        .find_map(|key| login[key].as_str().filter(|plan| !plan.is_empty()))
        .map(str::to_owned)
}

/// One place's part of the login.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Part {
    Nothing,
    // The project and plan, kept where the tokens did not fit.
    Tokenless(Value),
    Whole(Value),
}

impl Part {
    pub(crate) fn of(read: Option<&str>) -> Result<Part, Error> {
        let Some(text) = read else {
            return Ok(Part::Nothing);
        };
        let login: Value =
            serde_json::from_str(text).map_err(|e| Error::Malformed(e.to_string()))?;
        if !login.is_object() {
            return Err(Error::Malformed("it is not a JSON object".into()));
        }
        Ok(if has_token(&login) {
            Part::Whole(login)
        } else {
            Part::Tokenless(login)
        })
    }
}

/// The login `parts` make, in the order agy reads them: the first with tokens, every field it
/// lacks taken from the others (`healSplitKeyringToken`, `mergeMissingFromTokenlessKeyring`).
/// Two parts with tokens of different logins are no login Pitboard can tell is agy's: refused.
pub(crate) fn merged(parts: &[Part]) -> Result<Option<Value>, Error> {
    let mut wholes = parts.iter().filter_map(|part| match part {
        Part::Whole(login) => Some(login),
        Part::Nothing | Part::Tokenless(_) => None,
    });
    let Some(first) = wholes.next() else {
        return Ok(None);
    };
    for other in wholes {
        if refresh_token(other) != refresh_token(first) || email(other) != email(first) {
            return Err(Error::Unreadable(
                "Antigravity keeps two different logins, in its keyring and in its token files"
                    .into(),
            ));
        }
    }
    let mut login = first.clone();
    let fields = login.as_object_mut().expect("a part is an object");
    for part in parts {
        if let Part::Tokenless(rest) | Part::Whole(rest) = part {
            for (key, value) in rest.as_object().into_iter().flatten() {
                if !fields
                    .get(key)
                    .is_some_and(|held| !held.is_null() && held != "")
                {
                    fields.insert(key.clone(), value.clone());
                }
            }
        }
    }
    Ok(Some(login))
}

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

    #[test]
    fn a_keyring_item_opens_from_either_prefix_or_none() {
        let login = r#"{"token":{"refresh_token":"r"},"id_token_email":"đạt@example.com"}"#;
        assert_eq!(opened(&sealed(login, Os::MacOs)).unwrap(), login);
        assert!(sealed(login, Os::MacOs).starts_with("go-keyring-base64:"));
        assert_eq!(sealed(login, Os::Windows), login);
        assert_eq!(sealed(login, Os::Linux), login);
        let encoded = format!("go-keyring-encoded:{}", hex::encode(login));
        assert_eq!(opened(&encoded).unwrap(), login);
        assert_eq!(opened(login).unwrap(), login);
        assert!(matches!(
            opened("go-keyring-base64:%%%"),
            Err(Error::Malformed(_))
        ));
    }

    #[test]
    fn a_login_says_its_account_tokens_expiry_and_plan() {
        let login = super::super::login_for_a_test("a@example.com", "access", "refresh");
        assert!(has_token(&login));
        assert_eq!(email(&login), Some("a@example.com"));
        assert_eq!(refresh_token(&login), Some("refresh"));
        assert_eq!(
            access_expiry(&login),
            crate::time::parse("2026-11-28T12:00:00Z")
        );
        assert_eq!(plan(&login).as_deref(), Some("Google AI Pro"));
        let tokenless = json!({"project_id": "p", "user_tier": "g1"});
        assert!(!has_token(&tokenless));
        assert_eq!(plan(&tokenless).as_deref(), Some("g1"));
    }

    #[test]
    fn a_split_login_is_merged_as_agy_heals_one() {
        let whole = json!({"token": {"refresh_token": "r"}, "id_token_email": "a@example.com",
                           "project_id": ""});
        let tokenless = json!({"project_id": "p", "user_tier": "g1"});
        let parts = [
            Part::Whole(whole),
            Part::Tokenless(tokenless),
            Part::Nothing,
        ];
        let login = merged(&parts).unwrap().unwrap();
        assert_eq!(login["project_id"], "p");
        assert_eq!(login["user_tier"], "g1");
        assert_eq!(login["token"]["refresh_token"], "r");
        assert_eq!(merged(&[Part::Nothing, Part::Nothing]).unwrap(), None);
        assert_eq!(
            merged(&[Part::Tokenless(json!({"project_id": "p"}))]).unwrap(),
            None,
            "a project with no tokens is no login"
        );
    }

    #[test]
    fn two_different_logins_are_refused_and_one_login_twice_is_one() {
        let a = super::super::login_for_a_test("a@example.com", "x", "ra");
        let b = super::super::login_for_a_test("b@example.com", "y", "rb");
        assert!(matches!(
            merged(&[Part::Whole(a.clone()), Part::Whole(b)]),
            Err(Error::Unreadable(_))
        ));
        assert_eq!(
            merged(&[Part::Whole(a.clone()), Part::Whole(a.clone())]).unwrap(),
            Some(a)
        );
    }

    #[test]
    fn a_part_that_is_not_an_object_is_malformed() {
        assert!(matches!(Part::of(Some("[]")), Err(Error::Malformed(_))));
        assert!(matches!(Part::of(Some("{")), Err(Error::Malformed(_))));
        assert_eq!(Part::of(None).unwrap(), Part::Nothing);
    }
}