use serde_json::{Value, json};
use super::{ConsentError, Kind, Proof, Record, State, subject_digest};
pub const PROOF_MAX_AGE_MS: u64 = 30 * 60 * 1000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Choice {
ConsentId(String),
Presence(Value),
NeedsWeb { consent_id: String },
}
impl Choice {
pub fn attach(&self, body: &mut Value) -> Result<(), ConsentError> {
let Some(fields) = body.as_object_mut() else {
return Err(ConsentError::Local("request body is not an object".into()));
};
match self {
Choice::ConsentId(id) => {
fields.insert("consent_id".into(), id.clone().into());
}
Choice::Presence(proof) => {
fields.insert("consent_proof".into(), proof.clone());
}
Choice::NeedsWeb { consent_id } => {
return Err(ConsentError::WebOnly {
consent_id: consent_id.clone(),
});
}
}
Ok(())
}
}
pub fn choose(
record: &Record,
allow_local_consent: bool,
now: u64,
) -> Result<Choice, ConsentError> {
if !record.kind.server_gated() {
return Err(ConsentError::Local(format!(
"{} reaches no server route that takes a proof",
record.kind
)));
}
if record.state != State::Approved {
return Err(ConsentError::Required {
consent_id: record.consent_id.clone(),
kind: record.kind,
});
}
let fresh = record
.approved_at
.is_some_and(|at| now.saturating_sub(at) <= PROOF_MAX_AGE_MS);
let web = || Choice::NeedsWeb {
consent_id: record.consent_id.clone(),
};
Ok(match &record.proof {
Some(Proof::Statement(_)) if fresh => Choice::ConsentId(record.consent_id.clone()),
Some(Proof::Presence(signature))
if fresh && allow_local_consent && record.kind != Kind::ProcedureConfirm =>
{
Choice::Presence(json!({
"consent_id": record.consent_id,
"kind": record.kind,
"subject": record.subject,
"subject_digest": record.subject_digest,
"approved_at": record.approved_at,
"presence_key_id": signature.key_id,
"signature": signature.signature,
}))
}
_ => web(),
})
}
pub fn pledge_digest(pledge: &Value) -> Result<String, ConsentError> {
let field = |name: &str| pledge.get(name).cloned().unwrap_or(Value::Null);
subject_digest(&json!({
"mode": field("mode"),
"tasks_per_day": field("tasks_per_day"),
"tokens_per_day": field("tokens_per_day"),
"usd_cents_per_day": field("usd_cents_per_day"),
"window": field("window"),
"max_sessions": field("max_sessions"),
}))
}
pub fn swarm_join_subject(swarm: &str, pledge: &Value, cli: &str) -> Result<Value, ConsentError> {
Ok(json!({"swarm": swarm, "pledge_digest": pledge_digest(pledge)?, "cli": cli}))
}
pub fn pledge_change_subject(
swarm: &str,
before: &Value,
after: &Value,
) -> Result<Value, ConsentError> {
Ok(json!({
"swarm": swarm,
"before_digest": pledge_digest(before)?,
"after_digest": pledge_digest(after)?,
}))
}
pub fn unattended_subject(swarm: &str, pledge: &Value, cli: &str) -> Result<Value, ConsentError> {
Ok(json!({
"swarm": swarm,
"pledge_digest": pledge_digest(pledge)?,
"cli": cli,
"usd_cents_per_day": pledge.get("usd_cents_per_day").cloned().unwrap_or(Value::Null),
}))
}
pub fn loosens(before: &Value, after: &Value) -> bool {
let raised = |name: &str| match (before[name].as_u64(), after[name].as_u64()) {
(Some(b), Some(a)) => a > b,
(Some(_), None) => after[name].is_null(),
_ => false,
};
["tasks_per_day", "tokens_per_day", "usd_cents_per_day", "max_sessions"]
.into_iter()
.any(raised)
|| (after["mode"] == "unattended" && before["mode"] != "unattended")
|| (!before["window"].is_null() && after["window"].is_null())
|| window_widened(&before["window"], &after["window"])
}
fn window_widened(before: &Value, after: &Value) -> bool {
if before.is_null() || after.is_null() || before == after {
return false;
}
let days = |w: &Value| -> Vec<String> {
w["days"]
.as_array()
.map(|d| {
d.iter()
.filter_map(|x| x.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default()
};
let same_hours = before["from"] == after["from"]
&& before["to"] == after["to"]
&& before["tz"] == after["tz"];
let subset = days(after).iter().all(|d| days(before).contains(d));
!(same_hours && subset)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerRefusal {
pub kind: Option<Kind>,
pub reason: Option<String>,
}
impl ServerRefusal {
pub fn parse(body: &Value) -> Option<ServerRefusal> {
let error = &body["error"];
(error["code"] == "consent_required").then(|| ServerRefusal {
kind: error["kind"].as_str().and_then(Kind::parse),
reason: error["reason"].as_str().map(str::to_string),
})
}
pub fn needs_new_approval(&self) -> bool {
matches!(
self.reason.as_deref(),
None | Some("missing" | "stale" | "used" | "subject" | "channel")
)
}
}
#[cfg(test)]
#[path = "proof_tests.rs"]
mod tests;