Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-harness/src/oauth/login.rs

Raw
//! Durable CLI login through the sealed public credential effect (`SMH-SPEC-PLUG0001`).
use super::{LoginAuthority, LoginFlow, LoginPolicy, ProfileStore};
use crate::plugins::{Capability, PluginManifest};
use crate::storage::StorageWorker;
use crate::wasm::{PluginEngine, PluginGeneration, PluginRegistry};
use smith::config::Config;
use smith::error::{Result, SmithError};
use smith::structured::ToolArguments;
use smith_core::tools::{ToolDispatcher, ToolEffectContext, ToolSession};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::mpsc::Receiver;

/// Explicit subscription connection; never an API-key billing mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SubscriptionProvider {
    /// Verified dynamic `OpenAI` registration.
    OpenAi,
    /// Fixed-client Claude subscription with local opaque profile identity.
    Anthropic,
    /// Google installed-app OAuth and Code Assist project admission.
    Google,
}

impl SubscriptionProvider {
    /// Stable host connection namespace.
    #[must_use]
    pub const fn connection_id(self) -> &'static str {
        match self {
            Self::OpenAi => "openai-chatgpt-plan",
            Self::Anthropic => "anthropic-claude-plan",
            Self::Google => "google-gemini-cli-plan",
        }
    }
    pub(crate) const fn source(self) -> &'static str {
        match self {
            Self::OpenAi => "openai-chatgpt-plan@1",
            Self::Anthropic => "anthropic-claude-plan@1",
            Self::Google => "google-gemini-cli-plan@1",
        }
    }
    pub(crate) const fn consumer(self) -> &'static str {
        match self {
            Self::OpenAi => "smith:protocol-openai-responses/openai-chatgpt-plan",
            Self::Anthropic => "smith:protocol-anthropic/anthropic-claude-plan",
            Self::Google => "smith:protocol-google/google-gemini-cli-plan",
        }
    }
    pub(super) const fn endpoint(self) -> &'static str {
        match self {
            Self::OpenAi => "https://api.openai.com",
            Self::Anthropic => "https://api.anthropic.com",
            Self::Google => "https://cloudcode-pa.googleapis.com",
        }
    }
}

impl ToolDispatcher for PluginRegistry {
    fn begin_provider_round(&mut self) -> Result<smith_core::tools::ToolDispatcherSnapshot> {
        self.snapshot()
    }
    fn invoke(
        &mut self,
        name: &str,
        input: &ToolArguments,
        effects: &mut ToolEffectContext<'_>,
    ) -> Result<String> {
        let input =
            serde_json::to_string(input).map_err(|_| fault("OAuth input serialization failed"))?;
        self.invoke_with_effects(name, &input, effects)
    }
}

/// Select an isolated profile namespace; fixture issuers can never open production profiles.
///
/// # Errors
/// Rejects fixture authorities except literal `127.0.0.1` HTTP origins.
pub fn profile_store(fixture_issuer: Option<&str>) -> Result<ProfileStore> {
    profile_store_for(SubscriptionProvider::OpenAi, fixture_issuer)
}

/// Open only the selected subscription connection's isolated profile namespace.
/// # Errors
/// Rejects non-loopback fixture authorities.
pub fn profile_store_for(
    provider: SubscriptionProvider,
    fixture_issuer: Option<&str>,
) -> Result<ProfileStore> {
    let root = store_root(fixture_issuer)?;
    Ok(ProfileStore::at(match provider {
        SubscriptionProvider::OpenAi => root,
        SubscriptionProvider::Anthropic | SubscriptionProvider::Google => {
            root.join(provider.connection_id())
        }
    }))
}

fn store_root(fixture_issuer: Option<&str>) -> Result<PathBuf> {
    let root = smith::config::auth_dir();
    match fixture_issuer {
        None => Ok(root.join("oauth")),
        Some(issuer) => {
            super::validate_origin(issuer).map_err(fault)?;
            if !issuer.starts_with("http://127.0.0.1:") {
                return Err(fault("fixture issuer must be literal HTTP IPv4 loopback"));
            }
            Ok(root
                .join("oauth-fixtures")
                .join(smith::sha256::digest_hex(issuer.as_bytes())))
        }
    }
}

pub(super) fn authority_for(
    provider: SubscriptionProvider,
    fixture_issuer: Option<&str>,
    profile: Option<&str>,
) -> Result<LoginAuthority> {
    authority_at_for(
        provider,
        fixture_issuer,
        profile,
        profile_store_for(provider, fixture_issuer)?,
    )
}

pub(super) fn authority_at_for(
    provider: SubscriptionProvider,
    fixture_issuer: Option<&str>,
    profile: Option<&str>,
    store: ProfileStore,
) -> Result<LoginAuthority> {
    if provider == SubscriptionProvider::Google {
        let policy = google_policy(fixture_issuer);
        return selected_authority(policy, store, profile);
    }
    if provider == SubscriptionProvider::Anthropic {
        let policy = LoginPolicy {
            flow: LoginFlow::FixedClientPkceOpaque,
            connection_id: provider.connection_id().into(),
            issuer: fixture_issuer.unwrap_or("https://claude.ai").into(),
            token_origin: fixture_issuer
                .unwrap_or("https://platform.claude.com")
                .into(),
            resource: fixture_issuer.map_or_else(
                || "https://api.anthropic.com/v1".into(),
                |issuer| format!("{issuer}/v1"),
            ),
            initial_client: "9d1c250a-e61b-44d9-88ed-5944d1962f5e".into(),
            issued_prefix: String::new(),
            authorization_path: if fixture_issuer.is_some() {
                "/authorize"
            } else {
                "/oauth/authorize"
            }
            .into(),
            token_path: if fixture_issuer.is_some() {
                "/token"
            } else {
                "/v1/oauth/token"
            }
            .into(),
            agent_name: "Smith".into(),
            scopes: [
                "org:create_api_key",
                "user:profile",
                "user:inference",
                "user:sessions:claude_code",
                "user:mcp_servers",
                "user:file_upload",
            ]
            .into_iter()
            .map(str::to_string)
            .collect(),
            required_scopes: vec!["user:inference".into()],
        };
        return selected_authority(policy, store, profile);
    }
    let issuer = fixture_issuer.unwrap_or("https://auth.openai.com");
    let resource = fixture_issuer.map_or_else(
        || "https://api.openai.com/v1".to_string(),
        |issuer| format!("{issuer}/v1"),
    );
    let policy = LoginPolicy {
        flow: super::LoginFlow::DynamicOidc,
        connection_id: "openai-chatgpt-plan".into(),
        token_origin: issuer.to_string(),
        issuer: issuer.to_string(),
        resource,
        initial_client: "dynamic_agent_client".into(),
        issued_prefix: "oaiapp_".into(),
        authorization_path: if fixture_issuer.is_some() {
            "/authorize"
        } else {
            "/api/accounts/authorize"
        }
        .into(),
        token_path: if fixture_issuer.is_some() {
            "/token"
        } else {
            "/api/accounts/oauth/token"
        }
        .into(),
        agent_name: "Smith".into(),
        required_scopes: ["openid", "chatgpt.tokens.use.direct"]
            .into_iter()
            .map(str::to_string)
            .collect(),
        scopes: [
            "openid",
            "profile",
            "email",
            "offline_access",
            "resource.invoke",
            "chatgpt.tokens.use.direct",
        ]
        .into_iter()
        .map(str::to_string)
        .collect(),
    };
    selected_authority(policy, store, profile)
}

fn selected_authority(
    policy: LoginPolicy,
    store: ProfileStore,
    profile: Option<&str>,
) -> Result<LoginAuthority> {
    let authority = LoginAuthority::new(policy, store).map_err(fault)?;
    match profile {
        Some(id) => authority.select_profile(id).map_err(fault),
        None => Ok(authority),
    }
}

/// Continue with `ChatGPT` through the sealed guest and durable admission.
/// # Errors
/// Rejects invalid authority, component, storage, or authorization outcomes.
pub fn run(
    provider: SubscriptionProvider,
    journal: &Path,
    fixture_issuer: Option<&str>,
    profile: Option<&str>,
    project: Option<&str>,
    interrupt: Receiver<()>,
    stop_interrupt: impl FnOnce() -> Result<()>,
) -> Result<String> {
    let authority = authority_for(provider, fixture_issuer, profile)?;
    let authority = match project {
        Some(project) => authority.with_google_project(project).map_err(fault)?,
        None => authority,
    };
    let mut interrupt_worker = None;
    let result = run_operation(
        provider,
        journal,
        fixture_issuer,
        authority,
        "login",
        Some(interrupt),
        &mut interrupt_worker,
    );
    let stopped = stop_interrupt();
    let joined = interrupt_worker.map_or(Ok(()), |worker| {
        worker
            .join()
            .map_err(|_| fault("OAuth interrupt worker failed"))
    });
    let output = result?;
    stopped?;
    joined?;
    Ok(output)
}

/// End one explicitly selected session through the public OAuth guest effect.
/// # Errors
/// Rejects missing profile, failed durable admission, or failed local token clearing.
pub fn end_session(
    provider: SubscriptionProvider,
    journal: &Path,
    fixture_issuer: Option<&str>,
    profile: &str,
) -> Result<String> {
    let mut interrupt_worker = None;
    run_operation(
        provider,
        journal,
        fixture_issuer,
        authority_for(provider, fixture_issuer, Some(profile))?,
        "logout",
        None,
        &mut interrupt_worker,
    )
}

fn run_operation(
    provider: SubscriptionProvider,
    journal: &Path,
    fixture_issuer: Option<&str>,
    authority: LoginAuthority,
    operation: &str,
    interrupt: Option<Receiver<()>>,
    interrupt_worker: &mut Option<std::thread::JoinHandle<()>>,
) -> Result<String> {
    let profile = authority
        .selected
        .as_ref()
        .map(|profile| profile.id.clone());
    let engine = PluginEngine::new()?;
    let manifest = PluginManifest::parse(
        "id \"smith:oauth\"\nversion \"0.1.0\"\nworld \"0.1.0\"\nartifact \"smith_plugin_oauth.wasm\"\ncapability \"secret-proxy\"",
    )?;
    let mut generation = PluginGeneration::load_embedded(
        &engine,
        manifest,
        include_bytes!(concat!(env!("OUT_DIR"), "/smith_plugin_oauth.wasm")),
        &[Capability::SecretProxy],
    )?;
    generation.configure_login_authority(authority);
    let mut registry = PluginRegistry::default();
    registry.publish_all(vec![generation])?;
    let storage = Arc::new(StorageWorker::start(journal.to_path_buf()));
    storage.open(Config::default_valid())?;
    let description = format!("{operation} {}", provider.connection_id());
    let admission = storage.admit_foreground(&description, None)?;
    let root = admission.work.receipt.submission_id;
    let session = storage.claim(root)?;
    let append = Arc::clone(&storage);
    let completion = Arc::clone(&storage);
    let working_dir = journal
        .parent()
        .ok_or_else(|| fault("OAuth journal parent missing"))?;
    let mut tools = ToolSession::with_persist(working_dir, session, move |entry, bytes| {
        append.append(smith_core::session::EntryFrame {
            id: entry.id,
            parent: entry.parent,
            timestamp_ms: entry.timestamp_ms,
            kind: entry.kind,
            content: bytes.to_vec(),
        })
    })
    .with_completion_boundary(root, move |frame| completion.commit_completion(frame));
    tools.set_dispatcher(Box::new(registry));
    storage.register_cancel(root, tools.cancel_handle())?;
    if let Some(interrupt) = interrupt {
        let cancellation = Arc::clone(&storage);
        *interrupt_worker = Some(std::thread::spawn(move || {
            if interrupt.recv().is_ok() {
                let _abort = cancellation.abort(Some(root));
            }
        }));
    }
    tools.begin_provider_round()?;
    let input = if operation == "logout" {
        serde_json::json!({"profile":profile})
    } else {
        let mut input = serde_json::json!({"provider":provider.connection_id()});
        if let Some(issuer) = fixture_issuer {
            input["fixture_issuer"] = serde_json::json!(issuer);
        }
        input
    };
    let arguments =
        ToolArguments::from_serializable(&input).map_err(|_| fault("OAuth arguments invalid"))?;
    let result = tools.invoke(&format!("smith:oauth/{operation}"), &arguments);
    let reason = result
        .as_ref()
        .ok()
        .map(|_| smith::stream::StopReason::EndTurn);
    storage.settle(smith_core::frame::Frame::Settlement {
        submission_id: root,
        reason,
        output: None,
    })?;
    result.map(|outcome| outcome.output)
}

fn fault(message: &str) -> SmithError {
    SmithError::Config {
        field: "oauth".into(),
        message: message.into(),
    }
}

fn google_policy(fixture_issuer: Option<&str>) -> LoginPolicy {
    LoginPolicy {
        flow: LoginFlow::GoogleInstalledPkce,
        connection_id: "google-gemini-cli-plan".into(),
        issuer: fixture_issuer
            .unwrap_or("https://accounts.google.com")
            .into(),
        token_origin: fixture_issuer
            .unwrap_or("https://oauth2.googleapis.com")
            .into(),
        resource: fixture_issuer.map_or_else(
            || "https://cloudcode-pa.googleapis.com/v1internal".into(),
            |issuer| format!("{issuer}/v1internal"),
        ),
        initial_client: "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com"
            .into(),
        issued_prefix: String::new(),
        authorization_path: if fixture_issuer.is_some() {
            "/authorize"
        } else {
            "/o/oauth2/v2/auth"
        }
        .into(),
        token_path: "/token".into(),
        agent_name: "Smith".into(),
        scopes: [
            "https://www.googleapis.com/auth/cloud-platform",
            "https://www.googleapis.com/auth/userinfo.email",
            "https://www.googleapis.com/auth/userinfo.profile",
        ]
        .into_iter()
        .map(str::to_string)
        .collect(),
        required_scopes: vec!["https://www.googleapis.com/auth/cloud-platform".into()],
    }
}