Skip to main content

agentmux_common/
jekt_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Files sent with a jekt: the manifest, its digest, and how the msgid binds
5//! it (docs/specs/SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §3.2–§3.3).
6//!
7//! A jekt with files has a msgid ending in `.files-v1.<manifest digest>`.
8//! Every signing scheme already signs the msgid, so the signature covers the
9//! file list, and through each entry's SHA-256 every byte of every file,
10//! without any scheme changing. A text-only jekt is untouched.
11
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14
15/// At most this many files on one jekt.
16pub const MAX_FILES: usize = 10;
17/// What an instance that can receive files advertises, in its registry
18/// entries and its `GET /agentmux/reactive/agent` answer (spec §3.4).
19pub const FEATURE: &str = "files-v1";
20/// What an install that can fetch files sent through the cloud relay says in
21/// its agents' leases, which a sender asks about before sending (§4.4).
22pub const CLOUD_FEATURE: &str = "files-cloud-v1";
23const MIB: u64 = 1024 * 1024;
24
25/// The most one file, and all of a jekt's files together, may weigh when
26/// they travel on `tier` (spec §5): `(per file, per jekt)`. The same machine
27/// (`host`, `channel`) allows the most; LAN less; anything else nothing yet.
28pub fn tier_limits(tier: &str) -> Option<(u64, u64)> {
29    match tier {
30        "host" | "channel" => Some((100 * MIB, 200 * MIB)),
31        "lan" => Some((50 * MIB, 100 * MIB)),
32        "wan" => Some((25 * MIB, 50 * MIB)),
33        _ => None,
34    }
35}
36
37/// A file as a cloud jekt's manifest carries it (spec §4.4): the file, the
38/// key its blob is encrypted under, and the relay's name for the blob.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct CloudFile {
41    #[serde(flatten)]
42    pub file: JektFile,
43    /// Standard base64 of a 32-byte AES-256-GCM key, or that key sealed to
44    /// the receiving install ([`is_sealed_key`], spec §7).
45    pub key: String,
46    pub blob_id: String,
47}
48
49/// Leads a cloud manifest's digest: never the same input as a plain one.
50const CLOUD_DIGEST_LABEL: &str = "amx-jekt-files-cloud-v1";
51
52/// SHA-256 over a cloud manifest, keys and blob ids included, so the WAN
53/// signature that binds it covers them too.
54pub fn cloud_manifest_digest(files: &[CloudFile]) -> String {
55    let mut input = String::from(CLOUD_DIGEST_LABEL);
56    for f in files {
57        input.push(ENTRY_SEP);
58        input.push_str(&f.file.sha256);
59        for part in [f.file.name.as_str(), &f.file.size.to_string(), &f.key, &f.blob_id] {
60            input.push(FIELD_SEP);
61            input.push_str(part);
62        }
63    }
64    format!("{:x}", Sha256::digest(input.as_bytes()))
65}
66
67/// The msgid a WAN jekt carrying `files` is signed under: `msgid` without
68/// any digest it already ended in, then the cloud manifest's digest.
69pub fn bind_cloud_msgid(msgid: &str, files: &[CloudFile]) -> String {
70    let base = match bound_digest(msgid) {
71        Some(_) => &msgid[..msgid.rfind(MSGID_TAG).unwrap_or(msgid.len())],
72        None => msgid,
73    };
74    format!("{base}{MSGID_TAG}{}", cloud_manifest_digest(files))
75}
76
77/// Whether `msgid` binds exactly this cloud manifest.
78pub fn cloud_msgid_binds(msgid: &str, files: &[CloudFile]) -> bool {
79    bound_digest(msgid).is_some_and(|d| d == cloud_manifest_digest(files))
80}
81
82/// Leads a file key sealed to its receiver: `x25519.<the receiving agent's
83/// WAN key fingerprint>.<base64url of the ephemeral key, the wrapped key and
84/// its tag>` (spec §7).
85pub const SEALED_KEY_PREFIX: &str = "x25519.";
86/// Base64url length of a sealed key's last part: 32 + 32 + 16 bytes.
87const SEALED_KEY_BODY_CHARS: usize = 107;
88
89/// Whether `key` has a sealed key's shape. Says nothing about whether it opens.
90pub fn is_sealed_key(key: &str) -> bool {
91    let b64url = |s: &str| s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
92    key.strip_prefix(SEALED_KEY_PREFIX)
93        .and_then(|rest| rest.split_once('.'))
94        .is_some_and(|(fp, body)| fp.len() == 43 && body.len() == SEALED_KEY_BODY_CHARS && b64url(fp) && b64url(body))
95}
96
97/// Why a cloud manifest is refused: the plain checks within the cloud relay's
98/// limits, plus a 44-character base64 key (or a sealed one) and a relay blob
99/// id on every entry.
100pub fn validate_cloud(files: &[CloudFile]) -> Result<(), String> {
101    let plain: Vec<JektFile> = files.iter().map(|f| f.file.clone()).collect();
102    validate_for_tier(&plain, "wan")?;
103    let blob_id = |s: &str| s.len() == 41 && s.starts_with("blob-") && s[5..].bytes().all(|b| b.is_ascii_hexdigit() || b == b'-');
104    let key = |k: &str| (k.len() == 44 && k.ends_with('=')) || is_sealed_key(k);
105    if files.iter().any(|f| !key(&f.key) || !blob_id(&f.blob_id)) {
106        return Err("a cloud file entry is malformed".to_string());
107    }
108    Ok(())
109}
110
111/// How a tier's limit reads in a refusal: where the files are going.
112fn tier_place(tier: &str) -> &'static str {
113    match tier {
114        "host" | "channel" => "on this machine",
115        "lan" => "to another computer on the LAN",
116        _ => "through the cloud relay",
117    }
118}
119
120/// Why `files` can't travel on `tier`, if they can't. The text names the
121/// limit and where it applies.
122pub fn check_tier_limits(files: &[JektFile], tier: &str) -> Result<(), String> {
123    let Some((per_file, per_jekt)) = tier_limits(tier) else {
124        return Err(format!("files can't be sent over the {tier} tier yet"));
125    };
126    let place = tier_place(tier);
127    if let Some(f) = files.iter().find(|f| f.size > per_file) {
128        return Err(format!("{} is over the {} MB limit per file {place}", f.name, per_file / MIB));
129    }
130    if files.iter().fold(0u64, |sum, f| sum.saturating_add(f.size)) > per_jekt {
131        return Err(format!("the files come to more than the {} MB limit per message {place}", per_jekt / MIB));
132    }
133    Ok(())
134}
135
136/// [`validate`], and the comparison with the limits of `tier`: what a
137/// sender checks before it sends and a receiver checks before it reads a byte.
138pub fn validate_for_tier(files: &[JektFile], tier: &str) -> Result<(), String> {
139    validate(files)?;
140    check_tier_limits(files, tier)
141}
142/// A file name's length limit, in characters (the attachment store's).
143pub const MAX_NAME_CHARS: usize = 120;
144/// Separates the msgid a sender would otherwise use from the digest.
145pub const MSGID_TAG: &str = ".files-v1.";
146/// Leads the digest input, so it can't be read as any other signed material.
147const DIGEST_LABEL: &str = "amx-jekt-files-v1";
148const FIELD_SEP: char = '\u{1}';
149const ENTRY_SEP: char = '\u{2}';
150
151/// One file in a jekt's manifest, in send order.
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153pub struct JektFile {
154    /// Lowercase hex SHA-256 of the file's bytes.
155    pub sha256: String,
156    /// Base name only, as [`clean_name`] leaves it.
157    pub name: String,
158    pub size: u64,
159}
160
161/// A file's name as a manifest carries it: the base name of `name`, with
162/// control characters replaced, trimmed, and at most [`MAX_NAME_CHARS`]
163/// characters. `"file"` when nothing is left.
164pub fn clean_name(name: &str) -> String {
165    let base = name.rsplit(['/', '\\']).next().unwrap_or("");
166    let one_line: String = base.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
167    let short: String = one_line.trim().chars().take(MAX_NAME_CHARS).collect();
168    let short = short.trim();
169    if short.is_empty() || short == "." || short == ".." {
170        "file".to_string()
171    } else {
172        short.to_string()
173    }
174}
175
176/// Why a manifest is refused before anything else is checked.
177pub fn validate(files: &[JektFile]) -> Result<(), String> {
178    if files.is_empty() {
179        return Err("the file list is empty".to_string());
180    }
181    if files.len() > MAX_FILES {
182        return Err(format!("{} files is more than the limit of {MAX_FILES}", files.len()));
183    }
184    for f in files {
185        let hex = f.sha256.len() == 64 && f.sha256.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
186        if !hex {
187            return Err(format!("{}: not a lowercase SHA-256", clean_name(&f.name)));
188        }
189        if f.name != clean_name(&f.name) {
190            return Err(format!("{}: not a clean base name", clean_name(&f.name)));
191        }
192        if f.size == 0 {
193            return Err(format!("{}: empty file", f.name));
194        }
195    }
196    Ok(())
197}
198
199/// Lowercase hex SHA-256 over the label and the entries, in order (§3.2).
200pub fn manifest_digest(files: &[JektFile]) -> String {
201    let mut input = String::from(DIGEST_LABEL);
202    for f in files {
203        input.push(ENTRY_SEP);
204        input.push_str(&f.sha256);
205        input.push(FIELD_SEP);
206        input.push_str(&f.name);
207        input.push(FIELD_SEP);
208        input.push_str(&f.size.to_string());
209    }
210    format!("{:x}", Sha256::digest(input.as_bytes()))
211}
212
213/// The msgid for a jekt carrying `files`: `base` with the digest appended.
214pub fn bind_msgid(base: &str, files: &[JektFile]) -> String {
215    format!("{base}{MSGID_TAG}{}", manifest_digest(files))
216}
217
218/// The digest a msgid says its jekt was sent with, if it says one.
219pub fn bound_digest(msgid: &str) -> Option<&str> {
220    let at = msgid.rfind(MSGID_TAG)?;
221    let digest = &msgid[at + MSGID_TAG.len()..];
222    (digest.len() == 64 && digest.bytes().all(|b| b.is_ascii_hexdigit())).then_some(digest)
223}
224
225/// Whether `msgid` binds exactly this manifest.
226pub fn msgid_binds(msgid: &str, files: &[JektFile]) -> bool {
227    bound_digest(msgid).is_some_and(|d| d == manifest_digest(files))
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    fn file(n: u8, name: &str, size: u64) -> JektFile {
235        JektFile { sha256: format!("{:x}", Sha256::digest([n])), name: name.to_string(), size }
236    }
237
238    #[test]
239    fn binding_round_trips() {
240        let files = vec![file(1, "a.png", 10), file(2, "b.txt", 20)];
241        let msgid = bind_msgid("1792-42-0", &files);
242        assert!(msgid.starts_with("1792-42-0.files-v1."));
243        assert!(msgid_binds(&msgid, &files));
244    }
245
246    #[test]
247    fn any_change_to_the_manifest_breaks_the_binding() {
248        let files = vec![file(1, "a.png", 10), file(2, "b.txt", 20)];
249        let msgid = bind_msgid("m", &files);
250        let mut renamed = files.clone();
251        renamed[0].name = "c.png".into();
252        let mut resized = files.clone();
253        resized[1].size = 21;
254        let mut swapped = files.clone();
255        swapped[0].sha256 = file(3, "", 0).sha256;
256        let reordered = vec![files[1].clone(), files[0].clone()];
257        for other in [renamed, resized, swapped, reordered, files[..1].to_vec()] {
258            assert!(!msgid_binds(&msgid, &other), "{other:?}");
259        }
260    }
261
262    #[test]
263    fn entry_fields_cannot_shift_into_each_other() {
264        // A separator inside a name would let two manifests share a digest.
265        let a = vec![JektFile { sha256: "a".repeat(64), name: "x".into(), size: 1 }];
266        let b = vec![JektFile { sha256: "a".repeat(64), name: "x\u{1}1".into(), size: 1 }];
267        assert_ne!(manifest_digest(&a), manifest_digest(&b));
268        assert!(validate(&b).is_err(), "control characters never reach a manifest");
269    }
270
271    #[test]
272    fn a_text_msgid_binds_nothing() {
273        for msgid in ["1792-42-0", "", "abc.files-v1.", "abc.files-v1.zz", &format!("x.files-v1.{}", "g".repeat(64))] {
274            assert_eq!(bound_digest(msgid), None, "{msgid}");
275        }
276    }
277
278    #[test]
279    fn clean_name_keeps_only_a_short_base_name() {
280        assert_eq!(clean_name("C:\\shots\\a.png"), "a.png");
281        assert_eq!(clean_name("../../etc/passwd"), "passwd");
282        assert_eq!(clean_name("a\nb\u{7}.txt"), "a b .txt");
283        assert_eq!(clean_name("dir/"), "file");
284        assert_eq!(clean_name(".."), "file");
285        assert_eq!(clean_name(&"n".repeat(300)).chars().count(), MAX_NAME_CHARS);
286    }
287
288    fn cloud(n: u8) -> CloudFile {
289        CloudFile {
290            file: file(n, "a.png", 10),
291            key: "A".repeat(43) + "=",
292            blob_id: "blob-0123abcd-0000-4000-8000-0123456789ab".into(),
293        }
294    }
295
296    #[test]
297    fn a_cloud_manifest_binds_its_keys_and_blob_ids() {
298        let files = vec![cloud(1)];
299        let msgid = bind_cloud_msgid(&bind_msgid("m-1", &[cloud(1).file]), &files);
300        assert!(msgid.starts_with("m-1.files-v1."), "the plain digest is replaced, not stacked: {msgid}");
301        assert!(cloud_msgid_binds(&msgid, &files));
302        let mut other_key = files.clone();
303        other_key[0].key = "B".repeat(43) + "=";
304        let mut other_blob = files.clone();
305        other_blob[0].blob_id = "blob-ffffffff-0000-4000-8000-0123456789ab".into();
306        assert!(!cloud_msgid_binds(&msgid, &other_key));
307        assert!(!cloud_msgid_binds(&msgid, &other_blob));
308        assert!(!msgid_binds(&msgid, &[cloud(1).file]), "a plain manifest never matches a cloud digest");
309        assert!(validate_cloud(&files).is_ok());
310        let mut bad = files.clone();
311        bad[0].key = "short".into();
312        assert!(validate_cloud(&bad).is_err());
313    }
314
315    #[test]
316    fn a_sealed_key_passes_only_in_its_exact_shape() {
317        let sealed = format!("{SEALED_KEY_PREFIX}{}.{}", "F_-".repeat(14) + "x", "g".repeat(SEALED_KEY_BODY_CHARS));
318        assert!(is_sealed_key(&sealed));
319        let mut files = vec![cloud(1)];
320        files[0].key = sealed.clone();
321        assert!(validate_cloud(&files).is_ok());
322        for bad in [
323            sealed[..sealed.len() - 1].to_string(),
324            sealed.replace("x25519.", "x448."),
325            format!("{sealed}="),
326            sealed.replacen('g', "+", 1),
327            sealed.replacen('_', ".", 1),
328        ] {
329            assert!(!is_sealed_key(&bad), "{bad}");
330            files[0].key = bad;
331            assert!(validate_cloud(&files).is_err());
332        }
333    }
334
335    #[test]
336    fn tier_limits_are_tighter_further_away() {
337        let f = |size| JektFile { sha256: "a".repeat(64), name: "a".into(), size };
338        assert!(check_tier_limits(&[f(100 * MIB)], "channel").is_ok());
339        assert!(check_tier_limits(&[f(100 * MIB)], "lan").is_err());
340        assert!(check_tier_limits(&[f(40 * MIB), f(40 * MIB), f(40 * MIB)], "lan").is_err(), "per jekt");
341        assert!(check_tier_limits(&[f(30 * MIB)], "wan").is_err(), "cloud is tightest");
342        assert!(check_tier_limits(&[f(1)], "elsewhere").is_err());
343    }
344
345    #[test]
346    fn a_manifest_over_a_tiers_limit_is_refused_with_the_limit_in_the_message() {
347        let f = |size| JektFile { sha256: "a".repeat(64), name: "big.bin".into(), size };
348        assert!(validate_for_tier(&[f(100 * MIB)], "host").is_ok());
349        let per_file = validate_for_tier(&[f(100 * MIB + 1)], "host").unwrap_err();
350        assert!(per_file.contains("big.bin") && per_file.contains("100 MB limit per file on this machine"), "{per_file}");
351        let lan = validate_for_tier(&[f(51 * MIB)], "lan").unwrap_err();
352        assert!(lan.contains("50 MB limit per file to another computer on the LAN"), "{lan}");
353        let total = validate_for_tier(&[f(25 * MIB), f(25 * MIB), f(1)], "wan").unwrap_err();
354        assert!(total.contains("50 MB limit per message through the cloud relay"), "{total}");
355        assert!(validate_for_tier(&[f(0)], "host").is_err(), "the plain checks still apply");
356    }
357
358    #[test]
359    fn sizes_that_would_wrap_a_sum_still_go_over_the_limit() {
360        let f = |size| JektFile { sha256: "a".repeat(64), name: "a".into(), size };
361        assert!(check_tier_limits(&[f(u64::MAX), f(2)], "host").is_err());
362        assert!(check_tier_limits(&vec![f(100 * MIB); 3], "host").is_err(), "per message on this machine");
363    }
364
365    #[test]
366    fn a_cloud_manifest_over_the_relays_limits_is_refused() {
367        let mut files = vec![cloud(1)];
368        files[0].file.size = 26 * MIB;
369        assert!(validate_cloud(&files).unwrap_err().contains("25 MB limit per file through the cloud relay"));
370    }
371
372    #[test]
373    fn validate_refuses_bad_manifests() {
374        assert!(validate(&[]).is_err());
375        assert!(validate(&vec![file(1, "a", 1); MAX_FILES + 1]).is_err());
376        assert!(validate(&[JektFile { sha256: "A".repeat(64), name: "a".into(), size: 1 }]).is_err());
377        assert!(validate(&[file(1, "dir/a", 1)]).is_err());
378        assert!(validate(&[file(1, "a", 0)]).is_err());
379        assert!(validate(&[file(1, "a.png", 1)]).is_ok());
380    }
381}