dixscript 1.0.0

Config, code, and encryption in one file — a data interchange format with compile-time functions, AES-256/ChaCha20 built-in, and cross-platform FFI
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
//! Reverse orchestrator for DLM pipeline during loading.
//!
//! Execution order: Decryptor → Decompressor.

use crate::Compiler::DLM::{
    Auditor::{IAuditor, DiyAuditor},
    Compressor::{ICompressor, GzipCompressor},
    Encryptor::{IEncryptor, XorEncryptor, Aes128Encryptor, Aes256Encryptor, Chacha20Encryptor},
    KeyManagement::{KeyFileManager, KeyFileData},
    dlm_pipeline_result::DLMReverseResult,
};
use crate::ErrorManager::{ErrorManager, DebugConfig, DlmErrorType, ErrorSeverity};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use web_time::Instant;
use std::fs;

#[cfg(feature = "bzip2-support")]
use crate::Compiler::DLM::Compressor::Bzip2Compressor;
#[cfg(feature = "xz-support")]
use crate::Compiler::DLM::Compressor::LzmaCompressor;

pub struct DLMReverseExecutor {
    error_manager:       ErrorManager,
    debug_config:        DebugConfig,
    encrypted_file_path: PathBuf,
    key_file_path:       PathBuf,
    password:            Option<String>,
}

impl DLMReverseExecutor {
    pub fn new(
        encrypted_file_path: impl AsRef<Path>,
        key_file_path: impl AsRef<Path>,
        password: Option<String>,
        debug_mode: crate::Compiler::Core::Config::DebugMode,
    ) -> Self {
        Self::new_with_error_manager(encrypted_file_path,key_file_path,password,debug_mode,ErrorManager::get_shared_instance())
    }
    pub fn new_with_error_manager(
        encrypted_file_path: impl AsRef<Path>,
        key_file_path: impl AsRef<Path>,
        password: Option<String>,
        debug_mode: crate::Compiler::Core::Config::DebugMode,
        error_manager: ErrorManager
    ) -> Self {

        let debug_config  = DebugConfig::from_debug_mode(debug_mode);

        DLMReverseExecutor {
            error_manager,
            debug_config,
            encrypted_file_path: encrypted_file_path.as_ref().to_path_buf(),
            key_file_path:       key_file_path.as_ref().to_path_buf(),
            password,
        }
    }
    // ── Main entry point ──────────────────────────────────────────────────────

    pub fn execute(&self) -> DLMReverseResult {
        let start_time = Instant::now();

        self.error_manager.log_info("DLM reverse pipeline started");

        let encrypted_data = match fs::read(&self.encrypted_file_path) {
            Ok(data) => data,
            Err(e) => {
                let msg = format!("Failed to read encrypted file: {}", e);
                self.error_manager.add_dlm_error(
                    DlmErrorType::ModuleExecutionFailed,
                    msg.clone(),
                    Some(self.file_label()),
                    None,
                    Some("Ensure the .mdix.enc file exists".to_string()),
                    ErrorSeverity::Fatal,
                );
                let mut result = DLMReverseResult::new(0);
                result.errors.push(msg);
                result.total_duration = start_time.elapsed();
                return result;
            }
        };

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[DLMReverseExecutor] Read {} bytes from encrypted file",
                encrypted_data.len(),
            ));
        }

        let key_data = match self.load_key_file() {
            Ok(kd) => kd,
            Err(e) => {
                let mut result = DLMReverseResult::new(encrypted_data.len());
                result.errors.push(e);
                result.total_duration = start_time.elapsed();
                return result;
            }
        };

        self.execute_with_data(encrypted_data, key_data)
    }

    /// Same pipeline as `execute()`, but takes the encrypted bytes and the
    /// already-read `.mdix.key` file content directly instead of reading
    /// either from disk — for wasm32 (no real filesystem) or any caller
    /// that already has both in memory (e.g. from
    /// `DLMPipelineResult::processed_data` /
    /// `DLMPipelineResult::key_file_content` on the forward side, in the
    /// same process or round-tripped over the network/localStorage).
    ///
    /// `self.encrypted_file_path` / `self.key_file_path` from `new(...)`
    /// are still used for auditor/log labeling only in this path — they
    /// don't need to point at real files. Pass placeholder strings (e.g.
    /// `""` or `"in-memory"`) if there's nothing meaningful to put there.
    pub fn execute_from_bytes(
        &self,
        encrypted_data:   Vec<u8>,
        key_file_content: &str,
    ) -> DLMReverseResult {
        let key_data = match crate::Compiler::DLM::KeyManagement::MdixKeyParser::parse(key_file_content) {
            Ok(kd) => kd,
            Err(e) => {
                let msg = format!("Failed to parse key file content: {}", e);
                self.error_manager.add_dlm_error(
                    DlmErrorType::InvocationFailed,
                    msg.clone(),
                    Some(self.file_label()),
                    None,
                    Some("Key content may be corrupted or from an incompatible version".to_string()),
                    ErrorSeverity::Error,
                );
                let mut result = DLMReverseResult::new(encrypted_data.len());
                result.errors.push(msg);
                return result;
            }
        };

        self.execute_with_data(encrypted_data, key_data)
    }

    fn execute_with_data(
        &self,
        encrypted_data: Vec<u8>,
        key_data:       KeyFileData,
    ) -> DLMReverseResult {
        let start_time = Instant::now();

        let mut result = DLMReverseResult::new(encrypted_data.len());

        let (mut encryptor, compressor, mut auditor) =
            match self.instantiate_modules(&key_data) {
                Ok(modules) => modules,
                Err(e) => {
                    self.error_manager.add_dlm_error(
                        DlmErrorType::ModuleExecutionFailed,
                        e.clone(),
                        Some(self.file_label()),
                        None,
                        None,
                        ErrorSeverity::Fatal,
                    );
                    result.errors.push(e);
                    result.total_duration = start_time.elapsed();
                    return result;
                }
            };

        let mut processed_data = encrypted_data;

        // Phase 1: decrypt
        if let Some(ref mut enc) = encryptor {
            if let Some(ref password) = self.password {
                if let Err(e) = enc.set_password(password) {
                    self.error_manager.add_dlm_error(
                        DlmErrorType::ModuleExecutionFailed,
                        e.clone(),
                        Some(self.file_label()),
                        Some(enc.module_name().to_string()),
                        Some("Check the password is correct".to_string()),
                        ErrorSeverity::Fatal,
                    );
                    if let Some(ref mut aud) = auditor {
                        aud.log_decryption_attempt(
                            false,
                            &format!("Password setup failed: {}", e),
                            result.encrypted_size,
                            0,
                            start_time.elapsed().as_secs_f64() * 1000.0,
                        );
                        let _ = aud.finalize_audit();
                    }
                    result.errors.push(e);
                    result.total_duration = start_time.elapsed();
                    return result;
                }
            }

            let phase_start = Instant::now();
            match enc.decrypt(&processed_data) {
                Ok(decrypted) => {
                    let duration_ms = phase_start.elapsed().as_secs_f64() * 1000.0;

                    if let Some(ref mut aud) = auditor {
                        aud.log_decryption_attempt(
                            true,
                            &format!("Decrypted with {}", enc.algorithm()),
                            result.encrypted_size,
                            decrypted.len(),
                            duration_ms,
                        );
                    }

                    result.executed_modules.push(enc.module_name().to_string());

                    self.error_manager.log_info(&format!(
                        "Decryption complete: {} -> {} bytes",
                        result.encrypted_size,
                        decrypted.len(),
                    ));

                    processed_data = decrypted;
                }
                Err(e) => {
                    let duration_ms = phase_start.elapsed().as_secs_f64() * 1000.0;

                    self.error_manager.add_dlm_error(
                        DlmErrorType::ModuleExecutionFailed,
                        e.clone(),
                        Some(self.file_label()),
                        Some(enc.module_name().to_string()),
                        Some("Verify the password or key file is correct".to_string()),
                        ErrorSeverity::Fatal,
                    );

                    if let Some(ref mut aud) = auditor {
                        aud.log_decryption_attempt(
                            false,
                            &format!("Decryption failed: {}", e),
                            result.encrypted_size,
                            0,
                            duration_ms,
                        );
                        let _ = aud.finalize_audit();
                    }

                    result.errors.push(e);
                    result.total_duration = start_time.elapsed();
                    return result;
                }
            }
        }

        // Phase 2: decompress
        if let Some(ref comp) = compressor {
            let pre_size    = processed_data.len();
            let phase_start = Instant::now();
            match comp.decompress(&processed_data) {
                Ok(decompressed) => {
                    let duration_ms = phase_start.elapsed().as_secs_f64() * 1000.0;

                    result.executed_modules.push(comp.module_name().to_string());

                    self.error_manager.log_info(&format!(
                        "Decompression complete: {} -> {} bytes",
                        pre_size,
                        decompressed.len(),
                    ));

                    if let Some(ref mut aud) = auditor {
                        aud.log_step(
                            comp.module_name(),
                            &format!("Decompressed with {}", comp.algorithm()),
                            pre_size,
                            decompressed.len(),
                            duration_ms,
                        );
                    }

                    processed_data = decompressed;
                }
                Err(e) => {
                    self.error_manager.add_dlm_error(
                        DlmErrorType::ModuleExecutionFailed,
                        e.clone(),
                        Some(self.file_label()),
                        Some(comp.module_name().to_string()),
                        Some(
                            "The data may be corrupted or use an algorithm unavailable \
                             on this platform.".to_string()
                        ),
                        ErrorSeverity::Fatal,
                    );
                    if let Some(ref mut aud) = auditor {
                        let _ = aud.finalize_audit();
                    }
                    result.errors.push(e);
                    result.total_duration = start_time.elapsed();
                    return result;
                }
            }
        }

        // Finalize auditor
        if let Some(ref mut aud) = auditor {
            if let Err(e) = aud.finalize_audit() {
                self.error_manager.add_dlm_error(
                    DlmErrorType::ModuleExecutionFailed,
                    e.clone(),
                    Some(self.file_label()),
                    Some("DAuditor".to_string()),
                    None,
                    ErrorSeverity::Warning,
                );
                result.warnings.push(format!("Audit finalization warning: {}", e));
            }
        }

        result.restored_data  = processed_data;
        result.restored_size  = result.restored_data.len();
        result.is_success     = true;
        result.total_duration = start_time.elapsed();

        self.error_manager.log_info(&format!(
            "DLM reverse pipeline complete: {} modules, {} -> {} bytes, {:.2}ms",
            result.executed_modules.len(),
            result.encrypted_size,
            result.restored_size,
            result.total_duration.as_secs_f64() * 1000.0,
        ));

        result
    }

    // ── Key file loading ──────────────────────────────────────────────────────

    fn load_key_file(&self) -> Result<KeyFileData, String> {
        let dir = self.encrypted_file_path
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .to_string_lossy()
            .to_string();

        let key_manager  = KeyFileManager::new(dir.clone(), dir);
        let key_path_str = self.key_file_path.to_string_lossy().to_string();
        let data         = key_manager.read_key_file(&key_path_str)?;

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[DLMReverseExecutor] Key file loaded: mode={}, modules={}",
                data.config.key_type,
                data.pipeline.modules_used.join(","),
            ));
        }

        Ok(data)
    }

    // ── Module instantiation ──────────────────────────────────────────────────

    fn instantiate_modules(
        &self,
        key_data: &KeyFileData,
    ) -> Result<(
        Option<Box<dyn IEncryptor>>,
        Option<Box<dyn ICompressor>>,
        Option<Box<dyn IAuditor>>,
    ), String> {
        let dir = self.encrypted_file_path
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .to_string_lossy()
            .to_string();

        let key_manager = KeyFileManager::new(dir.clone(), dir.clone());

        let mut encryptor:  Option<Box<dyn IEncryptor>>  = None;
        let mut compressor: Option<Box<dyn ICompressor>> = None;
        let mut auditor:    Option<Box<dyn IAuditor>>    = None;

        if let Some(ref enc_data) = key_data.key_data.encryption {
            let config = key_manager
                .extract_encryption_config(key_data)
                .unwrap_or_default();
            encryptor = Some(self.create_decryptor(&enc_data.algorithm, &config)?);

            if self.debug_config.is_enabled {
                self.error_manager.log_debug(&format!(
                    "[DLMReverseExecutor] Decryptor: {}",
                    enc_data.algorithm,
                ));
            }
        }

        if let Some(ref comp_data) = key_data.key_data.compression {
            compressor = Some(self.create_decompressor(&comp_data.algorithm)?);

            if self.debug_config.is_enabled {
                self.error_manager.log_debug(&format!(
                    "[DLMReverseExecutor] Decompressor: {}",
                    comp_data.algorithm,
                ));
            }
        }

        let had_auditor = key_data.pipeline.modules_used.iter()
            .any(|m| m.to_lowercase().contains("dauditor"));

        if had_auditor {
            let source = self.derive_source_path();
            let output = self.encrypted_file_path
                .parent()
                .unwrap_or_else(|| Path::new("."));
            auditor = Some(Box::new(DiyAuditor::new(&source, output)));

            if self.debug_config.is_enabled {
                self.error_manager.log_debug(
                    "[DLMReverseExecutor] Auditor created for decryption logging",
                );
            }
        }

        Ok((encryptor, compressor, auditor))
    }

    fn create_decryptor(
        &self,
        algorithm: &str,
        config: &HashMap<String, String>,
    ) -> Result<Box<dyn IEncryptor>, String> {
        let mut enc: Box<dyn IEncryptor> = match algorithm.to_lowercase().as_str() {
            "xor"                              => Box::new(XorEncryptor::new(None)),
            "aes128-gcm" | "aes128"            => Box::new(Aes128Encryptor::new(None)),
            "aes256-gcm" | "aes256"            => Box::new(Aes256Encryptor::new(None)),
            "chacha20-poly1305" | "chacha20"   => Box::new(Chacha20Encryptor::new(None)),
            _ => {
                let msg = format!(
                    "Unknown encryption algorithm in key file: '{}'", algorithm
                );
                self.error_manager.add_dlm_error(
                    DlmErrorType::ModuleExecutionFailed,
                    msg.clone(),
                    Some(self.file_label()),
                    None,
                    None,
                    ErrorSeverity::Fatal,
                );
                return Err(msg);
            }
        };

        enc.initialize(config.clone());
        Ok(enc)
    }

    fn create_decompressor(
        &self,
        algorithm: &str,
    ) -> Result<Box<dyn ICompressor>, String> {
        match algorithm.to_lowercase().as_str() {
            "gzip" => Ok(Box::new(GzipCompressor::new())),

            #[cfg(feature = "bzip2-support")]
            "bzip2" => Ok(Box::new(Bzip2Compressor::new())),
            #[cfg(not(feature = "bzip2-support"))]
            "bzip2" => Err(
                "This file was compressed with bzip2, but this build of \
                 dixscript was compiled without the 'bzip2-support' feature. \
                 Rebuild with `--features bzip2-support` (or default \
                 features) to decompress it.".to_string()
            ),

            #[cfg(feature = "xz-support")]
            "lzma" => Ok(Box::new(LzmaCompressor::new())),
            #[cfg(not(feature = "xz-support"))]
            "lzma" => Err(
                "This file was compressed with XZ/LZMA, but this build of \
                 dixscript was compiled without the 'xz-support' feature. \
                 Rebuild with `--features xz-support` (or default features) \
                 to decompress it.".to_string()
            ),

            _ => {
                let msg = format!(
                    "Unknown compression algorithm in key file: '{}'", algorithm
                );
                self.error_manager.add_dlm_error(
                    DlmErrorType::ModuleExecutionFailed,
                    msg.clone(),
                    Some(self.file_label()),
                    None,
                    None,
                    ErrorSeverity::Fatal,
                );
                Err(msg)
            }
        }
    }

    // ── Utility ───────────────────────────────────────────────────────────────

    fn derive_source_path(&self) -> PathBuf {
        let dir = self.encrypted_file_path
            .parent()
            .unwrap_or_else(|| Path::new("."));

        let mut name = self.encrypted_file_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown")
            .to_string();

        // Strip compound suffix first, then single extension.
        // Previously this stripped ".dixscript" — must be ".mdix".
        if let Some(stripped) = name.strip_suffix(".enc")  { name = stripped.to_string(); }
        if let Some(stripped) = name.strip_suffix(".mdix") { name = stripped.to_string(); }

        let candidate = dir.join(format!("{}.mdix", name));

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "[DLMReverseExecutor] Derived source path: {}",
                candidate.display(),
            ));
        }

        candidate
    }

    #[inline]
    fn file_label(&self) -> String {
        self.encrypted_file_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown")
            .to_string()
    }
    }