//! The atproto data model: values, their DAG-CBOR encoding, CIDs, and the JSON form. use base64::Engine; use base64::alphabet; use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig}; use serde_json::Value as Json; use sha2::{Digest, Sha256}; const B64: GeneralPurpose = GeneralPurpose::new( &alphabet::STANDARD, GeneralPurposeConfig::new() .with_encode_padding(false) .with_decode_padding_mode(DecodePaddingMode::Indifferent), ); #[derive(Clone, Debug, PartialEq)] pub enum V { Null, Bool(bool), Int(i64), Str(String), Bytes(Vec), /// Binary CID. Link(Vec), Arr(Vec), Map(Vec<(String, V)>), } // ---- CIDs ---------------------------------------------------------------- const B32: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567"; pub fn base32_encode(data: &[u8]) -> String { let mut out = String::new(); let (mut buf, mut bits) = (0u32, 0); for &b in data { buf = (buf << 8) | b as u32; bits += 8; while bits >= 5 { out.push(B32[((buf >> (bits - 5)) & 31) as usize] as char); bits -= 5; } buf &= (1 << bits) - 1; } if bits > 0 { out.push(B32[((buf << (5 - bits)) & 31) as usize] as char); } out } pub fn base32_decode(s: &str) -> Option> { let mut out = Vec::new(); let (mut buf, mut bits) = (0u32, 0); for c in s.bytes() { let v = B32.iter().position(|&x| x == c)? as u32; buf = (buf << 5) | v; bits += 5; if bits >= 8 { out.push((buf >> (bits - 8)) as u8); bits -= 8; buf &= (1 << bits) - 1; } } if buf != 0 { return None; } Some(out) } /// The CID (version 1, sha-256) of `data` under `codec`, as binary. pub fn cid_of(codec: u8, data: &[u8]) -> Vec { let mut c = vec![1, codec, 0x12, 0x20]; c.extend_from_slice(&Sha256::digest(data)); c } pub fn cid_string(cid: &[u8]) -> String { format!("b{}", base32_encode(cid)) } /// Parse a blessed CID string into its binary form. pub fn parse_cid(s: &str) -> Option> { let rest = s.strip_prefix('b')?; let bytes = base32_decode(rest)?; if bytes.len() == 36 && bytes[0] == 1 && (bytes[1] == 0x71 || bytes[1] == 0x55) && bytes[2] == 0x12 && bytes[3] == 0x20 { Some(bytes) } else { None } } /// Whether `s` is a CID as text that, parsed, is written the same way /// again: version 0 in base58btc, a sha-256 multihash, or version 1 in /// lower-case base32 whose multihash is as long as it says. pub fn valid_cid_string(s: &str) -> bool { if s.starts_with("Qm") { return s.len() == 46 && bs58::decode(s) .into_vec() .is_ok_and(|b| b.len() == 34 && b[..2] == [0x12, 0x20]); } fn varint(rest: &mut &[u8]) -> Option { let mut n = 0; for i in 0..9 { let (&b, tail) = rest.split_first()?; *rest = tail; n |= u64::from(b & 0x7f) << (7 * i); if b < 0x80 { return Some(n); } } None } let Some(bytes) = s.strip_prefix('b').and_then(base32_decode) else { return false; }; let rest = &mut bytes.as_slice(); matches!((varint(rest), varint(rest), varint(rest), varint(rest)), (Some(1), Some(_), Some(_), Some(len)) if rest.len() as u64 == len) } // ---- DAG-CBOR -------------------------------------------------------------- fn head(out: &mut Vec, major: u8, n: u64) { let m = major << 5; if n < 24 { out.push(m | n as u8); } else if n < 0x100 { out.extend([m | 24, n as u8]); } else if n < 0x1_0000 { out.push(m | 25); out.extend((n as u16).to_be_bytes()); } else if n < 0x1_0000_0000 { out.push(m | 26); out.extend((n as u32).to_be_bytes()); } else { out.push(m | 27); out.extend(n.to_be_bytes()); } } pub fn encode(v: &V) -> Vec { let mut out = Vec::new(); enc(v, &mut out); out } fn enc(v: &V, out: &mut Vec) { match v { V::Null => out.push(0xf6), V::Bool(b) => out.push(if *b { 0xf5 } else { 0xf4 }), V::Int(i) => { if *i >= 0 { head(out, 0, *i as u64) } else { head(out, 1, (-1 - *i) as u64) } } V::Str(s) => { head(out, 3, s.len() as u64); out.extend(s.as_bytes()); } V::Bytes(b) => { head(out, 2, b.len() as u64); out.extend(b); } V::Link(c) => { out.extend([0xd8, 42]); head(out, 2, c.len() as u64 + 1); out.push(0); out.extend(c); } V::Arr(a) => { head(out, 4, a.len() as u64); for x in a { enc(x, out); } } V::Map(m) => { let mut sorted: Vec<&(String, V)> = m.iter().collect(); sorted.sort_by(|a, b| (a.0.len(), a.0.as_bytes()).cmp(&(b.0.len(), b.0.as_bytes()))); head(out, 5, m.len() as u64); for (k, x) in sorted { head(out, 3, k.len() as u64); out.extend(k.as_bytes()); enc(x, out); } } } } /// Decode one DAG-CBOR value that is all of `data`: what `encode` writes. pub fn decode(data: &[u8]) -> Result { let mut pos = 0; let v = dec(data, &mut pos, 0)?; if pos == data.len() { Ok(v) } else { Err("bytes after the value".into()) } } /// Decode the DAG-CBOR value at the start of `data`; answers it and how many bytes it took. pub fn decode_prefix(data: &[u8]) -> Result<(V, usize), String> { let mut pos = 0; let v = dec(data, &mut pos, 0)?; Ok((v, pos)) } fn take<'a>(data: &'a [u8], pos: &mut usize, n: usize) -> Result<&'a [u8], String> { let s = data .get(*pos..pos.saturating_add(n)) .ok_or("the value is cut short")?; *pos += n; Ok(s) } fn dec(d: &[u8], pos: &mut usize, depth: usize) -> Result { if depth > 128 { return Err("nested too deep".into()); } let first = take(d, pos, 1)?[0]; let (major, info) = (first >> 5, first & 31); let n = match info { 0..=23 => u64::from(info), 24..=27 => take(d, pos, 1 << (info - 24))? .iter() .fold(0, |n, &b| (n << 8) | u64::from(b)), _ => return Err(format!("unsupported CBOR head {first:#x}")), }; let int = || i64::try_from(n).map_err(|_| "integer out of range".to_string()); let len = || usize::try_from(n).map_err(|_| "length out of range".to_string()); Ok(match (major, n) { (0, _) => V::Int(int()?), (1, _) => V::Int(-1 - int()?), (2, _) => V::Bytes(take(d, pos, len()?)?.to_vec()), (3, _) => V::Str( String::from_utf8(take(d, pos, len()?)?.to_vec()) .map_err(|_| "a string that is not UTF-8")?, ), (4, _) => V::Arr( (0..n) .map(|_| dec(d, pos, depth + 1)) .collect::>()?, ), (5, _) => { let mut m = Vec::new(); for _ in 0..n { let V::Str(k) = dec(d, pos, depth + 1)? else { return Err("a map key that is not a string".into()); }; m.push((k, dec(d, pos, depth + 1)?)); } V::Map(m) } (6, 42) => match dec(d, pos, depth + 1)? { V::Bytes(b) if b.first() == Some(&0) => V::Link(b[1..].to_vec()), _ => return Err("a link that is not a CID".into()), }, (7, 20) => V::Bool(false), (7, 21) => V::Bool(true), (7, 22) => V::Null, _ => return Err(format!("unsupported CBOR head {first:#x}")), }) } // ---- JSON <-> values ------------------------------------------------------- /// Convert JSON to the data model, rejecting what the model does not allow. pub fn from_json(j: &Json) -> Result { Ok(match j { Json::Null => V::Null, Json::Bool(b) => V::Bool(*b), // A number whose value is whole is an integer however it is written: // `1e3` and `1000.0` are 1000, and `-0` is 0. Json::Number(n) => V::Int(match (n.as_i64(), n.as_f64()) { (Some(i), _) => i, (None, Some(f)) if f.fract() == 0.0 && (-(2f64.powi(63))..2f64.powi(63)).contains(&f) => { f as i64 } _ => return Err("numbers must be 64-bit integers".into()), }), Json::String(s) => V::Str(s.clone()), Json::Array(a) => V::Arr(a.iter().map(from_json).collect::>()?), Json::Object(o) => { // A `$link` beside other keys is no link but a map, kept as it is // (`spec/BLOBS.md`), as is any map of `$type` blob. if let Some(l) = o.get("$link").filter(|_| o.len() == 1) { let cid = l.as_str().and_then(parse_cid).ok_or("invalid $link")?; return Ok(V::Link(cid)); } if let Some(b) = o.get("$bytes") { if o.len() != 1 { return Err("$bytes object with other fields".into()); } let bytes = b .as_str() .and_then(|s| B64.decode(s).ok()) .ok_or("invalid $bytes")?; return Ok(V::Bytes(bytes)); } let mut m = Vec::new(); for (k, x) in o { m.push((k.clone(), from_json(x)?)); } V::Map(m) } }) } /// A record, from JSON: an object in the data model whose own `$type`, if it /// has one, is a non-empty string. An object within it may have a `$type` of /// any value, or none (`spec/VALIDATION.md`): its lexicon, if checked, says. pub fn record_from_json(j: &Json) -> Result { let Some(o) = j.as_object() else { return Err("record must be an object".into()); }; if o.get("$type") .is_some_and(|t| t.as_str().is_none_or(str::is_empty)) { return Err("$type must be a non-empty string".into()); } from_json(j) } pub fn to_json(v: &V) -> Json { match v { V::Null => Json::Null, V::Bool(b) => Json::Bool(*b), V::Int(i) => Json::from(*i), V::Str(s) => Json::String(s.clone()), V::Bytes(b) => serde_json::json!({ "$bytes": B64.encode(b) }), V::Link(c) => serde_json::json!({ "$link": cid_string(c) }), V::Arr(a) => Json::Array(a.iter().map(to_json).collect()), V::Map(m) => Json::Object(m.iter().map(|(k, x)| (k.clone(), to_json(x))).collect()), } } // ---- Syntax --------------------------------------------------------------- /// Whether `s` is an NSID (`atproto/nsid.md`). As atproto's vectors have it, /// only the whole is held to 317 characters, not the domain authority to 253. pub fn valid_nsid(s: &str) -> bool { if !s.is_ascii() || s.len() > 317 { return false; } let segs: Vec<&str> = s.split('.').collect(); if segs.len() < 3 { return false; } let (name, domain) = segs.split_last().unwrap(); for (i, seg) in domain.iter().enumerate() { let b = seg.as_bytes(); if b.is_empty() || b.len() > 63 || b[0] == b'-' || b[b.len() - 1] == b'-' { return false; } if !b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-') { return false; } if i == 0 && b[0].is_ascii_digit() { return false; } } let n = name.as_bytes(); !n.is_empty() && n.len() <= 63 && n[0].is_ascii_alphabetic() && n.iter().all(|c| c.is_ascii_alphanumeric()) } pub fn valid_rkey(s: &str) -> bool { !s.is_empty() && s.len() <= 512 && s != "." && s != ".." && s.bytes() .all(|c| c.is_ascii_alphanumeric() || b".-_:~".contains(&c)) } /// Whether `s` is a DID: `did:`, a lowercase method, then its identifier (`atproto/did.md`). pub fn valid_did(s: &str) -> bool { let Some((method, id)) = s.strip_prefix("did:").and_then(|r| r.split_once(':')) else { return false; }; s.len() <= 2048 && !method.is_empty() && method.bytes().all(|c| c.is_ascii_lowercase()) && !id.is_empty() && id .bytes() .all(|c| c.is_ascii_alphanumeric() || b"._:%-".contains(&c)) && !id.ends_with([':', '%']) } /// Whether `s` is a handle: a hostname of two or more labels whose last does /// not start with a digit (`atproto/handle.md`). pub fn valid_handle(s: &str) -> bool { let label = |l: &str| { let b = l.as_bytes(); (1..=63).contains(&b.len()) && b[0].is_ascii_alphanumeric() && b[b.len() - 1].is_ascii_alphanumeric() && b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-') }; s.len() <= 253 && s.split('.').count() >= 2 && s.split('.').all(label) && !s .rsplit('.') .next() .is_some_and(|l| l.starts_with(|c: char| c.is_ascii_digit())) } /// Whether `s` is an at-identifier: a DID or a handle. pub fn valid_at_identifier(s: &str) -> bool { valid_did(s) || valid_handle(s) } // ---- Datetimes -------------------------------------------------------------- /// Days since 1970-01-01 of a proleptic Gregorian date. fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { let y = if m <= 2 { y - 1 } else { y }; let era = y.div_euclid(400); let yoe = y.rem_euclid(400); let mp = (m + 9) % 12; let doy = (153 * mp + 2) / 5 + d - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146_097 + doe - 719_468 } /// The proleptic Gregorian date `(year, month, day)` of days since 1970-01-01. pub fn civil_from_days(days: i64) -> (i64, i64, i64) { let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z.rem_euclid(146_097); let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let day = doy - (153 * mp + 2) / 5 + 1; let month = if mp < 10 { mp + 3 } else { mp - 9 }; (yoe + era * 400 + i64::from(month <= 2), month, day) } /// Milliseconds since the epoch as an atproto datetime, in UTC to the millisecond. pub fn datetime_string(ms: i64) -> String { let (days, rem) = (ms.div_euclid(86_400_000), ms.rem_euclid(86_400_000)); let (year, month, day) = civil_from_days(days); format!( "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z", rem / 3_600_000, rem / 60_000 % 60, rem / 1000 % 60, rem % 1000 ) } /// A datetime as `atproto/lexicon.md` defines the format, as milliseconds /// since the epoch in UTC: `YYYY-MM-DDTHH:MM:SS`, optional fractional /// seconds, then `Z` or `±HH:MM` (not `-00:00`), naming a real date and /// time no earlier than year 0. None if it is not one. pub fn datetime_millis(s: &str) -> Option { let b = s.as_bytes(); let digits = |r: std::ops::Range| -> Option { let part = b.get(r)?; part.iter() .all(u8::is_ascii_digit) .then(|| part.iter().fold(0, |n, c| n * 10 + i64::from(c - b'0'))) }; if b.len() < 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' { return None; } let (year, month, day) = (digits(0..4)?, digits(5..7)?, digits(8..10)?); let (hour, minute, second) = (digits(11..13)?, digits(14..16)?, digits(17..19)?); let mut i = 19; let mut millis = 0; if b[i] == b'.' { let start = i + 1; i = start; while i < b.len() && b[i].is_ascii_digit() { i += 1; } if i == start || i - start > 20 { return None; } millis = (start..start + 3) .map(|j| if j < i { i64::from(b[j] - b'0') } else { 0 }) .fold(0, |n, d| n * 10 + d); } let offset = match &b[i..] { b"Z" => 0, [sign @ (b'+' | b'-'), _, _, b':', _, _] => { let (h, m) = (digits(i + 1..i + 3)?, digits(i + 4..i + 6)?); if h > 23 || m > 59 || (*sign == b'-' && h == 0 && m == 0) { return None; } (h * 60 + m) * if *sign == b'+' { 1 } else { -1 } } _ => return None, }; let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); let month_days = [ 31, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ]; if !(1..=12).contains(&month) || day < 1 || day > month_days[(month - 1) as usize] || hour > 23 || minute > 59 || second > 59 { return None; } let local = ((days_from_civil(year, month, day) * 24 + hour) * 60 + minute) * 60 + second; let utc = (local - offset * 60) * 1000 + millis; // Year 0 begins 719528 days before the epoch; nothing may come before it. (utc >= -719_528 * 86_400_000).then_some(utc) } /// Whether `s` is a datetime as `atproto/lexicon.md` defines the format. pub fn valid_datetime(s: &str) -> bool { datetime_millis(s).is_some() } #[cfg(test)] mod tests { use super::*; #[test] fn fixtures() { let text = std::fs::read_to_string(concat!( env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/data-model/data-model-fixtures.json" )) .unwrap(); let fixtures: Vec = serde_json::from_str(&text).unwrap(); for f in fixtures { let v = from_json(&f["json"]).unwrap(); let cbor = encode(&v); assert_eq!( B64.encode(&cbor), f["cbor_base64"].as_str().unwrap().trim_end_matches('=') ); assert_eq!(cid_string(&cid_of(0x71, &cbor)), f["cid"].as_str().unwrap()); assert_eq!(to_json(&v), f["json"]); assert_eq!(encode(&decode(&cbor).unwrap()), cbor); } } #[test] fn syntax() { assert!(valid_did("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa") && valid_did("did:web:example.com")); assert!( !valid_did("did:PLC:abc") && !valid_did("did:plc:") && !valid_did("plc:abc") && !valid_did("did:plc:abc:") ); assert!(valid_handle("alice.test") && valid_handle("a.b-c.example")); assert!( !valid_handle("alice") && !valid_handle("alice.3com") && !valid_handle("-a.test") && !valid_handle("a..test") ); let cid = cid_string(&cid_of(0x71, b"x")); assert!( valid_cid_string(&cid) && valid_cid_string("QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG") ); assert!( !valid_cid_string(&cid[..cid.len() - 2]) && !valid_cid_string("bafy") && !valid_cid_string("not a cid") ); } #[test] fn datetimes() { let valid = [ "1985-04-12T23:20:50.123Z", "1985-04-12T23:20:50.123456Z", "0001-01-01T00:00:00.000Z", "0000-01-01T00:00:00.000Z", "1985-04-12T23:20:50.12345678912345Z", "1985-04-12T23:20:50Z", "1985-04-12T23:20:50.0Z", "1985-04-12T23:20:50.123+00:00", "1985-04-12T23:20:50.123-07:00", "2024-02-29T00:00:00Z", ]; for s in valid { assert!(valid_datetime(s), "{s}"); } let invalid = [ "1985-04-12", "1985-04-12T23:20Z", "1985-04-12T23:20:5Z", "1985-04-12T23:20:50.123", "+001985-04-12T23:20:50.123Z", "23:20:50.123Z", "-1985-04-12T23:20:50.123Z", "1985-4-12T23:20:50.123Z", "01985-04-12T23:20:50.123Z", "1985-04-12T23:20:50.123+00", "1985-04-12T23:20:50.123+0000", "1985-04-12t23:20:50.123Z", "1985-04-12T23:20:50.123z", "1985-04-12T23:20:50.123-00:00", "1985-04-12 23:20:50.123Z", "1985-04-12T23:99:50.123Z", "1985-00-12T23:20:50.123Z", "0000-01-01T00:00:00+01:00", "2023-02-29T00:00:00Z", "1985-04-12T23:20:50.Z", ]; for s in invalid { assert!(!valid_datetime(s), "{s}"); } assert_eq!(datetime_millis("1970-01-01T01:00:00.5+01:00"), Some(500)); assert_eq!( datetime_string(datetime_millis("2026-11-09T12:34:56.789Z").unwrap()), "2026-11-09T12:34:56.789Z" ); } /// The data model's invalid values are refused, but for the maps that /// look like a blob or a link and are kept as they are (`spec/BLOBS.md`). #[test] fn invalid() { let text = std::fs::read_to_string(concat!( env!("CARGO_MANIFEST_DIR"), "/../../spec/interop/data-model/data-model-invalid.json" )) .unwrap(); let cases: Vec = serde_json::from_str(&text).unwrap(); let kept = [ "blob with string size", "blob with missing key", "link with extra fields", ]; for c in cases { let j = &c["json"]; let note = c["note"].as_str().unwrap(); type Parse = fn(&Json) -> Result; let (x, parse): (&Json, Parse) = match (j.get("rcrd"), j.get("blb").or(j.get("lnk"))) { (Some(r), _) => (r, record_from_json), (None, Some(x)) => (x, from_json), (None, None) => continue, }; if kept.contains(¬e) { let v = parse(x).unwrap(); assert!(matches!(v, V::Map(_)), "{note}"); assert_eq!(&to_json(&v), x, "{note}"); } else { assert!(parse(x).is_err(), "{note}"); } } // Within a record, an object's `$type` is any value. let nested = serde_json::json!({ "$type": "a.b.c", "x": { "$type": { "a": 1 } }, "y": [{ "$type": 5 }, { "$type": "" }] }); assert_eq!(to_json(&record_from_json(&nested).unwrap()), nested); assert!(record_from_json(&serde_json::json!([])).is_err()); for kept in [ serde_json::json!({ "$type": "blob", "ref": "bafkrei", "mimeType": "", "size": null }), serde_json::json!({ "$type": "blob", "ref": { "a": 1 }, "mimeType": 5, "size": -2, "x": 1 }), ] { assert_eq!(to_json(&from_json(&kept).unwrap()), kept); } assert!(from_json(&serde_json::json!({ "$type": "blob", "size": 1.5 })).is_err()); } #[test] fn base32() { assert_eq!( base32_decode(&base32_encode(b"hello world")).unwrap(), b"hello world" ); } }