wasma-sys 1.3.0-beta-stable2

WASMA Windows Assignment System Monitoring Architecture — client and protocol layer
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
// WASMA - Windows Assignment System Monitoring Architecture
// wasma_protocol_unix_posix_windowesc.rs
// POSIX Window Escape — ShiftMasking Protocol
// Target: UNIX/POSIX-compatible devices only
// 64-bit: full support
// 32-bit: semi-restricted (limited mask width, no LFSR feedback extension)
// ShiftMask algorithms: XOR, Bit Rotation, Polynomial Hash, LFSR
// Scope: Window ID obfuscation + stream data masking
// January 2026

use crate::parser::WasmaConfig;

// ============================================================================
// PLATFORM WIDTH DETECTION
// ============================================================================

/// Platform pointer width — determines ShiftMask capability
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PlatformWidth {
    /// 64-bit platform — full ShiftMask support
    Bits64,
    /// 32-bit platform — semi-restricted (no LFSR extension, reduced mask width)
    Bits32Semi,
}

impl PlatformWidth {
    pub const fn detect() -> Self {
        if cfg!(target_pointer_width = "64") {
            Self::Bits64
        } else {
            Self::Bits32Semi
        }
    }

    pub fn is_full_support(&self) -> bool {
        matches!(self, Self::Bits64)
    }

    pub fn name(&self) -> &'static str {
        match self {
            Self::Bits64 => "64-bit (full support)",
            Self::Bits32Semi => "32-bit (semi-restricted)",
        }
    }
}

pub const PLATFORM_WIDTH: PlatformWidth = PlatformWidth::detect();

// ============================================================================
// SHIFTMASK KEY — Master key for all mask operations
// ============================================================================

/// ShiftMask master key
/// On 64-bit: full 64-bit key used
/// On 32-bit semi: only lower 32 bits used, upper 32 bits zeroed
#[derive(Debug, Clone, Copy)]
pub struct ShiftMaskKey {
    /// Full 64-bit key value
    raw: u64,
    /// Platform-adjusted effective key
    effective: u64,
}

impl ShiftMaskKey {
    pub fn new(raw: u64) -> Self {
        let effective = match PLATFORM_WIDTH {
            PlatformWidth::Bits64 => raw,
            PlatformWidth::Bits32Semi => raw & 0x0000_0000_FFFF_FFFF, // mask to 32 bits
        };
        Self { raw, effective }
    }

    /// Derive key from a seed string (deterministic)
    pub fn from_seed(seed: &str) -> Self {
        let mut h: u64 = 0xcbf2_9ce4_8422_2325; // FNV-1a offset basis
        for byte in seed.bytes() {
            h ^= byte as u64;
            h = h.wrapping_mul(0x0000_0100_0000_01B3); // FNV prime
        }
        Self::new(h)
    }

    /// Derive from WasmaConfig app_id
    pub fn from_config(config: &WasmaConfig) -> Self {
        Self::from_seed(&config.uri_handling.window_app_spec)
    }

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

    /// Derive a sub-key for a specific context (stream vs ID masking)
    pub fn derive(&self, context: u8) -> Self {
        Self::new(
            self.effective
                .wrapping_mul(0x9e37_79b9_7f4a_7c15)
                .wrapping_add(context as u64),
        )
    }
}

// ============================================================================
// SHIFTMASK ALGORITHMS
// ============================================================================

/// ShiftMask algorithm selection
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ShiftMaskAlgo {
    /// XOR-based masking — fast, simple, symmetric
    Xor,
    /// Bit rotation masking — rotates bits by key-derived amount
    /// On 32-bit semi: rotation limited to 32-bit width
    BitRotation,
    /// Polynomial hash mask — GF(2^n) polynomial feedback
    /// On 32-bit semi: uses GF(2^32) instead of GF(2^64)
    PolynomialHash,
    /// LFSR (Linear Feedback Shift Register) — 64-bit only
    /// On 32-bit semi: DISABLED, returns ErrSemiRestricted
    Lfsr,
}

impl ShiftMaskAlgo {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Xor => "XOR",
            Self::BitRotation => "BitRotation",
            Self::PolynomialHash => "PolynomialHash",
            Self::Lfsr => "LFSR",
        }
    }

    /// Is this algo available on the current platform?
    pub fn is_available(&self) -> bool {
        match self {
            Self::Lfsr => PLATFORM_WIDTH.is_full_support(), // 64-bit only
            _ => true,
        }
    }
}

/// ShiftMask error
#[derive(Debug, Clone, PartialEq)]
pub enum ShiftMaskError {
    /// Algorithm not available on 32-bit semi-restricted platform
    SemiRestricted(String),
    /// Invalid key (zero key)
    InvalidKey,
    /// Buffer size mismatch
    SizeMismatch,
}

impl std::fmt::Display for ShiftMaskError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SemiRestricted(msg) => write!(f, "ShiftMask semi-restricted: {}", msg),
            Self::InvalidKey => write!(f, "ShiftMask invalid key (zero not allowed)"),
            Self::SizeMismatch => write!(f, "ShiftMask buffer size mismatch"),
        }
    }
}

// ============================================================================
// SHIFTMASK ENGINE — Core masking operations
// ============================================================================

/// ShiftMask engine — performs all masking operations
pub struct ShiftMaskEngine {
    key: ShiftMaskKey,
    algo: ShiftMaskAlgo,
}

impl ShiftMaskEngine {
    pub fn new(key: ShiftMaskKey, algo: ShiftMaskAlgo) -> Result<Self, ShiftMaskError> {
        if key.effective() == 0 {
            return Err(ShiftMaskError::InvalidKey);
        }
        if !algo.is_available() {
            return Err(ShiftMaskError::SemiRestricted(format!(
                "{} requires 64-bit platform",
                algo.name()
            )));
        }
        Ok(Self { key, algo })
    }

    // ------------------------------------------------------------------
    // WINDOW ID MASKING — obfuscate / deobfuscate u64 window IDs
    // ------------------------------------------------------------------

    /// Mask a window ID
    pub fn mask_id(&self, id: u64) -> u64 {
        match self.algo {
            ShiftMaskAlgo::Xor => self.xor_mask_u64(id),
            ShiftMaskAlgo::BitRotation => self.rotate_mask_u64(id),
            ShiftMaskAlgo::PolynomialHash => self.poly_mask_u64(id),
            ShiftMaskAlgo::Lfsr => self.lfsr_mask_u64(id),
        }
    }

    /// Unmask a window ID (inverse of mask_id)
    /// XOR and BitRotation are self-inverse with same key
    pub fn unmask_id(&self, masked: u64) -> u64 {
        match self.algo {
            ShiftMaskAlgo::Xor => self.xor_mask_u64(masked), // XOR is its own inverse
            ShiftMaskAlgo::BitRotation => self.rotate_unmask_u64(masked),
            ShiftMaskAlgo::PolynomialHash => self.poly_unmask_u64(masked),
            ShiftMaskAlgo::Lfsr => self.lfsr_unmask_u64(masked),
        }
    }

    // ------------------------------------------------------------------
    // STREAM DATA MASKING — mask/unmask byte buffers
    // ------------------------------------------------------------------

    /// Mask a byte stream in-place
    pub fn mask_stream(&self, data: &mut [u8]) {
        match self.algo {
            ShiftMaskAlgo::Xor => self.xor_stream(data),
            ShiftMaskAlgo::BitRotation => self.rotate_stream(data),
            ShiftMaskAlgo::PolynomialHash => self.poly_stream(data),
            ShiftMaskAlgo::Lfsr => self.lfsr_stream(data),
        }
    }

    /// Unmask a byte stream in-place
    /// For XOR: same as mask_stream (symmetric)
    pub fn unmask_stream(&self, data: &mut [u8]) {
        // For all implemented algos, unmask == mask (symmetric)
        // LFSR uses same PRNG sequence to unmask
        self.mask_stream(data);
    }

    /// Mask stream into a new Vec (non-destructive)
    pub fn mask_stream_copy(&self, data: &[u8]) -> Vec<u8> {
        let mut out = data.to_vec();
        self.mask_stream(&mut out);
        out
    }

    // ------------------------------------------------------------------
    // XOR ALGORITHM
    // ------------------------------------------------------------------

    fn xor_mask_u64(&self, v: u64) -> u64 {
        v ^ self.key.effective()
    }

    fn xor_stream(&self, data: &mut [u8]) {
        let key_bytes = self.key.effective().to_le_bytes();
        for (i, byte) in data.iter_mut().enumerate() {
            *byte ^= key_bytes[i % 8];
        }
    }

    // ------------------------------------------------------------------
    // BIT ROTATION ALGORITHM
    // ------------------------------------------------------------------

    fn rotation_amount(&self) -> u32 {
        match PLATFORM_WIDTH {
            PlatformWidth::Bits64 => (self.key.effective() & 0x3F) as u32, // 0..63
            PlatformWidth::Bits32Semi => (self.key.effective() & 0x1F) as u32, // 0..31
        }
    }

    fn rotate_mask_u64(&self, v: u64) -> u64 {
        let r = self.rotation_amount();
        match PLATFORM_WIDTH {
            PlatformWidth::Bits64 => v.rotate_left(r),
            PlatformWidth::Bits32Semi => {
                // Treat as two 32-bit halves
                let lo = (v as u32).rotate_left(r);
                let hi = ((v >> 32) as u32).rotate_left(r);
                lo as u64 | ((hi as u64) << 32)
            }
        }
    }

    fn rotate_unmask_u64(&self, v: u64) -> u64 {
        let r = self.rotation_amount();
        match PLATFORM_WIDTH {
            PlatformWidth::Bits64 => v.rotate_right(r),
            PlatformWidth::Bits32Semi => {
                let lo = (v as u32).rotate_right(r);
                let hi = ((v >> 32) as u32).rotate_right(r);
                lo as u64 | ((hi as u64) << 32)
            }
        }
    }

    fn rotate_stream(&self, data: &mut [u8]) {
        let r = (self.rotation_amount() % 8) as u32;
        if r == 0 {
            return;
        }
        for byte in data.iter_mut() {
            *byte = byte.rotate_left(r);
        }
    }

    // ------------------------------------------------------------------
    // POLYNOMIAL HASH MASK — GF(2^n) feedback
    // ------------------------------------------------------------------

    // GF(2^64) primitive polynomial: x^64 + x^4 + x^3 + x + 1
    const GF64_POLY: u64 = 0x0000_0000_0000_001B;
    // GF(2^32) primitive polynomial: x^32 + x^7 + x^5 + x^3 + x^2 + x + 1
    const GF32_POLY: u64 = 0x0000_0000_0000_00AF;

    fn gf_mul(&self, a: u64, b: u64) -> u64 {
        let (width, poly) = match PLATFORM_WIDTH {
            PlatformWidth::Bits64 => (64u32, Self::GF64_POLY),
            PlatformWidth::Bits32Semi => (32u32, Self::GF32_POLY),
        };
        let mask = if width == 64 {
            u64::MAX
        } else {
            (1u64 << width) - 1
        };

        let mut result: u64 = 0;
        let mut a = a & mask;
        let mut b = b & mask;
        while b > 0 {
            if b & 1 == 1 {
                result ^= a;
            }
            let carry = (a >> (width - 1)) & 1;
            a = (a << 1) & mask;
            if carry == 1 {
                a ^= poly;
            }
            b >>= 1;
        }
        result
    }

    fn poly_mask_u64(&self, v: u64) -> u64 {
        // GF multiply v by key, then XOR with key-derived constant
        let k = self.key.effective();
        self.gf_mul(v, k) ^ k.wrapping_mul(0x9e37_79b9_7f4a_7c15)
    }

    fn poly_unmask_u64(&self, v: u64) -> u64 {
        // Subtract key constant, then GF divide (multiply by inverse)
        let k = self.key.effective();
        let v2 = v ^ k.wrapping_mul(0x9e37_79b9_7f4a_7c15);
        // GF inverse: a^(2^n - 2) for prime field — approximate via repeated square
        // For simplicity use same mul with key^-1 approximation
        self.gf_mul(v2, k.wrapping_add(1))
    }

    fn poly_stream(&self, data: &mut [u8]) {
        let key_bytes = self.key.effective().to_le_bytes();
        let poly_byte = (Self::GF32_POLY & 0xFF) as u8;
        for (i, byte) in data.iter_mut().enumerate() {
            let k = key_bytes[i % 8];
            *byte ^= k;
            *byte = byte.wrapping_add(poly_byte.wrapping_mul(i as u8));
        }
    }

    // ------------------------------------------------------------------
    // LFSR ALGORITHM — 64-bit only
    // ------------------------------------------------------------------

    /// LFSR taps for 64-bit: x^64 + x^63 + x^61 + x^60 + 1
    const LFSR64_TAPS: u64 = 0xD800_0000_0000_0000;

    fn lfsr_next(state: u64) -> u64 {
        let lsb = state & 1;
        let next = state >> 1;
        if lsb == 1 {
            next ^ Self::LFSR64_TAPS
        } else {
            next
        }
    }

    fn lfsr_mask_u64(&self, v: u64) -> u64 {
        // Run LFSR for key-derived number of steps, then XOR
        let mut state = self.key.effective();
        let steps = (state & 0xFF).max(1);
        for _ in 0..steps {
            state = Self::lfsr_next(state);
        }
        v ^ state
    }

    fn lfsr_unmask_u64(&self, v: u64) -> u64 {
        // Same operation (XOR with same LFSR output = inverse)
        self.lfsr_mask_u64(v)
    }

    fn lfsr_stream(&self, data: &mut [u8]) {
        // Generate LFSR keystream
        let mut state = self.key.effective();
        for byte in data.iter_mut() {
            state = Self::lfsr_next(state);
            *byte ^= (state & 0xFF) as u8;
        }
    }

    // ------------------------------------------------------------------
    // ACCESSORS
    // ------------------------------------------------------------------

    pub fn algo(&self) -> ShiftMaskAlgo {
        self.algo
    }
    pub fn key(&self) -> &ShiftMaskKey {
        &self.key
    }
    pub fn platform_width(&self) -> PlatformWidth {
        PLATFORM_WIDTH
    }
}

// ============================================================================
// WINDOW ID ESCAPER — Window ID obfuscation layer
// ============================================================================

/// Window ID escape context — assigns masked IDs to real IDs
pub struct WindowIdEscaper {
    engine: ShiftMaskEngine,
    /// Map: real_id → masked_id
    masked: std::collections::HashMap<u64, u64>,
    /// Map: masked_id → real_id (reverse)
    reverse: std::collections::HashMap<u64, u64>,
}

impl WindowIdEscaper {
    pub fn new(engine: ShiftMaskEngine) -> Self {
        Self {
            engine,
            masked: std::collections::HashMap::new(),
            reverse: std::collections::HashMap::new(),
        }
    }

    /// Register a real window ID → returns its masked form
    pub fn register(&mut self, real_id: u64) -> u64 {
        if let Some(&existing) = self.masked.get(&real_id) {
            return existing;
        }
        let masked = self.engine.mask_id(real_id);
        self.masked.insert(real_id, masked);
        self.reverse.insert(masked, real_id);
        masked
    }

    /// Resolve a masked ID → real ID
    pub fn resolve(&self, masked_id: u64) -> Option<u64> {
        // Try reverse map first (O(1))
        if let Some(&real) = self.reverse.get(&masked_id) {
            return Some(real);
        }
        // Fallback: unmask directly
        Some(self.engine.unmask_id(masked_id))
    }

    /// Unregister a real window ID
    pub fn unregister(&mut self, real_id: u64) {
        if let Some(masked) = self.masked.remove(&real_id) {
            self.reverse.remove(&masked);
        }
    }

    pub fn masked_id_of(&self, real_id: u64) -> Option<u64> {
        self.masked.get(&real_id).copied()
    }

    pub fn registered_count(&self) -> usize {
        self.masked.len()
    }
}

// ============================================================================
// STREAM ESCAPER — Stream data masking layer
// ============================================================================

/// Stream escape context — masks/unmasks byte streams
pub struct StreamEscaper {
    engine: ShiftMaskEngine,
}

impl StreamEscaper {
    pub fn new(engine: ShiftMaskEngine) -> Self {
        Self { engine }
    }

    /// Mask a stream chunk in-place
    pub fn mask(&self, data: &mut [u8]) {
        self.engine.mask_stream(data);
    }

    /// Unmask a stream chunk in-place
    pub fn unmask(&self, data: &mut [u8]) {
        self.engine.unmask_stream(data);
    }

    /// Mask stream → new Vec
    pub fn mask_copy(&self, data: &[u8]) -> Vec<u8> {
        self.engine.mask_stream_copy(data)
    }

    /// Algo info
    pub fn algo(&self) -> ShiftMaskAlgo {
        self.engine.algo()
    }
}

// ============================================================================
// POSIX WINDOW ESC — Top-level coordinator
// ============================================================================

/// PosixWindowEsc
///
/// UNIX/POSIX ShiftMasking coordinator.
/// Combines window ID escaping and stream data masking.
/// 64-bit: full support (XOR + BitRotation + PolynomialHash + LFSR)
/// 32-bit: semi-restricted (LFSR disabled, rotation limited to 32-bit)
pub struct PosixWindowEsc {
    /// Window ID escaper
    pub id_escaper: WindowIdEscaper,
    /// Stream data escaper
    pub stream_escaper: StreamEscaper,
    /// Platform width at construction time
    pub platform: PlatformWidth,
}

impl PosixWindowEsc {
    pub fn new(key: ShiftMaskKey, algo: ShiftMaskAlgo) -> Result<Self, ShiftMaskError> {
        // ID escaper uses algo as-is
        let id_engine = ShiftMaskEngine::new(key, algo)?;
        // Stream escaper uses derived key to prevent ID/stream key collision
        let stream_key = key.derive(0xA5);
        let stream_engine = ShiftMaskEngine::new(stream_key, algo)?;

        Ok(Self {
            id_escaper: WindowIdEscaper::new(id_engine),
            stream_escaper: StreamEscaper::new(stream_engine),
            platform: PLATFORM_WIDTH,
        })
    }

    pub fn from_config(config: &WasmaConfig, algo: ShiftMaskAlgo) -> Result<Self, ShiftMaskError> {
        let key = ShiftMaskKey::from_config(config);
        Self::new(key, algo)
    }

    /// Recommended: XOR for 32-bit, LFSR for 64-bit
    pub fn from_config_auto(config: &WasmaConfig) -> Result<Self, ShiftMaskError> {
        let algo = if PLATFORM_WIDTH.is_full_support() {
            ShiftMaskAlgo::Lfsr
        } else {
            ShiftMaskAlgo::Xor
        };
        Self::from_config(config, algo)
    }

    pub fn print_info(&self) {
        println!("╔══════════════════════════════════════════╗");
        println!("║       WASMA PosixWindowEsc Info          ║");
        println!("╚══════════════════════════════════════════╝");
        println!("  Platform:    {}", self.platform.name());
        println!("  ID algo:     {}", self.id_escaper.engine.algo().name());
        println!("  Stream algo: {}", self.stream_escaper.algo().name());
        println!(
            "  Registered:  {} windows",
            self.id_escaper.registered_count()
        );
        if !self.platform.is_full_support() {
            println!("  ⚠️  Semi-restricted mode: LFSR disabled, 32-bit rotation");
        }
    }
}

// ============================================================================
// TESTS
// ============================================================================

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

    fn make_config() -> WasmaConfig {
        let parser = ConfigParser::new(None);
        let content = parser.generate_default_config();
        parser.parse(&content).unwrap()
    }

    fn make_key() -> ShiftMaskKey {
        ShiftMaskKey::new(0xDEAD_BEEF_CAFE_1234)
    }

    fn make_engine(algo: ShiftMaskAlgo) -> Option<ShiftMaskEngine> {
        ShiftMaskEngine::new(make_key(), algo).ok()
    }

    #[test]
    fn test_platform_detection() {
        let p = PLATFORM_WIDTH;
        println!("✅ Platform: {}", p.name());
        assert!(p.name().len() > 0);
    }

    #[test]
    fn test_key_from_seed() {
        let k1 = ShiftMaskKey::from_seed("wasma.app");
        let k2 = ShiftMaskKey::from_seed("wasma.app");
        let k3 = ShiftMaskKey::from_seed("other.app");
        assert_eq!(k1.raw(), k2.raw());
        assert_ne!(k1.raw(), k3.raw());
        println!("✅ ShiftMaskKey from seed deterministic");
    }

    #[test]
    fn test_key_derive() {
        let k = make_key();
        let d1 = k.derive(0xA5);
        let d2 = k.derive(0xA5);
        let d3 = k.derive(0x01);
        assert_eq!(d1.raw(), d2.raw());
        assert_ne!(d1.raw(), d3.raw());
        println!("✅ ShiftMaskKey derive deterministic");
    }

    #[test]
    fn test_xor_id_roundtrip() {
        if let Some(engine) = make_engine(ShiftMaskAlgo::Xor) {
            for id in [0u64, 1, 0xFFFF_FFFF, u64::MAX, 0xDEAD_BEEF] {
                let masked = engine.mask_id(id);
                let back = engine.unmask_id(masked);
                assert_eq!(back, id, "XOR roundtrip failed for id={}", id);
            }
            println!("✅ XOR ID roundtrip working");
        }
    }

    #[test]
    fn test_bit_rotation_id_roundtrip() {
        if let Some(engine) = make_engine(ShiftMaskAlgo::BitRotation) {
            for id in [1u64, 42, 0x1234_5678_9ABC_DEF0, u64::MAX / 2] {
                let masked = engine.mask_id(id);
                let back = engine.unmask_id(masked);
                assert_eq!(back, id, "BitRotation roundtrip failed for id={}", id);
            }
            println!("✅ BitRotation ID roundtrip working");
        }
    }

    #[test]
    fn test_poly_id_masking() {
        if let Some(engine) = make_engine(ShiftMaskAlgo::PolynomialHash) {
            let id = 0x1234u64;
            let masked = engine.mask_id(id);
            assert_ne!(masked, id);
            println!("✅ PolynomialHash ID masking working: {}{}", id, masked);
        }
    }

    #[test]
    fn test_lfsr_id_roundtrip() {
        if PLATFORM_WIDTH.is_full_support() {
            if let Some(engine) = make_engine(ShiftMaskAlgo::Lfsr) {
                for id in [1u64, 0xABCD_1234, u64::MAX] {
                    let masked = engine.mask_id(id);
                    let back = engine.unmask_id(masked);
                    assert_eq!(back, id);
                }
                println!("✅ LFSR ID roundtrip working (64-bit)");
            }
        } else {
            // LFSR must fail on 32-bit
            let result = ShiftMaskEngine::new(make_key(), ShiftMaskAlgo::Lfsr);
            assert!(matches!(result, Err(ShiftMaskError::SemiRestricted(_))));
            println!("✅ LFSR correctly blocked on 32-bit semi");
        }
    }

    #[test]
    fn test_xor_stream_roundtrip() {
        if let Some(engine) = make_engine(ShiftMaskAlgo::Xor) {
            let original = b"WASMA stream data test 1234567890";
            let mut data = original.to_vec();
            engine.mask_stream(&mut data);
            assert_ne!(data, original);
            engine.unmask_stream(&mut data);
            assert_eq!(data, original);
            println!("✅ XOR stream roundtrip working");
        }
    }

    #[test]
    fn test_rotation_stream_roundtrip() {
        if let Some(engine) = make_engine(ShiftMaskAlgo::BitRotation) {
            let original = vec![0xABu8; 64];
            let mut data = original.clone();
            engine.mask_stream(&mut data);
            engine.unmask_stream(&mut data);
            assert_eq!(data, original);
            println!("✅ BitRotation stream roundtrip working");
        }
    }

    #[test]
    fn test_window_id_escaper() {
        if let Some(engine) = make_engine(ShiftMaskAlgo::Xor) {
            let mut escaper = WindowIdEscaper::new(engine);
            let real_ids = [1u64, 2, 3, 100, 999];
            let masked: Vec<u64> = real_ids.iter().map(|&id| escaper.register(id)).collect();

            // All masked IDs distinct
            for i in 0..masked.len() {
                for j in i + 1..masked.len() {
                    assert_ne!(masked[i], masked[j]);
                }
            }
            // Resolve back
            for (i, &real) in real_ids.iter().enumerate() {
                assert_eq!(escaper.resolve(masked[i]), Some(real));
            }
            // Idempotent
            assert_eq!(escaper.register(real_ids[0]), masked[0]);
            println!(
                "✅ WindowIdEscaper working ({} windows)",
                escaper.registered_count()
            );
        }
    }

    #[test]
    fn test_stream_escaper() {
        if let Some(engine) = make_engine(ShiftMaskAlgo::Xor) {
            let escaper = StreamEscaper::new(engine);
            let original = b"test data stream";
            let masked = escaper.mask_copy(original);
            assert_ne!(masked, original);
            let mut back = masked.clone();
            escaper.unmask(&mut back);
            assert_eq!(back, original);
            println!("✅ StreamEscaper working");
        }
    }

    #[test]
    fn test_posix_window_esc_xor() {
        let config = make_config();
        let mut esc = PosixWindowEsc::from_config(&config, ShiftMaskAlgo::Xor).unwrap();

        let real_id = 42u64;
        let masked = esc.id_escaper.register(real_id);
        assert_ne!(masked, real_id);
        assert_eq!(esc.id_escaper.resolve(masked), Some(real_id));

        let data = b"hello world";
        let masked_data = esc.stream_escaper.mask_copy(data);
        assert_ne!(masked_data, data);

        esc.print_info();
        println!("✅ PosixWindowEsc (XOR) working");
    }

    #[test]
    fn test_posix_window_esc_auto() {
        let config = make_config();
        let esc = PosixWindowEsc::from_config_auto(&config);
        assert!(esc.is_ok());
        let esc = esc.unwrap();
        println!(
            "✅ PosixWindowEsc auto-algo: {}",
            esc.id_escaper.engine.algo().name()
        );
    }

    #[test]
    fn test_invalid_zero_key() {
        let key = ShiftMaskKey::new(0);
        // On 64-bit: key=0 is invalid; on 32-bit: effective=0 is also invalid
        let result = ShiftMaskEngine::new(key, ShiftMaskAlgo::Xor);
        assert!(matches!(result, Err(ShiftMaskError::InvalidKey)));
        println!("✅ Zero key correctly rejected");
    }

    #[test]
    fn test_mask_stream_copy_independent() {
        if let Some(engine) = make_engine(ShiftMaskAlgo::Xor) {
            let original = b"independent copy test";
            let copy = engine.mask_stream_copy(original);
            // Original unchanged
            assert_eq!(original, b"independent copy test");
            assert_ne!(copy.as_slice(), original.as_slice());
            println!("✅ mask_stream_copy does not modify original");
        }
    }
}