Skip to main content

hyprstream_pds/
name_record.rs

1//! `ai.hyprstream.name` — the NameRecord: the trusted, PQ-signed **name → DID
2//! URL** layer (#908, design #905 §1/§3/§6; #879 §Name-resolution).
3//!
4//! This is the thin naming layer that sits *on top of* `ai.hyprstream.model`
5//! (#387 D1). A NameRecord binds a human-chosen `label` to a `subject` **DID
6//! URL** and a content `pin`. It is the trusted complement the DHT must never
7//! answer: the DHT is an untrusted *locator*; the authoritative name → DID-URL
8//! mapping lives here, in a PQ-signed atproto record served from a PDS.
9//!
10//! The confirmed 4-field lexicon:
11//!
12//! ```json
13//! {
14//!   "lexicon": 1,
15//!   "id": "ai.hyprstream.name",
16//!   "defs": { "main": { "type": "record", "key": "tid", "record": {
17//!     "type": "object",
18//!     "required": ["subject", "pin", "label", "createdAt"],
19//!     "properties": {
20//!       "subject":   { "type": "string" },               // a DID URL, opaque
21//!       "pin":       { "type": "string", "format": "cid" },
22//!       "label":     { "type": "string" },               // human label
23//!       "createdAt": { "type": "string", "format": "datetime" }
24//!     }
25//! }}}
26//! ```
27//!
28//! # `subject` carries a DID URL, not an at-uri, and never a 9P path
29//!
30//! The `subject` field is a **DID URL** carried as an opaque string (a standard
31//! lexicon extension: unmodified Bluesky/Tangled can store, sync, and serve
32//! these records without understanding the field). The acceptance contract is
33//! that this DID URL *dereferences* via the G1 (#906) resolution path.
34//!
35//! Crucially, the value is a `did:`-scheme DID URL — **never** a raw 9P path and
36//! **never** an `at://` URI. `at://` addresses this record; the record's body
37//! resolves onward to a DID URL. Keeping 9P paths out of the at:// / record
38//! layer is the #879 name-resolution non-goal made structural: paths live below
39//! the DID, reached only after the DID URL dereferences.
40//!
41//! # Encoding
42//!
43//! Records are canonical **DAG-CBOR**: map keys in pure lexicographic byte order
44//! (RFC 7049 §4.2.1 "core determinism"), matching the rest of this crate. For
45//! these four keys that order is `createdAt`, `label`, `pin`, `subject`. Same
46//! record → same bytes → same CID.
47//!
48//! `pin` is a `format: "cid"` **string** (not a DAG-CBOR link): it references
49//! external content addressed outside this repo's MST, so it is carried as text
50//! and validated as a CID string — the same treatment `currentOid` gets in
51//! [`crate::record`].
52
53use anyhow::{ensure, Result};
54
55use crate::cid::Cid;
56use crate::dag_cbor::DagCbor;
57use crate::list_record::{map_get_str, validate_datetime, validate_nonempty};
58
59/// The NSID of this record type — the collection portion of an at-uri that
60/// addresses a NameRecord (`at://<repo>/ai.hyprstream.name/<rkey>`).
61pub const COLLECTION_NSID: &str = "ai.hyprstream.name";
62
63/// An `ai.hyprstream.name` record: the trusted name → DID-URL binding.
64///
65/// Construct with [`NameRecord::new`]; encode/decode via the DAG-CBOR
66/// conversion methods.
67#[derive(Clone, Debug, Eq, PartialEq)]
68pub struct NameRecord {
69    /// The **DID URL** this name resolves to, carried opaquely. Must be a
70    /// `did:`-scheme DID URL (it may carry a path/query/fragment); it dereferences
71    /// via G1. Never an `at://` URI and never a 9P path.
72    subject: String,
73    /// The content pin — a `format: "cid"` string addressing the pinned content.
74    pin: String,
75    /// A human-readable label for this name.
76    label: String,
77    /// ISO-8601 UTC datetime (`format: "datetime"`), millisecond precision, `Z`.
78    created_at: String,
79}
80
81impl NameRecord {
82    /// Validate and construct a NameRecord.
83    ///
84    /// `subject` must be a `did:`-scheme DID URL (a DID, optionally with a
85    /// path/query/fragment), `pin` a parseable CID string, `label` non-empty, and
86    /// `created_at` the atproto `datetime` shape (UTC, milliseconds, trailing `Z`).
87    pub fn new(
88        subject: impl Into<String>,
89        pin: impl Into<String>,
90        label: impl Into<String>,
91        created_at: impl Into<String>,
92    ) -> Result<Self> {
93        let subject = subject.into();
94        let pin = pin.into();
95        let label = label.into();
96        let created_at = created_at.into();
97        validate_did_url(&subject)?;
98        validate_pin_cid(&pin)?;
99        validate_nonempty(&label, "label")?;
100        validate_datetime(&created_at)?;
101        Ok(Self {
102            subject,
103            pin,
104            label,
105            created_at,
106        })
107    }
108
109    /// The DID URL this name resolves to.
110    pub fn subject(&self) -> &str {
111        &self.subject
112    }
113
114    /// The content CID string pinned by this name.
115    pub fn pin(&self) -> &str {
116        &self.pin
117    }
118
119    /// Human-readable label for this name.
120    pub fn label(&self) -> &str {
121        &self.label
122    }
123
124    /// Creation timestamp in canonical atproto datetime shape.
125    pub fn created_at(&self) -> &str {
126        &self.created_at
127    }
128
129    /// Encode to canonical DAG-CBOR bytes (deterministic).
130    pub fn to_dag_cbor(&self) -> Vec<u8> {
131        self.to_value().encode()
132    }
133
134    /// The CID of this record (CIDv1 dag-cbor over its canonical bytes).
135    pub fn cid(&self) -> Cid {
136        Cid::from_dag_cbor(&self.to_dag_cbor())
137    }
138
139    /// Build the typed [`DagCbor`] value form (fields in canonical order).
140    pub fn to_value(&self) -> DagCbor {
141        DagCbor::str_map([
142            ("createdAt", DagCbor::Text(self.created_at.clone())),
143            ("label", DagCbor::Text(self.label.clone())),
144            ("pin", DagCbor::Text(self.pin.clone())),
145            ("subject", DagCbor::Text(self.subject.clone())),
146        ])
147    }
148
149    /// Decode canonical DAG-CBOR bytes into a NameRecord, validating all fields.
150    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
151        Self::from_value(&DagCbor::decode(bytes)?)
152    }
153
154    pub fn from_value(value: &DagCbor) -> Result<Self> {
155        let map = value.as_map()?;
156        let subject = map_get_str(value, "subject", COLLECTION_NSID)?.to_owned();
157        let pin = map_get_str(value, "pin", COLLECTION_NSID)?.to_owned();
158        let label = map_get_str(value, "label", COLLECTION_NSID)?.to_owned();
159        let created_at = map_get_str(value, "createdAt", COLLECTION_NSID)?.to_owned();
160        // The lexicon is frozen at 4 fields — reject anything else.
161        for (k, _v) in map {
162            match k.as_str()? {
163                "subject" | "pin" | "label" | "createdAt" => {}
164                other => anyhow::bail!(
165                    "{COLLECTION_NSID}: unknown field {other:?} (lexicon is 4 fields)"
166                ),
167            }
168        }
169        // `DagCbor::decode` already rejects duplicate map keys on the wire path,
170        // but `from_value` is public: reject hand-built values where a recognized
171        // key appears twice (which would make `map_get_str` pick one of two
172        // conflicting values).
173        ensure!(
174            map.len() == 4,
175            "{COLLECTION_NSID}: duplicate field (lexicon is exactly 4 fields)"
176        );
177        Self::new(subject, pin, label, created_at)
178    }
179}
180
181/// A **DID URL** carried as an opaque string: it must be a `did:`-scheme URL
182/// with a non-empty `method` and `method-specific-id` (the id may carry a
183/// `/path`, `?query`, or `#fragment`). Deliberately lenient — full DID grammar
184/// and actual dereferencing are the resolver's job (G1) — but it firmly rejects
185/// the two things a NameRecord subject must never be: an `at://` URI and a bare
186/// 9P path.
187fn validate_did_url(s: &str) -> Result<()> {
188    ensure!(
189        s.starts_with("did:"),
190        "subject must be a did: DID URL (not an at-uri or 9P path): {s:?}"
191    );
192    let rest = &s[4..];
193    ensure!(
194        !rest.is_empty(),
195        "subject DID URL must have a method: {s:?}"
196    );
197    ensure!(
198        !rest.chars().any(char::is_whitespace),
199        "subject DID URL must not contain whitespace: {s:?}"
200    );
201    let mut parts = rest.splitn(2, ':');
202    let method = parts.next().unwrap_or("");
203    let id = parts.next().unwrap_or("");
204    ensure!(
205        !method.is_empty() && !id.is_empty(),
206        "subject must be \"did:<method>:<id>[/path][?query][#fragment]\": {s:?}"
207    );
208    ensure!(
209        !matches!(id.as_bytes().first(), Some(b'/' | b'?' | b'#')),
210        "subject DID URL must include a method-specific id before any path/query/fragment: {s:?}"
211    );
212    Ok(())
213}
214
215fn validate_pin_cid(s: &str) -> Result<()> {
216    hyprstream_rpc::cid::decode_cid(s)
217        .map(|_| ())
218        .map_err(|err| anyhow::anyhow!("pin must be a parseable CIDv1 base32 string: {s:?}: {err}"))
219}
220
221#[cfg(test)]
222fn sample_pin() -> String {
223    match hyprstream_rpc::cid::encode_cid(
224        hyprstream_rpc::cid::Codec::GitRaw,
225        hyprstream_rpc::cid::HashAlgo::Sha2_256,
226        &[0x42; 32],
227    ) {
228        Ok(cid) => cid,
229        Err(err) => panic!("valid sample CID: {err}"),
230    }
231}
232
233#[cfg(test)]
234fn sample_at9p_pin() -> String {
235    match hyprstream_rpc::cid::encode_cid(
236        hyprstream_rpc::cid::Codec::At9pCapsule,
237        hyprstream_rpc::cid::HashAlgo::Blake3,
238        &[0x24; 64],
239    ) {
240        Ok(cid) => cid,
241        Err(err) => panic!("valid sample at9p CID: {err}"),
242    }
243}
244
245#[cfg(test)]
246fn truncated_pin() -> String {
247    let cid = match hyprstream_rpc::cid::encode_cid(
248        hyprstream_rpc::cid::Codec::GitRaw,
249        hyprstream_rpc::cid::HashAlgo::Sha2_256,
250        &[0x11; 32],
251    ) {
252        Ok(cid) => cid,
253        Err(err) => panic!("valid CID: {err}"),
254    };
255    cid.chars().take(12).collect()
256}
257
258#[cfg(test)]
259mod tests {
260    #![allow(
261        clippy::unwrap_used,
262        clippy::expect_used,
263        clippy::indexing_slicing,
264        clippy::panic
265    )]
266    use super::*;
267
268    fn sample() -> NameRecord {
269        NameRecord::new(
270            "did:web:alice.example.com/models/qwen3",
271            sample_pin(),
272            "qwen3-serving",
273            "2026-06-23T12:34:56.789Z",
274        )
275        .expect("valid sample")
276    }
277
278    #[test]
279    fn round_trip_same_cid() {
280        let r = sample();
281        let bytes = r.to_dag_cbor();
282        let back = NameRecord::from_dag_cbor(&bytes).expect("round-trip");
283        assert_eq!(r, back);
284        assert_eq!(r.cid(), back.cid());
285        assert_eq!(r.to_dag_cbor(), back.to_dag_cbor());
286    }
287
288    #[test]
289    fn fields_canonical_order() {
290        let r = sample();
291        let v = DagCbor::decode(&r.to_dag_cbor()).expect("decode");
292        let map = v.as_map().expect("map");
293        let keys: Vec<&str> = map.iter().map(|(k, _)| k.as_str().expect("str")).collect();
294        assert_eq!(
295            keys,
296            vec!["createdAt", "label", "pin", "subject"],
297            "DAG-CBOR map keys must be pure-lexicographic byte order"
298        );
299    }
300
301    #[test]
302    fn subject_is_a_did_url_not_a_link() {
303        let r = sample();
304        let v = r.to_value();
305        // subject is carried as an opaque Text string, not a DAG-CBOR link.
306        assert!(matches!(v.get("subject"), Some(DagCbor::Text(_))));
307        // pin likewise is a cid-string, not a tag-42 link.
308        assert!(matches!(v.get("pin"), Some(DagCbor::Text(_))));
309    }
310
311    #[test]
312    fn accepts_did_at9p_subject() {
313        // The acceptance case: a did:at9p DID URL as subject.
314        let r = NameRecord::new(
315            "did:at9p:bafkrei1234567890abcdefghijklmnop#service",
316            sample_at9p_pin(),
317            "my-node",
318            "2026-06-23T12:34:56.789Z",
319        )
320        .expect("did:at9p subject must be accepted");
321        assert!(r.subject().starts_with("did:at9p:"));
322    }
323
324    #[test]
325    fn rejects_at_uri_subject() {
326        // A NameRecord subject must never be an at:// URI — at:// addresses the
327        // record; the body resolves onward to a DID URL.
328        assert!(NameRecord::new(
329            "at://did:web:alice.example.com/ai.hyprstream.model/3kxy",
330            sample_pin(),
331            "bad",
332            "2026-06-23T12:34:56.789Z",
333        )
334        .is_err());
335    }
336
337    #[test]
338    fn rejects_9p_path_subject() {
339        // A raw 9P path must never leak into the at:// / record layer (#879).
340        assert!(NameRecord::new(
341            "/models/qwen3/adapters",
342            sample_pin(),
343            "bad",
344            "2026-06-23T12:34:56.789Z",
345        )
346        .is_err());
347    }
348
349    #[test]
350    fn rejects_did_url_without_method_specific_id_before_suffix() {
351        for subject in ["did:web:/models/qwen3", "did:web:?q", "did:web:#f"] {
352            assert!(
353                NameRecord::new(subject, sample_pin(), "bad", "2026-06-23T12:34:56.789Z",).is_err(),
354                "{subject:?} must not treat a URL suffix delimiter as the DID id"
355            );
356        }
357
358        NameRecord::new(
359            "did:web:alice.example.com/models/qwen3?version=1#svc",
360            sample_pin(),
361            "ok",
362            "2026-06-23T12:34:56.789Z",
363        )
364        .expect("valid DID URL suffix after method-specific id");
365    }
366
367    #[test]
368    fn validates_formats() {
369        // Bad pin (not a cid).
370        assert!(NameRecord::new("did:web:x", "x", "l", "2026-06-23T12:34:56.789Z").is_err());
371        // Bad pin (malformed base32 CID body).
372        assert!(
373            NameRecord::new("did:web:x", "b!!!!!!!!", "l", "2026-06-23T12:34:56.789Z").is_err()
374        );
375        // Bad pin (valid base32 prefix but truncated multihash/CID body).
376        assert!(NameRecord::new(
377            "did:web:x",
378            truncated_pin(),
379            "l",
380            "2026-06-23T12:34:56.789Z"
381        )
382        .is_err());
383        // Empty label.
384        assert!(
385            NameRecord::new("did:web:x", sample_pin(), "", "2026-06-23T12:34:56.789Z").is_err()
386        );
387        // Bad datetime.
388        assert!(
389            NameRecord::new("did:web:x", sample_pin(), "l", "2026-06-23T12:34:56.789").is_err()
390        );
391    }
392
393    #[test]
394    fn rejects_extra_fields() {
395        let mut extra = sample().to_value();
396        if let DagCbor::Map(ref mut v) = extra {
397            v.push((DagCbor::Text("bogus".into()), DagCbor::Unsigned(1)));
398            v.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
399        }
400        assert!(NameRecord::from_value(&extra).is_err());
401    }
402
403    #[test]
404    fn rejects_duplicate_recognized_field() {
405        // A hand-built value with a second `subject` must not parse: the wire
406        // decoder rejects duplicate keys, and the value-level path must too.
407        let mut dup = sample().to_value();
408        if let DagCbor::Map(ref mut v) = dup {
409            v.push((
410                DagCbor::Text("subject".into()),
411                DagCbor::Text("did:web:evil.example.com".into()),
412            ));
413            v.sort_by(|a, b| a.0.as_str().unwrap_or("").cmp(b.0.as_str().unwrap_or("")));
414        }
415        assert!(NameRecord::from_value(&dup).is_err());
416    }
417
418    #[test]
419    fn deterministic_across_rebuild() {
420        let r1 = sample();
421        let r2 =
422            NameRecord::new(r1.subject(), r1.pin(), r1.label(), r1.created_at()).expect("rebuild");
423        assert_eq!(r1.to_dag_cbor(), r2.to_dag_cbor());
424        assert_eq!(r1.cid(), r2.cid());
425    }
426}