use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::error::GuardError;
use crate::policy::FinancialCallMetadata;
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CloudGuardAction {
ToolsList,
ToolsCall,
}
#[derive(Debug, Clone, Serialize)]
pub struct MetadataOnlyVerifyRequest {
pub session_id: String,
pub action: CloudGuardAction,
#[serde(skip_serializing_if = "Option::is_none")]
pub tools_list: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub args_sha256: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub financial_metadata: Option<FinancialCallMetadata>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CloudWormReceipt {
pub seq: u64,
pub timestamp_ms: u64,
pub entry_hmac: String,
pub prev_entry_hmac: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CloudVerifyResponse {
pub status: String,
pub quota_unlimited: bool,
pub renewal_warning: bool,
#[serde(default)]
pub canonical_tools_json: Option<Value>,
#[serde(default)]
pub tools_root_sha256: Option<String>,
pub worm_receipt: CloudWormReceipt,
#[serde(default)]
pub renewal_url: Option<String>,
#[serde(default)]
pub activated_at_ms: Option<u64>,
#[serde(default)]
pub expires_at_ms: Option<u64>,
#[serde(default)]
pub day1_native_model_priority: bool,
#[serde(default)]
pub trial_reminder_stage: Option<String>,
#[serde(default)]
pub trial_remaining_ms: Option<u64>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct CloudErrorPayload {
#[serde(default)]
error: String,
#[serde(default)]
reason: String,
#[serde(default)]
code: Option<i64>,
#[serde(default)]
renewal_url: Option<String>,
#[serde(default)]
upgrade_url: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TrialIssueResponse {
pub status: String,
pub tier: String,
pub certificate: String,
#[serde(default)]
pub trial_duration_ms: u64,
#[serde(default)]
pub day1_native_model_priority: bool,
#[serde(default)]
pub max_account_equity_cents: u64,
#[serde(default)]
pub activated_at_ms: Option<u64>,
#[serde(default)]
pub expires_at_ms: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct CloudGuardClient {
http: reqwest::Client,
base_url: String,
bearer_cert: String,
}
impl CloudGuardClient {
pub fn new(base_url: String, bearer_cert: String) -> Result<Self, GuardError> {
let http = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()
.map_err(|e| GuardError::CloudUnavailable(format!("http client init error: {e}")))?;
Ok(Self {
http,
base_url: base_url.trim_end_matches('/').to_string(),
bearer_cert,
})
}
pub fn hash_args_metadata(args: &Value) -> String {
let compact = serde_json::to_vec(args).unwrap_or_default();
hex::encode(Sha256::digest(&compact))
}
pub async fn verify_entitlement_remote(&self) -> Result<Value, GuardError> {
let url = format!("{}/v1/entitlement/verify", self.base_url);
let resp = self
.http
.get(&url)
.bearer_auth(&self.bearer_cert)
.send()
.await
.map_err(|e| {
GuardError::CloudUnavailable(format!("cloud verify request error: {e}"))
})?;
let status = resp.status();
let val: Value = resp
.json()
.await
.map_err(|e| GuardError::CloudUnavailable(format!("invalid JSON from cloud: {e}")))?;
if !status.is_success() {
return Err(GuardError::License(format!(
"cloud entitlement verification rejected ({status}): {val}"
)));
}
Ok(val)
}
pub async fn canonicalize_and_verify(
&self,
req: MetadataOnlyVerifyRequest,
) -> Result<CloudVerifyResponse, GuardError> {
let url = format!("{}/v1/guard/canonicalize-and-verify", self.base_url);
let resp = self
.http
.post(&url)
.bearer_auth(&self.bearer_cert)
.json(&req)
.send()
.await
.map_err(|e| {
GuardError::CloudUnavailable(format!("cloud canonicalize request failed: {e}"))
})?;
let status = resp.status();
let hdr_stage = resp
.headers()
.get("x-monaa-trial-reminder")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.split(';').next())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string);
let hdr_remaining_ms = resp
.headers()
.get("x-monaa-trial-remaining-ms")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok());
if status.is_success() {
let mut parsed = resp.json::<CloudVerifyResponse>().await.map_err(|e| {
GuardError::CloudUnavailable(format!("invalid cloud response JSON: {e}"))
})?;
if parsed.trial_reminder_stage.is_none() {
parsed.trial_reminder_stage = hdr_stage;
}
if parsed.trial_remaining_ms.is_none() {
parsed.trial_remaining_ms = hdr_remaining_ms;
}
return Ok(parsed);
}
let err_body = resp.json::<CloudErrorPayload>().await.ok();
if let Some(payload) = err_body {
if payload.code == Some(-32023)
|| payload.error == "account_cap_exceeded"
|| status == reqwest::StatusCode::FORBIDDEN
{
let upgrade = payload
.upgrade_url
.or(payload.renewal_url)
.unwrap_or_else(|| "https://monaa.dev".to_string());
return Err(GuardError::AccountCapExceeded(format!(
"{} (institutional enclave: {upgrade})",
payload.reason
)));
}
if payload.code == Some(-32021) || payload.error == "rug_pull_detected" {
return Err(GuardError::CloudRugPull(payload.reason));
}
if status == reqwest::StatusCode::PAYMENT_REQUIRED
|| status == reqwest::StatusCode::UNAUTHORIZED
{
return Err(GuardError::License(format!(
"{} ({status}) {}",
payload.reason,
payload.renewal_url.unwrap_or_default()
)));
}
return Err(GuardError::CloudUnavailable(format!(
"cloud error ({status}): {}",
payload.reason
)));
}
Err(GuardError::CloudUnavailable(format!(
"cloud returned HTTP {status}"
)))
}
pub async fn request_cloud_trial(
base_url: &str,
email: &str,
github_id: &str,
) -> Result<TrialIssueResponse, GuardError> {
let clean_email = email.trim();
let clean_github = github_id.trim();
if clean_email.is_empty() || !clean_email.contains('@') {
return Err(GuardError::Config(
"valid email address is required for 7-day cloud trial".to_string(),
));
}
if clean_github.is_empty() {
return Err(GuardError::Config(
"--github username/id is required for 7-day cloud trial".to_string(),
));
}
let http = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()
.map_err(|e| GuardError::CloudUnavailable(format!("http client init error: {e}")))?;
let url = format!("{}/v1/checkout/session", base_url.trim_end_matches('/'));
let resp = http
.post(&url)
.json(&serde_json::json!({
"email": clean_email,
"github_id": clean_github,
"plan": "free_launch",
"response_mode": "json",
}))
.send()
.await
.map_err(|e| GuardError::CloudUnavailable(format!("trial request failed: {e}")))?;
let status = resp.status();
if status.is_success() {
return resp.json::<TrialIssueResponse>().await.map_err(|e| {
GuardError::CloudUnavailable(format!("invalid trial response JSON: {e}"))
});
}
let err_body = resp.json::<CloudErrorPayload>().await.ok();
let reason = err_body
.map(|p| {
if p.reason.is_empty() {
p.error
} else {
p.reason
}
})
.filter(|s| !s.is_empty())
.unwrap_or_else(|| format!("trial request declined with HTTP {status}"));
Err(GuardError::License(reason))
}
}