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
26const CAPTURE_RULE: &str = "The rule: output capture (`>`, `>>`, `| tee`) may only go to a \
33 scratch path (/tmp, /var/tmp, $TMPDIR) or a directory listed in `write_allow_paths` in \
34 config.toml. Every other destination is refused, inside the project or not, and the \
35 project root stays refused even when listed. Commands that do not capture output are \
36 not restricted.";
37
38const WRITE_REASON: &str = "Files you keep are written with ctx_patch or the native Write/Edit \
47 tool, so the read-before-write gate and the edit checks apply to them; ctx_shell does not \
48 write them through output capture. This is unconditional: the redirect itself is not \
49 compressed, so a smaller command or `raw=true` does not change the verdict.";
50
51pub(crate) fn validate_command_in_cwd(
59 command: &str,
60 write_allow_paths: &[String],
61 project_root: Option<&str>,
62 cwd: Option<&str>,
63) -> Option<String> {
64 if command.len() > MAX_COMMAND_BYTES {
65 return Some(format!(
66 "ERROR: Command too large ({} bytes, limit {}). \
67 If you're writing file content, use the native Write/Edit tool instead. \
68 ctx_shell is for reading command output only (git, cargo, npm, etc.).",
69 command.len(),
70 MAX_COMMAND_BYTES
71 ));
72 }
73
74 let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
77 let segments = segments_in_cwd(&cmd_no_heredoc, cwd);
84 if let Some(target) = segments.iter().find_map(|(segment, here)| {
93 disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
94 }) {
95 return Some(format!(
96 "ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
97 not the size or content of the output. {WRITE_REASON} {CAPTURE_RULE} \
98 Write the file with ctx_patch or the native Write tool, or capture to a scratch \
99 path.{}",
100 relative_target_note(&target)
101 ));
102 }
103
104 if let Some(target) = segments.iter().find_map(|(segment, here)| {
115 disallowed_tee_target(segment, write_allow_paths, project_root, here.as_deref())
116 }) {
117 return Some(format!(
118 "ERROR: ctx_shell refuses `tee {target}`. Piping makes no difference: the \
119 destination decides. {WRITE_REASON} {CAPTURE_RULE} \
120 Write the file with ctx_patch or the native Write tool, or tee to a scratch \
121 path.{}",
122 relative_target_note(&target)
123 ));
124 }
125
126 if is_heredoc_file_write(command, &segments, write_allow_paths, project_root) {
127 return Some(format!(
128 "ERROR: ctx_shell detected a heredoc writing to a file. {WRITE_REASON} \
129 Create the file with ctx_patch (op=create) or the native Write tool. \
130 Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
131 ));
132 }
133
134 if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
140 return Some(format!(
141 "ERROR: ctx_shell detected a file download/write ({reason}). \
142 Download flags write a file without a redirect, so the capture rule applies \
143 to them as well (GH #391). \
144 For text, fetch to stdout: curl <url> / wget -qO- <url>. \
145 For a binary (image, PDF, archive) neither stdout nor the editor's Write \
146 tool can carry the bytes — download to an absolute scratch path instead, \
147 e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661). \
148 The target must be a literal path, $TMPDIR, or a variable this same command \
149 set to a literal earlier (D=/tmp/x; curl -o $D/f); any other variable cannot \
150 be resolved here and is refused."
151 ));
152 }
153
154 None
155}
156
157fn relative_target_note(target: &str) -> &'static str {
160 let t = target
161 .trim_start_matches(['>', '&', '|'])
162 .trim_matches(['"', '\'']);
163 if t.starts_with('/') || std::path::Path::new(t).is_absolute() {
164 return "";
165 }
166 " A relative target is placed in the directory its own command runs in: the call's \
167 `cwd`, moved by a plain `cd <dir> &&` before it. Where that directory cannot be \
168 known — a `cd` through a variable, `pushd`, a subshell, a `cd` that may not have \
169 run — a relative target is refused; give an absolute path."
170}
171
172fn segments_in_cwd(command: &str, cwd: Option<&str>) -> Vec<(String, Option<String>)> {
175 let base = cwd
176 .filter(|c| !c.trim().is_empty())
177 .map(std::path::Path::new);
178 crate::core::command_cwd::segments_with_cwd(command, base)
179 .into_iter()
180 .map(|s| {
181 let here = s.cwd.map(|p| p.to_string_lossy().into_owned());
182 (s.segment, here)
183 })
184 .collect()
185}
186
187fn is_unix_scratch_prefix(path: &str) -> bool {
191 for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
192 if path == prefix || path.starts_with(&format!("{prefix}/")) {
193 return true;
194 }
195 }
196 false
197}
198
199fn is_scratch_path(path: &str) -> bool {
203 if is_unix_scratch_prefix(path) {
204 return true;
205 }
206 if let Ok(tmpdir) = std::env::var("TMPDIR")
207 && !tmpdir.is_empty()
208 && std::path::Path::new(path).starts_with(tmpdir.as_str())
209 {
210 return true;
211 }
212 let tmp = std::env::temp_dir();
214 if std::path::Path::new(path).starts_with(&tmp) {
215 return true;
216 }
217 false
218}
219
220fn download_to_file_reason(command: &str) -> Option<String> {
223 let segments = crate::core::command_cwd::segments_with_cwd(command, None);
235 let known_vars = literal_assignments_before_each_segment(command, segments.len());
236 for (index, seg_cwd) in segments.into_iter().enumerate() {
237 let seg = seg_cwd.segment;
238 let here = seg_cwd.cwd;
239 let vars = &known_vars[index];
240 let resolve = |path: &str| -> String {
241 let expanded = expand_leading_variable(path, vars);
242 let path = expanded.as_deref().unwrap_or(path);
243 let p = std::path::Path::new(path);
244 if p.is_absolute() || path.starts_with('/') {
247 return path.to_string();
248 }
249 match here.as_deref() {
252 Some(dir) => crate::core::command_cwd::join_in(dir, path)
253 .to_string_lossy()
254 .into_owned(),
255 None => path.to_string(),
256 }
257 };
258 let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
259 let Some(first) = tokens.first() else {
260 continue;
261 };
262 let base = first.rsplit('/').next().unwrap_or(first);
263 match base {
264 "curl" => {
265 let tokens_slice = &tokens[1..];
266 for (i, tok) in tokens_slice.iter().enumerate() {
267 let target: Option<&str> = if tok == "--output" {
268 tokens_slice.get(i + 1).map(String::as_str)
269 } else if let Some(val) = tok.strip_prefix("--output=") {
270 Some(val)
271 } else if tok == "--output-dir" {
272 tokens_slice.get(i + 1).map(String::as_str)
273 } else if let Some(val) = tok.strip_prefix("--output-dir=") {
274 Some(val)
275 } else if tok.starts_with('-')
276 && !tok.starts_with("--")
277 && tok[1..].contains('o')
278 {
279 tokens_slice.get(i + 1).map(String::as_str)
281 } else if tok == "--remote-name"
282 || tok == "--remote-name-all"
283 || (tok.starts_with('-')
284 && !tok.starts_with("--")
285 && tok[1..].contains('O'))
286 {
287 Some(".")
288 } else {
289 None
290 };
291 if let Some(path) = target {
292 if is_scratch_path(&resolve(path)) {
293 continue;
294 }
295 return Some(format!("curl {tok}"));
296 }
297 }
298 }
299 "wget" => {
300 let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
302 tok == "--output-document=-"
303 || tok == "-O-"
304 || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
305 || ((tok == "-O" || tok == "--output-document")
306 && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
307 || tok == "--spider"
308 });
309 if !to_stdout {
310 return Some(
311 "wget downloads to a file by default; use wget -qO- <url> for stdout"
312 .to_string(),
313 );
314 }
315 }
316 "dd" => {
317 for tok in &tokens[1..] {
318 if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
319 return Some(format!("dd {tok}"));
320 }
321 }
322 }
323 _ => {}
324 }
325 }
326 None
327}
328
329fn literal_assignments_before_each_segment(
340 command: &str,
341 segment_count: usize,
342) -> Vec<std::collections::HashMap<String, String>> {
343 use crate::core::shell_allowlist::Separator;
344
345 let separated = crate::core::shell_allowlist::segments_with_separators(command);
346 if separated.len() != segment_count {
347 return vec![std::collections::HashMap::new(); segment_count];
349 }
350 let mut known = std::collections::HashMap::new();
351 let mut prev: Option<Separator> = None;
352 let mut before_each = Vec::with_capacity(segment_count);
353 for (segment, sep) in separated {
354 before_each.push(known.clone());
355 let tokens = crate::core::shell_allowlist::shell_tokenize(&segment);
356 let words: &[String] = match tokens.first().map(String::as_str) {
357 Some("export") => &tokens[1..],
358 _ => &tokens,
359 };
360 let assignments: Option<Vec<(&str, &str)>> = words
361 .iter()
362 .map(|word| {
363 let (name, value) = word.split_once('=')?;
364 let valid_name = name
365 .chars()
366 .next()
367 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
368 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
369 valid_name.then_some((name, value))
370 })
371 .collect();
372 match assignments {
373 Some(pairs) if !pairs.is_empty() => {
374 let in_current_shell = matches!(prev, None | Some(Separator::Sequence))
375 && matches!(sep, None | Some(Separator::Sequence | Separator::And));
376 for (name, value) in pairs {
377 let literal = !value.contains(['$', '`']) && !value.starts_with('~');
378 if in_current_shell && literal {
379 known.insert(name.to_string(), value.to_string());
380 } else {
381 known.remove(name);
382 }
383 }
384 }
385 _ => {
386 let rebinds = matches!(
387 tokens.first().map(String::as_str),
388 Some(
389 "read"
390 | "for"
391 | "select"
392 | "eval"
393 | "source"
394 | "."
395 | "unset"
396 | "declare"
397 | "typeset"
398 | "local"
399 | "readonly"
400 | "export"
401 | "mapfile"
402 | "readarray"
403 | "getopts"
404 | "printf"
405 )
406 );
407 if rebinds {
408 known.clear();
409 }
410 }
411 }
412 prev = sep;
413 }
414 before_each
415}
416
417fn expand_leading_variable(
421 path: &str,
422 known: &std::collections::HashMap<String, String>,
423) -> Option<String> {
424 let rest = path.strip_prefix('$')?;
425 let (name, tail) = if let Some(braced) = rest.strip_prefix('{') {
426 let (name, tail) = braced.split_once('}')?;
427 (name, tail)
428 } else {
429 let end = rest
430 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
431 .unwrap_or(rest.len());
432 rest.split_at(end)
433 };
434 if name.is_empty() || !(tail.is_empty() || tail.starts_with('/')) {
435 return None;
436 }
437 let value = match known.get(name) {
438 Some(value) => value.clone(),
439 None if name == "TMPDIR" => std::env::var("TMPDIR").ok().filter(|v| !v.is_empty())?,
440 None => return None,
441 };
442 Some(format!("{value}{tail}"))
443}
444
445fn is_heredoc_file_write(
449 command: &str,
450 segments: &[(String, Option<String>)],
451 write_allow_paths: &[String],
452 project_root: Option<&str>,
453) -> bool {
454 let has_heredoc = command.contains("<<");
455 if !has_heredoc {
456 return false;
457 }
458 let cmd_lower = command.to_lowercase();
459 let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
460 let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
461 if !has_known_heredoc {
462 return false;
463 }
464 segments.iter().any(|(segment, here)| {
467 disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
468 .is_some()
469 })
470}
471
472pub fn is_temp_redirect_target(target: &str) -> bool {
482 let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
483 is_write_allowed_redirect_target(target, &write_allow_paths, None, None)
486}
487
488fn is_write_allowed_redirect_target(
489 target: &str,
490 write_allow_paths: &[String],
491 project_root: Option<&str>,
492 cwd: Option<&str>,
493) -> bool {
494 let t = target.trim_start_matches(['>', '&', '|']);
496 let t = t.trim_matches(['"', '\'']);
499 if t.starts_with('$') || t.starts_with("${") {
500 return true;
502 }
503
504 if is_unix_scratch_prefix(t) {
509 return true;
510 }
511
512 let path = std::path::Path::new(t);
526 let resolved_input;
527 let path = if path.is_absolute() {
528 path
529 } else if let Some(base) = cwd.filter(|c| !c.trim().is_empty()) {
530 resolved_input = std::path::Path::new(base).join(path);
531 resolved_input.as_path()
532 } else {
533 return false;
534 };
535 let resolved = resolve_path_for_comparison(path);
536 if project_root.is_some_and(|root| {
537 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
538 }) {
539 return false;
540 }
541 write_allow_paths.iter().any(|allowed| {
542 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
543 })
544}
545
546fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
547 use std::path::{Component, PathBuf};
548
549 let mut normalized = PathBuf::new();
550 for component in path.components() {
551 match component {
552 Component::CurDir => {}
553 Component::ParentDir => {
554 normalized.pop();
555 }
556 other => normalized.push(other.as_os_str()),
557 }
558 }
559
560 let mut unresolved = Vec::new();
561 let mut existing = normalized.clone();
562 while !existing.exists() {
563 let Some(name) = existing.file_name() else {
564 break;
565 };
566 unresolved.push(name.to_os_string());
567 if !existing.pop() {
568 break;
569 }
570 }
571 let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
572 for component in unresolved.iter().rev() {
573 resolved.push(component);
574 }
575 resolved
576}
577
578fn tee_targets(command: &str) -> Vec<String> {
579 crate::core::shell_allowlist::extract_all_commands_pub(command)
580 .into_iter()
581 .filter_map(|segment| {
582 let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
583 let first = tokens.first()?;
584 if first.rsplit('/').next().unwrap_or(first) != "tee" {
585 return None;
586 }
587 let mut after_separator = false;
588 Some(
589 tokens
590 .iter()
591 .skip(1)
592 .find(|token| {
593 if *token == "--" {
594 after_separator = true;
595 return false;
596 }
597 after_separator || !token.starts_with('-')
598 })
599 .cloned()
600 .unwrap_or_default(),
601 )
602 })
603 .collect()
604}
605
606fn disallowed_tee_target(
613 command: &str,
614 write_allow_paths: &[String],
615 project_root: Option<&str>,
616 cwd: Option<&str>,
617) -> Option<String> {
618 tee_targets(command).into_iter().find(|target| {
619 !target.is_empty()
620 && !is_write_allowed_redirect_target(target, write_allow_paths, project_root, cwd)
621 })
622}
623
624#[cfg(test)]
631fn has_file_write_redirect(
632 command: &str,
633 write_allow_paths: &[String],
634 project_root: Option<&str>,
635) -> bool {
636 disallowed_write_redirect_target(command, write_allow_paths, project_root, None).is_some()
640}
641
642fn disallowed_write_redirect_target(
651 command: &str,
652 write_allow_paths: &[String],
653 project_root: Option<&str>,
654 cwd: Option<&str>,
655) -> Option<String> {
656 let bytes = command.as_bytes();
657 let len = bytes.len();
658 let mut i = 0;
659 let mut in_single_quote = false;
660 let mut in_double_quote = false;
661
662 while i < len {
663 let c = bytes[i];
664 if c == b'\\' && !in_single_quote {
665 i += 2;
671 continue;
672 }
673 if c == b'\'' && !in_double_quote {
674 in_single_quote = !in_single_quote;
675 } else if c == b'"' && !in_single_quote {
676 in_double_quote = !in_double_quote;
677 } else if c == b'>' && !in_single_quote && !in_double_quote {
678 if i > 0 && bytes[i - 1] == b'2' {
679 i += 1;
680 continue;
681 }
682 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
683 i + 2
684 } else {
685 i + 1
686 };
687 let rest = command[target_start..].trim_start();
692 let (rest, fd_dup) = match rest.strip_prefix('|') {
693 Some(r) => (r, false),
694 None => match rest.strip_prefix('&') {
695 Some(r) => (r, true),
696 None => (rest, false),
697 },
698 };
699 let word: String = rest
712 .chars()
713 .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
714 .collect();
715 let target = if fd_dup { format!("&{word}") } else { word };
716 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
717 i += 1;
718 continue;
719 }
720 if let Some(fd) = target.strip_prefix('&')
723 && !fd.is_empty()
724 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
725 {
726 i += 1;
727 continue;
728 }
729 if is_write_allowed_redirect_target(&target, write_allow_paths, project_root, cwd) {
732 i += 1;
733 continue;
734 }
735 if !target.is_empty() {
736 return Some(target);
737 }
738 }
739 i += 1;
740 }
741 None
742}
743
744pub fn normalize_command_for_shell(command: &str) -> String {
747 if !cfg!(windows) {
748 return command.to_string();
749 }
750 let (_, flag) = crate::shell::shell_and_flag();
751 if flag != "/C" {
752 return command.to_string();
753 }
754 let bytes = command.as_bytes();
755 let mut result = Vec::with_capacity(bytes.len() + 16);
756 let mut in_single = false;
757 let mut in_double = false;
758 for (i, &b) in bytes.iter().enumerate() {
759 if b == b'\'' && !in_double {
760 in_single = !in_single;
761 } else if b == b'"' && !in_single {
762 in_double = !in_double;
763 } else if b == b';' && !in_single && !in_double {
764 result.extend_from_slice(b" && ");
765 continue;
766 }
767 result.push(b);
768 let _ = i;
769 }
770 String::from_utf8(result).unwrap_or_else(|_| command.to_string())
771}
772
773pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
778 crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
779}
780
781pub fn handle_with_context(
782 command: &str,
783 output: &str,
784 exit_code: i32,
785 crp_mode: CrpMode,
786 project_root: Option<&str>,
787) -> String {
788 let mut result = handle(command, output, exit_code, crp_mode);
789
790 {
791 if let Some(root) = project_root {
792 let estimated_tokens = result.len() / 4;
793 if estimated_tokens > 500 {
794 let kernel_budget = 100;
795 if let Some(enrichment) =
796 crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
797 && !enrichment.blocks.is_empty()
798 {
799 result.push_str("\n--- kernel context ---\n");
800 result.push_str(&enrichment.blocks);
801 }
802 }
803 }
804 }
805
806 result
807}
808
809#[cfg(test)]
810mod kernel_tests {
811 use super::handle_with_context;
812 use crate::tools::CrpMode;
813
814 #[test]
815 fn handle_with_context_does_not_panic_on_short_output() {
816 let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
817 assert!(!result.is_empty());
818 }
819}
820
821#[cfg(test)]
822fn is_search_command(command: &str) -> bool {
823 let cmd = command.trim_start();
824 cmd.starts_with("grep ")
825 || cmd.starts_with("rg ")
826 || cmd.starts_with("find ")
827 || cmd.starts_with("fd ")
828 || cmd.starts_with("ag ")
829 || cmd.starts_with("ack ")
830}
831
832#[cfg(test)]
833fn generic_compress(output: &str) -> String {
834 let output = crate::core::compressor::strip_ansi(output);
835 let lines: Vec<&str> = output
836 .lines()
837 .filter(|l| {
838 let t = l.trim();
839 !t.is_empty()
840 })
841 .collect();
842
843 if lines.len() <= 20 {
844 return lines.join("\n");
845 }
846
847 let show_count = (lines.len() / 3).min(30);
848 let half = show_count / 2;
849 let first = &lines[..half];
850 let last = &lines[lines.len() - half..];
851 let omitted = lines.len() - (half * 2);
852 format!(
853 "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
854 first.join("\n"),
855 half * 2,
856 lines.len(),
857 omitted,
858 last.join("\n")
859 )
860}
861
862pub fn contains_auth_flow(output: &str) -> bool {
866 let lower = output.to_lowercase();
867
868 const STRONG_SIGNALS: &[&str] = &[
869 "devicelogin",
870 "deviceauth",
871 "device_code",
872 "device code",
873 "device-code",
874 "verification_uri",
875 "user_code",
876 "one-time code",
877 ];
878
879 if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
880 return true;
881 }
882
883 const WEAK_SIGNALS: &[&str] = &[
884 "enter the code",
885 "enter this code",
886 "enter code:",
887 "use the code",
888 "use a web browser to open",
889 "open the page",
890 "authenticate by visiting",
891 "sign in with the code",
892 "sign in using a code",
893 "verification code",
894 "authorize this device",
895 "waiting for authentication",
896 "waiting for login",
897 "waiting for you to authenticate",
898 "open your browser",
899 "open in your browser",
900 ];
901
902 let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
903 if !has_weak_signal {
904 return false;
905 }
906
907 lower.contains("http://") || lower.contains("https://")
908}
909
910#[cfg(test)]
911mod tests;