exochain-messaging 0.2.0-beta

EXOCHAIN constitutional trust fabric — end-to-end encrypted messaging with X25519 key exchange
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Compose & Lock — sender-side message encryption.
//!
//! Requires caller-supplied ephemeral X25519 key material, performs ECDH with
//! the recipient's public key, derives a symmetric key via HKDF, encrypts the
//! plaintext with XChaCha20-Poly1305, and signs the envelope with the sender's
//! Ed25519 key.

use exo_core::{Did, PublicKey, SecretKey, Signature, Timestamp};
use exo_identity::vault::{VAULT_NONCE_SIZE, VaultEncryptor};
use hkdf::Hkdf;
use sha2::Sha256;
use uuid::Uuid;

use crate::{
    envelope::{ContentType, EncryptedEnvelope, KDF_VERSION_TRANSCRIPT_SALTED},
    error::MessagingError,
    kex::{self, X25519KeyPair, X25519PublicKey},
};

/// The HKDF context string for message encryption key derivation.
const MESSAGE_KEX_CONTEXT: &[u8] = b"vitallock-message-v1";
const MESSAGE_VAULT_NONCE_DOMAIN: &[u8] = b"exo.messaging.vault-nonce.v1";

/// Caller-supplied provenance metadata for an encrypted envelope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ComposeMetadata {
    /// Unique message ID assigned by the caller's deterministic boundary.
    id: Uuid,
    /// Non-zero HLC timestamp assigned by the caller's deterministic boundary.
    created: Timestamp,
}

impl ComposeMetadata {
    /// Validate caller-supplied envelope metadata.
    pub fn new(id: Uuid, created: Timestamp) -> Result<Self, MessagingError> {
        let metadata = Self { id, created };
        metadata.validate()?;
        Ok(metadata)
    }

    /// Return the validated message ID.
    #[must_use]
    pub fn id(&self) -> Uuid {
        self.id
    }

    /// Return the validated message creation timestamp.
    #[must_use]
    pub fn created(&self) -> Timestamp {
        self.created
    }

    fn validate(&self) -> Result<(), MessagingError> {
        if self.id.is_nil() {
            return Err(MessagingError::InvalidEnvelope(
                "message id must be caller-supplied and non-nil".into(),
            ));
        }
        if self.created == Timestamp::ZERO {
            return Err(MessagingError::InvalidEnvelope(
                "message timestamp must be caller-supplied and non-zero".into(),
            ));
        }
        Ok(())
    }
}

/// Legacy Lock & Send entrypoint.
///
/// This fails closed because EXOCHAIN message composition must not fabricate
/// X25519 key material internally. Use [`lock_and_send_with_ephemeral`] with a
/// caller-supplied one-time X25519 keypair.
///
/// # Arguments
///
/// * `plaintext` — The message content to encrypt.
/// * `content_type` — Classification of the message content.
/// * `sender_did` — The sender's DID.
/// * `recipient_did` — The recipient's DID.
/// * `sender_signing_key` — The sender's Ed25519 secret key for signing.
/// * `recipient_x25519_public` — The recipient's X25519 public key.
/// * `metadata` — Caller-supplied non-nil ID and non-zero HLC timestamp.
/// * `release_on_death` — Whether to release after sender's death.
/// * `release_delay_hours` — Hours to wait after death verification.
///
/// # Returns
///
/// A fail-closed error directing callers to the explicit ephemeral-key API.
#[allow(clippy::too_many_arguments)]
// 8 args is the minimum for a sender→recipient envelope with
// death-trigger semantics: plaintext + content_type + sender DID +
// recipient DID + sender key + recipient pubkey + release_on_death +
// release_delay_hours. Grouping into a struct would add boilerplate
// for every single call site with zero safety benefit — every field
// is semantically required and independently typed.
pub fn lock_and_send(
    plaintext: &[u8],
    content_type: ContentType,
    sender_did: &Did,
    recipient_did: &Did,
    sender_signing_key: &SecretKey,
    recipient_x25519_public: &X25519PublicKey,
    metadata: ComposeMetadata,
    release_on_death: bool,
    release_delay_hours: u32,
) -> Result<EncryptedEnvelope, MessagingError> {
    let _ = (
        plaintext,
        content_type,
        sender_did,
        recipient_did,
        sender_signing_key,
        recipient_x25519_public,
        metadata,
        release_on_death,
        release_delay_hours,
    );
    Err(caller_supplied_ephemeral_required())
}

/// Lock & Send with caller-supplied X25519 ephemeral key material.
#[allow(clippy::too_many_arguments)]
pub fn lock_and_send_with_ephemeral(
    plaintext: &[u8],
    content_type: ContentType,
    sender_did: &Did,
    recipient_did: &Did,
    sender_signing_key: &SecretKey,
    recipient_x25519_public: &X25519PublicKey,
    ephemeral_x25519_keypair: &X25519KeyPair,
    metadata: ComposeMetadata,
    release_on_death: bool,
    release_delay_hours: u32,
) -> Result<EncryptedEnvelope, MessagingError> {
    let envelope = prepare_envelope_for_signing_with_ephemeral(
        plaintext,
        content_type,
        sender_did,
        recipient_did,
        recipient_x25519_public,
        ephemeral_x25519_keypair,
        metadata,
        release_on_death,
        release_delay_hours,
    )?;
    sign_prepared_envelope(envelope, sender_signing_key)
}

/// Legacy unsigned-envelope entrypoint.
///
/// This fails closed because EXOCHAIN message composition must not fabricate
/// X25519 key material internally. Use
/// [`prepare_envelope_for_signing_with_ephemeral`] with a caller-supplied
/// one-time X25519 keypair.
#[allow(clippy::too_many_arguments)]
pub fn prepare_envelope_for_signing(
    plaintext: &[u8],
    content_type: ContentType,
    sender_did: &Did,
    recipient_did: &Did,
    recipient_x25519_public: &X25519PublicKey,
    metadata: ComposeMetadata,
    release_on_death: bool,
    release_delay_hours: u32,
) -> Result<EncryptedEnvelope, MessagingError> {
    let _ = (
        plaintext,
        content_type,
        sender_did,
        recipient_did,
        recipient_x25519_public,
        metadata,
        release_on_death,
        release_delay_hours,
    );
    Err(caller_supplied_ephemeral_required())
}

/// Encrypt a message with caller-supplied X25519 ephemeral key material and
/// return the unsigned envelope whose signing payload can be signed externally.
#[allow(clippy::too_many_arguments)]
pub fn prepare_envelope_for_signing_with_ephemeral(
    plaintext: &[u8],
    content_type: ContentType,
    sender_did: &Did,
    recipient_did: &Did,
    recipient_x25519_public: &X25519PublicKey,
    ephemeral_x25519_keypair: &X25519KeyPair,
    metadata: ComposeMetadata,
    release_on_death: bool,
    release_delay_hours: u32,
) -> Result<EncryptedEnvelope, MessagingError> {
    metadata.validate()?;

    // 1. ECDH: derive shared symmetric key using caller-supplied ephemeral key.
    let shared_key = kex::derive_shared_key(
        &ephemeral_x25519_keypair.secret,
        recipient_x25519_public,
        MESSAGE_KEX_CONTEXT,
    )?;

    let nonce = derive_vault_nonce(
        &shared_key,
        &metadata,
        content_type,
        sender_did,
        recipient_did,
        ephemeral_x25519_keypair.public.as_bytes(),
        release_on_death,
        release_delay_hours,
    )?;

    // 3. Encrypt plaintext with XChaCha20-Poly1305
    //    Associated data = recipient DID (binds ciphertext to intended recipient)
    let encryptor = VaultEncryptor::from_key(shared_key);
    let ciphertext = encryptor
        .encrypt_with_nonce(plaintext, recipient_did.as_str().as_bytes(), &nonce)
        .map_err(|e| MessagingError::EncryptionFailed(e.to_string()))?;

    // 4. Build envelope (without signature first)
    let envelope = EncryptedEnvelope {
        id: metadata.id.to_string(),
        sender_did: sender_did.clone(),
        recipient_did: recipient_did.clone(),
        ephemeral_public_key: *ephemeral_x25519_keypair.public.as_bytes(),
        kdf_version: Some(KDF_VERSION_TRANSCRIPT_SALTED),
        ciphertext,
        content_type,
        signature: exo_core::Signature::empty(),
        release_on_death,
        release_delay_hours,
        created: metadata.created,
    };

    Ok(envelope)
}

fn caller_supplied_ephemeral_required() -> MessagingError {
    MessagingError::KeyExchangeFailed(
        "message composition requires caller-supplied ephemeral X25519 keypair".to_owned(),
    )
}

#[allow(clippy::too_many_arguments)]
fn derive_vault_nonce(
    shared_key: &[u8; 32],
    metadata: &ComposeMetadata,
    content_type: ContentType,
    sender_did: &Did,
    recipient_did: &Did,
    ephemeral_public_key: &[u8; 32],
    release_on_death: bool,
    release_delay_hours: u32,
) -> Result<[u8; VAULT_NONCE_SIZE], MessagingError> {
    let mut transcript = Vec::new();
    append_len_prefixed(&mut transcript, "id", metadata.id.as_bytes())?;
    transcript.extend_from_slice(&metadata.created.physical_ms.to_le_bytes());
    transcript.extend_from_slice(&metadata.created.logical.to_le_bytes());
    append_len_prefixed(
        &mut transcript,
        "sender_did",
        sender_did.as_str().as_bytes(),
    )?;
    append_len_prefixed(
        &mut transcript,
        "recipient_did",
        recipient_did.as_str().as_bytes(),
    )?;
    transcript.extend_from_slice(ephemeral_public_key);
    transcript.push(u8::from(content_type));
    transcript.push(u8::from(release_on_death));
    transcript.extend_from_slice(&release_delay_hours.to_le_bytes());

    let hk = Hkdf::<Sha256>::new(Some(MESSAGE_VAULT_NONCE_DOMAIN), shared_key);
    let mut nonce = [0u8; VAULT_NONCE_SIZE];
    hk.expand(&transcript, &mut nonce)
        .map_err(|e| MessagingError::EncryptionFailed(e.to_string()))?;
    Ok(nonce)
}

fn append_len_prefixed(
    transcript: &mut Vec<u8>,
    label: &'static str,
    value: &[u8],
) -> Result<(), MessagingError> {
    transcript.extend_from_slice(label.as_bytes());
    let len = u64::try_from(value.len())
        .map_err(|_| MessagingError::InvalidEnvelope(format!("{label} length exceeds u64::MAX")))?;
    transcript.extend_from_slice(&len.to_le_bytes());
    transcript.extend_from_slice(value);
    Ok(())
}

/// Sign a prepared envelope with an in-process Ed25519 secret key.
pub fn sign_prepared_envelope(
    mut envelope: EncryptedEnvelope,
    sender_signing_key: &SecretKey,
) -> Result<EncryptedEnvelope, MessagingError> {
    let signable = envelope.signing_payload()?;
    let signature = exo_core::crypto::sign(&signable, sender_signing_key);
    envelope.signature = signature;

    Ok(envelope)
}

/// Attach and verify a caller-produced Ed25519 signature to a prepared envelope.
pub fn attach_verified_signature(
    mut envelope: EncryptedEnvelope,
    signature: Signature,
    sender_public_key: &PublicKey,
) -> Result<EncryptedEnvelope, MessagingError> {
    if signature.is_empty() {
        return Err(MessagingError::SignatureVerificationFailed);
    }

    let signable = envelope.signing_payload()?;
    if !exo_core::crypto::verify(&signable, &signature, sender_public_key) {
        return Err(MessagingError::SignatureVerificationFailed);
    }
    envelope.signature = signature;
    Ok(envelope)
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use exo_core::{Hash256, Timestamp, crypto::generate_keypair};
    use uuid::Uuid;

    use super::*;

    fn metadata() -> ComposeMetadata {
        ComposeMetadata::new(
            Uuid::parse_str("018f7a96-8ad0-7c4f-8e0f-111111111111").unwrap(),
            Timestamp::new(7_000, 2),
        )
        .expect("valid compose metadata")
    }

    fn x25519_keypair(seed: u8) -> kex::X25519KeyPair {
        kex::X25519KeyPair::from_secret_bytes([seed; 32])
            .expect("valid deterministic X25519 keypair")
    }

    #[allow(clippy::too_many_arguments)]
    fn legacy_public_plaintext_hash_nonce(
        metadata: &ComposeMetadata,
        content_type: ContentType,
        sender_did: &Did,
        recipient_did: &Did,
        ephemeral_public_key: &[u8; 32],
        plaintext: &[u8],
        release_on_death: bool,
        release_delay_hours: u32,
    ) -> [u8; VAULT_NONCE_SIZE] {
        let plaintext_nonce_input = Hash256::digest(plaintext);
        let mut transcript = Vec::new();
        transcript.extend_from_slice(MESSAGE_VAULT_NONCE_DOMAIN);
        append_len_prefixed(&mut transcript, "id", metadata.id.as_bytes())
            .expect("append id to legacy nonce transcript");
        transcript.extend_from_slice(&metadata.created.physical_ms.to_le_bytes());
        transcript.extend_from_slice(&metadata.created.logical.to_le_bytes());
        append_len_prefixed(
            &mut transcript,
            "sender_did",
            sender_did.as_str().as_bytes(),
        )
        .expect("append sender did to legacy nonce transcript");
        append_len_prefixed(
            &mut transcript,
            "recipient_did",
            recipient_did.as_str().as_bytes(),
        )
        .expect("append recipient did to legacy nonce transcript");
        transcript.extend_from_slice(ephemeral_public_key);
        transcript.extend_from_slice(plaintext_nonce_input.as_bytes());
        transcript.push(u8::from(content_type));
        transcript.push(u8::from(release_on_death));
        transcript.extend_from_slice(&release_delay_hours.to_le_bytes());

        let digest = Hash256::digest(&transcript);
        let mut nonce = [0u8; VAULT_NONCE_SIZE];
        nonce.copy_from_slice(&digest.as_bytes()[..VAULT_NONCE_SIZE]);
        nonce
    }

    #[test]
    fn lock_and_send_produces_valid_envelope() {
        let sender_did = Did::new("did:exo:alice").unwrap();
        let recipient_did = Did::new("did:exo:bob").unwrap();
        let (_, sender_sk) = generate_keypair();
        let recipient_kp = x25519_keypair(0x21);
        let ephemeral_kp = x25519_keypair(0x31);
        let metadata = metadata();

        let envelope = lock_and_send_with_ephemeral(
            b"my secret password: hunter2",
            ContentType::Password,
            &sender_did,
            &recipient_did,
            &sender_sk,
            &recipient_kp.public,
            &ephemeral_kp,
            metadata,
            false,
            0,
        )
        .expect("lock_and_send");

        assert_eq!(
            envelope.id,
            "018f7a96-8ad0-7c4f-8e0f-111111111111".to_string()
        );
        assert_eq!(envelope.created, Timestamp::new(7_000, 2));
        assert_eq!(envelope.sender_did, sender_did);
        assert_eq!(envelope.recipient_did, recipient_did);
        assert_eq!(envelope.content_type, ContentType::Password);
        assert!(!envelope.ciphertext.is_empty());
        assert!(!envelope.release_on_death);
        assert_ne!(envelope.signature, exo_core::Signature::empty());
    }

    #[test]
    fn prepare_envelope_for_signing_returns_canonical_payload_without_signature() {
        let sender_did = Did::new("did:exo:alice").unwrap();
        let recipient_did = Did::new("did:exo:bob").unwrap();
        let recipient_kp = x25519_keypair(0x22);
        let ephemeral_kp = x25519_keypair(0x32);

        let envelope = prepare_envelope_for_signing_with_ephemeral(
            b"external signer",
            ContentType::Secret,
            &sender_did,
            &recipient_did,
            &recipient_kp.public,
            &ephemeral_kp,
            metadata(),
            false,
            0,
        )
        .expect("prepare envelope");

        assert_eq!(envelope.signature, exo_core::Signature::empty());
        assert!(
            !envelope
                .signing_payload()
                .expect("signing payload")
                .is_empty(),
            "prepared envelopes must expose canonical bytes for external signing"
        );
    }

    #[test]
    fn attach_verified_signature_accepts_external_signature() {
        let sender_did = Did::new("did:exo:alice").unwrap();
        let recipient_did = Did::new("did:exo:bob").unwrap();
        let (sender_pk, sender_sk) = generate_keypair();
        let recipient_kp = x25519_keypair(0x23);
        let ephemeral_kp = x25519_keypair(0x33);

        let envelope = prepare_envelope_for_signing_with_ephemeral(
            b"external signer",
            ContentType::Secret,
            &sender_did,
            &recipient_did,
            &recipient_kp.public,
            &ephemeral_kp,
            metadata(),
            false,
            0,
        )
        .expect("prepare envelope");
        let signature = exo_core::crypto::sign(
            &envelope.signing_payload().expect("signing payload"),
            &sender_sk,
        );

        let signed =
            attach_verified_signature(envelope, signature, &sender_pk).expect("attach signature");

        assert_ne!(signed.signature, exo_core::Signature::empty());
    }

    #[test]
    fn attach_verified_signature_rejects_wrong_sender_key() {
        let sender_did = Did::new("did:exo:alice").unwrap();
        let recipient_did = Did::new("did:exo:bob").unwrap();
        let (_, sender_sk) = generate_keypair();
        let (wrong_pk, _) = generate_keypair();
        let recipient_kp = x25519_keypair(0x24);
        let ephemeral_kp = x25519_keypair(0x34);

        let envelope = prepare_envelope_for_signing_with_ephemeral(
            b"external signer",
            ContentType::Secret,
            &sender_did,
            &recipient_did,
            &recipient_kp.public,
            &ephemeral_kp,
            metadata(),
            false,
            0,
        )
        .expect("prepare envelope");
        let signature = exo_core::crypto::sign(
            &envelope.signing_payload().expect("signing payload"),
            &sender_sk,
        );

        let result = attach_verified_signature(envelope, signature, &wrong_pk);

        assert!(matches!(
            result,
            Err(MessagingError::SignatureVerificationFailed)
        ));
    }

    #[test]
    fn afterlife_message_flags() {
        let sender_did = Did::new("did:exo:alice").unwrap();
        let recipient_did = Did::new("did:exo:bob").unwrap();
        let (_, sender_sk) = generate_keypair();
        let recipient_kp = x25519_keypair(0x25);
        let ephemeral_kp = x25519_keypair(0x35);
        let metadata = metadata();

        let envelope = lock_and_send_with_ephemeral(
            b"Read this after I'm gone",
            ContentType::AfterlifeMessage,
            &sender_did,
            &recipient_did,
            &sender_sk,
            &recipient_kp.public,
            &ephemeral_kp,
            metadata,
            true,
            72,
        )
        .expect("lock_and_send");

        assert!(envelope.release_on_death);
        assert_eq!(envelope.release_delay_hours, 72);
        assert_eq!(envelope.content_type, ContentType::AfterlifeMessage);
    }

    #[test]
    fn compose_metadata_rejects_nil_message_id() {
        let result = ComposeMetadata::new(Uuid::nil(), Timestamp::new(7_000, 2));

        assert!(
            matches!(result, Err(MessagingError::InvalidEnvelope(reason)) if reason.contains("message id"))
        );
    }

    #[test]
    fn compose_metadata_rejects_zero_timestamp() {
        let result = ComposeMetadata::new(
            Uuid::parse_str("018f7a96-8ad0-7c4f-8e0f-222222222222").unwrap(),
            Timestamp::ZERO,
        );

        assert!(
            matches!(result, Err(MessagingError::InvalidEnvelope(reason)) if reason.contains("timestamp"))
        );
    }

    #[test]
    fn prepare_envelope_rejects_directly_constructed_invalid_metadata() {
        let sender_did = Did::new("did:exo:alice").unwrap();
        let recipient_did = Did::new("did:exo:bob").unwrap();
        let recipient_kp = x25519_keypair(0x28);
        let ephemeral_kp = x25519_keypair(0x38);
        let invalid_metadata = ComposeMetadata {
            id: Uuid::nil(),
            created: Timestamp::ZERO,
        };

        let result = prepare_envelope_for_signing_with_ephemeral(
            b"constructor bypass",
            ContentType::Secret,
            &sender_did,
            &recipient_did,
            &recipient_kp.public,
            &ephemeral_kp,
            invalid_metadata,
            false,
            0,
        );

        assert!(
            matches!(result, Err(MessagingError::InvalidEnvelope(reason)) if reason.contains("message id"))
        );
    }

    #[test]
    fn compose_metadata_fields_are_not_public_constructor_bypass() {
        let source = include_str!("compose.rs");
        let metadata_section = source
            .split("pub struct ComposeMetadata")
            .nth(1)
            .and_then(|section| section.split("impl ComposeMetadata").next())
            .expect("metadata struct section");

        assert!(!metadata_section.contains("pub id:"));
        assert!(!metadata_section.contains("pub created:"));
    }

    #[test]
    fn compose_path_does_not_fabricate_envelope_metadata() {
        let source = include_str!("compose.rs");
        let production = source
            .split("// ===========================================================================")
            .next()
            .expect("production section");

        assert!(
            !production.contains("Uuid::new_v4"),
            "compose production path must not fabricate message IDs"
        );
        let forbidden_clock = ["HybridClock", "::new()"].concat();
        assert!(
            !production.contains(&forbidden_clock),
            "compose production path must not fabricate HLC timestamps"
        );
    }

    #[test]
    fn compose_path_supplies_explicit_vault_nonce() {
        let source = include_str!("compose.rs");
        let production = source
            .split("// ===========================================================================")
            .next()
            .expect("production section");

        assert!(
            production.contains("encrypt_with_nonce"),
            "compose must pass an explicit deterministic nonce into vault encryption"
        );
        assert!(
            !production.contains(".encrypt("),
            "compose must not call the implicit vault encryption entrypoint"
        );
    }

    #[test]
    fn encrypted_envelope_nonce_is_not_public_plaintext_hash_oracle() {
        let sender_did = Did::new("did:exo:alice").unwrap();
        let recipient_did = Did::new("did:exo:bob").unwrap();
        let recipient_kp = x25519_keypair(0x27);
        let ephemeral_kp = x25519_keypair(0x37);
        let metadata = metadata();
        let plaintext = b"known plaintext candidate";
        let content_type = ContentType::Secret;
        let release_on_death = true;
        let release_delay_hours = 24;

        let envelope = prepare_envelope_for_signing_with_ephemeral(
            plaintext,
            content_type,
            &sender_did,
            &recipient_did,
            &recipient_kp.public,
            &ephemeral_kp,
            metadata,
            release_on_death,
            release_delay_hours,
        )
        .expect("prepare envelope");

        let legacy_nonce = legacy_public_plaintext_hash_nonce(
            &metadata,
            content_type,
            &sender_did,
            &recipient_did,
            ephemeral_kp.public.as_bytes(),
            plaintext,
            release_on_death,
            release_delay_hours,
        );

        assert_ne!(
            &envelope.ciphertext[..VAULT_NONCE_SIZE],
            &legacy_nonce[..],
            "visible ciphertext nonce must not be derived from public metadata plus guessed plaintext"
        );
    }

    #[test]
    fn compose_path_does_not_feed_plaintext_hash_into_visible_nonce() {
        let source = include_str!("compose.rs");
        let production = source
            .split("// ===========================================================================")
            .next()
            .expect("production section");

        for pattern in [
            "Hash256::digest(plaintext)",
            "plaintext_nonce_input",
            "transcript.extend_from_slice(plaintext",
        ] {
            assert!(
                !production.contains(pattern),
                "compose production path must not expose plaintext-derived material through the visible vault nonce via {pattern}"
            );
        }
    }

    #[test]
    fn prepare_envelope_for_signing_requires_caller_supplied_ephemeral_key() {
        let sender_did = Did::new("did:exo:alice").unwrap();
        let recipient_did = Did::new("did:exo:bob").unwrap();
        let recipient_kp = x25519_keypair(0x26);

        let result = prepare_envelope_for_signing(
            b"external signer",
            ContentType::Secret,
            &sender_did,
            &recipient_did,
            &recipient_kp.public,
            metadata(),
            false,
            0,
        );

        assert!(
            matches!(result, Err(MessagingError::KeyExchangeFailed(reason)) if reason.contains("caller-supplied ephemeral")),
            "message composition must fail closed unless the caller supplies the ephemeral X25519 keypair"
        );
    }

    #[test]
    fn compose_path_requires_caller_supplied_ephemeral_key() {
        let source = include_str!("compose.rs");
        let production = source
            .split("// ===========================================================================")
            .next()
            .expect("production section");

        assert!(
            production.contains("prepare_envelope_for_signing_with_ephemeral"),
            "compose must expose an explicit ephemeral-key entrypoint"
        );
        for pattern in ["generate_ephemeral", "X25519KeyPair::generate"] {
            assert!(
                !production.contains(pattern),
                "compose production path must not fabricate X25519 ephemeral key material via {pattern}"
            );
        }
    }
}