use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct OpenRequest {
pub credential: Option<String>,
#[serde(default)]
pub mode: Option<OpenMode>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenMode {
#[default]
Full,
Renewal,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OpenOk {
#[serde(default)]
pub mode: OpenMode,
pub device_id: String,
pub device_did: String,
pub scopes: Vec<String>,
pub expires_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RenewRequest {}
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct RenewOk {
pub credential: String,
pub expires_at: String,
pub scopes: Vec<String>,
pub device_id: String,
pub device_did: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revocation_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct ServiceCall {
pub service: String,
#[serde(default)]
pub payload: Value,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Service {
pub name: &'static str,
pub capability: &'static str,
pub scope: &'static str,
}
pub(crate) const SERVICES: &[Service] = &[Service {
name: "agent",
capability: "agent.device.receive",
scope: "agent.device",
}];
pub(crate) fn service(name: &str) -> Option<&'static Service> {
SERVICES.iter().find(|s| s.name == name)
}
pub(crate) fn scope_allows(scopes: &[String], required: &str) -> bool {
scopes.iter().any(|scope| {
scope == required
|| scope
.strip_suffix(".*")
.is_some_and(|prefix| required.starts_with(&format!("{prefix}.")))
})
}
pub(crate) fn endpoint_hex(key: &[u8; 32]) -> String {
key.iter().map(|b| format!("{b:02x}")).collect()
}
pub(crate) struct StampIdentity<'a> {
pub device_id: &'a str,
pub device_did: &'a str,
pub scopes: &'a [String],
pub endpoint_hex: &'a str,
}
pub(crate) fn stamp(payload: Value, id: &StampIdentity<'_>) -> Value {
let mut map = match payload {
Value::Object(map) => map,
other => {
let mut m = Map::new();
m.insert("payload".into(), other);
m
}
};
map.insert("device_id".into(), Value::String(id.device_id.into()));
map.insert("device_did".into(), Value::String(id.device_did.into()));
map.insert(
"device_scopes".into(),
Value::Array(id.scopes.iter().cloned().map(Value::String).collect()),
);
map.insert(
"device_endpoint".into(),
Value::String(id.endpoint_hex.into()),
);
map.insert("sig_verified".into(), Value::Bool(false));
map.insert("caller".into(), Value::String("device".into()));
Value::Object(map)
}