chadtmiller.com/monolith
An atproto PDS
0
0
Spec and check what a build from scratch found the spec left open
crates/pds-lexicon/src/lib.rs+13−3
| @@ -201,6 +201,7 @@ fn read_method(doc: &Json) -> Option<Method> { | ||
_ => main["parameters"].clone(), | ||
}; | ||
let required: Vec<&str> = object["required"].as_array().map(|r| r.iter().filter_map(Json::as_str).collect()).unwrap_or_default(); | ||
let nullable: Vec<&str> = object["nullable"].as_array().map(|r| r.iter().filter_map(Json::as_str).collect()).unwrap_or_default(); | ||
let args = object["properties"] | ||
.as_object() | ||
.map(|props| { | ||
| @@ -213,7 +214,7 @@ fn read_method(doc: &Json) -> Option<Method> { | ||
ty, | ||
required: required.contains(&n.as_str()), | ||
description: p["description"].as_str().map(str::to_string), | ||
schema: schema_of(p, ty), | ||
schema: schema_of(p, ty, nullable.contains(&n.as_str())), | ||
} | ||
}) | ||
.collect() | ||
| @@ -241,7 +242,8 @@ fn type_of(p: &Json) -> Type { | ||
} | ||
} | ||
| ||
fn schema_of(p: &Json, ty: Type) -> Json { | ||
/// The JSON Schema of a value; one the lexicon lists as `nullable` may also be `null`. | ||
fn schema_of(p: &Json, ty: Type, nullable: bool) -> Json { | ||
let mut s = Map::new(); | ||
match ty { | ||
Type::String => { | ||
| @@ -257,7 +259,7 @@ fn schema_of(p: &Json, ty: Type) -> Json { | ||
s.insert("type".into(), json!("array")); | ||
let items = &p["items"]; | ||
if items.is_object() { | ||
s.insert("items".into(), schema_of(items, type_of(items))); | ||
s.insert("items".into(), schema_of(items, type_of(items), false)); | ||
} | ||
} | ||
Type::Object => { | ||
| @@ -265,6 +267,11 @@ fn schema_of(p: &Json, ty: Type) -> Json { | ||
} | ||
Type::Unknown => {} | ||
} | ||
if nullable { | ||
if let Some(t) = s.remove("type") { | ||
s.insert("type".into(), json!([t, "null"])); | ||
} | ||
} | ||
if matches!(ty, Type::String | Type::Integer) { | ||
for (from, to) in [("minimum", "minimum"), ("maximum", "maximum"), ("maxLength", "maxLength"), ("enum", "enum")] { | ||
if let Some(v) = p.get(from) { | ||
| @@ -321,6 +328,9 @@ mod tests { | ||
let c = method("com.atproto.repo.createRecord").unwrap().input_schema(); | ||
assert!(c["properties"]["record"].get("type").is_none()); | ||
assert_eq!(c["properties"]["rkey"]["maxLength"], 512); | ||
let p = method("com.atproto.repo.putRecord").unwrap().input_schema(); | ||
assert_eq!(p["properties"]["swapRecord"]["type"], json!(["string", "null"])); | ||
assert_eq!(p["properties"]["swapCommit"]["type"], "string"); | ||
let hints = |nsid: &str| method(nsid).unwrap().annotations(); | ||
for nsid in ["com.atproto.repo.deleteRecord", "com.atproto.repo.putRecord", "com.atproto.repo.applyWrites"] { | ||
assert_eq!(hints(nsid), Some(json!({ "readOnlyHint": false, "destructiveHint": true })), "{nsid}"); | ||
crates/pds-repo/src/lib.rs+58−1
| @@ -9,7 +9,7 @@ use crate::mst::Block; | ||
use k256::ecdsa::SigningKey; | ||
use k256::ecdsa::signature::hazmat::PrehashSigner; | ||
use sha2::{Digest, Sha256}; | ||
use std::collections::{BTreeMap, HashSet}; | ||
use std::collections::{BTreeMap, HashMap, HashSet}; | ||
use std::time::{SystemTime, UNIX_EPOCH}; | ||
| ||
pub struct ApiErr { | ||
| @@ -90,6 +90,9 @@ pub struct Change { | ||
pub ops: Vec<EvOp>, | ||
/// The tree blocks the event carries besides the commit. | ||
pub blocks: Vec<Block>, | ||
/// The CIDs of the blocks, records and tree nodes, that the repository | ||
/// holds after this commit and did not before. | ||
pub added: Vec<Vec<u8>>, | ||
} | ||
| ||
pub struct Repo { | ||
| @@ -103,6 +106,9 @@ pub struct Repo { | ||
tree: mst::Node, | ||
pub tids: Tids, | ||
pub change: Option<Change>, | ||
/// Every block the repository holds but its commit, by CID, with the rev | ||
/// of the commit that added it. | ||
held: HashMap<Vec<u8>, String>, | ||
} | ||
| ||
impl Repo { | ||
| @@ -118,6 +124,7 @@ impl Repo { | ||
tree: mst::build_tree(&[]), | ||
tids: Tids::new(), | ||
change: None, | ||
held: HashMap::new(), | ||
}; | ||
r.commit(); | ||
r | ||
| @@ -138,6 +145,21 @@ impl Repo { | ||
let blocks: Vec<Block> = tree.nodes().into_iter().map(|n| (n.cid.clone(), n.bytes.clone())).collect(); | ||
let fresh = blocks.iter().filter(|b| !old.contains(&b.0)).cloned().collect(); | ||
let rev = self.tids.next(); | ||
let mut held = HashMap::with_capacity(blocks.len() + self.records.len()); | ||
let mut added = Vec::new(); | ||
for cid in blocks.iter().map(|b| &b.0).chain(self.records.values().map(|r| &r.cid)) { | ||
if held.contains_key(cid) { | ||
continue; | ||
} | ||
let since = match self.held.remove(cid) { | ||
Some(r) => r, | ||
None => { | ||
added.push(cid.clone()); | ||
rev.clone() | ||
} | ||
}; | ||
held.insert(cid.clone(), since); | ||
} | ||
let unsigned = |sig: Option<Vec<u8>>| { | ||
let mut m = vec![ | ||
("did".to_string(), V::Str(self.did.clone())), | ||
| @@ -162,8 +184,10 @@ impl Repo { | ||
since: (!first).then(|| self.rev.clone()), | ||
prev_data: (!first).then(|| self.tree.cid.clone()), | ||
blocks: fresh, | ||
added, | ||
..Default::default() | ||
}); | ||
self.held = held; | ||
self.head_bytes = bytes; | ||
self.blocks = blocks; | ||
self.tree = tree; | ||
| @@ -179,6 +203,9 @@ impl Repo { | ||
self.records.remove(path); | ||
} | ||
self.rev = c.rev.clone(); | ||
for cid in &c.added { | ||
self.held.insert(cid.clone(), c.rev.clone()); | ||
} | ||
self.head_bytes = c.head_bytes.clone(); | ||
Ok(()) | ||
} | ||
| @@ -188,6 +215,9 @@ impl Repo { | ||
self.records.iter().map(|(k, r)| (k.as_bytes().to_vec(), r.cid.clone())).collect(); | ||
self.tree = mst::build_tree(&entries); | ||
self.blocks = self.tree.nodes().into_iter().map(|n| (n.cid.clone(), n.bytes.clone())).collect(); | ||
let current: HashSet<&[u8]> = | ||
self.blocks.iter().map(|b| b.0.as_slice()).chain(self.records.values().map(|r| r.cid.as_slice())).collect(); | ||
self.held.retain(|cid, _| current.contains(cid.as_slice())); | ||
self.head = cid_of(0x71, &self.head_bytes); | ||
self.tids.after(&self.rev); | ||
self.change = None; | ||
| @@ -311,6 +341,33 @@ impl Repo { | ||
blocks.extend(self.records.values().map(|r| (r.cid.as_slice(), r.bytes.as_slice()))); | ||
car_file(&self.head, blocks) | ||
} | ||
| ||
/// The repository as a CAR file whose root is the latest commit, holding | ||
/// only the blocks it holds now that commits after rev `since` added: none | ||
/// when `since` is the latest rev. | ||
pub fn car_since(&self, since: &str) -> Vec<u8> { | ||
let after = |cid: &[u8]| self.held.get(cid).is_some_and(|rev| rev.as_str() > since); | ||
let mut blocks: Vec<(&[u8], &[u8])> = Vec::new(); | ||
if self.rev.as_str() > since { | ||
blocks.push((&self.head, &self.head_bytes)); | ||
} | ||
blocks.extend(self.blocks.iter().filter(|(c, _)| after(c)).map(|(c, d)| (c.as_slice(), d.as_slice()))); | ||
let mut seen = HashSet::new(); | ||
blocks.extend( | ||
self.records | ||
.values() | ||
.filter(|r| after(&r.cid) && seen.insert(r.cid.as_slice())) | ||
.map(|r| (r.cid.as_slice(), r.bytes.as_slice())), | ||
); | ||
car_file(&self.head, blocks) | ||
} | ||
} | ||
| ||
/// Whether `s` is a TID: 13 characters of base32-sortable, the first of them | ||
/// one that leaves the top bit clear. | ||
pub fn valid_tid(s: &str) -> bool { | ||
let b = s.as_bytes(); | ||
b.len() == 13 && b"234567abcdefghij".contains(&b[0]) && b.iter().all(|c| TID_CHARS.contains(c)) | ||
} | ||
| ||
/// A CAR file with one root and these blocks, in order. | ||
crates/pds-server/src/lib.rs+156−36
| @@ -222,6 +222,10 @@ impl Server { | ||
head_bytes: hex::decode(text("head")).expect("head"), | ||
puts: e["puts"].as_array().unwrap().iter().map(|p| (p[0].as_str().unwrap().to_string(), p[1].clone())).collect(), | ||
dels: e["dels"].as_array().unwrap().iter().map(|d| d.as_str().unwrap().to_string()).collect(), | ||
added: e["added"] | ||
.as_array() | ||
.map(|a| a.iter().map(|x| hex::decode(x.as_str().unwrap()).expect("cid")).collect()) | ||
.unwrap_or_default(), | ||
..Default::default() | ||
}; | ||
self.repo.load(&c).expect("record"); | ||
| @@ -237,6 +241,7 @@ fn commit_entry(c: &Change) -> Json { | ||
json!({ | ||
"t": "commit", "rev": c.rev, "head": hex::encode(&c.head_bytes), | ||
"puts": c.puts.iter().map(|(k, v)| json!([k, v])).collect::<Vec<_>>(), "dels": c.dels, | ||
"added": c.added.iter().map(hex::encode).collect::<Vec<_>>(), | ||
}) | ||
} | ||
| ||
| @@ -263,31 +268,42 @@ fn dispatch( | ||
body: &[u8], | ||
auth: Auth, | ||
) -> Result<Resp, ApiErr> { | ||
let is_post = *method == Method::POST; | ||
// A query by POST or a procedure by GET is refused before anything else is looked at. | ||
let expected = match pds_lexicon::method(nsid).map(|m| m.kind) { | ||
Some(pds_lexicon::Kind::Query) => Some(Method::GET), | ||
Some(pds_lexicon::Kind::Procedure) => Some(Method::POST), | ||
_ => None, | ||
}; | ||
if let Some(want) = expected { | ||
if *method != want && !(want == Method::GET && *method == Method::HEAD) { | ||
return err(400, "InvalidRequest", format!("Incorrect HTTP method ({method}) expected {want}")); | ||
} | ||
} | ||
match nsid { | ||
"com.atproto.server.describeServer" => Ok(Resp::Json(json!({ | ||
"did": s.did, "availableUserDomains": [], "inviteCodeRequired": false | ||
}))), | ||
"com.atproto.server.createSession" if is_post => create_session(s, &parse_body(body)?), | ||
"com.atproto.server.getSession" if !is_post => match auth { | ||
"com.atproto.server.createSession" => create_session(s, &parse_body(body)?), | ||
"com.atproto.server.getSession" => match auth { | ||
Auth::Owner => Ok(Resp::Json(json!({ "handle": s.handle, "did": s.did, "active": true }))), | ||
Auth::None => err(401, "AuthMissing", "Authentication Required"), | ||
Auth::Invalid => invalid_token(), | ||
}, | ||
"com.atproto.repo.createRecord" | "com.atproto.repo.putRecord" | "com.atproto.repo.deleteRecord" | "com.atproto.repo.applyWrites" | ||
if is_post => | ||
{ | ||
let b = parse_body(body)?; | ||
// A write checks its token before its input. | ||
"com.atproto.repo.createRecord" | "com.atproto.repo.putRecord" | "com.atproto.repo.deleteRecord" | "com.atproto.repo.applyWrites" => { | ||
match auth { | ||
Auth::Owner => write(s, nsid, &b), | ||
Auth::None => err(401, "AuthenticationRequired", "Authentication Required"), | ||
Auth::Owner => write(s, nsid, &parse_body(body)?), | ||
Auth::None => err(401, "AuthMissing", "Authentication Required"), | ||
Auth::Invalid => invalid_token(), | ||
} | ||
} | ||
"com.atproto.repo.getRecord" if !is_post => get_record(s, params), | ||
"com.atproto.repo.listRecords" if !is_post => list_records(s, params), | ||
"com.atproto.repo.describeRepo" if !is_post => { | ||
check_repo(s, required(params, "repo")?)?; | ||
"com.atproto.repo.getRecord" => get_record(s, params), | ||
"com.atproto.repo.listRecords" => list_records(s, params), | ||
"com.atproto.repo.describeRepo" => { | ||
let repo = required(params, "repo")?; | ||
if repo != s.handle && repo != s.did { | ||
return err(400, "RepoNotFound", format!("Could not find repo: {repo}")); | ||
} | ||
let mut cols: Vec<&str> = s.repo.records.keys().filter_map(|k| k.split('/').next()).collect(); | ||
cols.dedup(); | ||
Ok(Resp::Json(json!({ | ||
| @@ -296,11 +312,15 @@ fn dispatch( | ||
"collections": cols, "handleIsCorrect": true | ||
}))) | ||
} | ||
"com.atproto.sync.getRepo" if !is_post => { | ||
"com.atproto.sync.getRepo" => { | ||
check_did(s, required(params, "did")?)?; | ||
Ok(Resp::Car(s.repo.car())) | ||
match param(params, "since") { | ||
None => Ok(Resp::Car(s.repo.car())), | ||
Some(since) if valid_tid(since) => Ok(Resp::Car(s.repo.car_since(since))), | ||
Some(_) => err(400, "InvalidRequest", "since must be a valid tid"), | ||
} | ||
} | ||
"com.atproto.sync.getLatestCommit" if !is_post => { | ||
"com.atproto.sync.getLatestCommit" => { | ||
check_did(s, required(params, "did")?)?; | ||
Ok(Resp::Json(json!({ "cid": s.repo.head_string(), "rev": s.repo.rev }))) | ||
} | ||
| @@ -406,15 +426,24 @@ fn check_rkey(k: &str) -> Result<(), ApiErr> { | ||
if valid_rkey(k) { Ok(()) } else { err(400, "InvalidRequest", "Invalid rkey") } | ||
} | ||
| ||
fn record_value(b: &serde_json::Map<String, Json>, field: &str, collection: &str) -> Result<V, ApiErr> { | ||
/// A record as input: present, in the data model, and an object. | ||
fn record_value(b: &serde_json::Map<String, Json>, field: &str) -> Result<V, ApiErr> { | ||
let Some(j) = b.get(field) else { return err(400, "InvalidRequest", format!("Input/{field} is required")) }; | ||
let v = from_json(j).or_else(|e| err(400, "InvalidRequest", e))?; | ||
let V::Map(m) = &v else { return err(400, "InvalidRequest", "record must be an object") }; | ||
if !matches!(v, V::Map(_)) { | ||
return err(400, "InvalidRequest", "record must be an object"); | ||
} | ||
Ok(v) | ||
} | ||
| ||
/// A record whose `$type` is its collection, given it if it has none. The | ||
/// reference checks this after the write's `repo`, not with its input. | ||
fn typed(v: V, collection: &str) -> Result<V, ApiErr> { | ||
let V::Map(mut m) = v else { unreachable!("record_value answers objects") }; | ||
match m.iter().find(|(k, _)| k == "$type") { | ||
Some((_, V::Str(t))) if t == collection => Ok(v), | ||
Some((_, V::Str(t))) if t == collection => Ok(V::Map(m)), | ||
Some((_, V::Str(_))) => err(400, "InvalidRequest", "$type does not match collection"), | ||
None => { | ||
let mut m = m.clone(); | ||
m.push(("$type".into(), V::Str(collection.into()))); | ||
Ok(V::Map(m)) | ||
} | ||
| @@ -430,8 +459,35 @@ fn invalid_token<T>() -> Result<T, ApiErr> { | ||
err(400, "InvalidToken", "Invalid token") | ||
} | ||
| ||
/// The `validationStatus` a write answers, as its `validate` asks: `unknown` | ||
/// by default, none with `false`. `true` is refused, as the server knows no | ||
/// lexicon for any record type. | ||
fn validation_status(b: &serde_json::Map<String, Json>) -> Result<Option<&'static str>, ApiErr> { | ||
match b.get("validate") { | ||
None | Some(Json::Null) => Ok(Some("unknown")), | ||
Some(Json::Bool(false)) => Ok(None), | ||
Some(Json::Bool(true)) => err(400, "InvalidRequest", "Lexicon not found"), | ||
Some(_) => err(400, "InvalidRequest", "Input/validate must be a boolean"), | ||
} | ||
} | ||
| ||
/// A write's answer, with its `validationStatus` if it has one. | ||
fn with_status(mut answer: Json, status: Option<&str>) -> Json { | ||
if let Some(v) = status { | ||
answer["validationStatus"] = json!(v); | ||
} | ||
answer | ||
} | ||
| ||
/// A write's `repo`, checked once its input is: `403 AccountNotFound` unless it names the account. | ||
fn check_account(s: &Server, repo: &str) -> Result<(), ApiErr> { | ||
if repo == s.handle || repo == s.did { Ok(()) } else { err(403, "AccountNotFound", "Could not find account") } | ||
} | ||
| ||
/// A write: its token was checked; now its input, then its `repo`, then what it does. | ||
fn write(s: &mut Server, nsid: &str, b: &serde_json::Map<String, Json>) -> Result<Resp, ApiErr> { | ||
check_repo(s, str_field(b, "repo")?)?; | ||
let repo = str_field(b, "repo")?; | ||
let status = if nsid == "com.atproto.repo.deleteRecord" { None } else { validation_status(b)? }; | ||
let swap_commit = opt_str(b, "swapCommit")?; | ||
match nsid { | ||
"com.atproto.repo.createRecord" => { | ||
| @@ -441,27 +497,37 @@ fn write(s: &mut Server, nsid: &str, b: &serde_json::Map<String, Json>) -> Resul | ||
if let Some(k) = rkey { | ||
check_rkey(k)?; | ||
} | ||
let value = record_value(b, "record", collection)?; | ||
let value = record_value(b, "record")?; | ||
check_account(s, repo)?; | ||
let value = typed(value, collection)?; | ||
let res = s.repo.apply(vec![Op::Create { collection: collection.into(), rkey: rkey.map(Into::into), value }], swap_commit)?; | ||
let Some(OpResult::Create { uri, cid }) = res.into_iter().next() else { unreachable!() }; | ||
Ok(Resp::Json(json!({ "uri": uri, "cid": cid, "commit": commit_meta(s), "validationStatus": "unknown" }))) | ||
Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": cid, "commit": commit_meta(s) }), status))) | ||
} | ||
"com.atproto.repo.putRecord" => { | ||
let collection = str_field(b, "collection")?; | ||
check_collection(collection)?; | ||
let rkey = str_field(b, "rkey")?; | ||
check_rkey(rkey)?; | ||
let value = record_value(b, "record", collection)?; | ||
let value = record_value(b, "record")?; | ||
let swap_record = match b.get("swapRecord") { | ||
None => None, | ||
Some(Json::Null) => Some(None), | ||
Some(Json::String(c)) => Some(Some(c.as_str())), | ||
Some(_) => return err(400, "InvalidRequest", "Input/swapRecord must be a string"), | ||
}; | ||
check_account(s, repo)?; | ||
let value = typed(value, collection)?; | ||
let existing = s.repo.records.get(&format!("{collection}/{rkey}")).map(|r| cid_string(&r.cid)); | ||
if existing.is_some() && existing.as_deref() == Some(cid_string(&make_record(value.clone()).cid).as_str()) { | ||
// Writing what is already there makes no commit. | ||
let uri = s.repo.uri(collection, rkey); | ||
return Ok(Resp::Json(json!({ "uri": uri, "cid": existing, "validationStatus": "unknown" }))); | ||
return Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": existing }), status))); | ||
} | ||
match b.get("swapRecord") { | ||
match swap_record { | ||
None => {} | ||
Some(Json::Null) if existing.is_none() => {} | ||
Some(Json::String(c)) if existing.as_deref() == Some(c) => {} | ||
Some(None) if existing.is_none() => {} | ||
Some(Some(c)) if existing.as_deref() == Some(c) => {} | ||
Some(_) => return err(400, "InvalidSwap", "Record was at a different CID"), | ||
} | ||
let op = if existing.is_some() { | ||
| @@ -471,18 +537,20 @@ fn write(s: &mut Server, nsid: &str, b: &serde_json::Map<String, Json>) -> Resul | ||
}; | ||
let res = s.repo.apply(vec![op], swap_commit)?; | ||
let (OpResult::Create { uri, cid } | OpResult::Update { uri, cid }) = res.into_iter().next().unwrap() else { unreachable!() }; | ||
Ok(Resp::Json(json!({ "uri": uri, "cid": cid, "commit": commit_meta(s), "validationStatus": "unknown" }))) | ||
Ok(Resp::Json(with_status(json!({ "uri": uri, "cid": cid, "commit": commit_meta(s) }), status))) | ||
} | ||
"com.atproto.repo.deleteRecord" => { | ||
let collection = str_field(b, "collection")?; | ||
check_collection(collection)?; | ||
let rkey = str_field(b, "rkey")?; | ||
check_rkey(rkey)?; | ||
let swap_record = opt_str(b, "swapRecord")?; | ||
check_account(s, repo)?; | ||
let existing = s.repo.records.get(&format!("{collection}/{rkey}")).map(|r| cid_string(&r.cid)); | ||
if existing.is_none() { | ||
return Ok(Resp::Json(json!({}))); | ||
} | ||
if let Some(c) = opt_str(b, "swapRecord")? { | ||
if let Some(c) = swap_record { | ||
if existing.as_deref() != Some(c) { | ||
return err(400, "InvalidSwap", "Record was at a different CID"); | ||
} | ||
| @@ -490,11 +558,17 @@ fn write(s: &mut Server, nsid: &str, b: &serde_json::Map<String, Json>) -> Resul | ||
s.repo.apply(vec![Op::Delete { collection: collection.into(), rkey: rkey.into() }], swap_commit)?; | ||
Ok(Resp::Json(json!({ "commit": commit_meta(s) }))) | ||
} | ||
_ => apply_writes(s, b, swap_commit), | ||
_ => apply_writes(s, b, repo, swap_commit, status), | ||
} | ||
} | ||
| ||
fn apply_writes(s: &mut Server, b: &serde_json::Map<String, Json>, swap_commit: Option<&str>) -> Result<Resp, ApiErr> { | ||
fn apply_writes( | ||
s: &mut Server, | ||
b: &serde_json::Map<String, Json>, | ||
repo: &str, | ||
swap_commit: Option<&str>, | ||
status: Option<&str>, | ||
) -> Result<Resp, ApiErr> { | ||
let Some(Json::Array(writes)) = b.get("writes") else { return err(400, "InvalidRequest", "Input/writes must be an array") }; | ||
let mut ops = Vec::new(); | ||
for w in writes { | ||
| @@ -508,13 +582,13 @@ fn apply_writes(s: &mut Server, b: &serde_json::Map<String, Json>, swap_commit: | ||
if let Some(k) = rkey { | ||
check_rkey(k)?; | ||
} | ||
let value = record_value(w, "value", collection)?; | ||
let value = record_value(w, "value")?; | ||
ops.push(Op::Create { collection: collection.into(), rkey: rkey.map(Into::into), value }); | ||
} | ||
"com.atproto.repo.applyWrites#update" => { | ||
let rkey = str_field(w, "rkey")?; | ||
check_rkey(rkey)?; | ||
let value = record_value(w, "value", collection)?; | ||
let value = record_value(w, "value")?; | ||
ops.push(Op::Update { collection: collection.into(), rkey: rkey.into(), value }); | ||
} | ||
"com.atproto.repo.applyWrites#delete" => { | ||
| @@ -525,12 +599,22 @@ fn apply_writes(s: &mut Server, b: &serde_json::Map<String, Json>, swap_commit: | ||
_ => return err(400, "InvalidRequest", "unknown write type"), | ||
} | ||
} | ||
check_account(s, repo)?; | ||
for op in &mut ops { | ||
if let Op::Create { collection, value, .. } | Op::Update { collection, value, .. } = op { | ||
*value = typed(std::mem::replace(value, V::Null), collection)?; | ||
} | ||
} | ||
let results = s.repo.apply(ops, swap_commit)?; | ||
let results: Vec<Json> = results | ||
.into_iter() | ||
.map(|r| match r { | ||
OpResult::Create { uri, cid } => json!({ "$type": "com.atproto.repo.applyWrites#createResult", "uri": uri, "cid": cid, "validationStatus": "unknown" }), | ||
OpResult::Update { uri, cid } => json!({ "$type": "com.atproto.repo.applyWrites#updateResult", "uri": uri, "cid": cid, "validationStatus": "unknown" }), | ||
OpResult::Create { uri, cid } => { | ||
with_status(json!({ "$type": "com.atproto.repo.applyWrites#createResult", "uri": uri, "cid": cid }), status) | ||
} | ||
OpResult::Update { uri, cid } => { | ||
with_status(json!({ "$type": "com.atproto.repo.applyWrites#updateResult", "uri": uri, "cid": cid }), status) | ||
} | ||
OpResult::Delete => json!({ "$type": "com.atproto.repo.applyWrites#deleteResult" }), | ||
}) | ||
.collect(); | ||
| @@ -623,6 +707,42 @@ mod tests { | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// `getRepo since` answers the same after a restart, which rebuilds when | ||
/// each block was added from the log. | ||
#[test] | ||
fn since_survives_restart() { | ||
let dir = scratch("since"); | ||
let mut s = open(&dir); | ||
let sess = call(&mut s, "com.atproto.server.createSession", None, json!({ "identifier": "h.test", "password": "pw" })).unwrap(); | ||
let owner = sess["accessJwt"].as_str().unwrap().to_string(); | ||
let mut revs = vec![s.repo.rev.clone()]; | ||
for (k, n) in [("one", 1), ("two", 2), ("one", 3), ("three", 1)] { | ||
let body = json!({ "repo": DID, "collection": "a.b.c", "rkey": k, "record": { "n": n } }); | ||
call(&mut s, "com.atproto.repo.putRecord", Some(&owner), body).unwrap(); | ||
revs.push(s.repo.rev.clone()); | ||
} | ||
call(&mut s, "com.atproto.repo.deleteRecord", Some(&owner), json!({ "repo": DID, "collection": "a.b.c", "rkey": "two" })).unwrap(); | ||
revs.push(s.repo.rev.clone()); | ||
let before: Vec<Vec<u8>> = revs.iter().map(|r| s.repo.car_since(r)).collect(); | ||
// At the latest rev, the CAR is its header alone. | ||
let latest = before.last().unwrap(); | ||
assert_eq!(latest, &car_file(&s.repo.head, std::iter::empty())); | ||
// A record's block is among them from the commit that last made the | ||
// repository hold it: `three` holds again what `one` first held. | ||
let holds = |car: &[u8], n: i64| { | ||
let r = make_record(from_json(&json!({ "n": n, "$type": "a.b.c" })).unwrap()); | ||
car.windows(r.bytes.len()).any(|w| w == r.bytes.as_slice()) | ||
}; | ||
assert!(holds(&before[3], 1) && !holds(&before[3], 2) && !holds(&before[3], 3)); | ||
assert!(!holds(&before[4], 1)); | ||
assert!(holds(&before[0], 1) && holds(&before[0], 3) && !holds(&before[0], 2)); | ||
drop(s); | ||
let s = open(&dir); | ||
let after: Vec<Vec<u8>> = revs.iter().map(|r| s.repo.car_since(r)).collect(); | ||
assert_eq!(before, after); | ||
let _ = std::fs::remove_dir_all(&dir); | ||
} | ||
| ||
/// Cut the log at every byte of each frame (and flip a byte in each): recovery | ||
/// must give the state before that frame or after it, and keep working. | ||
#[test] | ||
harness/compare.mjs+120−5
| @@ -211,7 +211,7 @@ async function xrpc(side, nsid, request = {}) { | ||
return xrpcHttp(side, nsid, request) | ||
} | ||
| ||
async function xrpcHttp(side, nsid, { params, body, token, raw } = {}) { | ||
async function xrpcHttp(side, nsid, { params, body, token, raw, method } = {}) { | ||
const url = new URL(`${side.url}/xrpc/${nsid}`) | ||
for (const [k, v] of Object.entries(params ?? {})) if (v !== undefined) url.searchParams.set(k, String(v)) | ||
const headers = {} | ||
| @@ -219,7 +219,7 @@ async function xrpcHttp(side, nsid, { params, body, token, raw } = {}) { | ||
if (body !== undefined) headers['content-type'] = 'application/json' | ||
let res | ||
try { | ||
res = await fetch(url, { method: body === undefined ? 'GET' : 'POST', headers, body: body === undefined ? undefined : JSON.stringify(body) }) | ||
res = await fetch(url, { method: method ?? (body === undefined ? 'GET' : 'POST'), headers, body: body === undefined ? undefined : JSON.stringify(body) }) | ||
} catch (err) { | ||
return { status: 0, body: { error: `request failed: ${err.message}` } } | ||
} | ||
| @@ -319,6 +319,7 @@ const METHODS = (() => { | ||
description: main.description, | ||
props: schema?.properties ?? {}, | ||
required: schema?.required ?? [], | ||
nullable: schema?.nullable ?? [], | ||
tool: main.type !== 'subscription' && json ? `${group}_${snake(name)}` : null, | ||
command: main.type !== 'subscription' ? kebab(name) : null, | ||
flag: (p) => `--${kebab(p)}`, | ||
| @@ -389,7 +390,7 @@ async function mcpRpc(method, params, token, shape) { | ||
/// status, beside the reference's XRPC one. | ||
const ERROR_STATUS = { | ||
InvalidRequest: 400, RecordNotFound: 400, InvalidSwap: 400, RepoNotFound: 400, InvalidToken: 400, ExpiredToken: 400, | ||
AuthMissing: 401, AuthenticationRequired: 401, InternalServerError: 500, MethodNotImplemented: 501, | ||
AuthMissing: 401, AuthenticationRequired: 401, AccountNotFound: 403, InternalServerError: 500, MethodNotImplemented: 501, | ||
} | ||
| ||
/// The method's arguments, as a tool or command takes them: sometimes | ||
| @@ -522,7 +523,9 @@ async function checkCommands() { | ||
const required = m.required.filter((k) => !ACCOUNT_ARGS.includes(k)).sort() | ||
if (!isDeepStrictEqual([...(s.required ?? [])].sort(), required)) await fail(`required ${required}`, s.required ?? []) | ||
for (const [k, lexProp] of Object.entries(m.props)) { | ||
if (props[k]?.type !== schemaType(lexProp.type)) await fail(`${k} of type ${schemaType(lexProp.type) ?? 'any'}, as its lexicon type ${lexProp.type}`, props[k]) | ||
const type = schemaType(lexProp.type) | ||
const want = m.nullable.includes(k) ? [type, 'null'] : type | ||
if (!isDeepStrictEqual(props[k]?.type, want)) await fail(`${k} of type ${JSON.stringify(want) ?? 'any'}, as its lexicon type ${lexProp.type}${m.nullable.includes(k) ? ', nullable' : ''}`, props[k]) | ||
for (const c of ['minimum', 'maximum', 'maxLength', 'enum']) if (lexProp[c] !== undefined && !isDeepStrictEqual(props[k]?.[c], lexProp[c])) await fail(`${k} with ${c} ${JSON.stringify(lexProp[c])}`, props[k]) | ||
} | ||
const destructive = ['com.atproto.repo.deleteRecord', 'com.atproto.repo.putRecord', 'com.atproto.repo.applyWrites'].includes(m.nsid) | ||
| @@ -736,6 +739,64 @@ async function badSession() { | ||
}) | ||
} | ||
| ||
/// A DID no server here holds. | ||
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa' | ||
| ||
/// Requests at the edges of what SLICE.md settles, each held to the | ||
/// reference: writes with no token or one never given out, whatever their | ||
/// input; a write to another repository; the sync methods and describeRepo | ||
/// of a DID no one holds; a method called with the other HTTP method; and | ||
/// writes with `validate` set. | ||
async function oddRequests() { | ||
const collection = pick(COLLECTIONS) | ||
const bad = chance(0.5) | ||
const writeBody = () => ({ repo: HANDLE, collection: bad ? 'not an nsid' : collection, rkey: pick(RKEYS), record: record(collection, cids) }) | ||
const r = rand() | ||
if (r < 0.2) { | ||
const nsid = pick(['com.atproto.repo.createRecord', 'com.atproto.repo.putRecord', 'com.atproto.repo.deleteRecord']) | ||
return void (await both(`write with no token${bad ? ', bad input' : ''}`, nsid, { body: writeBody() })) | ||
} | ||
if (r < 0.3) return void (await both('write with a token never given out, bad input', 'com.atproto.repo.createRecord', { body: { ...writeBody(), collection: 'not an nsid' }, token: 'never-given-out' })) | ||
if (r < 0.45) return void (await both('write to another repository', 'com.atproto.repo.createRecord', { body: { ...writeBody(), collection, repo: NOBODY }, token: 'owner' })) | ||
if (r < 0.6) { | ||
const [nsid, params] = pick([ | ||
['com.atproto.repo.describeRepo', { repo: NOBODY }], | ||
['com.atproto.sync.getLatestCommit', { did: NOBODY }], | ||
['com.atproto.sync.getRepo', { did: NOBODY }], | ||
]) | ||
return void (await both('a repository no one holds', nsid, { params })) | ||
} | ||
if (r < 0.75) { | ||
// The other HTTP method: a procedure by GET, a query by POST. | ||
const [nsid, request] = chance(0.5) | ||
? ['com.atproto.repo.createRecord', { method: 'GET' }] | ||
: ['com.atproto.repo.getRecord', { method: 'POST', body: {}, params: { repo: HANDLE, collection, rkey: pick(RKEYS) } }] | ||
const [a, b] = await Promise.all([ref, cand].map((side) => xrpcHttp(side, nsid, { ...request, token: side.token }))) | ||
const [na, nb] = [normalize(ref, a), normalize(cand, b)] | ||
if (!isDeepStrictEqual(na, nb)) await differ(nsid, { by: request.method }, na, nb, 'called with the other HTTP method') | ||
return count('the other HTTP method', false) | ||
} | ||
// validate: true is refused for want of a lexicon; false writes, with no validationStatus. | ||
const validate = chance(0.5) | ||
const key = pick(RKEYS) | ||
const value = { ...goodRecord(collection), batch: ++batchSerial } | ||
const [nsid, body] = pick([ | ||
['com.atproto.repo.createRecord', { repo: HANDLE, collection, rkey: key, record: value, validate }], | ||
['com.atproto.repo.putRecord', { repo: HANDLE, collection, rkey: key, record: value, validate }], | ||
['com.atproto.repo.applyWrites', { repo: HANDLE, validate, writes: [{ $type: `com.atproto.repo.applyWrites#${exists(collection, key) ? 'update' : 'create'}`, collection, rkey: key, value }] }], | ||
]) | ||
const [a, b] = await both(`validate: ${validate}`, nsid, { body, token: 'owner' }) | ||
if (a.status < 400) { | ||
const cid = a.body.cid ?? a.body.results?.[0]?.cid | ||
if (cid) { | ||
records.set(`${collection}/${key}`, cid) | ||
cids.push(cid) | ||
} | ||
} | ||
noteCommit(ref, a) | ||
noteCommit(cand, b) | ||
} | ||
| ||
/// getSession with the account's token, none, or one never given out. Of its | ||
/// answer, the handle, DID and whether the account is active are compared. | ||
async function getSession() { | ||
| @@ -1040,11 +1101,24 @@ async function checkReplay() { | ||
answers[side.name] = { events: sub.events.map(kind), closed: !sub.open } | ||
} | ||
if (!isDeepStrictEqual(answers.reference, answers.server)) await differ('subscribeRepos from a cursor in the future', { cursor: future }, answers.reference, answers.server) | ||
| ||
// A cursor that is not an integer is refused as the reference refuses it. | ||
const odd = {} | ||
for (const side of [ref, cand]) { | ||
const sub = subscribe(side, 'abc') | ||
const t = Date.now() | ||
while (sub.open && Date.now() - t < 2000) await wait(20) | ||
sub.ws.close() | ||
odd[side.name] = { events: sub.events.map(kind), closed: !sub.open } | ||
} | ||
if (!isDeepStrictEqual(odd.reference, odd.server)) await differ('subscribeRepos from a cursor that is not an integer', { cursor: 'abc' }, odd.reference, odd.server) | ||
} | ||
| ||
// ---- The whole repository ---------------------------------------------- | ||
| ||
let lastRev = '' | ||
/// Each side's rev at the last repository check, for `getRepo` with `since`. | ||
const revs = { reference: null, server: null } | ||
| ||
async function checkRepos() { | ||
const [a, b] = await Promise.all([ref, cand].map((side) => xrpc(side, 'com.atproto.sync.getRepo', { params: { did: side.did }, raw: true }))) | ||
| @@ -1070,6 +1144,9 @@ async function checkRepos() { | ||
if (latest.status !== 200 || latest.body.cid !== ours.root.toString() || latest.body.rev !== ourCommit.rev) { | ||
await differ('com.atproto.sync.getLatestCommit', {}, { cid: ours.root.toString(), rev: ourCommit.rev }, latest.body) | ||
} | ||
if (revs.server && chance(0.3)) await checkSince(theirCommit.rev, ourCommit.rev, theirs.root.toString(), ours.root.toString()) | ||
revs.reference = theirCommit.rev | ||
revs.server = ourCommit.rev | ||
count('repository check', Boolean(verified)) | ||
if (FIREHOSE) { | ||
await checkFirehose() | ||
| @@ -1077,6 +1154,44 @@ async function checkRepos() { | ||
} | ||
} | ||
| ||
/// `getRepo` with `since`: a CAR whose root is the latest commit, holding the | ||
/// blocks of the commits after that rev, none if it is the latest. Each side | ||
/// has its own revs, and its own commit blocks, so the two are compared by | ||
/// the records their blocks hold, which are the same records. | ||
async function checkSince(theirHead, ourHead, theirRoot, ourRoot) { | ||
const r = rand() | ||
const which = r < 0.25 ? 'latest' : r < 0.35 ? 'bad' : 'last' | ||
const since = which === 'latest' ? { reference: theirHead, server: ourHead } : which === 'bad' ? { reference: 'notarev', server: 'notarev' } : { ...revs } | ||
const [a, b] = await Promise.all([ref, cand].map((side) => xrpc(side, 'com.atproto.sync.getRepo', { params: { did: side.did, since: since[side.name] }, raw: true }))) | ||
const request = { since: { latest: 'the latest rev', bad: 'notarev', last: 'the rev at the last check' }[which] } | ||
if (a.status !== 200 || b.status !== 200) { | ||
const [na, nb] = [normalize(ref, a), normalize(cand, b)] | ||
if (!isDeepStrictEqual(na, nb)) await differ('com.atproto.sync.getRepo', request, na, nb) | ||
return count('getRepo since', false) | ||
} | ||
const read = async (bytes) => { | ||
const car = await readCarWithRoot(bytes) | ||
const recs = [] | ||
car.blocks.forEach((data, cid) => { | ||
const v = cborDecode(data) | ||
if (v && typeof v.$type === 'string') recs.push(cid.toString()) | ||
}) | ||
return { root: car.root.toString(), blocks: car.blocks.size, records: recs.sort() } | ||
} | ||
let theirsSince, oursSince | ||
try { | ||
oursSince = await read(b.bytes) | ||
} catch (err) { | ||
return differ('com.atproto.sync.getRepo', request, 'a CAR', String(err.message ?? err)) | ||
} | ||
theirsSince = await read(a.bytes) | ||
if (oursSince.root !== ourRoot) await differ('com.atproto.sync.getRepo', request, `the latest commit, ${ourRoot}, as root`, oursSince.root) | ||
if (theirsSince.root !== theirRoot) throw new Error(`the reference's getRepo since has root ${theirsSince.root}, not ${theirRoot}`) | ||
if (which === 'latest' && oursSince.blocks !== 0) await differ('com.atproto.sync.getRepo', request, 'no blocks', `${oursSince.blocks} blocks`) | ||
if (!isDeepStrictEqual(theirsSince.records, oursSince.records)) await differ('com.atproto.sync.getRepo', request, { records: theirsSince.records }, { records: oursSince.records }, 'the records written since') | ||
harness/compare.mjsline 1191Only records are compared. The spec also puts the MST nodes written since in this CAR, and nothing here checks them. Compare the count of non-record blocks too, or say in SLICE.md that the nodes are the server's choice, as is done for the firehose. | ||
count('getRepo since', true) | ||
} | ||
| ||
// ---- Crashes ------------------------------------------------------------ | ||
| ||
const crashes = { count: 0, inFlight: 0, landed: 0, restartMs: [] } | ||
| @@ -1151,7 +1266,7 @@ await checkRepos() | ||
const STEPS_BY_WEIGHT = [ | ||
[createRecord, 14], [putRecord, 14], [deleteRecord, 8], [applyWrites, 8], | ||
[getRecord, 10], [listRecords, 6], [describeRepo, 2], [badSession, 1], | ||
[getSession, 1], [createWithTid, 2], [concurrent, 6], | ||
[getSession, 1], [createWithTid, 2], [concurrent, 6], [oddRequests, 3], | ||
] | ||
const total = STEPS_BY_WEIGHT.reduce((n, [, w]) => n + w, 0) | ||
for (step = 1; step <= STEPS; step++) { | ||
spec/atproto/did.mdnew+193−0
| @@ -0,0 +1,193 @@ | ||
export const header = { | ||
title: 'DID', | ||
description: | ||
'Persistent decentralized identifiers (as used in atproto)', | ||
} | ||
| ||
# AT Protocol DIDs | ||
| ||
AT Protocol uses [Decentralized Identifiers](https://en.wikipedia.org/wiki/Decentralized_identifier) (DIDs) as persistent account identifiers. The core DID standard was developed by the W3C, and describes a framework for compliant identifier systems ("DID methods"), of which several exist. To ensure broad interoperation across the ecosystem, atproto only supports a small number of "blessed" DID methods. {{ className: 'lead' }} | ||
| ||
An example DID is `did:plc:ewvi7nxzyoun6zhxrhs64oiz`. | ||
| ||
| ||
## Blessed DID Methods | ||
| ||
Currently, atproto supports two DID methods: | ||
| ||
- `did:plc`: a self-authenticating DID method developed specifically for use with atproto. See the [DID PLC website](https://web.plc.directory) for more details. | ||
- `did:web`: a [W3C community draft](https://w3c-ccg.github.io/did-method-web/) based on HTTPS (and DNS). The identifier section is a hostname. This method is supported in atproto to provide an independent alternative to `did:plc`. See usage details below | ||
| ||
It is possible that other methods will be supported in the future, but the intention is to keep the "blessed" set as small as possible. It is certainly not the intention to support all or even a significant fraction of all DID methods. | ||
| ||
### `did:web` in AT Protocol | ||
| ||
The [DID Web method](https://w3c-ccg.github.io/did-method-web/) is inherently tied to the domain name used, and does not provide a mechanism for migration or recovering from loss of control of the domain name. | ||
| ||
In the context of atproto, only hostname-level `did:web` DIDs are supported: path-based DIDs are not supported. The same restrictions on top-level domains that apply to handles (eg, no `.arpa`) also apply to `did:web` domains. The special `localhost` hostname is allowed, but only in testing and development environments. Port numbers (with separating colon hex-encoded) are only allowed for `localhost`, and only in testing and development. | ||
| ||
| ||
## DID Identifier Syntax | ||
| ||
Lexicon string format type: `did` | ||
| ||
The DID Core specification places syntax restrictions on all DID identifiers, and individual DID methods might have their own more specific syntax. While atproto supports only a small set of DID methods today, it still makes sense to consider the general DID syntax in many parsing and validation contexts. | ||
| ||
The general syntax constraints used to validate generic DID identifiers in atproto are: | ||
| ||
- The entire URI is made up of a subset of ASCII, containing letters (`A-Z`, `a-z`), digits (`0-9`), period, underscore, colon, percent sign, or hyphen (`._:%-`) | ||
- The URI is case-sensitive | ||
- The URI starts with lowercase `did:` | ||
- The method segment is one or more lowercase letters (`a-z`), followed by `:` | ||
- The remainder of the URI (the identifier) may contain any of the above-allowed ASCII characters, except for percent-sign (`%`) | ||
- The URI (and thus the remaining identifier) may not end in `:`. | ||
- Percent-sign (`%`) is used for "percent encoding" in the identifier section, and must always be followed by two hex characters | ||
- Query (`?`) and fragment (`#`) sections are allowed in DID URIs, but not in DID identifiers. In the context of atproto, the query and fragment parts are not allowed. | ||
| ||
DID identifiers do not generally have a maximum length restriction, but in the context of atproto, there is a current hard limit of 2048 characters. | ||
| ||
In the context of atproto, implementations do not need to validate percent encoding. The percent symbol is allowed in DID identifier segments, but the identifier should not end in a percent symbol. A DID containing invalid percent encoding *should* fail any attempt at registration, resolution, etc. | ||
| ||
A reasonable starting-point regex for DIDs in the context of atproto is: | ||
| ||
``` | ||
// NOTE: does not constrain overall length | ||
/^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/ | ||
``` | ||
| ||
| ||
### Examples | ||
| ||
Valid DIDs for use in atproto (correct syntax, and supported method): | ||
| ||
``` | ||
did:plc:ewvi7nxzyoun6zhxrhs64oiz | ||
did:web:user.example.com | ||
``` | ||
| ||
Valid DID syntax (would pass Lexicon syntax validation), but unsupported DID method: | ||
| ||
``` | ||
did:method:val:two | ||
did:m:v | ||
did:method::::val | ||
did:method:-:_:. | ||
did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N | ||
``` | ||
| ||
Invalid DID identifier syntax (regardless of DID method): | ||
| ||
``` | ||
did:METHOD:val | ||
did:m123:val | ||
DID:method:val | ||
did:method: | ||
did:method:val/two | ||
did:method:val?two | ||
did:method:val#two | ||
``` | ||
| ||
| ||
## DID Documents | ||
| ||
After a DID document has been resolved, atproto-specific information needs to be extracted. This parsing process is agnostic to the DID method used to resolve the document. | ||
| ||
The DID declared in the document (in the `id` field) should always be verified against what was expected (eg, used for resolution). | ||
| ||
The [handle](/specs/handle) claimed by the DID is found in the `alsoKnownAs` array. Each element of this array is a URI string. Handles will have the URI prefix `at://`, followed by the handle hostname, with no other URI parts or trailing characters. The first syntaxtually valid handle found in the ordered list is treated as the claimed handle, even if it fails to resolve bi-directionally. Any other handle URIs should be ignored. | ||
| ||
It is crucial to validate the handle bidirectionally, by resolving the handle to a DID and checking that it matches the current DID document. See the [handle specification](/specs/handle) for details. | ||
| ||
The DID is the primary account identifier in atproto, and an account whose DID document does not contain a valid and confirmed handle can still participate in the atproto ecosystem. Software should be careful to either not display any handle for such account, or obviously indicate that any handle associated with it is invalid. | ||
| ||
The public **atproto signing key** for the account is found under the `verificationMethod` array, in an object with `id` ending `#atproto`, the `controller` matching the DID itself, and `type` matching the fixed string `Multikey`. The first valid atproto signing key in the array should be used, and any others ignored. The `publicKeyMultibase` field will be the public key in multibase encoding. A legacy format exists with slightly different requirements. See below for details about parsing fields for both formats. | ||
| ||
A valid signing key is required for most atproto functionality. An account with no valid key in their DID document is likely broken. | ||
| ||
The **PDS service network location** for the account is found under the `service` array, with `id` ending `#atproto_pds`, and `type` matching `AtprotoPersonalDataServer`. The first matching entry in the array should be used, and any others ignored. The `serviceEndpoint` field must contain an HTTPS URL of server. It should contain only the URI scheme (`http` or `https`), hostname, and optional port number, not any "userinfo", path prefix, or other components. | ||
| ||
A working PDS is required for most atproto account functionality. An account with no valid PDS location in their DID document is likely broken. | ||
| ||
Note that a valid URL doesn't mean the the PDS itself is currently functional or hosting content for the account. During account migrations or server downtime there may be windows when the PDS is not accessible, but this does not mean the account should immediately be considered broken or invalid. | ||
| ||
Other protocol and application features may make use of `verificationMethod` keys and `service` entries. For example, [labeling](/specs/label) uses an additional key type, and application-specific "AppView" instances use bespoke service entries. | ||
| ||
When parsing the `id` field in object elements of the `service` and `verificationMethod` arrays, implementations should support both relative fragment syntax (eg, `"id": "#atproto_pds"`) and fully-qualified syntax (eg, `"id": "did:web:example.com#atproto_pds"`). | ||
| ||
| ||
## Representation of Public Keys | ||
| ||
The atproto cryptographic systems are described in [Cryptography](/specs/cryptography), including details of byte and string encoding of public keys. | ||
| ||
Public keys in DID documents under `verificationMethod`, including atproto signing keys, are represented as an object with the following fields: | ||
| ||
- `id` (string, required): the DID followed by an identifying fragment. Use `#atproto` as the fragment for atproto signing keys | ||
- `type` (string, required): the fixed string `Multikey` | ||
- `controller` (string, required): DID controlling the key, which in the current version of atproto must match the account DID itself | ||
- `publicKeyMultibase` (string, required): the public key itself, encoded in "multikey" format | ||
| ||
The `publicKeyMultibase` format for `Multikey` is the same encoding scheme as used with `did:key`, but without the `did:key:` prefix. See [Cryptography](/specs/cryptography) for details. | ||
| ||
Note that there is not yet a formal W3C standard for using P-256 public keys in DID `verificationMethod` sections, but that the `Multikey` standard does clarify what the encoding encoding should be for this key type. | ||
| ||
| ||
### Legacy Representation | ||
| ||
Some older DID documents, which may still appear in `did:web` docs, had slightly different key encodings and `verificationMethod` syntax. Implementations may support these older DID documents during a transition period, but the intention is to require DID specification compliance going forward. | ||
| ||
The older `verificationMethod` for atproto signing keys contained: | ||
| ||
- `id` (string, required): the fixed string `#atproto`, without the full DID included | ||
- `type` (string, required): a fixed name identifying the key's curve type | ||
- `p256`: `EcdsaSecp256r1VerificationKey2019` (note the "r") | ||
- `k256`: `EcdsaSecp256k1VerificationKey2019` (note the "k") | ||
- `controller` (string, required): DID controlling the key, which in the current version of atproto must match the account DID itself | ||
- `publicKeyMultibase` (string, required): the public key itself, encoded in multibase format (*without* multicodec, and *uncompressed* key bytes) | ||
| ||
Note that the `EcdsaSecp256k1VerificationKey2019` type is not a formal W3C standard. | ||
| ||
A summary of the multibase encoding in this context: | ||
| ||
- Start with the full public key bytes. Do not use the "compressed" or "compact" representation (unlike for `did:key` or `Multikey` encoding) | ||
- Do *not* prefix with a multicodec value indicating the key type | ||
- Encode the key bytes with `base58btc`, yielding a string | ||
- Add the character `z` as a prefix, to indicate the multibase, and include no other multicodec indicators | ||
| ||
The decoding process is the same in reverse, using the curve type as context. | ||
| ||
Here is an example of a single public key encoded in the legacy and current formats: | ||
| ||
``` | ||
// legacy multibase encoding of K-256 public key | ||
{ | ||
"id": ..., | ||
"controller": ..., | ||
"type": "EcdsaSecp256k1VerificationKey2019", | ||
"publicKeyMultibase": "zQYEBzXeuTM9UR3rfvNag6L3RNAs5pQZyYPsomTsgQhsxLdEgCrPTLgFna8yqCnxPpNT7DBk6Ym3dgPKNu86vt9GR" | ||
} | ||
| ||
// preferred multibase encoding of same K-256 public key | ||
{ | ||
"id": ..., | ||
"controller": ..., | ||
"type": "Multikey", | ||
"publicKeyMultibase": "zQ3shXjHeiBuRCKmM36cuYnm7YEMzhGnCmCyW92sRJ9pribSF" | ||
} | ||
``` | ||
| ||
| ||
## Usage and Implementation Guidelines | ||
| ||
Protocol implementations should be flexible to processing content containing DIDs based on unsupported DID methods. This is important to allow gradual evolution of the protocol ecosystem over time. In other words, implementations should distinguish between at least the distinct cases "invalid DID syntax", "unsupported DID method" and "supported DID method, but specific DID resolution failed". | ||
| ||
While longer DIDs are supported in the protocol, a good best practice is to use relatively short DIDs, and to avoid DIDs longer than 64 characters. | ||
| ||
DIDs are case-sensitive. While the currently-supported methods are *not* case sensitive, and could be safely lowercased, protocol implementations should reject DIDs with invalid casing. It is permissible to attempt case normalization when receiving user-controlled input, such as when parsing public URL path components, or text input fields. | ||
| ||
Interop test vectors are available from the [atproto-interop-tests](https://github.com/bluesky-social/atproto-interop-tests) repository. | ||
| ||
## Possible Future Changes | ||
| ||
The hard maximum DID length limit may be reduced, at the protocol syntax level. We are not aware of any DID methods that we would consider supporting which have identifiers longer than, say, 256 characters. | ||
| ||
There is a chance that the set of "blessed" DID methods will slowly expand over time. | ||
spec/atproto/handle.mdnew+188−0
| @@ -0,0 +1,188 @@ | ||
export const header = { | ||
title: 'Handle', | ||
description: | ||
'A specification for human-friendly account identifiers.', | ||
} | ||
| ||
# Handles | ||
| ||
DIDs are the long-term persistent identifiers for accounts in atproto, but they can be opaque and unfriendly for human use. **Handles** are mutable and human-friendly account usernames, in the form of a DNS hostname. For example, `user.example.com`. Handles must be bi-directionally linked to a DID: the DID document must claim the handle, and the handle must resolve to the DID identifier. Two methods of resolving handles to DID are supported: one using TXT DNS records, and the other using an HTTPS `/.well-known/` URL path. {{ className: 'lead' }} | ||
| ||
The definition of "hostnames" (as a subset of all possible "DNS names") has evolved over time and across several IETF RFCs. Some relevant documents are [RFC-1035](https://www.rfc-editor.org/rfc/rfc1035), [RFC-3696](https://www.rfc-editor.org/rfc/rfc3696) section 2, and [RFC-3986](https://www.rfc-editor.org/rfc/rfc3986) section 3. Almost every valid "hostname" is also a valid handle, though there are a small number of exceptions (described below). {{ className: 'lead' }} | ||
| ||
## Handle Identifier Syntax | ||
| ||
Lexicon string format type: `handle` | ||
| ||
To synthesize other standards, and define "handle" syntax specifically: | ||
| ||
- The overall handle must contain only ASCII characters, and can be at most 253 characters long (in practice, handles may be restricted to a slightly shorter length) | ||
- The overall handle is split in to multiple segments (referred to as "labels" in standards documents), separated by ASCII periods (`.`) | ||
- No proceeding or trailing ASCII periods are allowed, and there must be at least two segments. That is, "bare" top-level domains are not allowed as handles, even if valid "hostnames" and "DNS names." "Trailing dot" syntax for DNS names is not allowed for handles. | ||
- Each segment must have at least 1 and at most 63 characters (not including the periods). The allowed characters are ASCII letters (`a-z`), digits (`0-9`), and hyphens (`-`). | ||
- Segments can not start or end with a hyphen | ||
- The last segment (the "top level domain") can not start with a numeric digit | ||
- Handles are not case-sensitive, and should be normalized to lowercase (that is, normalize ASCII `A-Z` to `a-z`) | ||
| ||
To be explicit (the above rules already specify this), no whitespace, null bytes, joining characters, or other ASCII control characters are allowed in the handle, including as prefix/suffix. | ||
| ||
Modern "hostnames" (and thus handles) allow ASCII digits in most positions, with the exception that the last segment (top-level domain, TLD) cannot start with a digit. | ||
| ||
IP addresses are not valid syntax: IPv4 addresses have a final segment starting with a digit, and IPv6 addresses are separated by colons (`:`). | ||
| ||
A reference regular expression (regex) for the handle syntax is: | ||
| ||
``` | ||
/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/ | ||
``` | ||
| ||
## Additional Non-Syntax Restrictions | ||
| ||
"Reserved" top-level domains should not fail syntax validation (eg, in atproto Lexicon validation), but they must immediately fail any attempt at registration, resolution, etc. See also: [https://en.wikipedia.org/wiki/Top-level_domain#Reserved_domains](https://en.wikipedia.org/wiki/Top-level_domain#Reserved_domains) | ||
| ||
`.local` hostnames (for mDNS on local networks) should not be used in atproto. | ||
| ||
The `.onion` TLD is a special case for Tor protocol hidden services. Resolution of handles via Tor would require ecosystem-wide support, so they are currently disallowed. | ||
| ||
To summarize the above, the initial list of disallowed TLDs includes: | ||
| ||
- `.alt` | ||
- `.arpa` | ||
- `.example` | ||
- `.internal` | ||
- `.invalid` | ||
- `.local` | ||
- `.localhost` | ||
- `.onion` | ||
| ||
The `.test` TLD is intended for examples, testing, and development. It may be used in atproto development, but should fail in real-world environments. | ||
| ||
The `.invalid` TLD should only be used for the special `handle.invalid` value (see below). This value is syntactically valid in the Lexicon schema language, but should not be accepted as a valid handle in most contexts. | ||
| ||
## Identifier Examples | ||
| ||
Syntactically valid handles (which may or may not have existing TLDs): | ||
| ||
``` | ||
jay.bsky.social | ||
8.cn | ||
name.t--t // not a real TLD, but syntax ok | ||
XX.LCS.MIT.EDU | ||
a.co | ||
xn--notarealidn.com | ||
xn--fiqa61au8b7zsevnm8ak20mc4a87e.xn--fiqs8s | ||
xn--ls8h.test | ||
example.t // not a real TLD, but syntax ok | ||
``` | ||
| ||
Invalid syntax: | ||
| ||
``` | ||
jo@hn.test | ||
💩.test | ||
john..test | ||
xn--bcher-.tld | ||
john.0 | ||
cn.8 | ||
www.masełkowski.pl.com | ||
org | ||
name.org. | ||
``` | ||
| ||
Valid syntax, but must always fail resolution due to other restrictions: | ||
| ||
``` | ||
2gzyxa5ihm7nsggfxnu52rck2vv4rvmdlkiu3zzui5du4xyclen53wid.onion | ||
laptop.local | ||
blah.arpa | ||
``` | ||
| ||
## Handle Resolution | ||
| ||
Handles have a limited role in atproto, and need to be resolved to a DID in almost all situations. Resolution mechanisms must demonstrate a reasonable degree of authority over the domain name at a point in time, and need to be relatively efficient to look up. There are currently two supported resolution mechanisms: one using a TXT DNS record containing the DID, and another over HTTPS at a special `/.well-known/` URL. | ||
| ||
Clients can rely on network services (eg, their PDS) to resolve handles for them, using the `com.atproto.identity.resolveHandle` endpoint, and don't usually need to implement resolution directly themselves. | ||
| ||
The DNS TXT method is the recommended and preferred resolution method for individual handle configuration, but services should fully support both methods. The intended use-case for the HTTPS method is existing large-scale web services which may not have the infrastructure to automate the registration of thousands or millions of DNS TXT records. | ||
| ||
Handles should not be trusted or considered valid until the DID is also resolved and the current DID document is confirmed to link back to the handle. The link between handle and DID must be confirmed bidirectionally, otherwise anybody could create handle aliases for third-party accounts. | ||
| ||
### DNS TXT Method | ||
| ||
For this resolution method, a DNS TXT record is registered for the `_atproto` sub-domain under the handle hostname. The record value should have the prefix `did=`, followed by the full DID. This method aligns with [RFC-1464](https://www.rfc-editor.org/rfc/rfc1464.html), "Using the Domain Name System To Store Arbitrary String Attributes". | ||
| ||
For example, the handle `user.example.com` would have a TXT record on the name `_atproto.user.example.com`, and the value would look like `did=did:plc:ewvi7nxzyoun6zhxrhs64oiz`. | ||
| ||
Any TXT records with values not starting with `did=` should be ignored. Only a single valid record should exist at any point in time. If multiple valid records with different DIDs are present, resolution should fail. In this case resolution can be re-tried after a delay, or using a recursive resolver. | ||
| ||
Note that very long handles can not be resolved using this method if the additional `_atproto.` name segment pushes the overall name over the 253 character maximum for DNS queries. The HTTPS method will work for such handles. | ||
| ||
DNSSEC is not required. | ||
| ||
### HTTPS well-known Method | ||
| ||
For this resolution method, a web server at the handle domain implements a special well-known endpoint at the path `/.well-known/atproto-did`. A valid HTTP response will have an HTTP success status (2xx), `Content-Type` header set to `text/plain`, and include the DID as the HTTP body with no prefix or wrapper formatting. | ||
| ||
For example, the handle `user.example.app` would be resolved by an GET request to `https://user.example.app/.well-known/atproto-did`, and a valid response would look like: | ||
| ||
``` | ||
HTTP/1.1 200 OK | ||
Content-Length: 33 | ||
Content-Type: text/plain | ||
Date: Wed, 14 Jun 2023 00:47:21 GMT | ||
| ||
did:plc:ewvi7nxzyoun6zhxrhs64oiz | ||
``` | ||
| ||
The response `Content-Type` header does not need to be strictly verified. | ||
| ||
The web server's response body should not contain any prefix or suffix whitespace, but clients should strip small amounts of prefix or suffix whitespace from the response body before attempting to parse as a DID. | ||
| ||
Secure HTTPS on the default port (443) is required for all real-world handle resolutions. Unsecured HTTP can only be used for local development and testing. | ||
| ||
HTTP redirects (eg, 301, 302) are allowed, up to a reasonable number of redirect hops. | ||
| ||
### Invalid Handles | ||
| ||
If the handle for a known DID is confirmed to no longer resolve, it should be marked as invalid. In API responses, the special handle value `handle.invalid` can be used to indicate that there is no bi-directionally valid handle for the given DID. This handle can not be used in most situations (search queries, API requests, etc). | ||
| ||
### Resolution Best Practices | ||
| ||
It is ok to attempt both resolution methods in parallel, and to use the first successful result available. If the two methods return conflicting results (aka, different DIDs), the DNS TXT result should be preferred, though it is also acceptable to record the result as ambiguous and try again later. | ||
| ||
It is considered a best practice for services to cache handle resolution results internally, up to some lifetime, and re-resolve periodically. DNS TTL values provide a possible cache lifetime, but are probably too aggressive (aka, too short a lifetime) for the handle resolution use case. | ||
| ||
Use of a recursive DNS resolver can help with propagation delays, which are important for the use case of an account changing their handle and waiting for confirmation. | ||
| ||
With both techniques, it is beneficial to initiate resolution requests from a relatively trusted network environment and configuration. Running resolution requests from multiple regions and environments can help mitigate (though not fully resolve) concerns about traffic manipulation or intentionally segmented responses. | ||
| ||
| ||
## Usage and Implementation Guidelines | ||
| ||
Handles may be prefixed with the "at" symbol (like `@user.example.com`) in user interfaces, but this is not a valid syntax for a handle in records, APIs, and other back-end contexts. | ||
| ||
Internationalized Domain Names ("IDN", or "punycode") are not directly relevant to the low-level handle syntax. In their encoded form, IDNs are already valid hostnames, and thus valid handles. Such handles must be stored and transmitted in encoded ASCII form. Handles that "look like" IDNs, but do not parse as valid IDNs, are valid handles, just as they are valid hostnames. Applications may, optionally, parse and display IDN handles as Unicode. | ||
| ||
Handles are not case-sensitive, which means they can be safely normalized from user input to lower-case (ASCII) form. Only normalized (lowercase) handles should be stored in records or used in outbound API calls. Applications should not preserve user-provided case information and attempt to display handles in anything other than lower-case. For example, the handle input string `BlueskyWeb.xyz` should be normalized, stored, and displayed as `blueskyweb.xyz`. Long all-lowercase handles can be a readability and accessibility challenge. Sub-domain separation (periods), hyphenation, or use of "display names" in application protocols can all help. | ||
| ||
Very long handles are known to present user interface challenges, but they are allowed in the protocol, and application developers are expected to support them. | ||
| ||
Handles which look similar to a well-known domain present security and impersonation challenges. For example, handles like `paypa1.com` or `paypal.cc` being confused for `paypal.com`. Very long handles can result in similar issues when truncated at the start or end (`paypal.com…`). | ||
| ||
Handles should generally not be truncated to local context. For example, the handle `@alice.example.com` should not be displayed as `@alice`, even in the local context of an `example.com` service. | ||
| ||
Providers of handle "namespaces" (eg, as subdomains on a registered domain) may impose any additional limits on handles that they wish. It is recommended to constrain the allowed segment length to something reasonable, and to reserve a common set of segment strings like `www`, `admin`, `mail`, etc. There are multiple public lists of "commonly disallowed usernames" that can be used as a starting point. | ||
| ||
From a practical standpoint, handles should be limited to at most 244 characters, fewer than the 253 allowed for DNS names. This is because DNS verification works with the prefix `_atproto.`, which adds 9 characters, and that overall name needs to be valid. | ||
| ||
Handle hostnames are expected to be mainstream DNS domain names, registered through the mainstream DNS name system. Handles with non-standard TLDs, or using non-standard naming systems, will fail to interoperate with other network services and protocol implementations in the atproto ecosystem. | ||
| ||
PDS implementations hosting an account *may* prevent repo mutation if the account's handle can no longer be verified (aka, `handle.invalid` situation). Other network services should generally continue to display the content (to prevent breakage), possibly with a contextual note or warning indicator. | ||
| ||
Interop test vectors are available from the [atproto-interop-tests](https://github.com/bluesky-social/atproto-interop-tests) repository. | ||
| ||
## Possible Future Changes | ||
| ||
The handle syntax is relatively stable. | ||
| ||
It is conceivable that `.onion` handles would be allowed at some point in the future. | ||
spec/COMMANDS.md+4−2
| @@ -56,8 +56,10 @@ which on this server, holding one account, is the account's. | ||
`integer` and `boolean` as themselves, with `minimum`, `maximum`, | ||
`maxLength` and `enum` where the lexicon has them; `array` as `array`; | ||
`unknown`, `object`, `ref` and `union` as any JSON value of their kind | ||
(`object`, or no constraint for `unknown`); and its `required` the | ||
lexicon's, less `repo` and `did`. A tool's `description` is the lexicon's. | ||
(`object`, or no constraint for `unknown`); an argument the lexicon lists | ||
as `nullable` has the type and `"null"`, as `["string", "null"]`; and its | ||
`required` the lexicon's, less `repo` and `did`. A tool's `description` is | ||
the lexicon's. | ||
Queries have `readOnlyHint: true`. Procedures have `readOnlyHint: false`, | ||
and `destructiveHint` `true` if they may delete or replace a record | ||
(`deleteRecord`, `putRecord`, `applyWrites`) and `false` otherwise. | ||
spec/SLICE.md+37−10
| @@ -28,7 +28,8 @@ tool and a CLI command, as `COMMANDS.md` says: | ||
`getRecord`, `listRecords`, `describeRepo` | ||
- `com.atproto.sync.getRepo`, `getLatestCommit`, `subscribeRepos` | ||
| ||
`repo` parameters name the account by its handle or DID. A session's | ||
`repo` parameters name the account by its handle or DID; DIDs and handles | ||
are as `atproto/did.md` and `atproto/handle.md` define them. A session's | ||
`accessJwt` is a bearer token for the account; how it is made is the | ||
server's choice. A bearer token the server did not give out, sent to a | ||
repository write or to `getSession`, is `400 InvalidToken`, as the | ||
| @@ -61,10 +62,33 @@ everything else. | ||
commit, and checks no `swapRecord`. Its answer otherwise is `{commit}` | ||
alone. | ||
- `putRecord` of exactly the record already stored changes nothing: it makes | ||
no commit, answers without `commit`, and checks no `swapRecord`. An | ||
`applyWrites` update to exactly the record stored does make a commit. | ||
- `getSession` with no token is `401 AuthMissing`, where a write with no | ||
token is `401 AuthenticationRequired`. | ||
no commit, answers `{uri, cid, validationStatus}` without `commit`, and | ||
checks no `swapRecord`. An `applyWrites` update to exactly the record | ||
stored does make a commit. | ||
- A write checks, in this order, its token, its input, its `repo`, and its | ||
record's `$type`. With no token it is `401 AuthMissing`, and with a token | ||
the server did not give out `400 InvalidToken`, however wrong its input. | ||
Input that is wrong, including a record outside the data model, is `400 | ||
InvalidRequest`, whatever its `repo`. Then a `repo` that is not the | ||
account is `403 AccountNotFound`, and only then a `$type` other than the | ||
collection `400 InvalidRequest`. `getSession` with no token is `401 | ||
AuthMissing` too. | ||
- `describeRepo`, `getRepo` and `getLatestCommit` of a repository the server | ||
does not hold are `400 RepoNotFound`. | ||
- A method called with the other HTTP method, a query by `POST` or a | ||
procedure by `GET`, is `400 InvalidRequest`. | ||
- `validate: true` on a write is `400 InvalidRequest`, as the server knows no | ||
lexicon for any record type. With `validate: false` the write is made, and | ||
its answer, or each `applyWrites` result, has no `validationStatus`. | ||
- `getRepo` with `since`, a rev, answers a CAR file whose root is the latest | ||
commit and whose blocks are those the repository holds now that commits | ||
after that rev added: the latest commit, and the records and MST nodes of | ||
the current tree written since. A record written after `since` and then | ||
replaced or deleted is not among them. There are no blocks at all when | ||
`since` is the latest rev. A `since` that is not a TID is `400 | ||
InvalidRequest`. | ||
- `subscribeRepos` with a `cursor` that is not an integer sends an error | ||
frame, `InvalidRequest`, and closes. | ||
| ||
One thing the reference does is a fault, and the server does not copy it. In | ||
one `applyWrites`, if a write gives a record exactly the content that another | ||
| @@ -107,11 +131,14 @@ body. | ||
| ||
- Every commit is a `#commit` event, in the order the commits were made, with | ||
`seq` increasing. Its `blocks` are a CAR file whose root is the signed | ||
commit, holding the record blocks it wrote and the MST nodes it changed, | ||
enough for a consumer to check every op against the commit and to undo the | ||
ops on the tree in the event: undone in reverse, they give the tree | ||
`prevData` names. Ops name `prev`, the CID a record had, for updates and | ||
deletes. `since` is the previous commit's `rev`, and `prevData` its `data`. | ||
commit, holding the record blocks it wrote and MST nodes enough for two | ||
things, which are what is checked: every op proved against the commit | ||
(each created or updated key present with its CID, each deleted key | ||
absent), and the ops undone on the tree in the event, in reverse, giving | ||
the tree `prevData` names (`atproto/sync.md`, the inversion it | ||
describes). Which other blocks it holds is the server's choice. Ops name | ||
`prev`, the CID a record had, for updates and deletes. `since` is the | ||
previous commit's `rev`, and `prevData` its `data`. | ||
`rebase` and `tooBig` are false. | ||
- A new account's stream starts as the reference's does: `#identity`, | ||
`#account`, a `#commit` of the empty repository with no ops, `since` or | ||
AGENTS.md+6−0
| @@ -30,6 +30,12 @@ PDS, so a change goes in this order: | ||
- add no atproto or MCP crates; | ||
- where the spec or the harness seems wrong, stop and say why, rather | ||
than work around it. | ||
| ||
The whole of `crates/` can be built again from nothing this way, to see | ||
whether the spec is enough: an agent given an empty `crates/` and no | ||
history. There, where the spec is silent and the harness settles it, it | ||
follows the harness and lists each such gap, which then becomes a spec | ||
change and a harness check. | ||
4. **Proof that the check bites.** Plant the bug the new check is for in | ||
the server, see the harness fail, and put the server back. | ||
5. **The gates.** `just gates`, once, at the end; the `gates` workflow runs | ||
README.md+1−1
| @@ -16,7 +16,7 @@ and the server's whole repository verified with the reference's own library. | ||
| `spec/` | the specification: `SLICE.md` for the server, `COMMANDS.md` for its MCP tools and CLI commands, with atproto's specs, the lexicons the server serves, atproto's test vectors, and MCP's specification | | ||
| `harness/` | runs the server beside the reference PDS and compares them | | ||
| `crates/pds-repo` | the data model (DAG-CBOR, CIDs), the MST, signed commits and CAR files, with no I/O; checked by atproto's test vectors | | ||
| `crates/pds-store` | the append-only log the server keeps its state in; checked by the server's tests, which cut it at every byte | | ||
| `crates/pds-store` | the append-only log the server keeps its state in; checked by its own tests and the server's, which cut the log at every byte of its last write | | ||
| `crates/pds-lexicon` | the lexicons in `spec/lexicons`, as data: each method's arguments, and the MCP tool and CLI command made from it | | ||
| `crates/pds-server` | the PDS: XRPC, the firehose and the MCP endpoint, over `pds-repo`, `pds-store` and `pds-lexicon` | | ||
| `crates/pds-cli` | the CLI: each method as a command, a client of a running server | | ||