techne-sdk 0.3.3

TechneSDK's logic written once: version ranking (eventState) and offline record verification over the published check, shipped to TypeScript as WebAssembly; with opt-in atproto plumbing (service auth, DID resolution, signed labels, proven record fetches, PDS password sessions) behind the `crypto` and `net` features.
Documentation
//! What an app can check for itself about a record it read (P13.5): the pure check from
//! `techne-lexicon-check`, over records the app holds, with nothing asked of the platform.
//!
//! [`verify`] answers three things about one record:
//! - **valid**: its body hashes to the CID it was served with (a tampered body does not), and
//!   [`decide`] calls the version valid (lexicon, placement, provenance) over the claims the app holds;
//! - **signer**: the repo it is from (the DID in its AT-URI). atproto signs a repo's commits, not each
//!   record, so this is whose repo the record claims to be in; proving the commit signature needs the
//!   commit and its MST path, which a read does not carry;
//! - **chainVerified**: an admin writer vouches for the signer's `publisher/self` declaration and the
//!   declaration covers the record's collection ([`chain::vouched`], [`chain::writer`]), checked
//!   offline: the credential pins the declaration by CID, and every record used is first checked
//!   against its own CID (which proves a body matches the CID it came with, not which repo served it:
//!   the credential's own place is its AT-URI in its issuer's repo, as `chain::vouched` requires). False
//!   whenever the record itself is not intact.
//!
//! The admin writers are the platform's (provenancePolicy#vouchedWriter, "option (b)"): the commons
//! root, and an operator the root names in a `pub.techne.draft.operator` record (in the root's repo, at
//! rkey `{did}` or `{did}-{millis}`, `subject` = that DID) whose period (`validFrom` inclusive,
//! `validUntil` exclusive, an absent end open) holds when the app first saw the credential
//! ([`Record::first_seen`]). A credential is revoked by a record at its own `revocation` address (in the
//! issuer's repo) or at the same rkey in the root's repo, so the root can revoke an operator's credential.
//!
//! The caller holds one declaration per account, its current one: an edited declaration is untrusted
//! until an admin writer re-issues, and an app that kept the old one beside an unrevoked credential would
//! still count it. Likewise one version per credential: when it holds several at one address, the
//! credential counts only if every one of them was first seen while its issuer was an admin writer.
//! Roles and admissions are as of the version's first-seen time, as the caller asserts.
//!
//! [`Claims`] is the data form of `techne_lexicon_check::Claims`: the root, the records the app has read
//! (credentials, declarations, revocations, the root's operator records), and any roles and admissions
//! it knows.

use techne_lexicon_check::chain;
use techne_lexicon_check::{parse_at_uri, same_name, same_uri};
use techne_lexicon_check::{dag_cbor, decide, Decision, Endorsements, Role, Vouch};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// The root's statement that an account is an operator for a period.
const OPERATOR: &str = "pub.techne.draft.operator";

/// One record as read: its address, the CID it was served with, and its body.
#[derive(Debug, Clone, Deserialize)]
pub struct Record {
    pub uri: String,
    pub cid: String,
    pub value: Value,
    /// When the app first saw this version (RFC 3339). Read for a credential an operator issued: it
    /// counts only if the root names the operator for a period holding then. Without it, only a period
    /// open at both ends holds.
    #[serde(default, rename = "firstSeen")]
    pub first_seen: Option<String>,
}

impl Record {
    fn as_chain(&self) -> chain::Record<'_> {
        chain::Record { uri: &self.uri, cid: &self.cid, body: &self.value }
    }

    /// The body hashes to `cid`.
    pub fn intact(&self) -> bool {
        dag_cbor::cid_for_json(&self.value).is_ok_and(|c| c.to_string() == self.cid)
    }
}

/// A member's role in a collective, as the app knows it.
#[derive(Debug, Clone, Deserialize)]
pub struct KnownRole {
    pub member: String,
    pub collective: String,
    /// The role held; `None`: a membership is known but none covered the time.
    pub role: Option<i16>,
}

/// Whether an author passed a space's write policy, as the app knows it.
#[derive(Debug, Clone, Deserialize)]
pub struct KnownAdmission {
    pub author: String,
    pub space: String,
    pub admitted: bool,
}

/// What the app holds to check records against.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Claims {
    /// The commons root DID.
    pub root: Option<String>,
    /// Records the app has read: credentials and revocations (the root's and its operators'), the root's
    /// operator records, accounts' declarations.
    /// A record whose body does not hash to its CID is ignored.
    pub records: Vec<Record>,
    pub roles: Vec<KnownRole>,
    pub admissions: Vec<KnownAdmission>,
}

impl Claims {
    fn intact(&self) -> impl Iterator<Item = &Record> {
        self.records.iter().filter(|r| r.intact())
    }

    /// The admin writer that issued `cred`, if its repo is one for it: the root, or an operator one of
    /// the root's intact operator records names for a period holding at `cred`'s first-seen time.
    fn issuer_of<'a>(&'a self, cred: &'a Record) -> Option<&'a str> {
        let root = self.root.as_deref()?;
        let (repo, _, _) = parse_at_uri(&cred.uri)?;
        if repo == root {
            return Some(root);
        }
        let seen = cred.first_seen.as_deref();
        self.intact().any(|o| names_operator(root, o, repo, seen)).then_some(repo)
    }

    /// A record is held at `cred`'s `revocation` address, or at the same rkey in the root's repo.
    fn revoked(&self, cred: &Record) -> bool {
        // A revocation counts wherever it is read: its presence is what revokes. A credential keeps the
        // spelling it was issued under, so its `revocation` matches a record read under any spelling of
        // the collection (`same_uri`: same repo and rkey, a renamed collection's old or new name).
        let Some(at) = cred.value.get("revocation").and_then(Value::as_str) else { return false };
        let at_root = match (self.root.as_deref(), parse_at_uri(at)) {
            (Some(root), Some((_, collection, rkey))) => Some(format!("at://{root}/{collection}/{rkey}")),
            _ => None,
        };
        self.records.iter().any(|r| same_uri(&r.uri, at) || at_root.as_deref().is_some_and(|a| same_uri(&r.uri, a)))
    }

    /// An admin writer's credential over `did`'s declaration, both held and intact: the pair that vouches
    /// now if there is one, else the first pair that names it (so `decide` can say why it does not).
    fn held_vouch(&self, did: &str) -> Option<Vouch<'_>> {
        let pairs: Vec<Vouch<'_>> = self
            .intact()
            .filter(|decl| parse_at_uri(&decl.uri).is_some_and(|(repo, _, _)| repo == did))
            .flat_map(|decl| {
                self.intact()
                    .filter(|cred| cred.value.get("record").and_then(Value::as_str).is_some_and(|r| same_uri(r, &decl.uri)))
                    .map(move |cred| Vouch { declaration: decl.as_chain(), credential: cred.as_chain(), revocation_present: self.revoked(cred) })
            })
            .collect();
        pairs.iter().find(|v| self.vouches(v)).or(pairs.first()).copied()
    }

    /// `v` vouches now: its credential's issuer is an admin writer for it ([`Self::credential_issuer`])
    /// and the chain holds.
    fn vouches(&self, v: &Vouch<'_>) -> bool {
        self.credential_issuer(v.credential.uri).is_some_and(|issuer| chain::vouched(issuer, v.credential, v.declaration, v.revocation_present))
    }

    /// `did`'s `publisher/self` declaration, when an admin writer vouches for it now.
    fn vouched_declaration(&self, did: &str) -> Option<&Value> {
        self.held_vouch(did).filter(|v| self.vouches(v)).map(|v| v.declaration.body)
    }
}

/// `o` is one of `root`'s operator records naming `did` (`subject` = `did`, at rkey `did` or
/// `{did}-...`) for a period holding at `seen` (`validFrom <= seen < validUntil`; an absent end is open,
/// a malformed time holds at no time, and with no `seen` only a period open at both ends holds).
fn names_operator(root: &str, o: &Record, did: &str, seen: Option<&str>) -> bool {
    let Some((repo, collection, rkey)) = parse_at_uri(&o.uri) else { return false };
    let named = repo == root
        && same_name(collection, OPERATOR)
        && o.value.get("subject").and_then(Value::as_str) == Some(did)
        && (rkey == did || rkey.strip_prefix(did).is_some_and(|rest| rest.starts_with('-')));
    let instant = |t: &str| chrono::DateTime::parse_from_rfc3339(t).ok();
    let at = seen.and_then(instant);
    // Compared at microseconds, the platform's timestamptz precision.
    let end = |key: &str, holds: fn(i64, i64) -> bool| match o.value.get(key) {
        None => true,
        Some(t) => match (t.as_str().and_then(instant), at) {
            (Some(t), Some(at)) => holds(t.timestamp_micros(), at.timestamp_micros()),
            _ => false,
        },
    };
    named && end("validFrom", |from, at| from <= at) && end("validUntil", |until, at| until > at)
}

impl Endorsements for Claims {
    fn root(&self) -> Option<&str> {
        self.root.as_deref()
    }
    fn endorses(&self, did: &str, collection: &str) -> bool {
        self.vouched_declaration(did).is_some_and(|decl| chain::writer(decl, collection))
    }
    /// The repo holding the credential at `credential_uri`, when it is an admin writer for every intact
    /// version held there ([`Claims::issuer_of`]); `None` when none is held.
    fn credential_issuer<'a>(&'a self, credential_uri: &'a str) -> Option<&'a str> {
        // Every version held at one address is in one repo, so they share an issuer when they have one.
        let mut issuers = self.intact().filter(|r| r.uri == credential_uri).map(|cred| self.issuer_of(cred));
        let first = issuers.next()??;
        issuers.all(|i| i.is_some()).then_some(first)
    }
}

impl techne_lexicon_check::Claims for Claims {
    fn role_at(&self, member: &str, collective: &str, _at: &str) -> Role {
        match self.roles.iter().find(|r| r.member == member && r.collective == collective) {
            Some(KnownRole { role: Some(n), .. }) => Role::Held(*n),
            Some(_) => Role::NotHeld,
            None => Role::Unknown,
        }
    }
    fn admitted(&self, author: &str, space: &str, _at: &str) -> Option<bool> {
        self.admissions.iter().find(|a| a.author == author && a.space == space).map(|a| a.admitted)
    }
    fn vouch(&self, author: &str) -> Option<Vouch<'_>> {
        self.held_vouch(author)
    }
}

/// What an app shows for one record.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Verification {
    pub valid: bool,
    pub signer: String,
    pub chain_verified: bool,
    /// Why it is not valid (empty when it is).
    pub problems: Vec<String>,
}

/// Verify one record against what the app holds. See the module docs.
pub fn verify(record: &Record, claims: &Claims) -> Verification {
    let Some((signer, collection, rkey)) = parse_at_uri(&record.uri) else {
        return Verification { valid: false, signer: String::new(), chain_verified: false, problems: vec!["uri: not an AT-URI".into()] };
    };
    let intact = record.intact();
    let mut problems = vec![];
    if !intact {
        problems.push(format!("cid: the body does not hash to {}", record.cid));
    }
    let version = techne_lexicon_check::Version { collection, author: signer, rkey, body: &record.value, space: None };
    match decide(&version, "", claims) {
        Decision::Valid => {}
        Decision::Pending => problems.push("pending: a claim it needs is not known".into()),
        Decision::Invalid { reason } => problems.push(reason),
    }
    Verification {
        valid: problems.is_empty(),
        signer: signer.to_string(),
        // A tampered body says nothing about its signer's chain either: fail closed.
        chain_verified: intact && claims.endorses(signer, collection),
        problems,
    }
}