Skip to main content

agentmux_srv_core/backend/user_sync/
record.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A record as it leaves a machine (SPEC_USER_DATA_SYNC_LAYER ยง3.2): a fixed, signed header in the clear and a
5//! sealed body. The header is signed by the origin machine's key over every field and a digest of the body, so
6//! no other member and no relay can write a record "from" a machine. The clear header is a fixed list
7//! ([`CLEAR_FIELDS`]); a collection's name and everything descriptive lives in the sealed body.
8
9use 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
16/// Every field a record carries in the clear, and no other.
17pub const CLEAR_FIELDS: [&str; 10] = ["collection", "record", "version", "base", "origin", "seq", "epoch", "tombstone", "size", "sig"];
18
19/// Separates the fields of the signed material; a field holding it is refused.
20const SEP: char = '\u{1f}';
21/// The most a record's sealed body may hold (a collection's own setting may lower it).
22pub const MAX_RECORD_BYTES: u64 = 25 * 1024 * 1024;
23const DOMAIN: &str = "agentmux-sync-record-v1";
24
25/// The header of a record.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Header {
28    pub collection: String,
29    /// A stable id made where the record was born, never reused.
30    pub record: String,
31    pub version: Version,
32    /// The version this change replaced on the machine that made it (`None` for a record's first version). It
33    /// lets an adapter tell an edit made on top of what a receiver holds from one made apart, from headers alone.
34    pub base: Option<Version>,
35    /// The machine that wrote this entry of its log (its pinned instance identifier).
36    pub origin: String,
37    /// The origin's own sequence number for this collection.
38    pub seq: u64,
39    pub epoch: u32,
40    pub tombstone: bool,
41    /// The length of the sealed body.
42    pub size: u64,
43}
44
45/// A record: its header, the origin's signature over it, and the sealed body (empty for a tombstone).
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct Record {
48    pub header: Header,
49    pub sig: String,
50    /// Carried as base64 text in JSON.
51    #[serde(with = "b64")]
52    pub body: Vec<u8>,
53}
54
55/// Why a record was not accepted as written.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57pub enum BadRecord {
58    /// A field holds the separator, the size does not match the body, or a tombstone has a body.
59    Malformed,
60    /// The version names a different machine than the origin.
61    VersionNotFromOrigin,
62    /// The signature does not verify against the origin's key.
63    Signature,
64}
65
66fn hex(bytes: &[u8]) -> String {
67    bytes.iter().map(|b| format!("{b:02x}")).collect()
68}
69
70impl Header {
71    /// The bytes the origin signs: every field, and a digest of the sealed body.
72    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    /// A record signed by `origin_private` (the 32-byte seed of the origin machine's signing key).
115    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    /// Checks the record against the origin's pinned public key.
124    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    /// What this record shows in the clear, as it is sent and stored: exactly [`CLEAR_FIELDS`].
139    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
159/// A body as base64 text, so a record is JSON like any other op's params.
160mod 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}