Skip to content

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

feat(api): add JWT authentication and billing classification support

Steven Enamakel1c5333452431
diff --git a/crates/openhuman-core/src/hosted/billing/classify.rs b/crates/openhuman-core/src/api/classify.rs
similarity index 100%
rename from crates/openhuman-core/src/hosted/billing/classify.rs
rename to crates/openhuman-core/src/api/classify.rs
diff --git a/crates/openhuman-core/src/hosted/billing/classify_tests.rs b/crates/openhuman-core/src/api/classify_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/hosted/billing/classify_tests.rs
rename to crates/openhuman-core/src/api/classify_tests.rs
diff --git a/crates/openhuman-core/src/api/jwt.rs b/crates/openhuman-core/src/api/jwt.rs
index 60ac4bcaeb..4cfcc1b874 100644
--- a/crates/openhuman-core/src/api/jwt.rs
+++ b/crates/openhuman-core/src/api/jwt.rs
@@ -1,16 +1,57 @@
//! Session JWT load and `Authorization` helpers for the TinyHumans API.
//!
-//! Parsing and header formatting live in the vendored SDK
-//! (`tinyhumans_sdk::jwt`) — they are properties of the backend's token, not of
-//! this client, and every host needs them. Re-exported here so existing call
-//! sites keep one import path.
+//! The backend issues a bare JWT as the session token. These helpers *read*
+//! it — they never verify it. The backend stays the authority on validity: a
+//! token revoked before its `exp` still returns 401, and callers must handle
+//! that. Reading `exp` locally is only an optimisation that avoids sending a
+//! request with a token already known to be dead.
+//!
+//! Parsing is pure and has no backend dependency, which is why it lives in the
+//! core rather than behind the backend transport: `security::credentials`
+//! needs it on a core that has no TinyHumans connection at all.
//!
//! What stays OpenHuman-specific is *where the token lives*: the credentials
//! store, keyring, and auth-profile names below.
+use base64::Engine;
use chrono::{DateTime, Utc};
+use serde_json::Value;
+
+/// Format a token as an `Authorization: Bearer …` header value.
+///
+/// Surrounding whitespace is trimmed — tokens pasted by hand or read from a
+/// file routinely carry a trailing newline, and the backend rejects the header
+/// if it survives. Interior whitespace is left alone: it cannot appear in a
+/// well-formed JWT, so trimming it would mask a malformed token rather than
+/// fix one.
+pub fn bearer_authorization_value(token: &str) -> String {
+ format!("Bearer {}", token.trim())
+}
-pub use tinyhumans_sdk::jwt::{bearer_authorization_value, decode_jwt_payload};
+/// Decode a JWT's payload without verifying the signature.
+///
+/// Returns `None` for anything that is not a JWT with a base64url payload
+/// holding JSON — including the non-JWT sentinels hosts store for offline or
+/// local sessions, which must not panic here.
+pub fn decode_jwt_payload(token: &str) -> Option<Value> {
+ // JWT = header.payload.signature (base64url, no padding). Only the payload
+ // segment is needed. Padded input is accepted as a fallback because not
+ // every issuer omits padding.
+ let payload_b64 = token.trim().split('.').nth(1)?;
+ let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .decode(payload_b64)
+ .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(payload_b64))
+ .ok()?;
+ serde_json::from_slice(&bytes).ok()
+}
+
+/// Read a JWT's `exp` claim as a Unix timestamp in seconds. `exp` is a
+/// NumericDate, so both integer and float encodings are accepted.
+pub fn decode_jwt_exp_unix(token: &str) -> Option<i64> {
+ decode_jwt_payload(token)?
+ .get("exp")
+ .and_then(|value| value.as_i64().or_else(|| value.as_f64().map(|f| f as i64)))
+}
pub use crate::security::credentials::session_support::get_session_token;
pub use crate::security::credentials::{APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};
@@ -30,10 +71,10 @@ pub use crate::security::credentials::{APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFIL
/// non-JWT / malformed / `exp`-less token, in which case expiry tracking
/// degrades to the previous behaviour (no local precheck).
///
-/// The SDK returns Unix seconds so it needs no datetime dependency; this wraps
-/// that in the `chrono` type the credentials store already uses.
+/// [`decode_jwt_exp_unix`] wrapped in the `chrono` type the credentials store
+/// already uses.
pub fn decode_jwt_exp(token: &str) -> Option<DateTime<Utc>> {
- DateTime::<Utc>::from_timestamp(tinyhumans_sdk::jwt::decode_jwt_exp_unix(token)?, 0)
+ DateTime::<Utc>::from_timestamp(decode_jwt_exp_unix(token)?, 0)
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/api/jwt_tests.rs b/crates/openhuman-core/src/api/jwt_tests.rs
index 6d639dc32c..d9a645d4e0 100644
--- a/crates/openhuman-core/src/api/jwt_tests.rs
+++ b/crates/openhuman-core/src/api/jwt_tests.rs
@@ -6,8 +6,43 @@ fn jwt_with_payload(payload_json: &str) -> String {
format!("eyJhbGciOiJIUzI1NiJ9.{payload}.sig")
}
-// The SDK owns the parsing rules and tests them directly. What matters here
-// is that the `chrono` conversion this crate depends on stays correct.
+#[test]
+fn bearer_value_trims_surrounding_whitespace_only() {
+ assert_eq!(bearer_authorization_value("my_token"), "Bearer my_token");
+ assert_eq!(
+ bearer_authorization_value(" spaced_token "),
+ "Bearer spaced_token"
+ );
+ assert_eq!(bearer_authorization_value(""), "Bearer ");
+ assert_eq!(bearer_authorization_value(" "), "Bearer ");
+ // Interior whitespace is preserved — see the doc comment.
+ assert_eq!(
+ bearer_authorization_value("token with spaces"),
+ "Bearer token with spaces"
+ );
+}
+
+#[test]
+fn decode_jwt_payload_reads_claims_and_accepts_padded_base64() {
+ let token = jwt_with_payload(r#"{"sub":"u1","exp":1700000000}"#);
+ let payload = decode_jwt_payload(&token).unwrap();
+ assert_eq!(payload["sub"], "u1");
+ assert_eq!(payload["exp"], 1_700_000_000);
+
+ use base64::Engine;
+ let padded = base64::engine::general_purpose::URL_SAFE.encode(r#"{"sub":"padded"}"#);
+ let token = format!("h.{padded}.s");
+ assert_eq!(decode_jwt_payload(&token).unwrap()["sub"], "padded");
+}
+
+#[test]
+fn decode_jwt_payload_none_for_non_jwt_input() {
+ assert!(decode_jwt_payload("").is_none());
+ assert!(decode_jwt_payload("not-a-jwt").is_none());
+ assert!(decode_jwt_payload("a.!!!.c").is_none());
+ assert!(decode_jwt_payload("embedded.harness.local").is_none());
+}
+
#[test]
fn decode_jwt_exp_reads_integer_exp() {
let token = jwt_with_payload(r#"{"sub":"u1","exp":1700000000}"#);
diff --git a/crates/openhuman-core/src/api/mod.rs b/crates/openhuman-core/src/api/mod.rs
index 0cca6d4255..2162626415 100644
--- a/crates/openhuman-core/src/api/mod.rs
+++ b/crates/openhuman-core/src/api/mod.rs
@@ -5,15 +5,24 @@
//! [`crate::api::rest`] for authenticated (bearer-only) REST calls,
//! [`crate::api::product`] for the `x-sdk-name` product identity every
//! backend-bound request carries,
+//! [`crate::api::transport`] for the backend port every request rides
+//! (the SDK-backed implementation lives in `openhuman-tinyhumans`),
+//! [`crate::api::headers`] for the attribution headers and client profiles
+//! that implementation builds from,
+//! [`crate::api::classify`] for backend error-body classification shared
+//! across domains,
//! and [`crate::api::socket`] for Socket.IO WebSocket URLs.
//! [`crate::api::models`] holds shared DTOs for realtime (server-adjacent).
+pub mod classify;
pub mod config;
+pub mod headers;
pub mod jwt;
pub mod models;
pub mod product;
pub mod rest;
pub mod socket;
+pub mod transport;
pub use config::{
api_base_from_env, effective_api_url, effective_backend_api_url, normalize_api_base_url,
@@ -29,3 +38,7 @@ pub use rest::{
BackendOAuthClient, ConnectResponse, IntegrationSummary, IntegrationTokensHandoff,
};
pub use socket::websocket_url;
+pub use transport::{
+ install_backend_transport, installed_backend_transport, resolve_backend_transport,
+ BackendRequest, BackendTransport, BackendTransportError, TransportProfile,
+};