agentmux_srv_core/backend/user_sync/
record.rs1use agentmux_common::jekt_sign::{ed25519_sign_b64, ed25519_verify_b64};
10use serde_json::{json, Map, Value};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13
14use super::hlc::Version;
15
16pub const CLEAR_FIELDS: [&str; 10] = ["collection", "record", "version", "base", "origin", "seq", "epoch", "tombstone", "size", "sig"];
18
19const SEP: char = '\u{1f}';
21pub const MAX_RECORD_BYTES: u64 = 25 * 1024 * 1024;
23const DOMAIN: &str = "agentmux-sync-record-v1";
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Header {
28 pub collection: String,
29 pub record: String,
31 pub version: Version,
32 pub base: Option<Version>,
35 pub origin: String,
37 pub seq: u64,
39 pub epoch: u32,
40 pub tombstone: bool,
41 pub size: u64,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct Record {
48 pub header: Header,
49 pub sig: String,
50 #[serde(with = "b64")]
52 pub body: Vec<u8>,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57pub enum BadRecord {
58 Malformed,
60 VersionNotFromOrigin,
62 Signature,
64}
65
66fn hex(bytes: &[u8]) -> String {
67 bytes.iter().map(|b| format!("{b:02x}")).collect()
68}
69
70impl Header {
71 fn material(&self, body: &[u8]) -> String {
73 let digest = hex(&Sha256::digest(body));
74 let base = match &self.base {
75 None => ["0".to_string(), String::new(), String::new(), String::new()],
76 Some(b) => ["1".to_string(), b.wall_ms.to_string(), b.counter.to_string(), b.machine.clone()],
77 };
78 [
79 DOMAIN.to_string(),
80 self.collection.clone(),
81 self.record.clone(),
82 self.version.wall_ms.to_string(),
83 self.version.counter.to_string(),
84 self.version.machine.clone(),
85 ]
86 .into_iter()
87 .chain(base)
88 .chain([
89 self.origin.clone(),
90 self.seq.to_string(),
91 self.epoch.to_string(),
92 (self.tombstone as u8).to_string(),
93 self.size.to_string(),
94 digest,
95 ])
96 .collect::<Vec<String>>()
97 .join(&SEP.to_string())
98 }
99
100 fn well_formed(&self, body: &[u8]) -> bool {
101 let clean = |s: &str| !s.is_empty() && !s.contains(SEP);
102 clean(&self.collection)
103 && clean(&self.record)
104 && clean(&self.origin)
105 && clean(&self.version.machine)
106 && self.base.as_ref().map_or(true, |b| clean(&b.machine))
107 && self.size == body.len() as u64
108 && self.size <= MAX_RECORD_BYTES
109 && (!self.tombstone || body.is_empty())
110 }
111}
112
113impl Record {
114 pub fn sign(origin_private: &[u8], header: Header, body: Vec<u8>) -> Option<Record> {
116 if !header.well_formed(&body) || header.version.machine != header.origin {
117 return None;
118 }
119 let sig = ed25519_sign_b64(origin_private, &header.material(&body))?;
120 Some(Record { header, sig, body })
121 }
122
123 pub fn verify(&self, origin_public: &[u8; 32]) -> Result<(), BadRecord> {
125 if !self.header.well_formed(&self.body) {
126 return Err(BadRecord::Malformed);
127 }
128 if self.header.version.machine != self.header.origin {
129 return Err(BadRecord::VersionNotFromOrigin);
130 }
131 if ed25519_verify_b64(origin_public, &self.header.material(&self.body), &self.sig) {
132 Ok(())
133 } else {
134 Err(BadRecord::Signature)
135 }
136 }
137
138 pub fn clear_fields(&self) -> Map<String, Value> {
140 let h = &self.header;
141 let Value::Object(map) = json!({
142 "collection": h.collection,
143 "record": h.record,
144 "version": { "wall_ms": h.version.wall_ms, "counter": h.version.counter, "machine": h.version.machine },
145 "base": h.base.as_ref().map(|b| json!({ "wall_ms": b.wall_ms, "counter": b.counter, "machine": b.machine })),
146 "origin": h.origin,
147 "seq": h.seq,
148 "epoch": h.epoch,
149 "tombstone": h.tombstone,
150 "size": h.size,
151 "sig": self.sig,
152 }) else {
153 return Map::new();
154 };
155 map
156 }
157}
158
159mod b64 {
161 use base64::{engine::general_purpose::STANDARD, Engine};
162 use serde::{Deserialize, Deserializer, Serializer};
163
164 pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
165 s.serialize_str(&STANDARD.encode(bytes))
166 }
167
168 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
169 let text = String::deserialize(d)?;
170 STANDARD.decode(text).map_err(serde::de::Error::custom)
171 }
172}