wireband-edge 0.4.1

Lightweight Wire.Band client — semantic data middleware for any domain (IoT, AI/ML, DeFi, legal, geospatial, supply chain, and more)
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
//! Frame cryptography — three independent, stackable layers.
//!
//! All layers are optional and compose in a fixed order:
//! - **Encrypt**: encrypt payload → remap symbol
//! - **Decrypt**: unmap symbol → decrypt payload
//!
//! # Layers
//!
//! 1. [`EnvelopeCipher`] — AES-256-GCM or ChaCha20-Poly1305 payload encryption.
//!    The 2-byte symbol prefix is used as AEAD Additional Authenticated Data,
//!    binding each ciphertext to its message type.
//!
//! 2. [`SymbolRemapper`] — Keyed bijective permutation of the 16-bit symbol space
//!    (65,536 values). Derived from a 32-byte secret via SHA-256 counter-mode PRNG
//!    + Fisher-Yates shuffle. Both parties independently derive the same table.
//!
//! 3. [`ContextualKeyDeriver`] — Handshake-less per-frame HKDF-SHA256 key derivation.
//!    Keys rotate on a configurable time window (default: 3600 s). After a window
//!    expires, past frames cannot be decrypted even with the master key —
//!    time-windowed forward secrecy with no key exchange.
//!
//! # Quick start
//!
//! ```no_run
//! use wireband_edge::crypto::CryptoContext;
//!
//! let ctx = CryptoContext::from_env().unwrap();
//! // or build manually:
//! // let ctx = CryptoContext::builder().envelope_key(&key).remap_key(&remap).build().unwrap();
//!
//! let plain_frame: Vec<u8> = vec![0xFC, 0x60, b'{', b'}'];
//! let encrypted = ctx.encrypt_frame(&plain_frame).unwrap();
//! let decrypted = ctx.decrypt_frame(&encrypted).unwrap();
//! assert_eq!(plain_frame, decrypted);
//! ```

use std::time::{SystemTime, UNIX_EPOCH};

use aes_gcm::{
    aead::{Aead, KeyInit, Payload},
    Aes256Gcm, Nonce as AesNonce,
};
use chacha20poly1305::{ChaCha20Poly1305, Nonce as ChachaNonce};
use hkdf::Hkdf;
use rand::{rngs::OsRng, RngCore};
use sha2::{Digest, Sha256};

// ---------------------------------------------------------------------------
// Internal constants
// ---------------------------------------------------------------------------

const ENVELOPE_MARKER: [u8; 2]  = [0xFF, 0x20];
const NONCE_LEN: usize          = 12;
const MIN_ENCRYPTED_LEN: usize  = 2 + 1 + NONCE_LEN + 16; // marker + algo + nonce + tag

const HKDF_INFO: &[u8] = b"wireband_frame_key_v1";

// ---------------------------------------------------------------------------
// AlgoId
// ---------------------------------------------------------------------------

/// Cipher algorithm selector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlgoId {
    Aes256Gcm        = 0x01,
    ChaCha20Poly1305 = 0x02,
}

impl AlgoId {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Aes256Gcm        => "aes256gcm",
            Self::ChaCha20Poly1305 => "chacha20poly1305",
        }
    }
    fn from_byte(b: u8) -> Option<Self> {
        match b {
            0x01 => Some(Self::Aes256Gcm),
            0x02 => Some(Self::ChaCha20Poly1305),
            _    => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Layer 1 — EnvelopeCipher
// ---------------------------------------------------------------------------

/// AES-256-GCM or ChaCha20-Poly1305 authenticated payload encryption.
///
/// The key is stored internally so derived keys can be constructed without
/// re-reading configuration.
#[derive(Clone)]
pub struct EnvelopeCipher {
    algo:        AlgoId,
    key:         [u8; 32],
    fingerprint: String, // first 8 hex chars of SHA-256(key)
}

impl std::fmt::Debug for EnvelopeCipher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EnvelopeCipher")
            .field("algo", &self.algo)
            .field("fingerprint", &self.fingerprint)
            .finish()
    }
}

impl EnvelopeCipher {
    /// Construct from raw key bytes (32 bytes).
    pub fn new(key: [u8; 32], algo: AlgoId) -> Self {
        let hash        = Sha256::digest(key);
        let fingerprint = hex_encode_lower(&hash[..4]);
        Self { algo, key, fingerprint }
    }

    /// Construct from a 64-character hex string.
    pub fn from_hex(hex: &str, algo: AlgoId) -> Result<Self, CryptoError> {
        let key = parse_hex32(hex)?;
        Ok(Self::new(key, algo))
    }

    /// First 8 hex chars of SHA-256(key) — safe to log for key identification.
    pub fn fingerprint(&self) -> &str {
        &self.fingerprint
    }

    pub fn algo(&self) -> AlgoId {
        self.algo
    }

    /// Encrypt `payload`, binding `aad` as Additional Authenticated Data.
    ///
    /// Returns the full encrypted region (header + ciphertext + auth tag).
    pub fn encrypt(&self, payload: &[u8], aad: &[u8]) -> Result<Vec<u8>, CryptoError> {
        let mut nonce_bytes = [0u8; NONCE_LEN];
        OsRng.fill_bytes(&mut nonce_bytes);

        let ct = match self.algo {
            AlgoId::Aes256Gcm => {
                let cipher = Aes256Gcm::new_from_slice(&self.key)
                    .map_err(|e| CryptoError::Init(e.to_string()))?;
                let nonce  = AesNonce::from_slice(&nonce_bytes);
                cipher.encrypt(nonce, Payload { msg: payload, aad })
                    .map_err(|e| CryptoError::Encrypt(e.to_string()))?
            }
            AlgoId::ChaCha20Poly1305 => {
                let cipher = ChaCha20Poly1305::new_from_slice(&self.key)
                    .map_err(|e| CryptoError::Init(e.to_string()))?;
                let nonce  = ChachaNonce::from_slice(&nonce_bytes);
                cipher.encrypt(nonce, Payload { msg: payload, aad })
                    .map_err(|e| CryptoError::Encrypt(e.to_string()))?
            }
        };

        let mut out = Vec::with_capacity(ENVELOPE_MARKER.len() + 1 + NONCE_LEN + ct.len());
        out.extend_from_slice(&ENVELOPE_MARKER);
        out.push(self.algo as u8);
        out.extend_from_slice(&nonce_bytes);
        out.extend_from_slice(&ct);
        Ok(out)
    }

    /// Decrypt an encrypted region produced by [`encrypt`].
    ///
    /// `data` must begin with the envelope marker.
    pub fn decrypt(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>, CryptoError> {
        if data.len() < MIN_ENCRYPTED_LEN {
            return Err(CryptoError::TooShort(data.len()));
        }
        if data[..2] != ENVELOPE_MARKER {
            return Err(CryptoError::BadMarker);
        }
        let algo_byte = data[2];
        if AlgoId::from_byte(algo_byte) != Some(self.algo) {
            return Err(CryptoError::AlgoMismatch {
                expected: self.algo as u8,
                got:      algo_byte,
            });
        }
        let nonce_bytes = &data[3..3 + NONCE_LEN];
        let ct          = &data[3 + NONCE_LEN..];

        match self.algo {
            AlgoId::Aes256Gcm => {
                let cipher = Aes256Gcm::new_from_slice(&self.key)
                    .map_err(|e| CryptoError::Init(e.to_string()))?;
                let nonce  = AesNonce::from_slice(nonce_bytes);
                cipher.decrypt(nonce, Payload { msg: ct, aad })
                    .map_err(|_| CryptoError::AuthFailed)
            }
            AlgoId::ChaCha20Poly1305 => {
                let cipher = ChaCha20Poly1305::new_from_slice(&self.key)
                    .map_err(|e| CryptoError::Init(e.to_string()))?;
                let nonce  = ChachaNonce::from_slice(nonce_bytes);
                cipher.decrypt(nonce, Payload { msg: ct, aad })
                    .map_err(|_| CryptoError::AuthFailed)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Layer 2 — SymbolRemapper
// ---------------------------------------------------------------------------

/// Keyed bijective permutation of the 16-bit symbol space (65,536 values).
///
/// Table derivation matches the Python implementation exactly for
/// cross-language interoperability. Both parties compute the same table
/// from the shared 32-byte secret — no table exchange required.
///
/// Build time is O(n): ~8 192 SHA-256 calls amortised, typically < 5 ms.
/// Tables are built once at construction and stored on the heap (~256 KB).
#[derive(Clone)]
pub struct SymbolRemapper {
    fwd:         Vec<u16>,
    inv:         Vec<u16>,
    fingerprint: String,
}

impl std::fmt::Debug for SymbolRemapper {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SymbolRemapper")
            .field("fingerprint", &self.fingerprint)
            .finish()
    }
}

impl SymbolRemapper {
    /// Construct from raw secret bytes (32 bytes).
    pub fn new(secret: [u8; 32]) -> Self {
        let (fwd, inv) = Self::derive_tables(&secret);
        let hash       = Sha256::digest(secret);
        let fingerprint = hex_encode_lower(&hash[..4]);
        Self { fwd, inv, fingerprint }
    }

    /// Construct from a 64-character hex string.
    pub fn from_hex(hex: &str) -> Result<Self, CryptoError> {
        Ok(Self::new(parse_hex32(hex)?))
    }

    /// First 8 hex chars of SHA-256(secret) — safe to log.
    pub fn fingerprint(&self) -> &str {
        &self.fingerprint
    }

    /// Map a symbol to its permuted equivalent.
    pub fn remap(&self, symbol: u16) -> u16 {
        self.fwd[symbol as usize]
    }

    /// Recover the original symbol from its permuted equivalent.
    pub fn unmap(&self, symbol: u16) -> u16 {
        self.inv[symbol as usize]
    }

    fn derive_tables(secret: &[u8; 32]) -> (Vec<u16>, Vec<u16>) {
        // SHA-256 counter-mode PRNG: 4 bytes per swap position
        let needed = 65536 * 4;
        let mut prng: Vec<u8> = Vec::with_capacity(needed);
        let mut counter: u32  = 0;
        while prng.len() < needed {
            let mut h = Sha256::new();
            h.update(secret);
            h.update(counter.to_be_bytes());
            prng.extend_from_slice(&h.finalize());
            counter += 1;
        }

        // Fisher-Yates — matches Python iteration exactly
        let mut table: Vec<u16> = (0..=65535u16).collect();
        for i in (1..=65535usize).rev() {
            let offset = (65535 - i) * 4;
            let r = u32::from_be_bytes(prng[offset..offset + 4].try_into().unwrap()) as usize;
            let j = r % (i + 1);
            table.swap(i, j);
        }

        let mut inv = vec![0u16; 65536];
        for (i, &v) in table.iter().enumerate() {
            inv[v as usize] = i as u16;
        }

        (table, inv)
    }
}

// ---------------------------------------------------------------------------
// Layer 3 — ContextualKeyDeriver
// ---------------------------------------------------------------------------

/// Handshake-less per-frame HKDF-SHA256 key derivation with time-windowed
/// forward secrecy.
///
/// Both edge and server derive the same 32-byte frame key from the shared
/// master key and the current time window — no key exchange, no state.
///
/// Keys rotate automatically every `window_seconds`. After a window expires,
/// past frames cannot be decrypted even with the master key.
#[derive(Clone)]
pub struct ContextualKeyDeriver {
    master_key:     [u8; 32],
    window_seconds: u64,
}

impl std::fmt::Debug for ContextualKeyDeriver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContextualKeyDeriver")
            .field("window_seconds", &self.window_seconds)
            .finish()
    }
}

impl ContextualKeyDeriver {
    /// Construct from raw master key bytes (32 bytes).
    pub fn new(master_key: [u8; 32], window_seconds: u64) -> Self {
        Self { master_key, window_seconds }
    }

    /// Construct from a 64-character hex string.
    pub fn from_hex(hex: &str, window_seconds: u64) -> Result<Self, CryptoError> {
        Ok(Self::new(parse_hex32(hex)?, window_seconds))
    }

    pub fn window_seconds(&self) -> u64 {
        self.window_seconds
    }

    /// Derive a 32-byte frame key for the given symbol bytes and time window.
    ///
    /// `at_secs` overrides the current Unix timestamp (useful for decryption
    /// boundary handling — try current window, then previous).
    pub fn derive_key(&self, sym_hi: u8, sym_lo: u8, at_secs: Option<u64>) -> [u8; 32] {
        let now    = at_secs.unwrap_or_else(unix_secs);
        let window = now / self.window_seconds;

        // salt = SHA-256(sym_hi ‖ sym_lo ‖ window_big_endian)
        let mut h = Sha256::new();
        h.update([sym_hi, sym_lo]);
        h.update(window.to_be_bytes());
        let salt: [u8; 32] = h.finalize().into();

        let hk  = Hkdf::<Sha256>::new(Some(&salt), &self.master_key);
        let mut okm = [0u8; 32];
        hk.expand(HKDF_INFO, &mut okm).expect("HKDF expand (L=32 ≤ HashLen=32)");
        okm
    }
}

// ---------------------------------------------------------------------------
// CryptoContext — combines all three layers
// ---------------------------------------------------------------------------

/// Combined crypto context — up to three independent, stackable layers.
///
/// Any combination of layers may be set; unset layers are no-ops.
///
/// ```
/// use wireband_edge::crypto::{CryptoContext, AlgoId};
///
/// let key = [0xABu8; 32];
/// let ctx = CryptoContext::builder()
///     .envelope_key(key, AlgoId::Aes256Gcm)
///     .remap_key(key)
///     .hkdf_window(key, 3600)
///     .build();
///
/// let frame = vec![0xFC, 0x60, b'{', b'}'];
/// let enc   = ctx.encrypt_frame(&frame).unwrap();
/// let dec   = ctx.decrypt_frame(&enc).unwrap();
/// assert_eq!(frame, dec);
/// ```
#[derive(Debug, Clone)]
pub struct CryptoContext {
    pub cipher:      Option<EnvelopeCipher>,
    pub remapper:    Option<SymbolRemapper>,
    pub key_deriver: Option<ContextualKeyDeriver>,
}

impl CryptoContext {
    /// Returns `true` if any crypto layer is active.
    pub fn is_active(&self) -> bool {
        self.cipher.is_some() || self.remapper.is_some()
    }

    /// Encrypt a Wire.Band frame (sym_hi, sym_lo, payload...).
    ///
    /// Steps: encrypt payload (AAD = canonical symbol) → remap symbol.
    pub fn encrypt_frame(&self, raw: &[u8]) -> Result<Vec<u8>, CryptoError> {
        if raw.len() < 2 {
            return Ok(raw.to_vec());
        }
        let mut sym_hi  = raw[0];
        let mut sym_lo  = raw[1];
        let mut payload = raw[2..].to_vec();

        if let Some(ref cipher) = self.cipher {
            let aad = [sym_hi, sym_lo];
            let c   = self.cipher_for_symbol(sym_hi, sym_lo, None)?;
            payload = c.unwrap_or(cipher.clone()).encrypt(&payload, &aad)?;
        }

        if let Some(ref remapper) = self.remapper {
            let canonical = ((sym_hi as u16) << 8) | sym_lo as u16;
            let ciphered  = remapper.remap(canonical);
            sym_hi        = (ciphered >> 8) as u8;
            sym_lo        = (ciphered & 0xFF) as u8;
        }

        let mut out = Vec::with_capacity(2 + payload.len());
        out.push(sym_hi);
        out.push(sym_lo);
        out.extend_from_slice(&payload);
        Ok(out)
    }

    /// Decrypt a Wire.Band frame. Inverse of [`encrypt_frame`].
    pub fn decrypt_frame(&self, raw: &[u8]) -> Result<Vec<u8>, CryptoError> {
        if raw.len() < 2 {
            return Ok(raw.to_vec());
        }
        let mut sym_hi  = raw[0];
        let mut sym_lo  = raw[1];
        let mut payload = raw[2..].to_vec();

        if let Some(ref remapper) = self.remapper {
            let ciphered  = ((sym_hi as u16) << 8) | sym_lo as u16;
            let canonical = remapper.unmap(ciphered);
            sym_hi        = (canonical >> 8) as u8;
            sym_lo        = (canonical & 0xFF) as u8;
        }

        if self.cipher.is_some() && payload.starts_with(&ENVELOPE_MARKER) {
            let aad = [sym_hi, sym_lo];
            if let Some(ref deriver) = self.key_deriver {
                // Try current window, then previous (handles boundary frames)
                let now  = unix_secs();
                let prev = now.saturating_sub(deriver.window_seconds());
                let mut last_err = CryptoError::AuthFailed;
                for at in [now, prev] {
                    if let Ok(c) = self.cipher_for_symbol(sym_hi, sym_lo, Some(at)) {
                        let cipher = c.or_else(|| self.cipher.clone()).unwrap();
                        match cipher.decrypt(&payload, &aad) {
                            Ok(pt) => { payload = pt; last_err = CryptoError::AuthFailed; break; }
                            Err(e) => { last_err = e; }
                        }
                    }
                }
                if !last_err.is_auth_failed_sentinel() {
                    return Err(last_err);
                }
            } else {
                let cipher = self.cipher.as_ref().unwrap();
                payload = cipher.decrypt(&payload, &aad)?;
            }
        }

        let mut out = Vec::with_capacity(2 + payload.len());
        out.push(sym_hi);
        out.push(sym_lo);
        out.extend_from_slice(&payload);
        Ok(out)
    }

    fn cipher_for_symbol(
        &self,
        sym_hi: u8,
        sym_lo: u8,
        at_secs: Option<u64>,
    ) -> Result<Option<EnvelopeCipher>, CryptoError> {
        let base = match &self.cipher {
            None    => return Ok(None),
            Some(c) => c,
        };
        let deriver = match &self.key_deriver {
            None    => return Ok(Some(base.clone())),
            Some(d) => d,
        };
        let frame_key = deriver.derive_key(sym_hi, sym_lo, at_secs);
        Ok(Some(EnvelopeCipher::new(frame_key, base.algo())))
    }

    /// Build a `CryptoContext` from environment variables.
    ///
    /// | Variable | Description |
    /// |---|---|
    /// | `THETA_ENVELOPE_KEY` | 64-char hex — enables envelope cipher |
    /// | `THETA_ENVELOPE_ALGO` | `"aes256gcm"` (default) or `"chacha20poly1305"` |
    /// | `THETA_SYMBOL_REMAP_KEY` | 64-char hex — enables symbol remapper |
    /// | `THETA_CONTEXTUAL_SALT=1` | Enable per-frame HKDF key derivation |
    /// | `THETA_CONTEXTUAL_SALT_WINDOW` | Rotation window in seconds (default 3600) |
    pub fn from_env() -> Result<Self, CryptoError> {
        let mut cipher:      Option<EnvelopeCipher>       = None;
        let mut remapper:    Option<SymbolRemapper>        = None;
        let mut key_deriver: Option<ContextualKeyDeriver> = None;

        if let Ok(hex) = std::env::var("THETA_ENVELOPE_KEY") {
            let algo_str = std::env::var("THETA_ENVELOPE_ALGO")
                .unwrap_or_else(|_| "aes256gcm".into());
            let algo = if algo_str.contains("chacha") {
                AlgoId::ChaCha20Poly1305
            } else {
                AlgoId::Aes256Gcm
            };
            cipher = Some(EnvelopeCipher::from_hex(&hex, algo)?);

            let salt_flag = std::env::var("THETA_CONTEXTUAL_SALT")
                .unwrap_or_default()
                .to_lowercase();
            if matches!(salt_flag.as_str(), "1" | "true" | "yes") {
                let window: u64 = std::env::var("THETA_CONTEXTUAL_SALT_WINDOW")
                    .ok()
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(3600);
                key_deriver = Some(ContextualKeyDeriver::from_hex(&hex, window)?);
            }
        }

        if let Ok(hex) = std::env::var("THETA_SYMBOL_REMAP_KEY") {
            remapper = Some(SymbolRemapper::from_hex(&hex)?);
        }

        Ok(Self { cipher, remapper, key_deriver })
    }

    /// Builder for manual construction.
    pub fn builder() -> CryptoContextBuilder {
        CryptoContextBuilder::default()
    }
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

#[derive(Default)]
pub struct CryptoContextBuilder {
    cipher:      Option<EnvelopeCipher>,
    remapper:    Option<SymbolRemapper>,
    key_deriver: Option<ContextualKeyDeriver>,
}

impl CryptoContextBuilder {
    pub fn envelope_key(mut self, key: [u8; 32], algo: AlgoId) -> Self {
        self.cipher = Some(EnvelopeCipher::new(key, algo));
        self
    }
    pub fn remap_key(mut self, secret: [u8; 32]) -> Self {
        self.remapper = Some(SymbolRemapper::new(secret));
        self
    }
    pub fn hkdf_window(mut self, master_key: [u8; 32], window_seconds: u64) -> Self {
        self.key_deriver = Some(ContextualKeyDeriver::new(master_key, window_seconds));
        self
    }
    pub fn build(self) -> CryptoContext {
        CryptoContext {
            cipher:      self.cipher,
            remapper:    self.remapper,
            key_deriver: self.key_deriver,
        }
    }
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum CryptoError {
    #[error("Invalid hex key: {0}")]
    BadHex(String),

    #[error("Cipher initialisation failed: {0}")]
    Init(String),

    #[error("Encryption failed: {0}")]
    Encrypt(String),

    #[error("Authentication failed (wrong key or tampered data)")]
    AuthFailed,

    #[error("Encrypted region too short: {0} bytes")]
    TooShort(usize),

    #[error("Missing envelope marker")]
    BadMarker,

    #[error("Algo mismatch: expected 0x{expected:02X}, got 0x{got:02X}")]
    AlgoMismatch { expected: u8, got: u8 },
}

impl CryptoError {
    // Used internally to check if the boundary-retry loop actually failed
    fn is_auth_failed_sentinel(&self) -> bool {
        matches!(self, CryptoError::AuthFailed)
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn unix_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn parse_hex32(hex: &str) -> Result<[u8; 32], CryptoError> {
    if hex.len() != 64 {
        return Err(CryptoError::BadHex(format!(
            "expected 64 hex chars (32 bytes), got {}",
            hex.len()
        )));
    }
    let mut out = [0u8; 32];
    for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
        let s = std::str::from_utf8(chunk)
            .map_err(|e| CryptoError::BadHex(e.to_string()))?;
        out[i] = u8::from_str_radix(s, 16)
            .map_err(|e| CryptoError::BadHex(e.to_string()))?;
    }
    Ok(out)
}

fn hex_encode_lower(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn test_key() -> [u8; 32] { [0x42u8; 32] }
    fn test_secret() -> [u8; 32] { [0x7Fu8; 32] }

    #[test]
    fn envelope_cipher_aes_round_trip() {
        let c       = EnvelopeCipher::new(test_key(), AlgoId::Aes256Gcm);
        let aad     = [0xFC, 0x60];
        let plain   = b"hello world";
        let enc     = c.encrypt(plain, &aad).unwrap();
        let dec     = c.decrypt(&enc, &aad).unwrap();
        assert_eq!(dec, plain);
    }

    #[test]
    fn envelope_cipher_chacha_round_trip() {
        let c     = EnvelopeCipher::new(test_key(), AlgoId::ChaCha20Poly1305);
        let plain = b"chacha test";
        let enc   = c.encrypt(plain, b"").unwrap();
        let dec   = c.decrypt(&enc, b"").unwrap();
        assert_eq!(dec, plain);
    }

    #[test]
    fn envelope_cipher_aad_binding() {
        let c   = EnvelopeCipher::new(test_key(), AlgoId::Aes256Gcm);
        let enc = c.encrypt(b"data", &[0xFC, 0x60]).unwrap();
        // Wrong AAD must fail authentication
        assert!(c.decrypt(&enc, &[0xFC, 0x61]).is_err());
    }

    #[test]
    fn symbol_remapper_bijection() {
        let r = SymbolRemapper::new(test_secret());
        for sym in [0u16, 1, 0xFC60, 0x00FF, 0xFFFF] {
            assert_eq!(r.unmap(r.remap(sym)), sym);
            assert_eq!(r.remap(r.unmap(sym)), sym);
        }
    }

    #[test]
    fn symbol_remapper_is_permutation() {
        let r      = SymbolRemapper::new(test_secret());
        let mapped: Vec<u16> = (0u16..=255).map(|s| r.remap(s)).collect();
        let mut sorted = mapped.clone();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), 256); // all distinct → bijection over this range
    }

    #[test]
    fn contextual_key_deriver_deterministic() {
        let d  = ContextualKeyDeriver::new(test_key(), 3600);
        let k1 = d.derive_key(0xFC, 0x60, Some(1_000_000));
        let k2 = d.derive_key(0xFC, 0x60, Some(1_000_000));
        assert_eq!(k1, k2);
    }

    #[test]
    fn contextual_key_deriver_window_rotation() {
        let d  = ContextualKeyDeriver::new(test_key(), 3600);
        let k1 = d.derive_key(0xFC, 0x60, Some(0));
        let k2 = d.derive_key(0xFC, 0x60, Some(3600));
        assert_ne!(k1, k2, "different windows must yield different keys");
    }

    #[test]
    fn contextual_key_deriver_symbol_binding() {
        let d  = ContextualKeyDeriver::new(test_key(), 3600);
        let k1 = d.derive_key(0xFC, 0x60, Some(0));
        let k2 = d.derive_key(0xFC, 0x61, Some(0));
        assert_ne!(k1, k2, "different symbols must yield different keys");
    }

    #[test]
    fn crypto_context_all_layers_round_trip() {
        let ctx = CryptoContext::builder()
            .envelope_key(test_key(), AlgoId::Aes256Gcm)
            .remap_key(test_secret())
            .hkdf_window(test_key(), 3600)
            .build();
        let frame = vec![0xFC, 0x60, b'{', b'"', b'v', b'"', b':', b'1', b'}'];
        let enc   = ctx.encrypt_frame(&frame).unwrap();
        assert_ne!(enc, frame);
        let dec   = ctx.decrypt_frame(&enc).unwrap();
        assert_eq!(dec, frame);
    }

    #[test]
    fn crypto_context_cipher_only() {
        let ctx = CryptoContext::builder()
            .envelope_key(test_key(), AlgoId::Aes256Gcm)
            .build();
        let frame = vec![0xF2, 0x10, b'{', b'}'];
        let enc   = ctx.encrypt_frame(&frame).unwrap();
        let dec   = ctx.decrypt_frame(&enc).unwrap();
        assert_eq!(dec, frame);
    }

    #[test]
    fn crypto_context_remapper_only() {
        let ctx = CryptoContext::builder()
            .remap_key(test_secret())
            .build();
        let frame = vec![0xFC, 0x60, b'{', b'}'];
        let enc   = ctx.encrypt_frame(&frame).unwrap();
        // Symbol bytes should be remapped
        let r     = SymbolRemapper::new(test_secret());
        assert_eq!(enc[0], (r.remap(0xFC60) >> 8) as u8);
        assert_eq!(enc[1], (r.remap(0xFC60) & 0xFF) as u8);
        let dec   = ctx.decrypt_frame(&enc).unwrap();
        assert_eq!(dec, frame);
    }

    #[test]
    fn crypto_context_inactive_passthrough() {
        let ctx   = CryptoContext { cipher: None, remapper: None, key_deriver: None };
        let frame = vec![0xFC, 0x60, b'{', b'}'];
        assert_eq!(ctx.encrypt_frame(&frame).unwrap(), frame);
        assert_eq!(ctx.decrypt_frame(&frame).unwrap(), frame);
    }
}