Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(oauth): add OAuth module with types, schemas, and operations

Steven Enamakel78022d5dbce2
diff --git a/crates/openhuman-tinyhumans/src/hosted/oauth/mod.rs b/crates/openhuman-tinyhumans/src/hosted/oauth/mod.rs
new file mode 100644
index 0000000000..9427464348
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/hosted/oauth/mod.rs
@@ -0,0 +1,20 @@
+//! Backend-brokered OAuth integrations (`/auth/{provider}/connect`,
+//! `/auth/integrations*`) on the SDK's typed `auth()` client.
+//!
+//! RPC names (`openhuman.auth_oauth_connect`, `auth_oauth_list_integrations`,
+//! `auth_oauth_fetch_integration_tokens`, `auth_oauth_revoke_integration`) are
+//! unchanged wire contracts. They share the `auth` namespace with the core's
+//! credential controllers, which stay in the core.
+//!
+//! `auth_oauth_fetch_client_key` is **not** here: its route
+//! (`POST /auth/integrations/{id}/client-key`) has no SDK method and is absent
+//! from the SDK's public-route registry, so it stays on the core's pre-SDK path
+//! until the route is added upstream.
+
+mod ops;
+mod schemas;
+mod types;
+
+pub use ops::*;
+pub use schemas::{all_oauth_controller_schemas, all_oauth_registered_controllers, oauth_schemas};
+pub use types::{IntegrationSummary, IntegrationTokensHandoff};
diff --git a/crates/openhuman-tinyhumans/src/hosted/oauth/ops.rs b/crates/openhuman-tinyhumans/src/hosted/oauth/ops.rs
new file mode 100644
index 0000000000..a0500d7bc3
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/hosted/oauth/ops.rs
@@ -0,0 +1,153 @@
+//! Backend-brokered OAuth connect flow and integration token retrieval.
+//!
+//! Validation runs first, then the credential is resolved ([`HostedClient`]):
+//! a user with no TinyHumans account gets the core's sentinel without a
+//! request. Tokens, keys and encrypted blobs are never logged.
+
+use serde_json::{json, Value};
+use tinyhumans_sdk::api::types::IntegrationTokenRequest;
+
+use openhuman_core::api::decrypt_handoff_blob;
+use openhuman_core::config::Config;
+use openhuman_core::rpc::RpcOutcome;
+
+use super::types::{IntegrationSummary, IntegrationTokensHandoff};
+use crate::hosted::client::HostedClient;
+
+const LOG_PREFIX: &str = "[hosted][oauth]";
+
+fn require_provider(provider: &str) -> Result<&str, String> {
+ let p = provider.trim().trim_matches('/');
+ if p.is_empty() {
+ return Err("provider is required".to_string());
+ }
+ Ok(p)
+}
+
+fn require_integration_id(integration_id: &str) -> Result<&str, String> {
+ let id = integration_id.trim();
+ if id.is_empty() || id.len() != 24 {
+ return Err("integrationId must be a 24-char hex id".to_string());
+ }
+ Ok(id)
+}
+
+fn non_empty(value: Option<&str>) -> Option<String> {
+ value.filter(|v| !v.is_empty()).map(str::to_string)
+}
+
+/// `GET /auth/{provider}/connect` — an authorize URL plus CSRF `state`.
+pub async fn oauth_connect(
+ config: &Config,
+ provider: &str,
+ skill_id: Option<&str>,
+ response_type: Option<&str>,
+ encryption_mode: Option<&str>,
+) -> Result<RpcOutcome<Value>, String> {
+ let provider = require_provider(provider)?;
+ let client = HostedClient::from_config(config)?;
+ let query = [
+ ("skillId", non_empty(skill_id)),
+ ("responseType", non_empty(response_type)),
+ ("encryptionMode", non_empty(encryption_mode)),
+ ];
+ log::debug!("{LOG_PREFIX} connect provider={provider}");
+ let value = client.finish_value(
+ "GET /auth/{provider}/connect",
+ client.sdk().auth().oauth_connect(provider, &query).await,
+ )?;
+ let oauth_url = value
+ .get("oauthUrl")
+ .or_else(|| value.get("oauth_url"))
+ .and_then(Value::as_str)
+ .filter(|url| !url.is_empty())
+ .ok_or_else(|| "auth connect request: missing oauthUrl in response".to_string())?;
+ let state = value
+ .get("state")
+ .and_then(Value::as_str)
+ .filter(|state| !state.is_empty())
+ .ok_or_else(|| "auth connect request: missing state".to_string())?;
+ Ok(RpcOutcome::single_log(
+ json!({ "oauthUrl": oauth_url, "state": state }),
+ "oauth connect URL ready",
+ ))
+}
+
+/// `GET /auth/integrations` — the user's active integrations.
+pub async fn oauth_list_integrations(config: &Config) -> Result<RpcOutcome<Value>, String> {
+ let client = HostedClient::from_config(config)?;
+ let value = client.finish_value(
+ "GET /auth/integrations",
+ client.sdk().auth().list_integrations().await,
+ )?;
+ let integrations = value
+ .get("integrations")
+ .cloned()
+ .unwrap_or_else(|| value.clone());
+ let list: Vec<IntegrationSummary> = serde_json::from_value(integrations)
+ .map_err(|e| format!("parse integrations response: {e}"))?;
+ Ok(RpcOutcome::single_log(
+ serde_json::to_value(&list).map_err(|e| e.to_string())?,
+ "integrations listed",
+ ))
+}
+
+/// `POST /auth/integrations/{id}/tokens` — a one-time handoff of the
+/// integration's OAuth tokens, encrypted by the backend with `encryption_key`
+/// and decrypted here. The key goes back to the backend as given (never
+/// re-encoded) so base64url keys stay base64url on the wire.
+pub async fn oauth_fetch_integration_tokens(
+ config: &Config,
+ integration_id: &str,
+ encryption_key: &str,
+) -> Result<RpcOutcome<Value>, String> {
+ let id = require_integration_id(integration_id)?;
+ let client = HostedClient::from_config(config)?;
+ let request = IntegrationTokenRequest {
+ key: encryption_key.trim().to_string(),
+ };
+ let value = client.finish_value(
+ "POST /auth/integrations/{integrationId}/tokens",
+ client
+ .sdk()
+ .auth()
+ .create_integration_token(id, &request)
+ .await,
+ )?;
+ let encrypted = value
+ .get("encrypted")
+ .and_then(Value::as_str)
+ .ok_or_else(|| "integration tokens response missing encrypted payload".to_string())?;
+ let plaintext = decrypt_handoff_blob(encrypted, encryption_key.trim())
+ .map_err(|e| format!("integration tokens handoff: {e:#}"))?;
+ let tokens: IntegrationTokensHandoff = serde_json::from_str(&plaintext)
+ .map_err(|e| format!("parse decrypted token JSON: {e}"))?;
+ Ok(RpcOutcome::single_log(
+ serde_json::to_value(&tokens).map_err(|e| e.to_string())?,
+ "integration tokens retrieved",
+ ))
+}
+
+/// `DELETE /auth/integrations/{id}`.
+pub async fn oauth_revoke_integration(
+ config: &Config,
+ integration_id: &str,
+) -> Result<RpcOutcome<Value>, String> {
+ let id = integration_id.trim();
+ if id.is_empty() {
+ return Err("integration id is required".to_string());
+ }
+ let client = HostedClient::from_config(config)?;
+ client.finish_value(
+ "DELETE /auth/integrations/{integrationId}",
+ client.sdk().auth().delete_integration(id).await,
+ )?;
+ Ok(RpcOutcome::single_log(
+ json!({ "revoked": true, "integrationId": integration_id }),
+ "integration revoked",
+ ))
+}
+
+#[cfg(test)]
+#[path = "ops_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-tinyhumans/src/hosted/oauth/schemas.rs b/crates/openhuman-tinyhumans/src/hosted/oauth/schemas.rs
new file mode 100644
index 0000000000..5eb958261d
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/hosted/oauth/schemas.rs
@@ -0,0 +1,208 @@
+use serde::de::DeserializeOwned;
+use serde::Deserialize;
+use serde_json::{Map, Value};
+
+use openhuman_core::config::rpc as config_rpc;
+use openhuman_core::core::all::{ControllerFuture, RegisteredController};
+use openhuman_core::core::{ControllerSchema, FieldSchema, TypeSchema};
+use openhuman_core::rpc::RpcOutcome;
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AuthOauthConnectParams {
+ provider: String,
+ #[serde(default)]
+ skill_id: Option<String>,
+ #[serde(default)]
+ response_type: Option<String>,
+ #[serde(default)]
+ encryption_mode: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AuthOauthIntegrationTokensParams {
+ integration_id: String,
+ key: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AuthOauthRevokeParams {
+ integration_id: String,
+}
+
+const FUNCTIONS: &[&str] = &[
+ "auth_oauth_connect",
+ "auth_oauth_list_integrations",
+ "auth_oauth_fetch_integration_tokens",
+ "auth_oauth_revoke_integration",
+];
+
+pub fn all_oauth_controller_schemas() -> Vec<ControllerSchema> {
+ FUNCTIONS.iter().map(|f| oauth_schemas(f)).collect()
+}
+
+pub fn all_oauth_registered_controllers() -> Vec<RegisteredController> {
+ vec![
+ RegisteredController {
+ schema: oauth_schemas("auth_oauth_connect"),
+ handler: handle_auth_oauth_connect,
+ },
+ RegisteredController {
+ schema: oauth_schemas("auth_oauth_list_integrations"),
+ handler: handle_auth_oauth_list_integrations,
+ },
+ RegisteredController {
+ schema: oauth_schemas("auth_oauth_fetch_integration_tokens"),
+ handler: handle_auth_oauth_fetch_integration_tokens,
+ },
+ RegisteredController {
+ schema: oauth_schemas("auth_oauth_revoke_integration"),
+ handler: handle_auth_oauth_revoke_integration,
+ },
+ ]
+}
+
+/// Schema for one hosted `auth.oauth_*` function (unchanged wire contract).
+pub fn oauth_schemas(function: &str) -> ControllerSchema {
+ match function {
+ "auth_oauth_connect" => ControllerSchema {
+ namespace: "auth",
+ function: "oauth_connect",
+ description: "Create OAuth connect URL for provider.",
+ inputs: vec![
+ required_string("provider", "Provider id."),
+ optional_string("skillId", "Optional skill id."),
+ optional_string("responseType", "Optional OAuth response type."),
+ optional_string("encryptionMode", "Optional encryption mode ('encrypted')."),
+ ],
+ outputs: vec![json_output("result", "OAuth connect payload.")],
+ },
+ "auth_oauth_list_integrations" => ControllerSchema {
+ namespace: "auth",
+ function: "oauth_list_integrations",
+ description: "List OAuth integrations for current session.",
+ inputs: vec![],
+ outputs: vec![json_output("integrations", "OAuth integration list.")],
+ },
+ "auth_oauth_fetch_integration_tokens" => ControllerSchema {
+ namespace: "auth",
+ function: "oauth_fetch_integration_tokens",
+ description: "Fetch integration handoff tokens.",
+ inputs: vec![
+ required_string("integrationId", "Integration id."),
+ required_string("key", "Encryption key."),
+ ],
+ outputs: vec![json_output("tokens", "Integration tokens handoff payload.")],
+ },
+ "auth_oauth_revoke_integration" => ControllerSchema {
+ namespace: "auth",
+ function: "oauth_revoke_integration",
+ description: "Revoke OAuth integration.",
+ inputs: vec![required_string("integrationId", "Integration id.")],
+ outputs: vec![json_output("result", "Integration revoke result.")],
+ },
+ _ => ControllerSchema {
+ namespace: "auth",
+ function: "unknown",
+ description: "Unknown auth controller function.",
+ inputs: vec![],
+ outputs: vec![FieldSchema {
+ name: "error",
+ ty: TypeSchema::String,
+ comment: "Lookup error details.",
+ required: true,
+ }],
+ },
+ }
+}
+
+fn handle_auth_oauth_connect(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let payload = deserialize_params::<AuthOauthConnectParams>(params)?;
+ to_json(
+ crate::hosted::oauth::oauth_connect(
+ &config,
+ payload.provider.trim(),
+ payload.skill_id.as_deref().map(str::trim),
+ payload.response_type.as_deref().map(str::trim),
+ payload.encryption_mode.as_deref().map(str::trim),
+ )
+ .await?,
+ )
+ })
+}
+
+fn handle_auth_oauth_list_integrations(_params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ to_json(crate::hosted::oauth::oauth_list_integrations(&config).await?)
+ })
+}
+
+fn handle_auth_oauth_fetch_integration_tokens(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let payload = deserialize_params::<AuthOauthIntegrationTokensParams>(params)?;
+ to_json(
+ crate::hosted::oauth::oauth_fetch_integration_tokens(
+ &config,
+ payload.integration_id.trim(),
+ payload.key.trim(),
+ )
+ .await?,
+ )
+ })
+}
+
+fn handle_auth_oauth_revoke_integration(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let config = config_rpc::load_config_with_timeout().await?;
+ let payload = deserialize_params::<AuthOauthRevokeParams>(params)?;
+ to_json(
+ crate::hosted::oauth::oauth_revoke_integration(&config, payload.integration_id.trim())
+ .await?,
+ )
+ })
+}
+
+fn deserialize_params<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {
+ serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))
+}
+
+fn required_string(name: &'static str, comment: &'static str) -> FieldSchema {
+ FieldSchema {
+ name,
+ ty: TypeSchema::String,
+ comment,
+ required: true,
+ }
+}
+
+fn optional_string(name: &'static str, comment: &'static str) -> FieldSchema {
+ FieldSchema {
+ name,
+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),
+ comment,
+ required: false,
+ }
+}
+
+fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
+ FieldSchema {
+ name,
+ ty: TypeSchema::Json,
+ comment,
+ required: true,
+ }
+}
+
+fn to_json<T: serde::Serialize>(outcome: RpcOutcome<T>) -> Result<Value, String> {
+ outcome.into_cli_compatible_json()
+}
+
+#[cfg(test)]
+#[path = "schemas_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-tinyhumans/src/hosted/oauth/types.rs b/crates/openhuman-tinyhumans/src/hosted/oauth/types.rs
new file mode 100644
index 0000000000..10a1d92ad7
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/hosted/oauth/types.rs
@@ -0,0 +1,29 @@
+//! Serde shapes of the backend-brokered OAuth payloads (unchanged wire
+//! contracts of the `auth_oauth_*` RPCs).
+
+use serde::{Deserialize, Serialize};
+
+/// A summary of an active integration, as returned by the backend.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct IntegrationSummary {
+ /// Unique identifier for the integration.
+ pub id: String,
+ /// The name of the integration provider (e.g., "google", "slack").
+ pub provider: String,
+ /// RFC3339 timestamp of when the integration was created.
+ pub created_at: String,
+}
+
+/// Decrypted OAuth token payload for handing off tokens to a local service or skill.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct IntegrationTokensHandoff {
+ /// The OAuth access token.
+ pub access_token: String,
+ /// The optional OAuth refresh token.
+ #[serde(default)]
+ pub refresh_token: Option<String>,
+ /// RFC3339 timestamp of when the access token expires.
+ pub expires_at: String,
+}