node-device-session 7.6.219

Shared server for /econ-v1/device-session/1 behind transport-neutral traits (C-5)
Documentation
//! Session open/renew message shapes and device.call service table.

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>,
}

/// Session mode after a successful open.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenMode {
    /// Full attested session (credential verified).
    #[default]
    Full,
    /// Renewal-only session (`http.request/1` to registration paths).
    Renewal,
}

/// Proven session identity after a successful `session.open/1`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OpenOk {
    /// Full or renewal.
    #[serde(default)]
    pub mode: OpenMode,
    /// Stable device id.
    pub device_id: String,
    /// Device DID.
    pub device_did: String,
    /// Granted scopes (empty in renewal mode).
    pub scopes: Vec<String>,
    /// Expiry (RFC3339 or epoch seconds for renewal).
    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)
}