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 go to the \
33 session's project, a directory in `allow_paths` / `extra_roots`, a directory listed in \
34 `write_allow_paths` in config.toml, or a scratch path (/tmp, /var/tmp, $TMPDIR). Every \
35 other destination is refused. Commands that do not capture output are not restricted.";
36
37pub(crate) fn capture_roots(
44 project_root: &str,
45 session_extra_roots: &[String],
46 cfg: &crate::core::config::Config,
47) -> Vec<String> {
48 std::iter::once(project_root.to_string())
49 .chain(session_extra_roots.iter().cloned())
50 .chain(cfg.allow_paths.iter().cloned())
51 .chain(cfg.extra_roots.iter().cloned())
52 .filter(|raw| !raw.trim().is_empty())
53 .map(|raw| crate::core::pathjail::expand_user_path(&raw))
54 .filter(|path| {
55 let contains_home = dirs::home_dir().is_some_and(|home| home.starts_with(path));
56 path.is_absolute()
57 && !contains_home
58 && !crate::core::pathutil::is_broad_or_unsafe_root(path)
59 && !crate::core::pathjail::is_read_only_path(path)
60 })
61 .map(|path| path.to_string_lossy().into_owned())
62 .collect()
63}
64
65const WRITE_REASON: &str = "Files you keep are written with ctx_patch or the native Write/Edit \
74 tool, so the read-before-write gate and the edit checks apply to them; ctx_shell does not \
75 write them through output capture. This is unconditional: the redirect itself is not \
76 compressed, so a smaller command or `raw=true` does not change the verdict.";
77
78pub(crate) fn validate_command_in_cwd(
86 command: &str,
87 write_allow_paths: &[String],
88 project_root: Option<&str>,
89 cwd: Option<&str>,
90) -> Option<String> {
91 if command.len() > MAX_COMMAND_BYTES {
92 return Some(format!(
93 "ERROR: Command too large ({} bytes, limit {}). \
94 If you're writing file content, use the native Write/Edit tool instead. \
95 ctx_shell is for reading command output only (git, cargo, npm, etc.).",
96 command.len(),
97 MAX_COMMAND_BYTES
98 ));
99 }
100
101 let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
104 let segments = segments_in_cwd(&cmd_no_heredoc, cwd);
111 if let Some(target) = segments.iter().find_map(|(segment, here)| {
120 disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
121 }) {
122 return Some(format!(
123 "ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
124 not the size or content of the output. {WRITE_REASON} {CAPTURE_RULE} \
125 Write the file with ctx_patch or the native Write tool, or capture to a scratch \
126 path.{}",
127 relative_target_note(&target)
128 ));
129 }
130
131 if let Some(target) = segments.iter().find_map(|(segment, here)| {
142 disallowed_tee_target(segment, write_allow_paths, project_root, here.as_deref())
143 }) {
144 return Some(format!(
145 "ERROR: ctx_shell refuses `tee {target}`. Piping makes no difference: the \
146 destination decides. {WRITE_REASON} {CAPTURE_RULE} \
147 Write the file with ctx_patch or the native Write tool, or tee to a scratch \
148 path.{}",
149 relative_target_note(&target)
150 ));
151 }
152
153 if is_heredoc_file_write(command, &segments, write_allow_paths, project_root) {
154 return Some(format!(
155 "ERROR: ctx_shell detected a heredoc writing to a file. {WRITE_REASON} \
156 Create the file with ctx_patch (op=create) or the native Write tool. \
157 Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
158 ));
159 }
160
161 if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
167 return Some(format!(
168 "ERROR: ctx_shell detected a file download/write ({reason}). \
169 Download flags write a file without a redirect, so the capture rule applies \
170 to them as well (GH #391). \
171 For text, fetch to stdout: curl <url> / wget -qO- <url>. \
172 For a binary (image, PDF, archive) neither stdout nor the editor's Write \
173 tool can carry the bytes — download to an absolute scratch path instead, \
174 e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661). \
175 The target must be a literal path, $TMPDIR, or a variable this same command \
176 set to a literal earlier (D=/tmp/x; curl -o $D/f); any other variable cannot \
177 be resolved here and is refused."
178 ));
179 }
180
181 None
182}
183
184fn relative_target_note(target: &str) -> &'static str {
187 let t = target
188 .trim_start_matches(['>', '&', '|'])
189 .trim_matches(['"', '\'']);
190 if t.starts_with('/') || std::path::Path::new(t).is_absolute() {
191 return "";
192 }
193 " A relative target is placed in the directory its own command runs in: the call's \
194 `cwd`, moved by a plain `cd <dir> &&` before it. Where that directory cannot be \
195 known — a `cd` through a variable, `pushd`, a subshell, a `cd` that may not have \
196 run — a relative target is refused; give an absolute path."
197}
198
199fn segments_in_cwd(command: &str, cwd: Option<&str>) -> Vec<(String, Option<String>)> {
202 let base = cwd
203 .filter(|c| !c.trim().is_empty())
204 .map(std::path::Path::new);
205 crate::core::command_cwd::segments_with_cwd(command, base)
206 .into_iter()
207 .map(|s| {
208 let here = s.cwd.map(|p| p.to_string_lossy().into_owned());
209 (s.segment, here)
210 })
211 .collect()
212}
213
214fn is_unix_scratch_prefix(path: &str) -> bool {
218 for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
219 if path == prefix || path.starts_with(&format!("{prefix}/")) {
220 return true;
221 }
222 }
223 false
224}
225
226fn is_scratch_path(path: &str) -> bool {
230 if is_unix_scratch_prefix(path) {
231 return true;
232 }
233 if let Ok(tmpdir) = std::env::var("TMPDIR")
234 && !tmpdir.is_empty()
235 && std::path::Path::new(path).starts_with(tmpdir.as_str())
236 {
237 return true;
238 }
239 let tmp = std::env::temp_dir();
241 if std::path::Path::new(path).starts_with(&tmp) {
242 return true;
243 }
244 false
245}
246
247fn download_to_file_reason(command: &str) -> Option<String> {
250 let segments = crate::core::command_cwd::segments_with_cwd(command, None);
262 let known_vars = literal_assignments_before_each_segment(command, segments.len());
263 for (index, seg_cwd) in segments.into_iter().enumerate() {
264 let seg = seg_cwd.segment;
265 let here = seg_cwd.cwd;
266 let vars = &known_vars[index];
267 let resolve = |path: &str| -> String {
268 let expanded = expand_leading_variable(path, vars);
269 let path = expanded.as_deref().unwrap_or(path);
270 let p = std::path::Path::new(path);
271 if p.is_absolute() || path.starts_with('/') {
274 return path.to_string();
275 }
276 match here.as_deref() {
279 Some(dir) => crate::core::command_cwd::join_in(dir, path)
280 .to_string_lossy()
281 .into_owned(),
282 None => path.to_string(),
283 }
284 };
285 let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
286 let Some(first) = tokens.first() else {
287 continue;
288 };
289 let base = first.rsplit('/').next().unwrap_or(first);
290 match base {
291 "curl" => {
292 let tokens_slice = &tokens[1..];
293 for (i, tok) in tokens_slice.iter().enumerate() {
294 let target: Option<&str> = if tok == "--output" {
295 tokens_slice.get(i + 1).map(String::as_str)
296 } else if let Some(val) = tok.strip_prefix("--output=") {
297 Some(val)
298 } else if tok == "--output-dir" {
299 tokens_slice.get(i + 1).map(String::as_str)
300 } else if let Some(val) = tok.strip_prefix("--output-dir=") {
301 Some(val)
302 } else if tok.starts_with('-')
303 && !tok.starts_with("--")
304 && tok[1..].contains('o')
305 {
306 tokens_slice.get(i + 1).map(String::as_str)
308 } else if tok == "--remote-name"
309 || tok == "--remote-name-all"
310 || (tok.starts_with('-')
311 && !tok.starts_with("--")
312 && tok[1..].contains('O'))
313 {
314 Some(".")
315 } else {
316 None
317 };
318 if let Some(path) = target {
319 if is_scratch_path(&resolve(path)) {
320 continue;
321 }
322 return Some(format!("curl {tok}"));
323 }
324 }
325 }
326 "wget" => {
327 let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
329 tok == "--output-document=-"
330 || tok == "-O-"
331 || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
332 || ((tok == "-O" || tok == "--output-document")
333 && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
334 || tok == "--spider"
335 });
336 if !to_stdout {
337 return Some(
338 "wget downloads to a file by default; use wget -qO- <url> for stdout"
339 .to_string(),
340 );
341 }
342 }
343 "dd" => {
344 for tok in &tokens[1..] {
345 if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
346 return Some(format!("dd {tok}"));
347 }
348 }
349 }
350 _ => {}
351 }
352 }
353 None
354}
355
356fn literal_assignments_before_each_segment(
367 command: &str,
368 segment_count: usize,
369) -> Vec<std::collections::HashMap<String, String>> {
370 use crate::core::shell_allowlist::Separator;
371
372 let separated = crate::core::shell_allowlist::segments_with_separators(command);
373 if separated.len() != segment_count {
374 return vec![std::collections::HashMap::new(); segment_count];
376 }
377 let mut known = std::collections::HashMap::new();
378 let mut prev: Option<Separator> = None;
379 let mut before_each = Vec::with_capacity(segment_count);
380 for (segment, sep) in separated {
381 before_each.push(known.clone());
382 let tokens = crate::core::shell_allowlist::shell_tokenize(&segment);
383 let words: &[String] = match tokens.first().map(String::as_str) {
384 Some("export") => &tokens[1..],
385 _ => &tokens,
386 };
387 let assignments: Option<Vec<(&str, &str)>> = words
388 .iter()
389 .map(|word| {
390 let (name, value) = word.split_once('=')?;
391 let valid_name = name
392 .chars()
393 .next()
394 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
395 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
396 valid_name.then_some((name, value))
397 })
398 .collect();
399 match assignments {
400 Some(pairs) if !pairs.is_empty() => {
401 let in_current_shell = matches!(prev, None | Some(Separator::Sequence))
402 && matches!(sep, None | Some(Separator::Sequence | Separator::And));
403 for (name, value) in pairs {
404 let literal = !value.contains(['$', '`']) && !value.starts_with('~');
405 if in_current_shell && literal {
406 known.insert(name.to_string(), value.to_string());
407 } else {
408 known.remove(name);
409 }
410 }
411 }
412 _ => {
413 let rebinds = matches!(
414 tokens.first().map(String::as_str),
415 Some(
416 "read"
417 | "for"
418 | "select"
419 | "eval"
420 | "source"
421 | "."
422 | "unset"
423 | "declare"
424 | "typeset"
425 | "local"
426 | "readonly"
427 | "export"
428 | "mapfile"
429 | "readarray"
430 | "getopts"
431 | "printf"
432 )
433 );
434 if rebinds {
435 known.clear();
436 }
437 }
438 }
439 prev = sep;
440 }
441 before_each
442}
443
444fn expand_leading_variable(
448 path: &str,
449 known: &std::collections::HashMap<String, String>,
450) -> Option<String> {
451 let rest = path.strip_prefix('$')?;
452 let (name, tail) = if let Some(braced) = rest.strip_prefix('{') {
453 let (name, tail) = braced.split_once('}')?;
454 (name, tail)
455 } else {
456 let end = rest
457 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
458 .unwrap_or(rest.len());
459 rest.split_at(end)
460 };
461 if name.is_empty() || !(tail.is_empty() || tail.starts_with('/')) {
462 return None;
463 }
464 let value = match known.get(name) {
465 Some(value) => value.clone(),
466 None if name == "TMPDIR" => std::env::var("TMPDIR").ok().filter(|v| !v.is_empty())?,
467 None => return None,
468 };
469 Some(format!("{value}{tail}"))
470}
471
472fn is_heredoc_file_write(
476 command: &str,
477 segments: &[(String, Option<String>)],
478 write_allow_paths: &[String],
479 project_root: Option<&str>,
480) -> bool {
481 let has_heredoc = command.contains("<<");
482 if !has_heredoc {
483 return false;
484 }
485 let cmd_lower = command.to_lowercase();
486 let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
487 let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
488 if !has_known_heredoc {
489 return false;
490 }
491 segments.iter().any(|(segment, here)| {
494 disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
495 .is_some()
496 })
497}
498
499pub fn is_temp_redirect_target(target: &str) -> bool {
509 let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
510 is_write_allowed_redirect_target(target, &write_allow_paths, None, None)
513}
514
515fn is_write_allowed_redirect_target(
516 target: &str,
517 write_allow_paths: &[String],
518 project_root: Option<&str>,
519 cwd: Option<&str>,
520) -> bool {
521 let t = target.trim_start_matches(['>', '&', '|']);
523 let t = t.trim_matches(['"', '\'']);
526 if t.starts_with('$') || t.starts_with("${") {
527 return true;
529 }
530
531 if is_unix_scratch_prefix(t) {
536 return true;
537 }
538
539 let path = std::path::Path::new(t);
553 let resolved_input;
554 let path = if path.is_absolute() {
555 path
556 } else if let Some(base) = cwd.filter(|c| !c.trim().is_empty()) {
557 resolved_input = std::path::Path::new(base).join(path);
558 resolved_input.as_path()
559 } else {
560 return false;
561 };
562 let resolved = resolve_path_for_comparison(path);
563 if project_root.is_some_and(|root| {
564 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
565 }) {
566 return false;
567 }
568 write_allow_paths.iter().any(|allowed| {
569 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
570 })
571}
572
573fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
574 use std::path::{Component, PathBuf};
575
576 let mut normalized = PathBuf::new();
577 for component in path.components() {
578 match component {
579 Component::CurDir => {}
580 Component::ParentDir => {
581 normalized.pop();
582 }
583 other => normalized.push(other.as_os_str()),
584 }
585 }
586
587 let mut unresolved = Vec::new();
588 let mut existing = normalized.clone();
589 while !existing.exists() {
590 let Some(name) = existing.file_name() else {
591 break;
592 };
593 unresolved.push(name.to_os_string());
594 if !existing.pop() {
595 break;
596 }
597 }
598 let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
599 for component in unresolved.iter().rev() {
600 resolved.push(component);
601 }
602 resolved
603}
604
605fn tee_targets(command: &str) -> Vec<String> {
606 crate::core::shell_allowlist::extract_all_commands_pub(command)
607 .into_iter()
608 .filter_map(|segment| {
609 let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
610 let first = tokens.first()?;
611 if first.rsplit('/').next().unwrap_or(first) != "tee" {
612 return None;
613 }
614 let mut after_separator = false;
615 Some(
616 tokens
617 .iter()
618 .skip(1)
619 .find(|token| {
620 if *token == "--" {
621 after_separator = true;
622 return false;
623 }
624 after_separator || !token.starts_with('-')
625 })
626 .cloned()
627 .unwrap_or_default(),
628 )
629 })
630 .collect()
631}
632
633fn disallowed_tee_target(
640 command: &str,
641 write_allow_paths: &[String],
642 project_root: Option<&str>,
643 cwd: Option<&str>,
644) -> Option<String> {
645 tee_targets(command).into_iter().find(|target| {
646 !target.is_empty()
647 && !is_write_allowed_redirect_target(target, write_allow_paths, project_root, cwd)
648 })
649}
650
651#[cfg(test)]
658fn has_file_write_redirect(
659 command: &str,
660 write_allow_paths: &[String],
661 project_root: Option<&str>,
662) -> bool {
663 disallowed_write_redirect_target(command, write_allow_paths, project_root, None).is_some()
667}
668
669fn disallowed_write_redirect_target(
678 command: &str,
679 write_allow_paths: &[String],
680 project_root: Option<&str>,
681 cwd: Option<&str>,
682) -> Option<String> {
683 let bytes = command.as_bytes();
684 let len = bytes.len();
685 let mut i = 0;
686 let mut in_single_quote = false;
687 let mut in_double_quote = false;
688
689 while i < len {
690 let c = bytes[i];
691 if c == b'\\' && !in_single_quote {
692 i += 2;
698 continue;
699 }
700 if c == b'\'' && !in_double_quote {
701 in_single_quote = !in_single_quote;
702 } else if c == b'"' && !in_single_quote {
703 in_double_quote = !in_double_quote;
704 } else if c == b'>' && !in_single_quote && !in_double_quote {
705 if i > 0 && bytes[i - 1] == b'2' {
706 i += 1;
707 continue;
708 }
709 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
710 i + 2
711 } else {
712 i + 1
713 };
714 let rest = command[target_start..].trim_start();
719 let (rest, fd_dup) = match rest.strip_prefix('|') {
720 Some(r) => (r, false),
721 None => match rest.strip_prefix('&') {
722 Some(r) => (r, true),
723 None => (rest, false),
724 },
725 };
726 let word: String = rest
739 .chars()
740 .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
741 .collect();
742 let target = if fd_dup { format!("&{word}") } else { word };
743 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
744 i += 1;
745 continue;
746 }
747 if let Some(fd) = target.strip_prefix('&')
750 && !fd.is_empty()
751 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
752 {
753 i += 1;
754 continue;
755 }
756 if is_write_allowed_redirect_target(&target, write_allow_paths, project_root, cwd) {
759 i += 1;
760 continue;
761 }
762 if !target.is_empty() {
763 return Some(target);
764 }
765 }
766 i += 1;
767 }
768 None
769}
770
771pub fn normalize_command_for_shell(command: &str) -> String {
774 if !cfg!(windows) {
775 return command.to_string();
776 }
777 let (_, flag) = crate::shell::shell_and_flag();
778 if flag != "/C" {
779 return command.to_string();
780 }
781 let bytes = command.as_bytes();
782 let mut result = Vec::with_capacity(bytes.len() + 16);
783 let mut in_single = false;
784 let mut in_double = false;
785 for (i, &b) in bytes.iter().enumerate() {
786 if b == b'\'' && !in_double {
787 in_single = !in_single;
788 } else if b == b'"' && !in_single {
789 in_double = !in_double;
790 } else if b == b';' && !in_single && !in_double {
791 result.extend_from_slice(b" && ");
792 continue;
793 }
794 result.push(b);
795 let _ = i;
796 }
797 String::from_utf8(result).unwrap_or_else(|_| command.to_string())
798}
799
800pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
805 crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
806}
807
808pub fn handle_with_context(
809 command: &str,
810 output: &str,
811 exit_code: i32,
812 crp_mode: CrpMode,
813 project_root: Option<&str>,
814) -> String {
815 let mut result = handle(command, output, exit_code, crp_mode);
816
817 {
818 if let Some(root) = project_root {
819 let estimated_tokens = result.len() / 4;
820 if estimated_tokens > 500 {
821 let kernel_budget = 100;
822 if let Some(enrichment) =
823 crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
824 && !enrichment.blocks.is_empty()
825 {
826 result.push_str("\n--- kernel context ---\n");
827 result.push_str(&enrichment.blocks);
828 }
829 }
830 }
831 }
832
833 result
834}
835
836#[cfg(test)]
837mod kernel_tests {
838 use super::handle_with_context;
839 use crate::tools::CrpMode;
840
841 #[test]
842 fn handle_with_context_does_not_panic_on_short_output() {
843 let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
844 assert!(!result.is_empty());
845 }
846}
847
848#[cfg(test)]
849fn is_search_command(command: &str) -> bool {
850 let cmd = command.trim_start();
851 cmd.starts_with("grep ")
852 || cmd.starts_with("rg ")
853 || cmd.starts_with("find ")
854 || cmd.starts_with("fd ")
855 || cmd.starts_with("ag ")
856 || cmd.starts_with("ack ")
857}
858
859#[cfg(test)]
860fn generic_compress(output: &str) -> String {
861 let output = crate::core::compressor::strip_ansi(output);
862 let lines: Vec<&str> = output
863 .lines()
864 .filter(|l| {
865 let t = l.trim();
866 !t.is_empty()
867 })
868 .collect();
869
870 if lines.len() <= 20 {
871 return lines.join("\n");
872 }
873
874 let show_count = (lines.len() / 3).min(30);
875 let half = show_count / 2;
876 let first = &lines[..half];
877 let last = &lines[lines.len() - half..];
878 let omitted = lines.len() - (half * 2);
879 format!(
880 "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
881 first.join("\n"),
882 half * 2,
883 lines.len(),
884 omitted,
885 last.join("\n")
886 )
887}
888
889pub fn contains_auth_flow(output: &str) -> bool {
893 let lower = output.to_lowercase();
894
895 const STRONG_SIGNALS: &[&str] = &[
896 "devicelogin",
897 "deviceauth",
898 "device_code",
899 "device code",
900 "device-code",
901 "verification_uri",
902 "user_code",
903 "one-time code",
904 ];
905
906 if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
907 return true;
908 }
909
910 const WEAK_SIGNALS: &[&str] = &[
911 "enter the code",
912 "enter this code",
913 "enter code:",
914 "use the code",
915 "use a web browser to open",
916 "open the page",
917 "authenticate by visiting",
918 "sign in with the code",
919 "sign in using a code",
920 "verification code",
921 "authorize this device",
922 "waiting for authentication",
923 "waiting for login",
924 "waiting for you to authenticate",
925 "open your browser",
926 "open in your browser",
927 ];
928
929 let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
930 if !has_weak_signal {
931 return false;
932 }
933
934 lower.contains("http://") || lower.contains("https://")
935}
936
937#[cfg(test)]
938mod tests;