1use crate::tools::CrpMode;
2
3const MAX_COMMAND_BYTES: usize = 8192;
4
5pub fn validate_command(command: &str) -> Option<String> {
8 let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
9 let project_root = crate::core::config::Config::find_project_root();
10 validate_command_with_write_allow_paths(command, &write_allow_paths, project_root.as_deref())
11}
12
13pub(crate) fn validate_command_with_write_allow_paths(
19 command: &str,
20 write_allow_paths: &[String],
21 project_root: Option<&str>,
22) -> Option<String> {
23 validate_command_in_cwd(command, write_allow_paths, project_root, None)
24}
25
26pub(crate) fn validate_command_in_cwd(
34 command: &str,
35 write_allow_paths: &[String],
36 project_root: Option<&str>,
37 cwd: Option<&str>,
38) -> Option<String> {
39 if command.len() > MAX_COMMAND_BYTES {
40 return Some(format!(
41 "ERROR: Command too large ({} bytes, limit {}). \
42 If you're writing file content, use the native Write/Edit tool instead. \
43 ctx_shell is for reading command output only (git, cargo, npm, etc.).",
44 command.len(),
45 MAX_COMMAND_BYTES
46 ));
47 }
48
49 let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
52 let segments = segments_in_cwd(&cmd_no_heredoc, cwd);
59 if let Some(target) = segments.iter().find_map(|(segment, here)| {
71 disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
72 }) {
73 return Some(format!(
74 "ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
75 not the size of the output. ctx_shell compresses what it returns, so capturing \
76 that output into a file you keep can write compression markers instead of the \
77 command's own bytes. \
78 The rule is output capture (`>`, `>>`, `| tee`) into a project path — other \
79 commands are not restricted. \
80 Write the file with the native Write tool or ctx_patch, or capture to a scratch \
81 path (/tmp, /var/tmp, $TMPDIR), which is allowed and keeps the output out of \
82 the MCP channel entirely.{}",
83 relative_target_note(&target)
84 ));
85 }
86
87 if let Some(target) = segments.iter().find_map(|(segment, here)| {
98 disallowed_tee_target(segment, write_allow_paths, project_root, here.as_deref())
99 }) {
100 return Some(format!(
101 "ERROR: ctx_shell refuses `tee {target}` — the destination is inside the \
102 project, and ctx_shell compresses what it returns, so the captured bytes may \
103 not be the command's own. \
104 Piping makes no difference: the destination decides. \
105 The rule is output capture into a project path — other commands are not \
106 restricted. \
107 Write the file with the native Write tool, or tee to a scratch path \
108 (/tmp, /var/tmp, $TMPDIR), which is allowed.{}",
109 relative_target_note(&target)
110 ));
111 }
112
113 if is_heredoc_file_write(command, &segments, write_allow_paths, project_root) {
114 return Some(
115 "ERROR: ctx_shell detected a heredoc writing to a file. \
116 ctx_shell compresses what it returns, so content it captures into a file may \
117 not be the bytes you wrote. Use the native Write tool to create the file. \
118 Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
119 .to_string(),
120 );
121 }
122
123 if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
129 return Some(format!(
130 "ERROR: ctx_shell detected a file download/write ({reason}). \
131 Writing fetched bytes through ctx_shell risks capturing compressed output \
132 instead of the payload — redirect-free flags bypass the redirect check, so \
133 they are blocked too (GH #391). \
134 For text, fetch to stdout: curl <url> / wget -qO- <url>. \
135 For a binary (image, PDF, archive) neither stdout nor the editor's Write \
136 tool can carry the bytes — download to an absolute scratch path instead, \
137 e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661)."
138 ));
139 }
140
141 None
142}
143
144fn relative_target_note(target: &str) -> &'static str {
147 let t = target
148 .trim_start_matches(['>', '&', '|'])
149 .trim_matches(['"', '\'']);
150 if t.starts_with('/') || std::path::Path::new(t).is_absolute() {
151 return "";
152 }
153 " A relative target is placed in the directory its own command runs in: the call's \
154 `cwd`, moved by a plain `cd <dir> &&` before it. Where that directory cannot be \
155 known — a `cd` through a variable, `pushd`, a subshell, a `cd` that may not have \
156 run — a relative target is refused; give an absolute path."
157}
158
159fn segments_in_cwd(command: &str, cwd: Option<&str>) -> Vec<(String, Option<String>)> {
162 let base = cwd
163 .filter(|c| !c.trim().is_empty())
164 .map(std::path::Path::new);
165 crate::core::command_cwd::segments_with_cwd(command, base)
166 .into_iter()
167 .map(|s| {
168 let here = s.cwd.map(|p| p.to_string_lossy().into_owned());
169 (s.segment, here)
170 })
171 .collect()
172}
173
174fn is_unix_scratch_prefix(path: &str) -> bool {
178 for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
179 if path == prefix || path.starts_with(&format!("{prefix}/")) {
180 return true;
181 }
182 }
183 false
184}
185
186fn is_scratch_path(path: &str) -> bool {
190 if is_unix_scratch_prefix(path) {
191 return true;
192 }
193 if let Ok(tmpdir) = std::env::var("TMPDIR")
194 && !tmpdir.is_empty()
195 && std::path::Path::new(path).starts_with(tmpdir.as_str())
196 {
197 return true;
198 }
199 let tmp = std::env::temp_dir();
201 if std::path::Path::new(path).starts_with(&tmp) {
202 return true;
203 }
204 false
205}
206
207fn download_to_file_reason(command: &str) -> Option<String> {
210 for seg_cwd in crate::core::command_cwd::segments_with_cwd(command, None) {
218 let seg = seg_cwd.segment;
219 let here = seg_cwd.cwd;
220 let resolve = |path: &str| -> String {
221 let p = std::path::Path::new(path);
222 if p.is_absolute() || path.starts_with('/') {
225 return path.to_string();
226 }
227 match here.as_deref() {
230 Some(dir) => crate::core::command_cwd::join_in(dir, path)
231 .to_string_lossy()
232 .into_owned(),
233 None => path.to_string(),
234 }
235 };
236 let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
237 let Some(first) = tokens.first() else {
238 continue;
239 };
240 let base = first.rsplit('/').next().unwrap_or(first);
241 match base {
242 "curl" => {
243 let tokens_slice = &tokens[1..];
244 for (i, tok) in tokens_slice.iter().enumerate() {
245 let target: Option<&str> = if tok == "--output" {
246 tokens_slice.get(i + 1).map(String::as_str)
247 } else if let Some(val) = tok.strip_prefix("--output=") {
248 Some(val)
249 } else if tok == "--output-dir" {
250 tokens_slice.get(i + 1).map(String::as_str)
251 } else if let Some(val) = tok.strip_prefix("--output-dir=") {
252 Some(val)
253 } else if tok.starts_with('-')
254 && !tok.starts_with("--")
255 && tok[1..].contains('o')
256 {
257 tokens_slice.get(i + 1).map(String::as_str)
259 } else if tok == "--remote-name"
260 || tok == "--remote-name-all"
261 || (tok.starts_with('-')
262 && !tok.starts_with("--")
263 && tok[1..].contains('O'))
264 {
265 Some(".")
266 } else {
267 None
268 };
269 if let Some(path) = target {
270 if is_scratch_path(&resolve(path)) {
271 continue;
272 }
273 return Some(format!("curl {tok}"));
274 }
275 }
276 }
277 "wget" => {
278 let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
280 tok == "--output-document=-"
281 || tok == "-O-"
282 || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
283 || ((tok == "-O" || tok == "--output-document")
284 && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
285 || tok == "--spider"
286 });
287 if !to_stdout {
288 return Some(
289 "wget downloads to a file by default; use wget -qO- <url> for stdout"
290 .to_string(),
291 );
292 }
293 }
294 "dd" => {
295 for tok in &tokens[1..] {
296 if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
297 return Some(format!("dd {tok}"));
298 }
299 }
300 }
301 _ => {}
302 }
303 }
304 None
305}
306
307fn is_heredoc_file_write(
311 command: &str,
312 segments: &[(String, Option<String>)],
313 write_allow_paths: &[String],
314 project_root: Option<&str>,
315) -> bool {
316 let has_heredoc = command.contains("<<");
317 if !has_heredoc {
318 return false;
319 }
320 let cmd_lower = command.to_lowercase();
321 let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
322 let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
323 if !has_known_heredoc {
324 return false;
325 }
326 segments.iter().any(|(segment, here)| {
329 disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
330 .is_some()
331 })
332}
333
334pub fn is_temp_redirect_target(target: &str) -> bool {
344 let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
345 is_write_allowed_redirect_target(target, &write_allow_paths, None, None)
348}
349
350fn is_write_allowed_redirect_target(
351 target: &str,
352 write_allow_paths: &[String],
353 project_root: Option<&str>,
354 cwd: Option<&str>,
355) -> bool {
356 let t = target.trim_start_matches(['>', '&', '|']);
358 let t = t.trim_matches(['"', '\'']);
361 if t.starts_with('$') || t.starts_with("${") {
362 return true;
364 }
365
366 if is_unix_scratch_prefix(t) {
371 return true;
372 }
373
374 let path = std::path::Path::new(t);
388 let resolved_input;
389 let path = if path.is_absolute() {
390 path
391 } else if let Some(base) = cwd.filter(|c| !c.trim().is_empty()) {
392 resolved_input = std::path::Path::new(base).join(path);
393 resolved_input.as_path()
394 } else {
395 return false;
396 };
397 let resolved = resolve_path_for_comparison(path);
398 if project_root.is_some_and(|root| {
399 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
400 }) {
401 return false;
402 }
403 write_allow_paths.iter().any(|allowed| {
404 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
405 })
406}
407
408fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
409 use std::path::{Component, PathBuf};
410
411 let mut normalized = PathBuf::new();
412 for component in path.components() {
413 match component {
414 Component::CurDir => {}
415 Component::ParentDir => {
416 normalized.pop();
417 }
418 other => normalized.push(other.as_os_str()),
419 }
420 }
421
422 let mut unresolved = Vec::new();
423 let mut existing = normalized.clone();
424 while !existing.exists() {
425 let Some(name) = existing.file_name() else {
426 break;
427 };
428 unresolved.push(name.to_os_string());
429 if !existing.pop() {
430 break;
431 }
432 }
433 let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
434 for component in unresolved.iter().rev() {
435 resolved.push(component);
436 }
437 resolved
438}
439
440fn tee_targets(command: &str) -> Vec<String> {
441 crate::core::shell_allowlist::extract_all_commands_pub(command)
442 .into_iter()
443 .filter_map(|segment| {
444 let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
445 let first = tokens.first()?;
446 if first.rsplit('/').next().unwrap_or(first) != "tee" {
447 return None;
448 }
449 let mut after_separator = false;
450 Some(
451 tokens
452 .iter()
453 .skip(1)
454 .find(|token| {
455 if *token == "--" {
456 after_separator = true;
457 return false;
458 }
459 after_separator || !token.starts_with('-')
460 })
461 .cloned()
462 .unwrap_or_default(),
463 )
464 })
465 .collect()
466}
467
468fn disallowed_tee_target(
475 command: &str,
476 write_allow_paths: &[String],
477 project_root: Option<&str>,
478 cwd: Option<&str>,
479) -> Option<String> {
480 tee_targets(command).into_iter().find(|target| {
481 !target.is_empty()
482 && !is_write_allowed_redirect_target(target, write_allow_paths, project_root, cwd)
483 })
484}
485
486#[cfg(test)]
493fn has_file_write_redirect(
494 command: &str,
495 write_allow_paths: &[String],
496 project_root: Option<&str>,
497) -> bool {
498 disallowed_write_redirect_target(command, write_allow_paths, project_root, None).is_some()
502}
503
504fn disallowed_write_redirect_target(
513 command: &str,
514 write_allow_paths: &[String],
515 project_root: Option<&str>,
516 cwd: Option<&str>,
517) -> Option<String> {
518 let bytes = command.as_bytes();
519 let len = bytes.len();
520 let mut i = 0;
521 let mut in_single_quote = false;
522 let mut in_double_quote = false;
523
524 while i < len {
525 let c = bytes[i];
526 if c == b'\\' && !in_single_quote {
527 i += 2;
533 continue;
534 }
535 if c == b'\'' && !in_double_quote {
536 in_single_quote = !in_single_quote;
537 } else if c == b'"' && !in_single_quote {
538 in_double_quote = !in_double_quote;
539 } else if c == b'>' && !in_single_quote && !in_double_quote {
540 if i > 0 && bytes[i - 1] == b'2' {
541 i += 1;
542 continue;
543 }
544 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
545 i + 2
546 } else {
547 i + 1
548 };
549 let rest = command[target_start..].trim_start();
554 let (rest, fd_dup) = match rest.strip_prefix('|') {
555 Some(r) => (r, false),
556 None => match rest.strip_prefix('&') {
557 Some(r) => (r, true),
558 None => (rest, false),
559 },
560 };
561 let word: String = rest
574 .chars()
575 .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
576 .collect();
577 let target = if fd_dup { format!("&{word}") } else { word };
578 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
579 i += 1;
580 continue;
581 }
582 if let Some(fd) = target.strip_prefix('&')
585 && !fd.is_empty()
586 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
587 {
588 i += 1;
589 continue;
590 }
591 if is_write_allowed_redirect_target(&target, write_allow_paths, project_root, cwd) {
594 i += 1;
595 continue;
596 }
597 if !target.is_empty() {
598 return Some(target);
599 }
600 }
601 i += 1;
602 }
603 None
604}
605
606pub fn normalize_command_for_shell(command: &str) -> String {
609 if !cfg!(windows) {
610 return command.to_string();
611 }
612 let (_, flag) = crate::shell::shell_and_flag();
613 if flag != "/C" {
614 return command.to_string();
615 }
616 let bytes = command.as_bytes();
617 let mut result = Vec::with_capacity(bytes.len() + 16);
618 let mut in_single = false;
619 let mut in_double = false;
620 for (i, &b) in bytes.iter().enumerate() {
621 if b == b'\'' && !in_double {
622 in_single = !in_single;
623 } else if b == b'"' && !in_single {
624 in_double = !in_double;
625 } else if b == b';' && !in_single && !in_double {
626 result.extend_from_slice(b" && ");
627 continue;
628 }
629 result.push(b);
630 let _ = i;
631 }
632 String::from_utf8(result).unwrap_or_else(|_| command.to_string())
633}
634
635pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
640 crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
641}
642
643pub fn handle_with_context(
644 command: &str,
645 output: &str,
646 exit_code: i32,
647 crp_mode: CrpMode,
648 project_root: Option<&str>,
649) -> String {
650 let mut result = handle(command, output, exit_code, crp_mode);
651
652 {
653 if let Some(root) = project_root {
654 let estimated_tokens = result.len() / 4;
655 if estimated_tokens > 500 {
656 let kernel_budget = 100;
657 if let Some(enrichment) =
658 crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
659 && !enrichment.blocks.is_empty()
660 {
661 result.push_str("\n--- kernel context ---\n");
662 result.push_str(&enrichment.blocks);
663 }
664 }
665 }
666 }
667
668 result
669}
670
671#[cfg(test)]
672mod kernel_tests {
673 use super::handle_with_context;
674 use crate::tools::CrpMode;
675
676 #[test]
677 fn handle_with_context_does_not_panic_on_short_output() {
678 let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
679 assert!(!result.is_empty());
680 }
681}
682
683#[cfg(test)]
684fn is_search_command(command: &str) -> bool {
685 let cmd = command.trim_start();
686 cmd.starts_with("grep ")
687 || cmd.starts_with("rg ")
688 || cmd.starts_with("find ")
689 || cmd.starts_with("fd ")
690 || cmd.starts_with("ag ")
691 || cmd.starts_with("ack ")
692}
693
694#[cfg(test)]
695fn generic_compress(output: &str) -> String {
696 let output = crate::core::compressor::strip_ansi(output);
697 let lines: Vec<&str> = output
698 .lines()
699 .filter(|l| {
700 let t = l.trim();
701 !t.is_empty()
702 })
703 .collect();
704
705 if lines.len() <= 20 {
706 return lines.join("\n");
707 }
708
709 let show_count = (lines.len() / 3).min(30);
710 let half = show_count / 2;
711 let first = &lines[..half];
712 let last = &lines[lines.len() - half..];
713 let omitted = lines.len() - (half * 2);
714 format!(
715 "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
716 first.join("\n"),
717 half * 2,
718 lines.len(),
719 omitted,
720 last.join("\n")
721 )
722}
723
724pub fn contains_auth_flow(output: &str) -> bool {
728 let lower = output.to_lowercase();
729
730 const STRONG_SIGNALS: &[&str] = &[
731 "devicelogin",
732 "deviceauth",
733 "device_code",
734 "device code",
735 "device-code",
736 "verification_uri",
737 "user_code",
738 "one-time code",
739 ];
740
741 if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
742 return true;
743 }
744
745 const WEAK_SIGNALS: &[&str] = &[
746 "enter the code",
747 "enter this code",
748 "enter code:",
749 "use the code",
750 "use a web browser to open",
751 "open the page",
752 "authenticate by visiting",
753 "sign in with the code",
754 "sign in using a code",
755 "verification code",
756 "authorize this device",
757 "waiting for authentication",
758 "waiting for login",
759 "waiting for you to authenticate",
760 "open your browser",
761 "open in your browser",
762 ];
763
764 let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
765 if !has_weak_signal {
766 return false;
767 }
768
769 lower.contains("http://") || lower.contains("https://")
770}
771
772#[cfg(test)]
773mod tests;