node-device-session 7.7.2

Shared server for /econ-v1/device-session/1 behind transport-neutral traits (C-5)
Documentation
//! Periodic revalidation of live sessions.
//!
//! Ported from `node-app-iroh`'s `iroh.device.revalidate`: re-verify every live
//! session so a device revoked, unpaired or expired since it connected loses
//! its session within a minute.
//!
//! Only a *definitive* refusal from the host closes a session.
//! `verifier_unavailable`, timeouts and other errors leave the session open
//! and are counted as skipped.

use crate::registry::SessionRegistry;
use crate::traits::HostBus;
use std::time::Duration;

/// Per-session verify budget during a revalidation pass.
const VERIFY_DEADLINE: Duration = Duration::from_secs(10);

/// Verify-refusal codes that are a definitive refusal of the credential
/// itself — the host has positively decided this session is no longer valid.
const DEFINITIVE_REFUSALS: &[&str] = &[
    "device_revoked",
    "expired",
    "invalid_credential",
    "endpoint_mismatch",
];

/// The six refusal codes `core.device_session.verify` can answer with.
const VERIFY_REFUSAL_CODES: &[&str] = &[
    "invalid_request",
    "endpoint_mismatch",
    "invalid_credential",
    "device_revoked",
    "expired",
    "verifier_unavailable",
];

/// Result of one [`SessionRegistry::revalidate`] pass.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RevalidateReport {
    /// Device ids whose sessions were closed on a definitive refusal.
    pub closed: Vec<String>,
    /// Sessions left open because verify failed non-definitively (or timed out).
    pub skipped: u64,
}

/// Exact-match check: only these codes close a live session.
pub fn is_definitive_refusal_code(code: &str) -> bool {
    DEFINITIVE_REFUSALS
        .iter()
        .copied()
        .any(|known| known == code)
}

/// Pull a known verify refusal *code* out of a host error string, if (and only
/// if) it is one of the six codes the host's refusal shape carries.
///
/// Accepts either a bare code (`"device_revoked"`), a wire form
/// (`"device_revoked: detail"`), or the production capability-bus shape
/// (`"core.device_session.verify failed: device_revoked: detail"`). An
/// invocation failure (`"… invocation failed: …"`) never parses to a code.
pub fn verify_refusal_code(error: &str) -> Option<&str> {
    let prefix = format!("{} failed: ", crate::caps::VERIFY);
    let rest = error.strip_prefix(prefix.as_str()).unwrap_or(error);
    let candidate = rest.split(':').next().unwrap_or(rest).trim();
    VERIFY_REFUSAL_CODES
        .iter()
        .copied()
        .find(|&known| known == candidate)
}

impl SessionRegistry {
    /// Re-verify every live session via [`HostBus::verify`].
    ///
    /// Closes a session only on a definitive refusal code
    /// (`device_revoked`, `expired`, `invalid_credential`, `endpoint_mismatch`).
    /// `verifier_unavailable`, timeouts and other errors leave it open and
    /// increment [`RevalidateReport::skipped`].
    pub async fn revalidate(&self, bus: &dyn HostBus) -> RevalidateReport {
        let live = self.credentials();
        let mut closed = Vec::new();
        let mut skipped = 0u64;
        for (device_id, session_id, credential, endpoint_hex) in &live {
            let verdict =
                tokio::time::timeout(VERIFY_DEADLINE, bus.verify(credential, endpoint_hex)).await;
            match verdict {
                Ok(Ok(_)) => {}
                Ok(Err(refusal)) if is_definitive_refusal_code(&refusal.code) => {
                    if self.close(device_id, *session_id, b"revoked or expired") {
                        closed.push(device_id.clone());
                    }
                }
                Ok(Err(_)) | Err(_) => {
                    skipped += 1;
                }
            }
        }
        RevalidateReport { closed, skipped }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn definitive_codes_are_exact_matches_only() {
        assert!(is_definitive_refusal_code("device_revoked"));
        assert!(is_definitive_refusal_code("expired"));
        assert!(is_definitive_refusal_code("invalid_credential"));
        assert!(is_definitive_refusal_code("endpoint_mismatch"));
        assert!(!is_definitive_refusal_code("verifier_unavailable"));
        assert!(!is_definitive_refusal_code("invalid_request"));
        assert!(!is_definitive_refusal_code("device_revoked_extra"));
        assert!(!is_definitive_refusal_code(""));
    }

    #[test]
    fn verify_refusal_code_parses_production_shapes() {
        for code in VERIFY_REFUSAL_CODES {
            let error = format!("{} failed: {code}: some detail", crate::caps::VERIFY);
            assert_eq!(verify_refusal_code(&error), Some(*code));
            assert_eq!(verify_refusal_code(code), Some(*code));
        }
        assert_eq!(
            verify_refusal_code(&format!(
                "{} invocation failed: host closed",
                crate::caps::VERIFY
            )),
            None
        );
        assert_eq!(
            verify_refusal_code(&format!(
                "{} failed: something_else: detail",
                crate::caps::VERIFY
            )),
            None
        );
        assert_eq!(verify_refusal_code("totally unrelated string"), None);
        assert_eq!(verify_refusal_code(""), None);
    }
}