modelbridge 0.5.2

One provider-neutral Rust client for OpenAI, Anthropic, Gemini, Groq, Ollama and friends: streaming, tool calling, an agent loop, usage accounting, and subscription sign-in
Documentation
//! Claude sign-in (OAuth with PKCE), so an application can run on a Claude
//! subscription instead of a metered Anthropic key.
//!
//! Same shape and same caveat as the ChatGPT route: it authenticates as the
//! public Claude Code client against an endpoint scoped to that client. That is
//! off-label use, Anthropic's consumer terms are written around their own apps,
//! and it can stop working at any time. The supported path is
//! `provider = "anthropic"` with `ANTHROPIC_API_KEY`.

use serde_json::{json, Value};

use crate::Error;

use super::store::{now, Tokens};
use super::{pkce, post_json};

pub const CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
pub const REDIRECT_PORT: u16 = 54545;
pub const API_URL: &str = "https://api.anthropic.com/v1/messages";
/// Subscription tokens are rejected on `x-api-key`; they need this opt-in.
pub const BETA_HEADER: &str = "oauth-2025-04-20";
/// The endpoint is scoped to Claude Code and rejects a system prompt that does
/// not identify the caller as such, so it leads every request.
pub const SYSTEM_PREFIX: &str = "You are Claude Code, Anthropic's official CLI for Claude.";

const AUTHORIZE_URL: &str = "https://claude.ai/oauth/authorize";
const TOKEN_URL: &str = "https://console.anthropic.com/v1/oauth/token";
const REDIRECT_URI: &str = "http://localhost:54545/callback";
const SCOPE: &str = "org:create_api_key user:profile user:inference";

/// This flow echoes the verifier back as `state`, so the caller compares the
/// returned state against the verifier rather than a separate nonce.
pub fn authorize_url(challenge: &str, verifier: &str) -> String {
    format!(
        "{AUTHORIZE_URL}?{}",
        pkce::form(&[
            ("code", "true"),
            ("client_id", CLIENT_ID),
            ("response_type", "code"),
            ("redirect_uri", REDIRECT_URI),
            ("scope", SCOPE),
            ("code_challenge", challenge),
            ("code_challenge_method", "S256"),
            ("state", verifier),
        ])
    )
}

pub fn exchange(code: &str, verifier: &str) -> crate::Result<Tokens> {
    parse(&post_json(
        TOKEN_URL,
        &json!({
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": REDIRECT_URI,
            "client_id": CLIENT_ID,
            "code_verifier": verifier,
            "state": verifier,
        })
        .to_string(),
    )?)
}

pub fn refresh(current: &Tokens) -> crate::Result<Tokens> {
    if current.refresh_token.is_empty() {
        return Err(Error::Auth(
            "no refresh token stored; sign in to Claude again".into(),
        ));
    }
    let mut fresh = parse(&post_json(
        TOKEN_URL,
        &json!({
            "grant_type": "refresh_token",
            "refresh_token": current.refresh_token,
            "client_id": CLIENT_ID,
        })
        .to_string(),
    )?)?;
    if fresh.refresh_token.is_empty() {
        fresh.refresh_token = current.refresh_token.clone();
    }
    Ok(fresh)
}

pub fn parse(body: &str) -> crate::Result<Tokens> {
    let value: Value = serde_json::from_str(body)
        .map_err(|error| Error::Decode(format!("bad token JSON: {error}")))?;
    Ok(Tokens {
        access_token: value["access_token"]
            .as_str()
            .ok_or_else(|| Error::Auth("token response had no access_token".into()))?
            .to_string(),
        refresh_token: value["refresh_token"]
            .as_str()
            .unwrap_or_default()
            .to_string(),
        account_id: String::new(),
        expires_at: now() + value["expires_in"].as_i64().unwrap_or(3600),
    })
}

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

    #[test]
    fn the_authorize_url_carries_the_challenge_and_uses_the_verifier_as_state() {
        let url = authorize_url("challenge/value", "verifier value");
        let params: HashMap<String, String> = url
            .split_once('?')
            .unwrap()
            .1
            .split('&')
            .map(|pair| {
                let (key, value) = pair.split_once('=').unwrap();
                (pkce::decode(key), pkce::decode(value))
            })
            .collect();
        assert_eq!(params["client_id"], CLIENT_ID);
        assert_eq!(params["response_type"], "code");
        assert_eq!(params["redirect_uri"], REDIRECT_URI);
        assert_eq!(params["scope"], SCOPE);
        assert_eq!(params["code_challenge"], "challenge/value");
        assert_eq!(params["code_challenge_method"], "S256");
        assert_eq!(params["state"], "verifier value");
    }

    #[test]
    fn a_token_response_parses() {
        let tokens =
            parse(r#"{"access_token":"at","refresh_token":"rt","expires_in":30}"#).unwrap();
        assert_eq!(tokens.access_token, "at");
        assert_eq!(tokens.refresh_token, "rt");
        assert!(
            tokens.expired(),
            "30 seconds is inside the early-refresh window"
        );
    }

    #[test]
    fn errors_are_reported_rather_than_panicked_on() {
        assert!(parse(r#"{"error":"invalid_grant"}"#).is_err());
        assert!(refresh(&Tokens::default()).is_err());
    }
}