mesh-llm-client 0.64.0

Low-level Rust client implementation for Mesh LLM embedded integrations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use crypto_box::aead::{Aead, AeadCore, OsRng as CryptoOsRng};
use crypto_box::SalsaBox;
use ed25519_dalek::{Signer, Verifier};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use super::error::CryptoError;
use super::keys::OwnerKeypair;

/// A signed-then-encrypted envelope for confidential control messages.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SignedEncryptedEnvelope {
    pub version: u32,
    pub sender_owner_id: String,
    pub sender_sign_public_key: String,
    pub sender_box_public_key: String,
    pub recipient_box_public_key: String,
    pub message_type: String,
    pub timestamp_unix_ms: u64,
    pub nonce: String,
    pub ciphertext: String,
}

/// The decrypted and verified message contents.
#[derive(Debug)]
pub struct OpenedMessage {
    pub sender_owner_id: String,
    pub sender_sign_public_key: [u8; 32],
    pub sender_box_public_key: [u8; 32],
    pub message_type: String,
    pub timestamp_unix_ms: u64,
    pub payload: Vec<u8>,
}

/// Inner plaintext: payload + detached signature.
#[derive(Serialize, Deserialize)]
struct InnerPayload {
    payload: Vec<u8>,
    signature: Vec<u8>,
}

/// Build the canonical bytes that get signed.
///
/// Includes all metadata fields + a hash of the payload to bind the signature
/// to both the envelope context and the message content.
fn canonical_signed_bytes(
    version: u32,
    sender_owner_id: &str,
    sender_box_public_key: &[u8],
    recipient_box_public_key: &[u8],
    message_type: &str,
    timestamp_unix_ms: u64,
    payload: &[u8],
) -> Vec<u8> {
    let mut buf = Vec::new();
    let sender_owner_id_bytes = sender_owner_id.as_bytes();
    let message_type_bytes = message_type.as_bytes();

    // Domain separation tag to prevent cross-protocol signature reuse.
    buf.extend_from_slice(b"mesh-llm-envelope-v1:");
    buf.extend_from_slice(&version.to_le_bytes());
    buf.extend_from_slice(&(sender_owner_id_bytes.len() as u64).to_le_bytes());
    buf.extend_from_slice(sender_owner_id_bytes);
    buf.extend_from_slice(sender_box_public_key);
    buf.extend_from_slice(recipient_box_public_key);
    buf.extend_from_slice(&(message_type_bytes.len() as u64).to_le_bytes());
    buf.extend_from_slice(message_type_bytes);
    buf.extend_from_slice(&timestamp_unix_ms.to_le_bytes());
    // Include a hash of the payload rather than the raw payload to keep
    // the signed data compact for large payloads.
    let payload_hash = Sha256::digest(payload);
    buf.extend_from_slice(&payload_hash);
    buf
}

/// Sign and encrypt a message for a specific recipient.
pub fn seal_message(
    sender: &OwnerKeypair,
    recipient_box_public_key: &crypto_box::PublicKey,
    message_type: &str,
    payload: &[u8],
    timestamp_unix_ms: u64,
) -> Result<SignedEncryptedEnvelope, CryptoError> {
    let version = 1u32;
    let sender_owner_id = sender.owner_id();
    let sender_box_pk = sender.encryption_public_key();

    // 1. Build canonical bytes and sign.
    let signed_bytes = canonical_signed_bytes(
        version,
        &sender_owner_id,
        sender_box_pk.as_bytes(),
        recipient_box_public_key.as_bytes(),
        message_type,
        timestamp_unix_ms,
        payload,
    );
    let signature = sender.signing.sign(&signed_bytes);

    // 2. Build inner payload with detached signature.
    let inner = InnerPayload {
        payload: payload.to_vec(),
        signature: signature.to_bytes().to_vec(),
    };
    let inner_bytes = serde_json::to_vec(&inner)?;

    // 3. Encrypt with crypto_box (XSalsa20Poly1305).
    let salsa_box = SalsaBox::new(recipient_box_public_key, &sender.encryption);
    let nonce = SalsaBox::generate_nonce(&mut CryptoOsRng);
    let ct = salsa_box
        .encrypt(&nonce, inner_bytes.as_ref())
        .map_err(|_| CryptoError::VerificationFailed {
            reason: "encryption failed".into(),
        })?;

    Ok(SignedEncryptedEnvelope {
        version,
        sender_owner_id,
        sender_sign_public_key: hex::encode(sender.verifying_key().as_bytes()),
        sender_box_public_key: hex::encode(sender_box_pk.as_bytes()),
        recipient_box_public_key: hex::encode(recipient_box_public_key.as_bytes()),
        message_type: message_type.to_string(),
        timestamp_unix_ms,
        nonce: hex::encode(nonce),
        ciphertext: hex::encode(ct),
    })
}

/// Decrypt and verify an envelope addressed to this recipient.
pub fn open_message(
    recipient: &OwnerKeypair,
    envelope: &SignedEncryptedEnvelope,
) -> Result<OpenedMessage, CryptoError> {
    // 0. Reject unknown envelope versions.
    if envelope.version != 1 {
        return Err(CryptoError::VerificationFailed {
            reason: format!("unsupported envelope version: {}", envelope.version),
        });
    }

    // 1. Parse sender public keys.
    let sender_sign_pk_bytes: [u8; 32] = hex::decode(&envelope.sender_sign_public_key)
        .map_err(|_| CryptoError::InvalidKeyMaterial {
            reason: "bad sender signing key hex".into(),
        })?
        .try_into()
        .map_err(|_| CryptoError::InvalidKeyMaterial {
            reason: "sender signing key must be 32 bytes".into(),
        })?;

    let sender_box_pk_bytes: [u8; 32] = hex::decode(&envelope.sender_box_public_key)
        .map_err(|_| CryptoError::InvalidKeyMaterial {
            reason: "bad sender box key hex".into(),
        })?
        .try_into()
        .map_err(|_| CryptoError::InvalidKeyMaterial {
            reason: "sender box key must be 32 bytes".into(),
        })?;

    let recipient_box_pk_bytes: [u8; 32] = hex::decode(&envelope.recipient_box_public_key)
        .map_err(|_| CryptoError::InvalidKeyMaterial {
            reason: "bad recipient box key hex".into(),
        })?
        .try_into()
        .map_err(|_| CryptoError::InvalidKeyMaterial {
            reason: "recipient box key must be 32 bytes".into(),
        })?;

    let sender_box_pk = crypto_box::PublicKey::from(sender_box_pk_bytes);

    // 2. Verify that the envelope's claimed recipient key matches the actual recipient.
    // This prevents an attacker from encrypting to the correct recipient while claiming
    // a different recipient in the signed metadata.
    let actual_recipient_box_pk_bytes = *recipient.encryption_public_key().as_bytes();
    if recipient_box_pk_bytes != actual_recipient_box_pk_bytes {
        return Err(CryptoError::VerificationFailed {
            reason: "recipient_box_public_key does not match recipient encryption public key"
                .into(),
        });
    }

    // 3. Verify sender_owner_id matches the signing key (prevents identity spoofing).
    let sender_verifying_key = ed25519_dalek::VerifyingKey::from_bytes(&sender_sign_pk_bytes)
        .map_err(|_| CryptoError::InvalidSignature)?;
    let expected_owner_id = super::keys::owner_id_from_verifying_key(&sender_verifying_key);
    if envelope.sender_owner_id != expected_owner_id {
        return Err(CryptoError::VerificationFailed {
            reason: "sender_owner_id does not match signing public key".into(),
        });
    }

    // 4. Decrypt.
    let nonce_bytes = hex::decode(&envelope.nonce).map_err(|_| CryptoError::DecryptionFailed)?;
    if nonce_bytes.len() != 24 {
        return Err(CryptoError::DecryptionFailed);
    }
    let nonce = crypto_box::Nonce::from_slice(&nonce_bytes);
    let ct = hex::decode(&envelope.ciphertext).map_err(|_| CryptoError::DecryptionFailed)?;

    let salsa_box = SalsaBox::new(&sender_box_pk, &recipient.encryption);
    let inner_bytes = salsa_box
        .decrypt(nonce, ct.as_ref())
        .map_err(|_| CryptoError::DecryptionFailed)?;

    // 5. Parse inner payload.
    let inner: InnerPayload =
        serde_json::from_slice(&inner_bytes).map_err(|_| CryptoError::DecryptionFailed)?;

    // 6. Verify signature.
    let signed_bytes = canonical_signed_bytes(
        envelope.version,
        &envelope.sender_owner_id,
        &sender_box_pk_bytes,
        &recipient_box_pk_bytes,
        &envelope.message_type,
        envelope.timestamp_unix_ms,
        &inner.payload,
    );

    let sig_bytes: [u8; 64] = inner
        .signature
        .try_into()
        .map_err(|_| CryptoError::InvalidSignature)?;
    let signature = ed25519_dalek::Signature::from_bytes(&sig_bytes);

    sender_verifying_key
        .verify(&signed_bytes, &signature)
        .map_err(|_| CryptoError::InvalidSignature)?;

    Ok(OpenedMessage {
        sender_owner_id: expected_owner_id,
        sender_sign_public_key: sender_sign_pk_bytes,
        sender_box_public_key: sender_box_pk_bytes,
        message_type: envelope.message_type.clone(),
        timestamp_unix_ms: envelope.timestamp_unix_ms,
        payload: inner.payload,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn seal_open_round_trip() {
        let sender = OwnerKeypair::generate();
        let recipient = OwnerKeypair::generate();

        let payload = b"hello, mesh-llm!";
        let timestamp = 1_700_000_000_000u64;

        let envelope = seal_message(
            &sender,
            &recipient.encryption_public_key(),
            "test.message",
            payload,
            timestamp,
        )
        .unwrap();

        let opened = open_message(&recipient, &envelope).unwrap();
        assert_eq!(opened.payload, payload);
        assert_eq!(opened.message_type, "test.message");
        assert_eq!(opened.timestamp_unix_ms, timestamp);
        assert_eq!(opened.sender_owner_id, sender.owner_id());
    }

    #[test]
    fn wrong_recipient_cannot_decrypt() {
        let sender = OwnerKeypair::generate();
        let recipient = OwnerKeypair::generate();
        let wrong_recipient = OwnerKeypair::generate();

        let envelope = seal_message(
            &sender,
            &recipient.encryption_public_key(),
            "secret",
            b"classified",
            0,
        )
        .unwrap();

        let result = open_message(&wrong_recipient, &envelope);
        assert!(result.is_err(), "wrong recipient should fail to decrypt");
    }

    #[test]
    fn tampered_ciphertext_fails() {
        let sender = OwnerKeypair::generate();
        let recipient = OwnerKeypair::generate();

        let mut envelope = seal_message(
            &sender,
            &recipient.encryption_public_key(),
            "test",
            b"payload",
            0,
        )
        .unwrap();

        // Flip a byte in the ciphertext.
        let mut ct_bytes = hex::decode(&envelope.ciphertext).unwrap();
        if let Some(byte) = ct_bytes.last_mut() {
            *byte ^= 0xff;
        }
        envelope.ciphertext = hex::encode(&ct_bytes);

        let result = open_message(&recipient, &envelope);
        assert!(result.is_err(), "tampered ciphertext should fail");
    }

    #[test]
    fn spoofed_owner_id_rejected() {
        let sender = OwnerKeypair::generate();
        let recipient = OwnerKeypair::generate();

        let mut envelope = seal_message(
            &sender,
            &recipient.encryption_public_key(),
            "test",
            b"payload",
            0,
        )
        .unwrap();

        // Spoof the owner_id to a different value.
        envelope.sender_owner_id =
            "0000000000000000000000000000000000000000000000000000000000000000".into();

        let result = open_message(&recipient, &envelope);
        assert!(
            matches!(result, Err(CryptoError::VerificationFailed { .. })),
            "spoofed owner_id should be rejected"
        );
    }

    #[test]
    fn unknown_envelope_version_rejected() {
        let sender = OwnerKeypair::generate();
        let recipient = OwnerKeypair::generate();

        let mut envelope = seal_message(
            &sender,
            &recipient.encryption_public_key(),
            "test",
            b"payload",
            0,
        )
        .unwrap();

        envelope.version = 99;

        let result = open_message(&recipient, &envelope);
        assert!(
            matches!(result, Err(CryptoError::VerificationFailed { .. })),
            "unknown version should be rejected"
        );
    }

    #[test]
    fn mismatched_recipient_key_rejected() {
        let sender = OwnerKeypair::generate();
        let recipient = OwnerKeypair::generate();

        let mut envelope = seal_message(
            &sender,
            &recipient.encryption_public_key(),
            "test",
            b"payload",
            0,
        )
        .unwrap();

        // Claim a different recipient key in the envelope metadata.
        let other = OwnerKeypair::generate();
        envelope.recipient_box_public_key = hex::encode(other.encryption_public_key().as_bytes());

        let result = open_message(&recipient, &envelope);
        assert!(
            matches!(result, Err(CryptoError::VerificationFailed { .. })),
            "mismatched recipient key should be rejected"
        );
    }

    #[test]
    fn canonical_bytes_length_prefix_variable_fields() {
        let sender_box_key = [7u8; 32];
        let recipient_box_key = [9u8; 32];

        let left = canonical_signed_bytes(
            1,
            "ab",
            &sender_box_key,
            &recipient_box_key,
            "c",
            42,
            b"payload",
        );
        let right = canonical_signed_bytes(
            1,
            "a",
            &sender_box_key,
            &recipient_box_key,
            "bc",
            42,
            b"payload",
        );

        assert_ne!(left, right, "variable-length fields must be unambiguous");
    }
}