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
//! ChatGPT sign-in (OAuth with PKCE), so an application can run on a ChatGPT
//! subscription instead of a metered API key.
//!
//! This authenticates as the public Codex CLI client and talks to a
//! Codex-scoped backend. That is off-label use of a first-party client: it can
//! stop working whenever OpenAI changes it, and it is not what a consumer
//! subscription is sold for. The supported path is `provider = "openai"` with
//! `OPENAI_API_KEY`, and nothing above [`crate::Client`] can tell the two
//! apart.

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use serde_json::Value;

use crate::Error;

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

pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
pub const REDIRECT_PORT: u16 = 1455;
pub const ORIGINATOR: &str = "codex_cli_rs";
/// The same Responses wire format as the API, on a different host with
/// different headers.
pub const API_URL: &str = "https://chatgpt.com/backend-api/codex/responses";

const AUTHORIZE_URL: &str = "https://auth.openai.com/oauth/authorize";
const TOKEN_URL: &str = "https://auth.openai.com/oauth/token";
const REDIRECT_URI: &str = "http://localhost:1455/auth/callback";
const SCOPE: &str = "openid profile email offline_access api.connectors.read api.connectors.invoke";

pub fn authorize_url(challenge: &str, state: &str) -> String {
    format!(
        "{AUTHORIZE_URL}?{}",
        pkce::form(&[
            ("response_type", "code"),
            ("client_id", CLIENT_ID),
            ("redirect_uri", REDIRECT_URI),
            ("scope", SCOPE),
            ("code_challenge", challenge),
            ("code_challenge_method", "S256"),
            ("state", state),
            ("id_token_add_organizations", "true"),
            ("codex_cli_simplified_flow", "true"),
            ("originator", ORIGINATOR),
        ])
    )
}

pub fn exchange(code: &str, verifier: &str) -> crate::Result<Tokens> {
    parse(&post_form(
        TOKEN_URL,
        &pkce::form(&[
            ("grant_type", "authorization_code"),
            ("code", code),
            ("redirect_uri", REDIRECT_URI),
            ("client_id", CLIENT_ID),
            ("code_verifier", verifier),
        ]),
    )?)
}

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 ChatGPT again".into(),
        ));
    }
    let mut fresh = parse(&post_form(
        TOKEN_URL,
        &pkce::form(&[
            ("grant_type", "refresh_token"),
            ("refresh_token", &current.refresh_token),
            ("client_id", CLIENT_ID),
            ("scope", "openid profile email"),
        ]),
    )?)?;
    // Refresh responses commonly omit fields; keep what was already known.
    if fresh.refresh_token.is_empty() {
        fresh.refresh_token = current.refresh_token.clone();
    }
    if fresh.account_id.is_empty() {
        fresh.account_id = current.account_id.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}")))?;
    let access_token = value["access_token"]
        .as_str()
        .ok_or_else(|| Error::Auth("token response had no access_token".into()))?
        .to_string();
    let id_token = value["id_token"].as_str().unwrap_or_default().to_string();
    Ok(Tokens {
        account_id: account_id(&id_token)
            .or_else(|| account_id(&access_token))
            .unwrap_or_default(),
        refresh_token: value["refresh_token"]
            .as_str()
            .unwrap_or_default()
            .to_string(),
        expires_at: now() + value["expires_in"].as_i64().unwrap_or(3600),
        access_token,
    })
}

/// Read the account id out of a JWT payload. There is no signature check here:
/// this is a local read of a token just received over TLS, not an
/// authorization decision, and the server validates it on every request.
fn account_id(jwt: &str) -> Option<String> {
    let payload = jwt.split('.').nth(1)?;
    let value: Value = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload).ok()?).ok()?;
    for pointer in [
        "/https:~1~1api.openai.com~1auth/chatgpt_account_id",
        "/https:~1~1api.openai.com~1auth/user_id",
        "/chatgpt_account_id",
    ] {
        if let Some(id) = value.pointer(pointer).and_then(Value::as_str) {
            return Some(id.to_string());
        }
    }
    value
        .as_object()?
        .values()
        .find_map(|nested| nested["chatgpt_account_id"].as_str().map(str::to_string))
}

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

    fn query(url: &str) -> 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()
    }

    #[test]
    fn the_authorize_url_matches_the_codex_login_contract() {
        let params = query(&authorize_url("challenge/value", "state value"));
        assert_eq!(params["response_type"], "code");
        assert_eq!(params["client_id"], CLIENT_ID);
        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"], "state value");
        assert_eq!(params["id_token_add_organizations"], "true");
        assert_eq!(params["codex_cli_simplified_flow"], "true");
        assert_eq!(params["originator"], ORIGINATOR);
        assert_eq!(params.len(), 10);
    }

    #[test]
    fn a_token_response_yields_an_expiry_and_an_account() {
        let id_token = format!(
            "header.{}.signature",
            URL_SAFE_NO_PAD.encode(r#"{"chatgpt_account_id":"acct_123"}"#)
        );
        let body = format!(
            r#"{{"access_token":"at","refresh_token":"rt","id_token":"{id_token}","expires_in":60}}"#
        );
        let tokens = parse(&body).unwrap();
        assert_eq!(tokens.access_token, "at");
        assert_eq!(tokens.account_id, "acct_123");
        assert!(tokens.expires_at > now());
    }

    #[test]
    fn a_response_without_an_access_token_is_an_error() {
        assert!(parse(r#"{"error":"invalid_grant"}"#).is_err());
        assert!(parse("not json").is_err());
    }

    #[test]
    fn refreshing_without_a_refresh_token_fails_before_any_request() {
        assert!(refresh(&Tokens::default()).is_err());
    }
}