intermcp 0.3.0

Ultra-fast, safe Model Context Protocol (MCP) engine and multiplexing hub in pure Rust, built for Interlayer Blockchain and open for all
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
use serde_json::{json, Value};
use std::env;
use std::time::Duration;
use tokio::process::Command;

use crate::error::FastMcpError;
use crate::protocol::CallToolResult;
use crate::tool::{SimpleTool, Tool};

const DEFAULT_ALLOWED_BINARIES: &[&str] = &[
    "git", "ls", "cat", "grep", "echo", "pwd", "npm", "node", "python", "python3", "curl", "rg",
];

pub const SAFE_ENV_VARS: &[&str] = &[
    "PATH",
    "Path",
    "SYSTEMROOT",
    "SystemRoot",
    "TEMP",
    "TMP",
    "HOMEDRIVE",
    "HOMEPATH",
    "USERPROFILE",
    "HOME",
    "LANG",
    "LC_ALL",
    "TERM",
];

pub fn apply_isolated_environment(cmd: &mut Command) {
    cmd.env_clear();
    for &key in SAFE_ENV_VARS {
        if let Ok(val) = env::var(key) {
            cmd.env(key, val);
        }
    }
}

pub fn create_system_info_tool() -> Box<dyn Tool> {
    Box::new(SimpleTool::new(
        "system_info",
        "Retrieve host system architecture, operating system, and hardware environment diagnostics",
        json!({
            "type": "object",
            "properties": {}
        }),
        |_args: Value| async move {
            let os = env::consts::OS;
            let arch = env::consts::ARCH;
            let current_dir = env::current_dir().unwrap_or_default().to_string_lossy().to_string();

            let info = json!({
                "os": os,
                "arch": arch,
                "currentWorkingDir": current_dir,
                "processId": std::process::id(),
                "rustRuntime": "Pure Native Rust Engine (InterMCP)",
                "memoryOverhead": "< 4MB RSS",
            });

            Ok(CallToolResult::text(serde_json::to_string_pretty(&info).unwrap_or_default()))
        },
    ).with_cacheable(true))
}

fn get_path_dirs() -> &'static [std::path::PathBuf] {
    static PATH_DIRS: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();
    PATH_DIRS.get_or_init(|| {
        let path_var = env::var_os("PATH")
            .or_else(|| env::var_os("Path"))
            .unwrap_or_default();
        env::split_paths(&path_var).collect()
    })
}

pub fn resolve_binary_in_path(binary: &str) -> Option<std::path::PathBuf> {
    for dir in get_path_dirs() {
        let candidate = dir.join(binary);
        if candidate.is_file() {
            return Some(candidate);
        }
        #[cfg(windows)]
        {
            let candidate_exe = dir.join(format!("{}.exe", binary));
            if candidate_exe.is_file() {
                return Some(candidate_exe);
            }
            let candidate_cmd = dir.join(format!("{}.cmd", binary));
            if candidate_cmd.is_file() {
                return Some(candidate_cmd);
            }
            let candidate_bat = dir.join(format!("{}.bat", binary));
            if candidate_bat.is_file() {
                return Some(candidate_bat);
            }
        }
    }
    None
}

fn contains_unquoted_shell_meta(cmd: &str) -> bool {
    let mut in_single = false;
    let mut in_double = false;

    for c in cmd.chars() {
        if c == '\'' && !in_double {
            in_single = !in_single;
        } else if c == '"' && !in_single {
            in_double = !in_double;
        } else if !in_single
            && !in_double
            && matches!(c, ';' | '&' | '|' | '\n' | '\r' | '(' | ')' | '<' | '>')
        {
            return true;
        }
    }
    false
}

pub fn create_shell_exec_tool() -> Box<dyn Tool> {
    create_shell_exec_tool_with_allowlist(Vec::new())
}

pub fn create_shell_exec_tool_with_allowlist(extra_allowed: Vec<String>) -> Box<dyn Tool> {
    Box::new(SimpleTool::new(
        "system_run_command",
        "Execute a safe terminal command and return stdout/stderr with a 30-second timeout",
        json!({
            "type": "object",
            "properties": {
                "command": { "type": "string", "description": "The command to run (e.g. 'git status' or 'cargo check')" }
            },
            "required": ["command"]
        }),
        move |args: Value| {
            let extra = extra_allowed.clone();
            async move {
                let cmd_str = args
                    .get("command")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| FastMcpError::InvalidRequest("Missing command".into()))?;

                if contains_unquoted_shell_meta(cmd_str)
                    || cmd_str.contains('`')
                    || cmd_str.contains("$(")
                {
                    return Ok(CallToolResult::error(
                        "Safe-Shell Violation: Chained/shell-meta commands are prohibited. Invoke each command in a separate tools/call. Execution blocked by security policy.".to_string(),
                    ));
                }

                if let Err(violation) = validate_shell_command(cmd_str, &extra) {
                    return Ok(CallToolResult::error(format!(
                        "Safe-Shell Violation: {}. Execution blocked by security policy.",
                        violation
                    )));
                }

                let tokens = match tokenize(cmd_str) {
                    Ok(t) => t,
                    Err(e) => {
                        return Ok(CallToolResult::error(format!(
                            "Safe-Shell Violation: {}",
                            e
                        )))
                    }
                };
                if tokens.is_empty() {
                    return Ok(CallToolResult::error("Empty command".to_string()));
                }

                #[cfg(target_os = "windows")]
                let is_builtin = matches!(
                    tokens[0].to_lowercase().as_str(),
                    "echo" | "dir" | "type" | "cls" | "cd"
                );
                #[cfg(not(target_os = "windows"))]
                let is_builtin = false;

                let mut cmd = if is_builtin {
                    #[cfg(target_os = "windows")]
                    {
                        let mut c = Command::new("cmd");
                        c.arg("/D").arg("/C").args(&tokens);
                        c
                    }
                    #[cfg(not(target_os = "windows"))]
                    {
                        let mut c = Command::new(&tokens[0]);
                        if tokens.len() > 1 {
                            c.args(&tokens[1..]);
                        }
                        c
                    }
                } else {
                    let mut c = Command::new(&tokens[0]);
                    if tokens.len() > 1 {
                        c.args(&tokens[1..]);
                    }
                    c
                };

                apply_isolated_environment(&mut cmd);
                crate::reaper::configure_child_isolation(&mut cmd);

                cmd.stdout(std::process::Stdio::piped());
                cmd.stderr(std::process::Stdio::piped());

                let mut child = match cmd.spawn() {
                    Ok(c) => c,
                    Err(e) => {
                        return Ok(CallToolResult::error(format!(
                            "Command failed to start: {}",
                            e
                        )));
                    }
                };

                let mut guard = match crate::reaper::ChildIsolationGuard::new(&child) {
                    Ok(g) => g,
                    Err(e) => {
                        let _ = child.kill().await;
                        return Ok(CallToolResult::error(format!(
                            "Failed to establish process isolation: {}",
                            e
                        )));
                    }
                };
                let timeout_duration = Duration::from_secs(30);

                let stdout_handle = child.stdout.take();
                let stderr_handle = child.stderr.take();

                let mut stdout_buf = bytes::BytesMut::with_capacity(64 * 1024);
                let mut stderr_buf = bytes::BytesMut::with_capacity(64 * 1024);

                const MAX_READ_CAP: u64 = 32 * 1024 * 1024;

                let out_fut = async {
                    if let Some(h) = stdout_handle {
                        use tokio::io::AsyncReadExt;
                        let mut limited = h.take(MAX_READ_CAP);
                        let mut chunk = [0u8; 8192];
                        while let Ok(n) = limited.read(&mut chunk).await {
                            if n == 0 {
                                break;
                            }
                            stdout_buf.extend_from_slice(&chunk[..n]);
                        }
                    }
                };

                let err_fut = async {
                    if let Some(h) = stderr_handle {
                        use tokio::io::AsyncReadExt;
                        let mut limited = h.take(MAX_READ_CAP);
                        let mut chunk = [0u8; 8192];
                        while let Ok(n) = limited.read(&mut chunk).await {
                            if n == 0 {
                                break;
                            }
                            stderr_buf.extend_from_slice(&chunk[..n]);
                        }
                    }
                };

                let stream_fut = async {
                    tokio::join!(out_fut, err_fut);
                    child.wait().await
                };

                match tokio::time::timeout(timeout_duration, stream_fut).await {
                    Ok(status_res) => match status_res {
                        Ok(status) => {
                            guard.disarm();
                            let mut stdout = String::from_utf8_lossy(&stdout_buf).to_string();
                            let mut stderr = String::from_utf8_lossy(&stderr_buf).to_string();

                            const MAX_OUTPUT_CHARS: usize = 256 * 1024;
                            if stdout.len() > MAX_OUTPUT_CHARS {
                                stdout.truncate(MAX_OUTPUT_CHARS);
                                stdout.push_str("\n... [Output truncated: exceeded 256KB]");
                            }
                            if stderr.len() > MAX_OUTPUT_CHARS {
                                stderr.truncate(MAX_OUTPUT_CHARS);
                                stderr.push_str("\n... [Stderr truncated: exceeded 256KB]");
                            }

                            let exit_code = status.code().unwrap_or(-1);
                            let res = json!({
                                "exitCode": exit_code,
                                "stdout": stdout,
                                "stderr": stderr
                            });

                            Ok(CallToolResult::text(
                                serde_json::to_string_pretty(&res).unwrap_or_default(),
                            ))
                        }
                        Err(e) => {
                            guard.kill_group();
                            Ok(CallToolResult::error(format!("Command failed: {}", e)))
                        }
                    },
                    Err(_) => {
                        let _ = child.kill().await;
                        guard.kill_group();
                        Ok(CallToolResult::error(
                            "Execution timed out after 30 seconds",
                        ))
                    }
                }
            }
        },
    ))
}

pub fn validate_shell_command(cmd: &str, extra_allowed: &[String]) -> Result<(), String> {
    let raw = cmd.trim();
    if raw.is_empty() {
        return Err("Empty command".into());
    }

    if raw.contains("$(") {
        return Err("Command substitution using '$(' is prohibited. Chained/redirected/parenthesized commands are prohibited.".into());
    }
    if raw.contains('`') {
        return Err("Command substitution using backticks (`) is prohibited. Chained/redirected/parenthesized commands are prohibited.".into());
    }
    if raw.contains("${") {
        return Err("Variable expansion using '${' is prohibited".into());
    }
    if contains_tilde_expansion(raw) {
        return Err("Tilde expansion (~) is prohibited".into());
    }
    if contains_unquoted_shell_meta(raw) {
        return Err("Chained/redirected/parenthesized commands are prohibited. Invoke each command in a separate tools/call.".into());
    }

    if raw.contains(":(){ :|:& };:") || raw.contains(":(){:|:&};:") {
        return Err("Fork bomb detected".into());
    }

    let collapsed: Vec<&str> = raw.split_whitespace().collect();
    if !collapsed.is_empty()
        && (collapsed[0] == "rm" || collapsed[0].ends_with("/rm") || collapsed[0].ends_with("\\rm"))
    {
        let destructive_flags = [
            "-rf",
            "-fr",
            "-r",
            "-f",
            "-R",
            "-Rf",
            "-RF",
            "--recursive",
            "--force",
        ];
        let has_destructive_flag = collapsed[1..]
            .iter()
            .any(|&t| destructive_flags.contains(&t));
        let mut has_positional = false;
        let mut past_dashdash = false;
        for &tok in &collapsed[1..] {
            if past_dashdash {
                has_positional = true;
                break;
            }
            if tok == "--" {
                past_dashdash = true;
                continue;
            }
            if !tok.starts_with('-') {
                has_positional = true;
                break;
            }
        }
        if has_destructive_flag && has_positional {
            return Err("Destructive recursive deletion (rm -rf) is prohibited".into());
        }
    }

    let tokens = tokenize(raw)?;
    if tokens.is_empty() {
        return Err("Empty command".into());
    }

    let raw_binary = &tokens[0];
    if raw_binary.contains('=') {
        return Err(
            "Inline environment variable assignment in command prefix is prohibited".into(),
        );
    }

    let normalized_raw = raw_binary.to_lowercase().replace('\\', "/");
    if normalized_raw == "/usr/bin/env"
        || normalized_raw == "/usr/bin/env.exe"
        || normalized_raw == "env"
        || normalized_raw == "env.exe"
        || normalized_raw.ends_with("/env")
        || normalized_raw.ends_with("/env.exe")
    {
        return Err(
            "Use of /usr/bin/env is prohibited to prevent PATH-driven binary escalation".into(),
        );
    }

    let has_path_separator = raw_binary.contains('/') || raw_binary.contains('\\');
    if has_path_separator {
        let is_explicitly_allowed_path = extra_allowed
            .iter()
            .any(|b| b.eq_ignore_ascii_case(raw_binary) || b.eq_ignore_ascii_case(&normalized_raw));
        if !is_explicitly_allowed_path {
            return Err(format!(
                "Path-qualified executable '{}' is prohibited. Direct path execution is restricted to prevent binary hijacking.",
                raw_binary
            ));
        }
    }

    let normalized_binary = extract_binary_name(raw_binary);

    let is_allowed = DEFAULT_ALLOWED_BINARIES
        .iter()
        .any(|&b| b.eq_ignore_ascii_case(&normalized_binary))
        || extra_allowed
            .iter()
            .any(|b| b.eq_ignore_ascii_case(&normalized_binary));

    if !is_allowed {
        return Err(format!(
            "Binary '{}' is not in the execution allowlist",
            normalized_binary
        ));
    }

    #[cfg(target_os = "windows")]
    let is_builtin = matches!(
        normalized_binary.to_lowercase().as_str(),
        "echo" | "dir" | "type" | "cls" | "cd"
    );
    #[cfg(not(target_os = "windows"))]
    let is_builtin = false;

    if !is_builtin && !has_path_separator {
        if let Some(resolved) = resolve_binary_in_path(&normalized_binary) {
            let stem = resolved
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_lowercase();
            let base_matches = DEFAULT_ALLOWED_BINARIES
                .iter()
                .any(|&b| b.eq_ignore_ascii_case(&stem))
                || extra_allowed.iter().any(|b| b.eq_ignore_ascii_case(&stem));
            if !base_matches {
                return Err(format!(
                    "Binary '{}' resolved in PATH as '{}' which does not match allowlist",
                    normalized_binary,
                    resolved.display()
                ));
            }
        } else {
            let base_matches = DEFAULT_ALLOWED_BINARIES
                .iter()
                .any(|&b| b.eq_ignore_ascii_case(&normalized_binary))
                || extra_allowed
                    .iter()
                    .any(|b| b.eq_ignore_ascii_case(&normalized_binary));
            if !base_matches {
                return Err(format!(
                    "Binary '{}' not allowed for PATH-search execution",
                    normalized_binary
                ));
            }
        }
    }

    if normalized_binary.eq_ignore_ascii_case("rm") {
        let mut has_r = false;
        let mut has_f = false;
        for token in &tokens[1..] {
            let t = token.trim();
            match t {
                "-rf" | "-fr" | "-Rf" | "-RF" => {
                    return Err("Destructive recursive deletion (rm -rf) is prohibited".into());
                }
                "-r" | "-R" | "--recursive" => {
                    has_r = true;
                }
                "-f" | "--force" => {
                    has_f = true;
                }
                _ => {}
            }
            if has_r && has_f {
                return Err("Destructive recursive deletion (rm -rf) is prohibited".into());
            }
        }
    }

    if normalized_binary.eq_ignore_ascii_case("git") {
        let lower_cmd = raw.to_lowercase();
        if lower_cmd.contains("core.editor")
            || lower_cmd.contains("core.pager")
            || lower_cmd.contains("--upload-pack")
            || lower_cmd.contains("receive.fsck")
        {
            if lower_cmd.contains("rm -rf") {
                return Err(
                    "Git option injection with destructive command (rm -rf) is prohibited".into(),
                );
            }
            return Err("Git option injection (core.editor / execution hook) is prohibited".into());
        }
    }

    let lower_tokens: Vec<String> = tokens.iter().map(|t| t.to_lowercase()).collect();
    let joined_sub = lower_tokens.join(" ");

    let has_opt_in =
        |flag: &str| -> bool { extra_allowed.iter().any(|b| b.eq_ignore_ascii_case(flag)) };

    if (normalized_binary.eq_ignore_ascii_case("python")
        || normalized_binary.eq_ignore_ascii_case("python3"))
        && lower_tokens.iter().any(|t| t == "-c")
        && !has_opt_in("python -c")
        && !has_opt_in("python3 -c")
    {
        return Err("Arbitrary code execution flag 'python -c' is prohibited".into());
    }

    if normalized_binary.eq_ignore_ascii_case("perl")
        && lower_tokens.iter().any(|t| t == "-e")
        && !has_opt_in("perl -e")
    {
        return Err("Arbitrary code execution flag 'perl -e' is prohibited".into());
    }

    if normalized_binary.eq_ignore_ascii_case("ruby")
        && lower_tokens.iter().any(|t| t == "-e")
        && !has_opt_in("ruby -e")
    {
        return Err("Arbitrary code execution flag 'ruby -e' is prohibited".into());
    }

    if normalized_binary.eq_ignore_ascii_case("node")
        && lower_tokens.iter().any(|t| t == "-e" || t == "--eval")
        && !has_opt_in("node -e")
    {
        return Err("Arbitrary code execution flag 'node -e' is prohibited".into());
    }

    if (normalized_binary.eq_ignore_ascii_case("powershell")
        || normalized_binary.eq_ignore_ascii_case("pwsh"))
        && lower_tokens
            .iter()
            .any(|t| t == "-encodedcommand" || t == "-e")
    {
        return Err("PowerShell -EncodedCommand is prohibited".into());
    }

    if normalized_binary.eq_ignore_ascii_case("find")
        && (joined_sub.contains("-delete") || joined_sub.contains("-exec rm"))
    {
        return Err("Destructive find execution (-delete or -exec rm) is prohibited".into());
    }

    if normalized_binary.eq_ignore_ascii_case("rsync") && joined_sub.contains("--delete") {
        return Err("Destructive rsync execution (--delete) is prohibited".into());
    }

    if normalized_binary.eq_ignore_ascii_case("mv")
        && (joined_sub.contains("/dev/null") || joined_sub.contains("/*"))
    {
        return Err("Destructive move to /dev/null is prohibited".into());
    }

    if normalized_binary.eq_ignore_ascii_case("chmod")
        && (joined_sub.contains("-r 000") || joined_sub.contains("000 /"))
    {
        return Err("Destructive permission zeroing (chmod 000) is prohibited".into());
    }

    if (normalized_binary.eq_ignore_ascii_case("rd")
        || normalized_binary.eq_ignore_ascii_case("rmdir"))
        && (joined_sub.contains("/s") || joined_sub.contains("-s"))
    {
        return Err("Destructive recursive directory removal is prohibited".into());
    }

    if normalized_binary.eq_ignore_ascii_case("format")
        || normalized_binary.eq_ignore_ascii_case("diskpart")
        || (normalized_binary.eq_ignore_ascii_case("cipher") && joined_sub.contains("/w"))
    {
        return Err("Disk destruction/formatting command is prohibited".into());
    }

    if raw.contains("/dev/sd")
        || raw.contains("/dev/nvme")
        || raw.contains("/dev/hd")
        || raw.contains("/dev/disk")
    {
        return Err("Direct raw block device access or modification is prohibited".into());
    }

    if (normalized_binary.eq_ignore_ascii_case("curl")
        || normalized_binary.eq_ignore_ascii_case("wget")
        || normalized_binary.eq_ignore_ascii_case("base64"))
        && (raw.contains("| sh")
            || raw.contains("| bash")
            || raw.contains("|sh")
            || raw.contains("|bash")
            || raw.contains("| zsh")
            || raw.contains("| powershell")
            || raw.contains("| cmd"))
    {
        return Err(
            "Unchecked remote code execution pipeline (curl/base64 | sh) is prohibited".into(),
        );
    }

    if joined_sub.contains("/dev/tcp/")
        || (normalized_binary.eq_ignore_ascii_case("nc")
            && (joined_sub.contains("-e /bin/sh") || joined_sub.contains("-e /bin/bash")))
    {
        return Err("Reverse shell pattern detected".into());
    }

    Ok(())
}

pub(crate) fn split_chained_commands(cmd: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut in_single_quote = false;
    let mut in_double_quote = false;
    let chars: Vec<char> = cmd.chars().collect();
    let len = chars.len();
    let mut i = 0;

    while i < len {
        let c = chars[i];
        if c == '\'' && !in_double_quote {
            in_single_quote = !in_single_quote;
            current.push(c);
        } else if c == '"' && !in_single_quote {
            in_double_quote = !in_double_quote;
            current.push(c);
        } else if !in_single_quote && !in_double_quote {
            if c == ';' || c == '\n' {
                parts.push(std::mem::take(&mut current));
            } else if i + 1 < len
                && ((c == '&' && chars[i + 1] == '&') || (c == '|' && chars[i + 1] == '|'))
            {
                parts.push(std::mem::take(&mut current));
                i += 1;
            } else if c == '|' || c == '&' {
                parts.push(std::mem::take(&mut current));
            } else {
                current.push(c);
            }
        } else {
            current.push(c);
        }
        i += 1;
    }

    if !current.trim().is_empty() {
        parts.push(current);
    }

    parts
}

fn contains_tilde_expansion(s: &str) -> bool {
    let chars: Vec<char> = s.chars().collect();
    for (i, &c) in chars.iter().enumerate() {
        if c == '~' {
            let prev = if i > 0 { Some(chars[i - 1]) } else { None };
            let next = if i + 1 < chars.len() {
                Some(chars[i + 1])
            } else {
                None
            };
            match prev {
                None => return true,
                Some(p)
                    if p.is_whitespace()
                        || p == '"'
                        || p == '\''
                        || p == '='
                        || p == ':'
                        || p == ';'
                        || p == '|'
                        || p == '&'
                        || p == '/' =>
                {
                    return true;
                }
                _ => {}
            }
            if let Some('/') = next {
                return true;
            }
            if next.is_none() || next.unwrap().is_whitespace() {
                return true;
            }
        }
    }
    false
}

fn tokenize(cmd: &str) -> Result<Vec<String>, String> {
    if cmd.contains("$(") {
        return Err("Command substitution using '$(' is prohibited".into());
    }
    if cmd.contains('`') {
        return Err("Command substitution using backticks (`) is prohibited".into());
    }
    if cmd.contains("${") {
        return Err("Variable expansion using '${' is prohibited".into());
    }
    if contains_tilde_expansion(cmd) {
        return Err("Tilde expansion (~) is prohibited".into());
    }

    shell_words::split(cmd).map_err(|e| format!("Invalid shell syntax: {}", e))
}

fn extract_binary_name(raw: &str) -> String {
    let mut s = raw.trim();
    let p = std::path::Path::new(s);
    if s.starts_with('/') {
        if let Some(name) = p.file_name().and_then(|f| f.to_str()) {
            return name.strip_suffix(".exe").unwrap_or(name).to_string();
        }
    }
    while s.starts_with('\\') || s.starts_with('/') {
        s = &s[1..];
    }

    let last_segment = s.rsplit(['/', '\\']).next().unwrap_or(s);
    let p = std::path::Path::new(last_segment);
    let stem = p
        .file_stem()
        .and_then(|f| f.to_str())
        .unwrap_or(last_segment);

    stem.to_string()
}

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

    #[test]
    fn validate_rejects_chained_semicolon() {
        let res = validate_shell_command("git status; echo pwned", &[]);
        assert!(res.is_err());
        assert!(res
            .unwrap_err()
            .contains("Chained/redirected/parenthesized commands are prohibited"));
    }

    #[test]
    fn validate_rejects_rm_rf_with_dashdash() {
        let res = validate_shell_command("rm -rf -- target", &[]);
        assert!(res.is_err());
        assert!(res
            .unwrap_err()
            .contains("Destructive recursive deletion (rm -rf) is prohibited"));
    }

    #[test]
    fn validate_accepts_plain_git_status() {
        let res = validate_shell_command("git status", &[]);
        assert!(
            res.is_ok(),
            "Expected git status to be allowed, got {:?}",
            res
        );
    }
}