chadtmiller.com/group-host
atmosphere group host
0
0
The atproto crate comes from its own repository's Cargo registry
.cargo/config.tomlnew+4−0
| @@ -0,0 +1,4 @@ | ||
# The registry the atproto crate is published to, from its own repository | ||
# (knotless.dev/chadtmiller.com/atproto). Reading it needs no login. | ||
[registries.atproto] | ||
index = "sparse+https://knotless.dev/cargo/did:plc:bcgltzqazw5tb6k2g3ttenbj/3mzr5vldibtui/" | ||
crates/atproto/src/base32.rsdeleted+0−43
| @@ -1,43 +0,0 @@ | ||
//! Base32 without padding, in the two alphabets atproto uses: RFC 4648's, | ||
//! lower case, for CIDs (multibase `b`), and the sortable one TIDs are | ||
//! written in. | ||
| ||
/// RFC 4648's alphabet, lower case: a CID's multibase `b`. | ||
pub const LOWER: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567"; | ||
| ||
/// The sortable alphabet a TID is written in, so that text order is time order. | ||
pub const SORTABLE: &[u8; 32] = b"234567abcdefghijklmnopqrstuvwxyz"; | ||
| ||
pub fn encode(alphabet: &[u8; 32], bytes: &[u8]) -> String { | ||
let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8); | ||
let (mut buffer, mut bits) = (0u32, 0); | ||
for &b in bytes { | ||
buffer = (buffer << 8) | u32::from(b); | ||
bits += 8; | ||
while bits >= 5 { | ||
bits -= 5; | ||
out.push(alphabet[((buffer >> bits) & 31) as usize] as char); | ||
} | ||
} | ||
if bits > 0 { | ||
out.push(alphabet[((buffer << (5 - bits)) & 31) as usize] as char); | ||
} | ||
out | ||
} | ||
| ||
/// The bytes `text` holds, or `None` for a character outside `alphabet` | ||
/// or bits left over that are not zero. | ||
pub fn decode(alphabet: &[u8; 32], text: &str) -> Option<Vec<u8>> { | ||
let mut out = Vec::with_capacity(text.len() * 5 / 8); | ||
let (mut buffer, mut bits) = (0u32, 0); | ||
for c in text.bytes() { | ||
let value = alphabet.iter().position(|&a| a == c)? as u32; | ||
buffer = (buffer << 5) | value; | ||
bits += 5; | ||
if bits >= 8 { | ||
bits -= 8; | ||
out.push((buffer >> bits) as u8); | ||
} | ||
} | ||
(buffer & ((1 << bits) - 1) == 0).then_some(out) | ||
} | ||
crates/atproto/src/car.rsdeleted+0−138
| @@ -1,138 +0,0 @@ | ||
//! CAR files (CARv1): a header naming the roots, then blocks, each its | ||
//! CID and bytes. How a repo is exported, imported, and sent down the | ||
//! firehose a commit at a time. | ||
| ||
use crate::cid::{Cid, DAG_CBOR}; | ||
use crate::drisl::{self, Value}; | ||
use std::collections::BTreeMap; | ||
use std::fmt; | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct CarError(pub String); | ||
| ||
impl fmt::Display for CarError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(&self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for CarError {} | ||
| ||
fn err<T>(what: impl Into<String>) -> Result<T, CarError> { | ||
Err(CarError(what.into())) | ||
} | ||
| ||
/// A CAR file read: its roots, and its blocks by CID. | ||
#[derive(Debug, Clone, PartialEq, Default)] | ||
pub struct Car { | ||
pub roots: Vec<Cid>, | ||
pub blocks: BTreeMap<Cid, Vec<u8>>, | ||
} | ||
| ||
fn varint(mut n: u64, out: &mut Vec<u8>) { | ||
while n >= 0x80 { | ||
out.push((n as u8) | 0x80); | ||
n >>= 7; | ||
} | ||
out.push(n as u8); | ||
} | ||
| ||
/// A CAR file of `roots` and `blocks`, the blocks in the order given. | ||
pub fn write<'a>(roots: &[Cid], blocks: impl IntoIterator<Item = (&'a Cid, &'a [u8])>) -> Vec<u8> { | ||
let header = drisl::encode(&Value::Map(BTreeMap::from([ | ||
( | ||
"roots".into(), | ||
Value::Array(roots.iter().map(|c| Value::Link(*c)).collect()), | ||
), | ||
("version".into(), Value::Integer(1)), | ||
]))); | ||
let mut out = Vec::new(); | ||
varint(header.len() as u64, &mut out); | ||
out.extend(header); | ||
for (cid, bytes) in blocks { | ||
let cid = cid.to_bytes(); | ||
varint((cid.len() + bytes.len()) as u64, &mut out); | ||
out.extend(cid); | ||
out.extend(bytes); | ||
} | ||
out | ||
} | ||
| ||
struct Reader<'a> { | ||
bytes: &'a [u8], | ||
at: usize, | ||
} | ||
| ||
impl Reader<'_> { | ||
fn varint(&mut self) -> Result<usize, CarError> { | ||
let mut n: u64 = 0; | ||
for shift in (0..64).step_by(7) { | ||
let Some(&b) = self.bytes.get(self.at) else { | ||
return err("the file ends in the middle of a length"); | ||
}; | ||
self.at += 1; | ||
n |= u64::from(b & 0x7f) << shift; | ||
if b & 0x80 == 0 { | ||
// Past what this machine can hold, `take` refuses it. | ||
return Ok(usize::try_from(n).unwrap_or(usize::MAX)); | ||
} | ||
} | ||
err("a length too long") | ||
} | ||
| ||
fn take(&mut self, n: usize) -> Result<&[u8], CarError> { | ||
if n > self.bytes.len() - self.at { | ||
return err("the file ends in the middle of a block"); | ||
} | ||
let start = self.at; | ||
self.at += n; | ||
Ok(&self.bytes[start..self.at]) | ||
} | ||
} | ||
| ||
/// The CAR file `bytes` hold. Each block's CID is checked against its | ||
/// bytes; a block whose CID is not one atproto blesses is refused. | ||
pub fn read(bytes: &[u8]) -> Result<Car, CarError> { | ||
let mut r = Reader { bytes, at: 0 }; | ||
let len = r.varint()?; | ||
let header = drisl::decode(r.take(len)?).or_else(|e| err(format!("the header: {e}")))?; | ||
let Value::Map(header) = header else { | ||
return err("the header is not a map"); | ||
}; | ||
let (Some(Value::Integer(1)), Some(Value::Array(roots))) = | ||
(header.get("version"), header.get("roots")) | ||
else { | ||
return err("the header is not version 1 with roots"); | ||
}; | ||
let roots = roots | ||
.iter() | ||
.map(|r| match r { | ||
Value::Link(c) => Ok(*c), | ||
_ => err("a root is not a link"), | ||
}) | ||
.collect::<Result<_, _>>()?; | ||
let mut car = Car { | ||
roots, | ||
blocks: BTreeMap::new(), | ||
}; | ||
while r.at < bytes.len() { | ||
let len = r.varint()?; | ||
let block = r.take(len)?; | ||
// A blessed CID is 36 bytes: version, codec, hash and its length. | ||
let Some((cid, data)) = block.split_at_checked(36) else { | ||
return err("a block too short for its CID"); | ||
}; | ||
let cid = Cid::from_bytes(cid).or_else(|e| err(format!("a block's CID: {e}")))?; | ||
// Cid::from_bytes allows only these two codecs. | ||
let hashed = if cid.codec() == DAG_CBOR { | ||
Cid::of_cbor(data) | ||
} else { | ||
Cid::of_raw(data) | ||
}; | ||
if hashed != cid { | ||
return err(format!("block {cid} does not hash to its CID")); | ||
} | ||
car.blocks.insert(cid, data.to_vec()); | ||
} | ||
Ok(car) | ||
} | ||
crates/atproto/src/cid.rsdeleted+0−102
| @@ -1,102 +0,0 @@ | ||
//! CIDs, as atproto blesses them: version 1, SHA-256, and either DAG-CBOR | ||
//! (a record, a commit, a tree node) or raw (a blob). | ||
| ||
use crate::base32; | ||
use sha2::{Digest, Sha256}; | ||
use std::fmt; | ||
| ||
/// The codec of a record, a commit or an MST node. | ||
pub const DAG_CBOR: u8 = 0x71; | ||
/// The codec of a blob. | ||
pub const RAW: u8 = 0x55; | ||
const SHA256: u8 = 0x12; | ||
| ||
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] | ||
pub struct Cid { | ||
codec: u8, | ||
digest: [u8; 32], | ||
} | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub enum CidError { | ||
/// Not multibase `b`, or not base32 within it. | ||
Encoding, | ||
/// Not version 1, SHA-256, DAG-CBOR or raw. | ||
Unblessed, | ||
} | ||
| ||
impl fmt::Display for CidError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(match self { | ||
CidError::Encoding => "a CID is base32, starting with b", | ||
CidError::Unblessed => "a CID is version 1 and SHA-256, of DAG-CBOR or raw", | ||
}) | ||
} | ||
} | ||
| ||
impl std::error::Error for CidError {} | ||
| ||
impl Cid { | ||
/// The CID of DRISL bytes: a record's, a commit's, a tree node's. | ||
pub fn of_cbor(bytes: &[u8]) -> Cid { | ||
Cid::of(DAG_CBOR, bytes) | ||
} | ||
| ||
/// The CID of a blob's bytes. | ||
pub fn of_raw(bytes: &[u8]) -> Cid { | ||
Cid::of(RAW, bytes) | ||
} | ||
| ||
fn of(codec: u8, bytes: &[u8]) -> Cid { | ||
Cid { | ||
codec, | ||
digest: Sha256::digest(bytes).into(), | ||
} | ||
} | ||
| ||
pub fn codec(&self) -> u8 { | ||
self.codec | ||
} | ||
| ||
pub fn digest(&self) -> &[u8; 32] { | ||
&self.digest | ||
} | ||
| ||
/// The CID as binary, as a CAR file and a DAG-CBOR link hold it. | ||
pub fn to_bytes(&self) -> Vec<u8> { | ||
[&[1, self.codec, SHA256, 32][..], &self.digest].concat() | ||
} | ||
| ||
pub fn from_bytes(bytes: &[u8]) -> Result<Cid, CidError> { | ||
match bytes { | ||
[1, codec @ (DAG_CBOR | RAW), SHA256, 32, digest @ ..] if digest.len() == 32 => { | ||
Ok(Cid { | ||
codec: *codec, | ||
digest: digest.try_into().expect("32 bytes"), | ||
}) | ||
} | ||
_ => Err(CidError::Unblessed), | ||
} | ||
} | ||
| ||
/// A CID as text: multibase `b`, base32 lower case. | ||
pub fn parse(text: &str) -> Result<Cid, CidError> { | ||
let bytes = text | ||
.strip_prefix('b') | ||
.and_then(|b32| base32::decode(base32::LOWER, b32)) | ||
.ok_or(CidError::Encoding)?; | ||
Cid::from_bytes(&bytes) | ||
} | ||
} | ||
| ||
impl fmt::Display for Cid { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "b{}", base32::encode(base32::LOWER, &self.to_bytes())) | ||
} | ||
} | ||
| ||
impl fmt::Debug for Cid { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "Cid({self})") | ||
} | ||
} | ||
crates/atproto/src/commit.rsdeleted+0−120
| @@ -1,120 +0,0 @@ | ||
//! A repo's signed commit (version 3): the account, the root of its | ||
//! records' tree, a revision, and the account's signature over the rest. | ||
| ||
use crate::cid::Cid; | ||
use crate::drisl::{self, Value}; | ||
use crate::keys::{Keypair, PublicKey}; | ||
use std::collections::BTreeMap; | ||
use std::fmt; | ||
| ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Commit { | ||
pub did: String, | ||
/// The root of the records' tree. | ||
pub data: Cid, | ||
/// A TID, later than every commit's before it. | ||
pub rev: String, | ||
/// Kept for version 2's sake, and almost always none. | ||
pub prev: Option<Cid>, | ||
pub sig: Vec<u8>, | ||
} | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct CommitError(pub &'static str); | ||
| ||
impl fmt::Display for CommitError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for CommitError {} | ||
| ||
impl Commit { | ||
/// The commit of `did`'s tree `data` at `rev`, signed with `key`. | ||
pub fn sign(did: &str, data: Cid, rev: &str, key: &Keypair) -> Commit { | ||
let mut commit = Commit { | ||
did: did.to_string(), | ||
data, | ||
rev: rev.to_string(), | ||
prev: None, | ||
sig: Vec::new(), | ||
}; | ||
commit.sig = key.sign(&drisl::encode(&commit.unsigned())).to_vec(); | ||
commit | ||
} | ||
| ||
fn unsigned(&self) -> Value { | ||
Value::Map(self.fields()) | ||
} | ||
| ||
fn fields(&self) -> BTreeMap<String, Value> { | ||
BTreeMap::from([ | ||
("did".into(), Value::String(self.did.clone())), | ||
("version".into(), Value::Integer(3)), | ||
("data".into(), Value::Link(self.data)), | ||
("rev".into(), Value::String(self.rev.clone())), | ||
("prev".into(), self.prev.map_or(Value::Null, Value::Link)), | ||
]) | ||
} | ||
| ||
/// The signed commit, as its block holds it. | ||
pub fn to_bytes(&self) -> Vec<u8> { | ||
let mut map = self.fields(); | ||
map.insert("sig".into(), Value::Bytes(self.sig.clone())); | ||
drisl::encode(&Value::Map(map)) | ||
} | ||
| ||
pub fn cid(&self) -> Cid { | ||
Cid::of_cbor(&self.to_bytes()) | ||
} | ||
| ||
/// The commit a block holds: version 3, with every field it needs. | ||
pub fn from_bytes(bytes: &[u8]) -> Result<Commit, CommitError> { | ||
let bad = CommitError("not a version 3 commit"); | ||
let Ok(Value::Map(map)) = drisl::decode(bytes) else { | ||
return Err(bad); | ||
}; | ||
// Its fields and no others: one more would be dropped here, and the | ||
// commit written back would not come to its CID. | ||
if map.len() != 6 { | ||
return Err(bad); | ||
} | ||
let field = |k: &str| map.get(k); | ||
let ( | ||
Some(Value::String(did)), | ||
Some(Value::Integer(3)), | ||
Some(Value::Link(data)), | ||
Some(Value::String(rev)), | ||
Some(prev), | ||
Some(Value::Bytes(sig)), | ||
) = ( | ||
field("did"), | ||
field("version"), | ||
field("data"), | ||
field("rev"), | ||
field("prev"), | ||
field("sig"), | ||
) | ||
else { | ||
return Err(bad); | ||
}; | ||
let prev = match prev { | ||
Value::Null => None, | ||
Value::Link(c) => Some(*c), | ||
_ => return Err(bad), | ||
}; | ||
Ok(Commit { | ||
did: did.clone(), | ||
data: *data, | ||
rev: rev.clone(), | ||
prev, | ||
sig: sig.clone(), | ||
}) | ||
} | ||
| ||
/// Whether `key`, the account's signing key, signed this. | ||
pub fn verify(&self, key: &PublicKey) -> bool { | ||
key.verify(&drisl::encode(&self.unsigned()), &self.sig) | ||
} | ||
} | ||
crates/atproto/src/did.rsdeleted+0−92
| @@ -1,92 +0,0 @@ | ||
//! DID documents: the services and keys an account's document names, each | ||
//! found by the end of its id, as a document may write `#atproto` or | ||
//! `did:…#atproto`. | ||
| ||
use crate::keys::{KeyError, PublicKey}; | ||
use serde_json::{Value, json}; | ||
| ||
/// The endpoint of the service whose id ends in `id`, as `#atproto_pds`, | ||
/// with no trailing slash. | ||
pub fn service(doc: &Value, id: &str) -> Option<String> { | ||
doc.get("service")? | ||
.as_array()? | ||
.iter() | ||
.find(|s| { | ||
s.get("id") | ||
.and_then(Value::as_str) | ||
.is_some_and(|i| i.ends_with(id)) | ||
})? | ||
.get("serviceEndpoint")? | ||
.as_str() | ||
.map(|s| s.trim_end_matches('/').to_string()) | ||
} | ||
| ||
/// The account's PDS. | ||
pub fn pds(doc: &Value) -> Option<String> { | ||
service(doc, "#atproto_pds") | ||
} | ||
| ||
/// The key of the verification method whose id ends in `id`. | ||
pub fn method_key(doc: &Value, id: &str) -> Result<PublicKey, KeyError> { | ||
let method = doc | ||
.get("verificationMethod") | ||
.and_then(Value::as_array) | ||
.and_then(|methods| { | ||
methods.iter().find(|m| { | ||
m.get("id") | ||
.and_then(Value::as_str) | ||
.is_some_and(|i| i.ends_with(id)) | ||
}) | ||
}) | ||
.ok_or(KeyError("the document names no such key"))?; | ||
let kind = method | ||
.get("type") | ||
.and_then(Value::as_str) | ||
.unwrap_or_default(); | ||
let multibase = method.get("publicKeyMultibase").and_then(Value::as_str); | ||
PublicKey::from_method( | ||
kind, | ||
multibase.ok_or(KeyError("a key with no publicKeyMultibase"))?, | ||
) | ||
} | ||
| ||
/// The key the account's repo, and its service tokens, are signed with. | ||
pub fn signing_key(doc: &Value) -> Result<PublicKey, KeyError> { | ||
method_key(doc, "#atproto") | ||
} | ||
| ||
/// The key a space's syncing service agrees a secret with (the space | ||
/// alpha's `#atproto_kem`). | ||
pub fn kem_key(doc: &Value) -> Result<PublicKey, KeyError> { | ||
method_key(doc, "#atproto_kem") | ||
} | ||
| ||
/// The handle the document claims, its first `at://`. Whether the handle | ||
/// claims the DID back is for whoever resolves it. | ||
pub fn handle(doc: &Value) -> Option<String> { | ||
doc.get("alsoKnownAs")? | ||
.as_array()? | ||
.iter() | ||
.find_map(|a| a.as_str()?.strip_prefix("at://")) | ||
.map(String::from) | ||
} | ||
| ||
/// The document of a service's own `did:web`, `did`, at `endpoint`, with | ||
/// `key` its signing key, and its services, each an id (`#…`), a type and | ||
/// an endpoint. | ||
pub fn service_document(did: &str, key: &PublicKey, services: &[(&str, &str, &str)]) -> Value { | ||
json!({ | ||
"@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"], | ||
"id": did, | ||
"verificationMethod": [{ | ||
"id": format!("{did}#atproto"), | ||
"type": "Multikey", | ||
"controller": did, | ||
"publicKeyMultibase": key.to_multibase(), | ||
}], | ||
"service": services | ||
.iter() | ||
.map(|(id, kind, endpoint)| json!({"id": id, "type": kind, "serviceEndpoint": endpoint})) | ||
.collect::<Vec<_>>(), | ||
}) | ||
} | ||
crates/atproto/src/drisl.rsdeleted+0−377
| @@ -1,377 +0,0 @@ | ||
//! DRISL, atproto's deterministic CBOR (DAG-CBOR): the bytes a record, a | ||
//! commit and a tree node are hashed as. Written out in the one form it | ||
//! allows, and read back refusing any other, so that what reads is what | ||
//! was signed: the shortest lengths, map keys in order, no floats, no | ||
//! tags but links. | ||
//! | ||
//! Records arrive as JSON, in which a link is `{"$link": cid}` and bytes | ||
//! `{"$bytes": base64}`; [`Value::from_json`] and [`Value::to_json`] go | ||
//! between the two. | ||
| ||
use crate::cid::Cid; | ||
use base64::Engine; | ||
use base64::engine::general_purpose::STANDARD_NO_PAD; | ||
use std::collections::BTreeMap; | ||
use std::fmt; | ||
| ||
/// What a record can hold. | ||
#[derive(Clone, Debug, PartialEq)] | ||
pub enum Value { | ||
Null, | ||
Bool(bool), | ||
Integer(i64), | ||
String(String), | ||
Bytes(Vec<u8>), | ||
Link(Cid), | ||
Array(Vec<Value>), | ||
/// Keys in DRISL's order is the encoding's business; a map here is a map. | ||
Map(BTreeMap<String, Value>), | ||
} | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct DrislError(pub String); | ||
| ||
impl fmt::Display for DrislError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(&self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for DrislError {} | ||
| ||
fn err<T>(what: impl Into<String>) -> Result<T, DrislError> { | ||
Err(DrislError(what.into())) | ||
} | ||
| ||
/// How deep values may nest, so that bytes from anyone cannot run the | ||
/// reader out of stack. | ||
pub const MAX_DEPTH: usize = 128; | ||
| ||
/// `value` in DRISL. | ||
pub fn encode(value: &Value) -> Vec<u8> { | ||
let mut out = Vec::new(); | ||
write(value, &mut out); | ||
out | ||
} | ||
| ||
/// The CID of `value`, as DRISL. | ||
pub fn cid(value: &Value) -> Cid { | ||
Cid::of_cbor(&encode(value)) | ||
} | ||
| ||
fn head(major: u8, n: u64, out: &mut Vec<u8>) { | ||
let m = major << 5; | ||
match n { | ||
0..=23 => out.push(m | n as u8), | ||
24..=0xff => out.extend([m | 24, n as u8]), | ||
0x100..=0xffff => { | ||
out.push(m | 25); | ||
out.extend((n as u16).to_be_bytes()); | ||
} | ||
0x1_0000..=0xffff_ffff => { | ||
out.push(m | 26); | ||
out.extend((n as u32).to_be_bytes()); | ||
} | ||
_ => { | ||
out.push(m | 27); | ||
out.extend(n.to_be_bytes()); | ||
} | ||
} | ||
} | ||
| ||
/// DRISL's order of map keys: shorter first, then bytewise. | ||
fn key_order(a: &str, b: &str) -> std::cmp::Ordering { | ||
a.len().cmp(&b.len()).then_with(|| a.cmp(b)) | ||
} | ||
| ||
fn write(value: &Value, out: &mut Vec<u8>) { | ||
match value { | ||
Value::Null => out.push(0xf6), | ||
Value::Bool(b) => out.push(if *b { 0xf5 } else { 0xf4 }), | ||
Value::Integer(i) if *i >= 0 => head(0, *i as u64, out), | ||
Value::Integer(i) => head(1, (-1 - *i) as u64, out), | ||
Value::String(s) => { | ||
head(3, s.len() as u64, out); | ||
out.extend(s.as_bytes()); | ||
} | ||
Value::Bytes(b) => { | ||
head(2, b.len() as u64, out); | ||
out.extend(b); | ||
} | ||
Value::Link(cid) => { | ||
head(6, 42, out); | ||
let bytes = cid.to_bytes(); | ||
head(2, bytes.len() as u64 + 1, out); | ||
out.push(0); | ||
out.extend(bytes); | ||
} | ||
Value::Array(items) => { | ||
head(4, items.len() as u64, out); | ||
items.iter().for_each(|v| write(v, out)); | ||
} | ||
Value::Map(map) => { | ||
head(5, map.len() as u64, out); | ||
let mut keys: Vec<&String> = map.keys().collect(); | ||
keys.sort_by(|a, b| key_order(a, b)); | ||
for k in keys { | ||
head(3, k.len() as u64, out); | ||
out.extend(k.as_bytes()); | ||
write(&map[k], out); | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// The value `bytes` hold, all of them, refusing any form but DRISL's one. | ||
pub fn decode(bytes: &[u8]) -> Result<Value, DrislError> { | ||
let (value, read) = decode_first(bytes)?; | ||
if read != bytes.len() { | ||
return err("bytes after the value"); | ||
} | ||
Ok(value) | ||
} | ||
| ||
/// The first value in `bytes`, and how many bytes it took: a firehose | ||
/// frame is a header and a body, one after the other. | ||
pub fn decode_first(bytes: &[u8]) -> Result<(Value, usize), DrislError> { | ||
let mut reader = Reader { bytes, at: 0 }; | ||
let value = reader.value(0)?; | ||
Ok((value, reader.at)) | ||
} | ||
| ||
struct Reader<'a> { | ||
bytes: &'a [u8], | ||
at: usize, | ||
} | ||
| ||
impl Reader<'_> { | ||
fn take(&mut self, n: u64) -> Result<&[u8], DrislError> { | ||
let left = (self.bytes.len() - self.at) as u64; | ||
if n > left { | ||
return err("the bytes end in the middle of a value"); | ||
} | ||
let start = self.at; | ||
self.at += n as usize; | ||
Ok(&self.bytes[start..self.at]) | ||
} | ||
| ||
/// A head's major type and the number it carries, refusing a number | ||
/// written longer than it needs, and lengths left open. | ||
fn head(&mut self) -> Result<(u8, u8, u64), DrislError> { | ||
let first = self.take(1)?[0]; | ||
let (major, info) = (first >> 5, first & 31); | ||
let n = match info { | ||
0..=23 => u64::from(info), | ||
24 => u64::from(self.take(1)?[0]), | ||
25 => u64::from(u16::from_be_bytes(self.take(2)?.try_into().expect("2"))), | ||
26 => u64::from(u32::from_be_bytes(self.take(4)?.try_into().expect("4"))), | ||
27 => u64::from_be_bytes(self.take(8)?.try_into().expect("8")), | ||
_ => return err("an indefinite or reserved length"), | ||
}; | ||
let shortest = match info { | ||
24 => n >= 24, | ||
25 => n > 0xff, | ||
26 => n > 0xffff, | ||
27 => n > 0xffff_ffff, | ||
_ => true, | ||
}; | ||
if !shortest && major != 7 { | ||
return err("a number written longer than it needs"); | ||
} | ||
Ok((major, info, n)) | ||
} | ||
| ||
fn text(&mut self, n: u64) -> Result<String, DrislError> { | ||
let bytes = self.take(n)?.to_vec(); | ||
String::from_utf8(bytes).or_else(|_| err("text that is not UTF-8")) | ||
} | ||
| ||
fn value(&mut self, depth: usize) -> Result<Value, DrislError> { | ||
if depth > MAX_DEPTH { | ||
return err("values nested too deep"); | ||
} | ||
let (major, info, n) = self.head()?; | ||
Ok(match major { | ||
0 => Value::Integer(i64::try_from(n).or_else(|_| err("an integer past 64 bits"))?), | ||
1 => Value::Integer( | ||
i64::try_from(n) | ||
.map(|n| -1 - n) | ||
.or_else(|_| err("an integer past 64 bits"))?, | ||
), | ||
2 => Value::Bytes(self.take(n)?.to_vec()), | ||
3 => Value::String(self.text(n)?), | ||
4 => { | ||
let mut items = Vec::new(); | ||
for _ in 0..n { | ||
items.push(self.value(depth + 1)?); | ||
} | ||
Value::Array(items) | ||
} | ||
5 => { | ||
let mut map = BTreeMap::new(); | ||
let mut last: Option<String> = None; | ||
for _ in 0..n { | ||
let (major, _, len) = self.head()?; | ||
if major != 3 { | ||
return err("a map key that is not text"); | ||
} | ||
let key = self.text(len)?; | ||
if let Some(last) = &last | ||
&& key_order(last, &key) != std::cmp::Ordering::Less | ||
{ | ||
return err("map keys out of order, or repeated"); | ||
} | ||
let v = self.value(depth + 1)?; | ||
map.insert(key.clone(), v); | ||
last = Some(key); | ||
} | ||
Value::Map(map) | ||
} | ||
6 if n == 42 => { | ||
let (major, _, len) = self.head()?; | ||
let bytes = self.take(len)?; | ||
match (major, bytes) { | ||
(2, [0, cid @ ..]) => { | ||
Value::Link(Cid::from_bytes(cid).or_else(|e| err(format!("a link: {e}")))?) | ||
} | ||
_ => return err("a link that is not bytes starting with 0"), | ||
} | ||
} | ||
6 => return err(format!("tag {n}: only links (42) are allowed")), | ||
_ => match info { | ||
20 => Value::Bool(false), | ||
21 => Value::Bool(true), | ||
22 => Value::Null, | ||
25..=27 => return err("a float"), | ||
_ => return err(format!("simple value {info}")), | ||
}, | ||
}) | ||
} | ||
} | ||
| ||
impl Value { | ||
/// The map this is, if it is one. | ||
pub fn into_map(self) -> Option<BTreeMap<String, Value>> { | ||
match self { | ||
Value::Map(map) => Some(map), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// The bytes this is, if it is bytes. | ||
pub fn into_bytes(self) -> Option<Vec<u8>> { | ||
match self { | ||
Value::Bytes(bytes) => Some(bytes), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// The value a record's JSON holds, as atproto writes it: an object | ||
/// of `$link` alone a link, of `$bytes` alone bytes, a number with a | ||
/// fraction refused. | ||
pub fn from_json(json: &serde_json::Value) -> Result<Value, DrislError> { | ||
use serde_json::Value as J; | ||
Ok(match json { | ||
J::Null => Value::Null, | ||
J::Bool(b) => Value::Bool(*b), | ||
J::Number(n) => match n.as_i64() { | ||
Some(i) => Value::Integer(i), | ||
// JSON cannot tell 123.0 from 123, so neither does a record. | ||
None => match n.as_f64() { | ||
Some(f) if f.fract() == 0.0 && f.abs() < 9_007_199_254_740_992.0 => { | ||
Value::Integer(f as i64) | ||
} | ||
_ => return err(format!("{n} is not an integer")), | ||
}, | ||
}, | ||
J::String(s) => Value::String(s.clone()), | ||
J::Array(items) => Value::Array( | ||
items | ||
.iter() | ||
.map(Value::from_json) | ||
.collect::<Result<_, _>>()?, | ||
), | ||
J::Object(map) => { | ||
if let Some(link) = map.get("$link") { | ||
let (Some(text), 1) = (link.as_str(), map.len()) else { | ||
return err("a $link is a CID's text, alone in its object"); | ||
}; | ||
return Cid::parse(text) | ||
.map(Value::Link) | ||
.or_else(|e| err(format!("$link: {e}"))); | ||
} | ||
if let Some(bytes) = map.get("$bytes") { | ||
let (Some(text), 1) = (bytes.as_str(), map.len()) else { | ||
return err("$bytes is base64 text, alone in its object"); | ||
}; | ||
let text = text.trim_end_matches('='); | ||
return STANDARD_NO_PAD | ||
.decode(text) | ||
.map(Value::Bytes) | ||
.or_else(|_| err("$bytes is not base64")); | ||
} | ||
Value::Map( | ||
map.iter() | ||
.map(|(k, v)| Ok((k.clone(), Value::from_json(v)?))) | ||
.collect::<Result<_, DrislError>>()?, | ||
) | ||
} | ||
}) | ||
} | ||
| ||
/// The value as a record's JSON. | ||
pub fn to_json(&self) -> serde_json::Value { | ||
use serde_json::{Value as J, json}; | ||
match self { | ||
Value::Null => J::Null, | ||
Value::Bool(b) => J::Bool(*b), | ||
Value::Integer(i) => J::from(*i), | ||
Value::String(s) => J::String(s.clone()), | ||
Value::Bytes(b) => json!({ "$bytes": STANDARD_NO_PAD.encode(b) }), | ||
Value::Link(cid) => json!({ "$link": cid.to_string() }), | ||
Value::Array(items) => J::Array(items.iter().map(Value::to_json).collect()), | ||
Value::Map(map) => { | ||
J::Object(map.iter().map(|(k, v)| (k.clone(), v.to_json())).collect()) | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// Whether `json` is a record as atproto's data model has one: an object, | ||
/// whose every `$type` is a name, and whose every blob says what it holds. | ||
/// What fails is said. | ||
pub fn check_record(json: &serde_json::Value) -> Result<(), DrislError> { | ||
if !json.is_object() { | ||
return err("a record is an object"); | ||
} | ||
Value::from_json(json)?; | ||
check_types(json) | ||
} | ||
| ||
fn check_types(json: &serde_json::Value) -> Result<(), DrislError> { | ||
use serde_json::Value as J; | ||
match json { | ||
J::Array(items) => items.iter().try_for_each(check_types), | ||
J::Object(map) => { | ||
match map.get("$type") { | ||
None => {} | ||
Some(J::String(t)) if t == "blob" && !is_blob(map) => { | ||
return err("a blob has a ref, a mimeType and a size"); | ||
} | ||
Some(J::String(t)) if !t.is_empty() => {} | ||
Some(_) => return err("a $type is a name"), | ||
} | ||
map.values().try_for_each(check_types) | ||
} | ||
_ => Ok(()), | ||
} | ||
} | ||
| ||
/// Whether an object whose `$type` is `blob` says what a blob does. | ||
fn is_blob(map: &serde_json::Map<String, serde_json::Value>) -> bool { | ||
map.get("ref").and_then(|r| r.get("$link")).is_some() | ||
&& map | ||
.get("mimeType") | ||
.is_some_and(serde_json::Value::is_string) | ||
&& map.get("size").is_some_and(serde_json::Value::is_i64) | ||
} | ||
crates/atproto/src/jose.rsdeleted+0−159
| @@ -1,159 +0,0 @@ | ||
//! JOSE as atproto OAuth uses it: public keys as JWKs, their RFC 7638 | ||
//! thumbprints (a DPoP key's `jkt`), and compact JWTs signed with ES256 or | ||
//! ES256K, the two curves atproto keys are on. What jose, which the | ||
//! reference OAuth provider uses, makes of the same keys is in | ||
//! `tests/reference/jose.json`. | ||
| ||
use crate::keys::{Curve, Keypair, PublicKey}; | ||
use base64::Engine; | ||
use base64::engine::general_purpose::URL_SAFE_NO_PAD; | ||
use serde_json::{Value, json}; | ||
use sha2::{Digest, Sha256}; | ||
use std::fmt; | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct JoseError(pub String); | ||
| ||
impl fmt::Display for JoseError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(&self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for JoseError {} | ||
| ||
fn err<T>(what: impl Into<String>) -> Result<T, JoseError> { | ||
Err(JoseError(what.into())) | ||
} | ||
| ||
/// `bytes`, base64url without padding. | ||
pub fn b64(bytes: impl AsRef<[u8]>) -> String { | ||
URL_SAFE_NO_PAD.encode(bytes) | ||
} | ||
| ||
/// The bytes `text` holds, base64url without padding. | ||
pub fn unb64(text: &str) -> Option<Vec<u8>> { | ||
URL_SAFE_NO_PAD.decode(text).ok() | ||
} | ||
| ||
/// The JSON object `part` holds, base64url: a JWT's header or claims. | ||
pub fn json_of(part: &str) -> Option<Value> { | ||
let bytes = URL_SAFE_NO_PAD.decode(part).ok()?; | ||
serde_json::from_slice::<Value>(&bytes) | ||
.ok() | ||
.filter(Value::is_object) | ||
} | ||
| ||
/// SHA-256 of `text`, base64url: a PKCE challenge, a DPoP proof's `ath`. | ||
pub fn sha256(text: &str) -> String { | ||
b64(Sha256::digest(text.as_bytes())) | ||
} | ||
| ||
/// `bytes` random bytes, base64url: a token, a nonce, a `jti`. | ||
pub fn random(bytes: usize) -> String { | ||
let mut buf = vec![0; bytes]; | ||
rand_core::RngCore::fill_bytes(&mut rand_core::OsRng, &mut buf); | ||
b64(buf) | ||
} | ||
| ||
fn crv(curve: Curve) -> &'static str { | ||
match curve { | ||
Curve::K256 => "secp256k1", | ||
Curve::P256 => "P-256", | ||
} | ||
} | ||
| ||
/// `key` as a public JWK. | ||
pub fn jwk(key: &PublicKey) -> Value { | ||
let point = match key { | ||
PublicKey::K256(k) => k.to_encoded_point(false).as_bytes().to_vec(), | ||
PublicKey::P256(k) => k.to_encoded_point(false).as_bytes().to_vec(), | ||
}; | ||
json!({ | ||
"kty": "EC", | ||
"crv": crv(key.curve()), | ||
"x": b64(&point[1..33]), | ||
"y": b64(&point[33..]), | ||
}) | ||
} | ||
| ||
/// The public key a JWK holds: an EC key on P-256 or secp256k1, never one | ||
/// with its private part. | ||
pub fn from_jwk(jwk: &Value) -> Result<PublicKey, JoseError> { | ||
if jwk.get("d").is_some() { | ||
return err("a JWK with its private key"); | ||
} | ||
if jwk["kty"] != "EC" { | ||
return err("a JWK that is not an EC key"); | ||
} | ||
let curve = match jwk["crv"].as_str() { | ||
Some("P-256") => Curve::P256, | ||
Some("secp256k1") => Curve::K256, | ||
other => return err(format!("a JWK on the curve {other:?}")), | ||
}; | ||
let coordinate = |name: &str| { | ||
let text = jwk[name].as_str().unwrap_or_default(); | ||
URL_SAFE_NO_PAD | ||
.decode(text) | ||
.ok() | ||
.filter(|c| c.len() == 32) | ||
.ok_or_else(|| JoseError(format!("a JWK whose {name} is not 32 bytes"))) | ||
}; | ||
let point = [&[4u8][..], &coordinate("x")?, &coordinate("y")?].concat(); | ||
PublicKey::from_sec1(curve, &point).map_err(|e| JoseError(e.0.into())) | ||
} | ||
| ||
/// A JWK's RFC 7638 thumbprint, SHA-256: its required members, in order, | ||
/// as JSON with no spaces. | ||
pub fn thumbprint(key: &PublicKey) -> String { | ||
let jwk = jwk(key); | ||
let canonical = format!( | ||
r#"{{"crv":"{}","kty":"EC","x":"{}","y":"{}"}}"#, | ||
jwk["crv"].as_str().unwrap_or_default(), | ||
jwk["x"].as_str().unwrap_or_default(), | ||
jwk["y"].as_str().unwrap_or_default(), | ||
); | ||
b64(Sha256::digest(canonical.as_bytes())) | ||
} | ||
| ||
/// `claims` signed with `key` as a compact JWT, under `header` with the | ||
/// key's `alg` added. | ||
pub fn sign(key: &Keypair, header: &Value, claims: &Value) -> String { | ||
let mut header = header.clone(); | ||
header["alg"] = key.curve().alg().into(); | ||
let body = format!("{}.{}", b64(header.to_string()), b64(claims.to_string())); | ||
format!("{body}.{}", b64(key.sign(body.as_bytes()))) | ||
} | ||
| ||
/// A compact JWT's header and claims, unchecked: to find whose key to | ||
/// check it with. | ||
pub fn parts(token: &str) -> Result<(Value, Value), JoseError> { | ||
let pieces: Vec<&str> = token.split('.').collect(); | ||
let [header, claims, _] = pieces[..] else { | ||
return err("not a compact JWT"); | ||
}; | ||
let decode = |part: &str, what: &str| { | ||
json_of(part).ok_or_else(|| JoseError(format!("bad JSON in a JWT {what}"))) | ||
}; | ||
Ok((decode(header, "header")?, decode(claims, "payload")?)) | ||
} | ||
| ||
/// A JWT's header and claims, once it is signed by `key` with the key's | ||
/// `alg`. Its claims' times are the caller's to check. Either `s` is | ||
/// taken, as jose signs with either. | ||
pub fn verify(token: &str, key: &PublicKey) -> Result<(Value, Value), JoseError> { | ||
let (header, claims) = parts(token)?; | ||
let alg = key.curve().alg(); | ||
if header["alg"] != alg { | ||
return err(format!( | ||
"a JWT signed with {} where {alg} was expected", | ||
header["alg"] | ||
)); | ||
} | ||
let (signed, sig) = token.rsplit_once('.').unwrap_or_default(); | ||
let sig = URL_SAFE_NO_PAD.decode(sig).unwrap_or_default(); | ||
if !key.verify_either_s(signed.as_bytes(), &sig) { | ||
return err("bad signature"); | ||
} | ||
Ok((header, claims)) | ||
} | ||
crates/atproto/src/keys.rsdeleted+0−222
| @@ -1,222 +0,0 @@ | ||
//! The keys atproto signs with, secp256k1 (`ES256K`) and P-256 (`ES256`): | ||
//! a group's repo and rotation keys, the host's own, and the keys in a DID | ||
//! document, as multikeys and `did:key`s. Signatures are 64 bytes, `r` | ||
//! then `s`, with `s` in the low half: atproto refuses any other. | ||
| ||
use rand_core::OsRng; | ||
use std::fmt; | ||
| ||
const K256_CODEC: [u8; 2] = [0xe7, 0x01]; | ||
const P256_CODEC: [u8; 2] = [0x80, 0x24]; | ||
| ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
pub struct KeyError(pub &'static str); | ||
| ||
impl fmt::Display for KeyError { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(self.0) | ||
} | ||
} | ||
| ||
impl std::error::Error for KeyError {} | ||
| ||
/// Which curve a key is on. | ||
#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
pub enum Curve { | ||
K256, | ||
P256, | ||
} | ||
| ||
impl Curve { | ||
/// Its JWT algorithm. | ||
pub fn alg(self) -> &'static str { | ||
match self { | ||
Curve::K256 => "ES256K", | ||
Curve::P256 => "ES256", | ||
} | ||
} | ||
} | ||
| ||
/// A key that signs. | ||
#[derive(Clone)] | ||
pub enum Keypair { | ||
K256(k256::ecdsa::SigningKey), | ||
P256(p256::ecdsa::SigningKey), | ||
} | ||
| ||
impl fmt::Debug for Keypair { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
write!(f, "Keypair({})", self.public().did_key()) | ||
} | ||
} | ||
| ||
impl Keypair { | ||
pub fn generate(curve: Curve) -> Keypair { | ||
match curve { | ||
Curve::K256 => Keypair::K256(k256::ecdsa::SigningKey::random(&mut OsRng)), | ||
Curve::P256 => Keypair::P256(p256::ecdsa::SigningKey::random(&mut OsRng)), | ||
} | ||
} | ||
| ||
/// The key whose secret is the 32 bytes `secret`. | ||
pub fn from_bytes(curve: Curve, secret: &[u8]) -> Result<Keypair, KeyError> { | ||
let bad = |_| KeyError("not a secret key on its curve"); | ||
Ok(match curve { | ||
Curve::K256 => Keypair::K256(k256::ecdsa::SigningKey::from_slice(secret).map_err(bad)?), | ||
Curve::P256 => Keypair::P256(p256::ecdsa::SigningKey::from_slice(secret).map_err(bad)?), | ||
}) | ||
} | ||
| ||
/// The 32 bytes of its secret, to keep. | ||
pub fn to_bytes(&self) -> [u8; 32] { | ||
match self { | ||
Keypair::K256(k) => k.to_bytes().into(), | ||
Keypair::P256(k) => k.to_bytes().into(), | ||
} | ||
} | ||
| ||
pub fn curve(&self) -> Curve { | ||
match self { | ||
Keypair::K256(_) => Curve::K256, | ||
Keypair::P256(_) => Curve::P256, | ||
} | ||
} | ||
| ||
pub fn public(&self) -> PublicKey { | ||
match self { | ||
Keypair::K256(k) => PublicKey::K256(*k.verifying_key()), | ||
Keypair::P256(k) => PublicKey::P256(*k.verifying_key()), | ||
} | ||
} | ||
| ||
/// `message` signed, hashed with SHA-256: `r` then `s`, low-S. | ||
pub fn sign(&self, message: &[u8]) -> [u8; 64] { | ||
use ecdsa::signature::Signer; | ||
match self { | ||
Keypair::K256(k) => { | ||
let sig: k256::ecdsa::Signature = k.sign(message); | ||
sig.normalize_s().unwrap_or(sig).to_bytes().into() | ||
} | ||
Keypair::P256(k) => { | ||
let sig: p256::ecdsa::Signature = k.sign(message); | ||
sig.normalize_s().unwrap_or(sig).to_bytes().into() | ||
} | ||
} | ||
} | ||
} | ||
| ||
/// A key that checks signatures: one a DID document or `did:key` names. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub enum PublicKey { | ||
K256(k256::ecdsa::VerifyingKey), | ||
P256(p256::ecdsa::VerifyingKey), | ||
} | ||
| ||
fn base58(text: &str) -> Result<Vec<u8>, KeyError> { | ||
let b58 = text | ||
.strip_prefix('z') | ||
.ok_or(KeyError("a multikey is base58btc, starting with z"))?; | ||
bs58::decode(b58) | ||
.into_vec() | ||
.map_err(|_| KeyError("bad base58 in a key")) | ||
} | ||
| ||
impl PublicKey { | ||
/// The key a multikey (multibase `z`, base58btc, with its multicodec) holds. | ||
pub fn from_multibase(text: &str) -> Result<PublicKey, KeyError> { | ||
let bytes = base58(text)?; | ||
let (codec, key) = bytes.split_at(2.min(bytes.len())); | ||
match <[u8; 2]>::try_from(codec) { | ||
Ok(K256_CODEC) => PublicKey::from_sec1(Curve::K256, key), | ||
Ok(P256_CODEC) => PublicKey::from_sec1(Curve::P256, key), | ||
_ => Err(KeyError("not a secp256k1 or P-256 multikey")), | ||
} | ||
} | ||
| ||
/// The key of a DID document's verification method: a `Multikey`, or | ||
/// one of the older types, whose multibase holds the bare key. | ||
pub fn from_method(kind: &str, multibase: &str) -> Result<PublicKey, KeyError> { | ||
match kind { | ||
"EcdsaSecp256k1VerificationKey2019" => { | ||
PublicKey::from_sec1(Curve::K256, &base58(multibase)?) | ||
} | ||
"EcdsaSecp256r1VerificationKey2019" => { | ||
PublicKey::from_sec1(Curve::P256, &base58(multibase)?) | ||
} | ||
_ => PublicKey::from_multibase(multibase), | ||
} | ||
} | ||
| ||
pub fn from_did_key(did: &str) -> Result<PublicKey, KeyError> { | ||
let multibase = did | ||
.strip_prefix("did:key:") | ||
.ok_or(KeyError("not a did:key"))?; | ||
PublicKey::from_multibase(multibase) | ||
} | ||
| ||
/// The key as SEC1 bytes, compressed or not. | ||
pub fn from_sec1(curve: Curve, bytes: &[u8]) -> Result<PublicKey, KeyError> { | ||
match curve { | ||
Curve::K256 => k256::ecdsa::VerifyingKey::from_sec1_bytes(bytes) | ||
.map(PublicKey::K256) | ||
.map_err(|_| KeyError("not a secp256k1 key")), | ||
Curve::P256 => p256::ecdsa::VerifyingKey::from_sec1_bytes(bytes) | ||
.map(PublicKey::P256) | ||
.map_err(|_| KeyError("not a P-256 key")), | ||
} | ||
} | ||
| ||
pub fn curve(&self) -> Curve { | ||
match self { | ||
PublicKey::K256(_) => Curve::K256, | ||
PublicKey::P256(_) => Curve::P256, | ||
} | ||
} | ||
| ||
/// The key as SEC1 bytes, compressed. | ||
pub fn to_sec1(&self) -> Vec<u8> { | ||
match self { | ||
PublicKey::K256(k) => k.to_encoded_point(true).as_bytes().to_vec(), | ||
PublicKey::P256(k) => k.to_encoded_point(true).as_bytes().to_vec(), | ||
} | ||
} | ||
| ||
/// The key as a multikey, as a DID document's `publicKeyMultibase`. | ||
pub fn to_multibase(&self) -> String { | ||
let codec = match self { | ||
PublicKey::K256(_) => K256_CODEC, | ||
PublicKey::P256(_) => P256_CODEC, | ||
}; | ||
let bytes = [&codec[..], &self.to_sec1()].concat(); | ||
format!("z{}", bs58::encode(bytes).into_string()) | ||
} | ||
| ||
pub fn did_key(&self) -> String { | ||
format!("did:key:{}", self.to_multibase()) | ||
} | ||
| ||
/// Whether `signature` is this key's of `message`, low-S or not: what an | ||
/// HTTP message signature on a space request is held to, as the space | ||
/// alpha takes either. Everywhere else, [`PublicKey::verify`]. | ||
pub fn verify_either_s(&self, message: &[u8], signature: &[u8]) -> bool { | ||
use ecdsa::signature::Verifier; | ||
match self { | ||
PublicKey::K256(k) => k256::ecdsa::Signature::from_slice(signature) | ||
.is_ok_and(|s| k.verify(message, &s.normalize_s().unwrap_or(s)).is_ok()), | ||
PublicKey::P256(k) => p256::ecdsa::Signature::from_slice(signature) | ||
.is_ok_and(|s| k.verify(message, &s).is_ok()), | ||
} | ||
} | ||
| ||
/// Whether `signature` is this key's of `message`: 64 bytes, `r` then | ||
/// `s`, low-S. A DER signature, or a high-S one, is refused. | ||
pub fn verify(&self, message: &[u8], signature: &[u8]) -> bool { | ||
use ecdsa::signature::Verifier; | ||
match self { | ||
PublicKey::K256(k) => k256::ecdsa::Signature::from_slice(signature) | ||
.is_ok_and(|s| s.normalize_s().is_none() && k.verify(message, &s).is_ok()), | ||
PublicKey::P256(k) => p256::ecdsa::Signature::from_slice(signature) | ||
.is_ok_and(|s| s.normalize_s().is_none() && k.verify(message, &s).is_ok()), | ||
} | ||
} | ||
} | ||
crates/atproto/src/lexicon.rsdeleted+0−849
849 lines changed: not loaded until asked for.
crates/atproto/src/lib.rsdeleted+0−32
| @@ -1,32 +0,0 @@ | ||
//! The atproto a group host needs, written for it rather than taken from a | ||
//! framework: DRISL (DAG-CBOR) and CIDs, the keys a repo and a PLC | ||
//! operation are signed with, the Merkle search tree a repo's records hang | ||
//! from, CAR files, PLC operations, the service-auth tokens one server | ||
//! hands another, and the JWKs and JWTs of OAuth's DPoP proofs and client | ||
//! assertions. | ||
//! | ||
//! Each part is checked against atproto's interop test vectors, under | ||
//! `tests/interop`. The parts still to come are in `docs/design/README.md`. | ||
| ||
pub mod base32; | ||
pub mod car; | ||
pub mod cid; | ||
pub mod commit; | ||
pub mod did; | ||
pub mod drisl; | ||
pub mod jose; | ||
pub mod keys; | ||
pub mod lexicon; | ||
pub mod mst; | ||
pub mod plc; | ||
pub mod service_auth; | ||
pub mod space; | ||
pub mod space_auth; | ||
pub mod syntax; | ||
pub mod tid; | ||
pub mod time; | ||
| ||
pub use cid::Cid; | ||
pub use commit::Commit; | ||
pub use drisl::Value; | ||
pub use keys::{Curve, Keypair, PublicKey}; | ||
crates/atproto/src/mst.rsdeleted+0−368
crates/atproto/src/plc.rsdeleted+0−275
crates/atproto/src/service_auth.rsdeleted+0−142
crates/atproto/src/space.rsdeleted+0−570
570 lines changed: not loaded until asked for.
crates/atproto/src/space_auth.rsdeleted+0−395
crates/atproto/src/syntax.rsdeleted+0−74
crates/atproto/src/tid.rsdeleted+0−63
crates/atproto/src/time.rsdeleted+0−26
crates/atproto/tests/interop/crypto/signature-fixtures.jsondeleted+0−68
crates/atproto/tests/interop/crypto/w3c_didkey_K256.jsondeleted+0−22
crates/atproto/tests/interop/crypto/w3c_didkey_P256.jsondeleted+0−6
crates/atproto/tests/interop/data-model/data-model-fixtures.jsondeleted+0−64
crates/atproto/tests/interop/data-model/data-model-invalid.jsondeleted+0−111
crates/atproto/tests/interop/data-model/data-model-valid.jsondeleted+0−48
crates/atproto/tests/interop/firehose/commit-proof-fixtures.jsondeleted+0−118
crates/atproto/tests/interop/mst/common_prefix.jsondeleted+0−15
crates/atproto/tests/interop/mst/example_keys.txtdeleted+0−156
crates/atproto/tests/interop/mst/key_heights.jsondeleted+0−11
crates/atproto/tests/interop/syntax/atidentifier_syntax_invalid.txtdeleted+0−28
crates/atproto/tests/interop/syntax/atidentifier_syntax_valid.txtdeleted+0−15
crates/atproto/tests/interop/syntax/aturi_syntax_invalid.txtdeleted+0−89
crates/atproto/tests/interop/syntax/aturi_syntax_valid.txtdeleted+0−35
crates/atproto/tests/interop/syntax/cid_syntax_invalid.txtdeleted+0−16
crates/atproto/tests/interop/syntax/cid_syntax_valid.txtdeleted+0−14
crates/atproto/tests/interop/syntax/datetime_parse_invalid.txtdeleted+0−10
crates/atproto/tests/interop/syntax/datetime_syntax_invalid.txtdeleted+0−66
crates/atproto/tests/interop/syntax/datetime_syntax_valid.txtdeleted+0−42
crates/atproto/tests/interop/syntax/did_syntax_invalid.txtdeleted+0−19
crates/atproto/tests/interop/syntax/did_syntax_valid.txtdeleted+0−26
crates/atproto/tests/interop/syntax/handle_syntax_invalid.txtdeleted+0−61
crates/atproto/tests/interop/syntax/handle_syntax_valid.txtdeleted+0−90
crates/atproto/tests/interop/syntax/language_syntax_invalid.txtdeleted+0−10
crates/atproto/tests/interop/syntax/language_syntax_valid.txtdeleted+0−26
crates/atproto/tests/interop/syntax/nsid_syntax_invalid.txtdeleted+0−30
crates/atproto/tests/interop/syntax/nsid_syntax_valid.txtdeleted+0−32
crates/atproto/tests/interop/syntax/recordkey_syntax_invalid.txtdeleted+0−15
crates/atproto/tests/interop/syntax/recordkey_syntax_valid.txtdeleted+0−21
crates/atproto/tests/interop/syntax/tid_syntax_invalid.txtdeleted+0−19
crates/atproto/tests/interop/syntax/tid_syntax_valid.txtdeleted+0−7
crates/atproto/tests/interop/syntax/uri_syntax_invalid.txtdeleted+0−17
crates/atproto/tests/interop/syntax/uri_syntax_valid.txtdeleted+0−14
crates/atproto/tests/interop/LICENSE-CC0deleted+0−121
crates/atproto/tests/interop/README.mddeleted+0−8
crates/atproto/tests/reference/identity.jsondeleted+0−209
crates/atproto/tests/reference/identity.mjsdeleted+0−60
crates/atproto/tests/reference/jose.jsondeleted+0−40
crates/atproto/tests/reference/jose.mjsdeleted+0−38
crates/atproto/tests/reference/knotless.jsondeleted+0−7
crates/atproto/tests/reference/lexicon.jsondeleted+0−10087
A large diff, not shown.
crates/atproto/tests/reference/lexicon.mjsdeleted+0−221
crates/atproto/tests/reference/README.mddeleted+0−39
crates/atproto/tests/reference/space-meta.jsondeleted+0−157
crates/atproto/tests/reference/space-meta.mjsdeleted+0−156
crates/atproto/tests/reference/space-vectors.jsondeleted+0−101
crates/atproto/tests/car.rsdeleted+0−84
crates/atproto/tests/cid.rsdeleted+0−45
crates/atproto/tests/commit.rsdeleted+0−68
crates/atproto/tests/did.rsdeleted+0−66
crates/atproto/tests/drisl.rsdeleted+0−181
crates/atproto/tests/jose.rsdeleted+0−113
crates/atproto/tests/keys.rsdeleted+0−130
crates/atproto/tests/lexicon.rsdeleted+0−271
crates/atproto/tests/mst.rsdeleted+0−209
crates/atproto/tests/plc.rsdeleted+0−145
crates/atproto/tests/service_auth.rsdeleted+0−127
crates/atproto/tests/space.rsdeleted+0−404
404 lines changed: not loaded until asked for.
crates/atproto/tests/space_auth.rsdeleted+0−448
448 lines changed: not loaded until asked for.