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 match crate::core::workspace_authority::current() {
51 crate::core::workspace_authority::Authority::Legacy => {}
52 crate::core::workspace_authority::Authority::Workspace(snapshot) => {
53 return snapshot
54 .granting_roots()
55 .filter(|(_, access)| {
56 *access == crate::core::workspace_authority::Access::ReadWrite
57 })
58 .map(|(root, _)| root.to_string_lossy().into_owned())
59 .collect();
60 }
61 crate::core::workspace_authority::Authority::Unavailable(_) => return Vec::new(),
62 }
63 std::iter::once(project_root.to_string())
64 .chain(session_extra_roots.iter().cloned())
65 .chain(cfg.allow_paths.iter().cloned())
66 .chain(cfg.extra_roots.iter().cloned())
67 .filter(|raw| !raw.trim().is_empty())
68 .map(|raw| crate::core::pathjail::expand_user_path(&raw))
69 .filter(|path| {
70 let contains_home = dirs::home_dir().is_some_and(|home| home.starts_with(path));
71 path.is_absolute()
72 && !contains_home
73 && !crate::core::pathutil::is_broad_or_unsafe_root(path)
74 && !crate::core::pathjail::is_read_only_path(path)
75 })
76 .map(|path| path.to_string_lossy().into_owned())
77 .collect()
78}
79
80const WRITE_REASON: &str = "Files you keep are written with ctx_patch or the native Write/Edit \
89 tool, so the read-before-write gate and the edit checks apply to them; ctx_shell does not \
90 write them through output capture. This is unconditional: the redirect itself is not \
91 compressed, so a smaller command or `raw=true` does not change the verdict.";
92
93pub(crate) fn validate_command_in_cwd(
101 command: &str,
102 write_allow_paths: &[String],
103 project_root: Option<&str>,
104 cwd: Option<&str>,
105) -> Option<String> {
106 if command.len() > MAX_COMMAND_BYTES {
107 return Some(format!(
108 "ERROR: Command too large ({} bytes, limit {}). \
109 If you're writing file content, use the native Write/Edit tool instead. \
110 ctx_shell is for reading command output only (git, cargo, npm, etc.).",
111 command.len(),
112 MAX_COMMAND_BYTES
113 ));
114 }
115
116 let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
119 let segments = segments_in_cwd(&cmd_no_heredoc, cwd);
126 if let Some(target) = segments.iter().find_map(|(segment, here)| {
135 disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
136 }) {
137 return Some(format!(
138 "ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
139 not the size or content of the output. {WRITE_REASON} {CAPTURE_RULE} \
140 Write the file with ctx_patch or the native Write tool, or capture to a scratch \
141 path.{}",
142 relative_target_note(&target)
143 ));
144 }
145
146 if let Some(target) = segments.iter().find_map(|(segment, here)| {
157 disallowed_tee_target(segment, write_allow_paths, project_root, here.as_deref())
158 }) {
159 return Some(format!(
160 "ERROR: ctx_shell refuses `tee {target}`. Piping makes no difference: the \
161 destination decides. {WRITE_REASON} {CAPTURE_RULE} \
162 Write the file with ctx_patch or the native Write tool, or tee to a scratch \
163 path.{}",
164 relative_target_note(&target)
165 ));
166 }
167
168 if is_heredoc_file_write(command, &segments, write_allow_paths, project_root) {
169 return Some(format!(
170 "ERROR: ctx_shell detected a heredoc writing to a file. {WRITE_REASON} \
171 Create the file with ctx_patch (op=create) or the native Write tool. \
172 Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
173 ));
174 }
175
176 if let Some(reason) = disallowed_download(&cmd_no_heredoc, write_allow_paths, project_root, cwd)
193 {
194 return Some(format!(
195 "ERROR: ctx_shell refuses the download ({reason}) — the destination decides. \
196 A download (curl -o/-O, wget, dd of=) may write where output capture may: the \
197 session's project, a directory in `allow_paths` / `extra_roots`, a directory \
198 listed in `write_allow_paths` in config.toml, or a scratch path (/tmp, \
199 /var/tmp, $TMPDIR). The target must be one that can be placed: an absolute \
200 path, $TMPDIR/…, a variable this same command set to a literal path \
201 (D=/x; curl -o $D/f), or a relative name in the directory its command runs in \
202 (the call's `cwd`, moved by a plain `cd`). Any other variable cannot be \
203 resolved here and is refused. A binary (image, PDF, archive) downloads to such \
204 a path directly, e.g. curl -sL -o /tmp/shot.png <url>; for text, fetch to \
205 stdout: curl <url> / wget -qO- <url>."
206 ));
207 }
208
209 None
210}
211
212fn relative_target_note(target: &str) -> &'static str {
215 let t = target
216 .trim_start_matches(['>', '&', '|'])
217 .trim_matches(['"', '\'']);
218 if t.starts_with('/') || std::path::Path::new(t).is_absolute() {
219 return "";
220 }
221 " A relative target is placed in the directory its own command runs in: the call's \
222 `cwd`, moved by a plain `cd <dir> &&` before it. Where that directory cannot be \
223 known — a `cd` through a variable, `pushd`, a subshell, a `cd` that may not have \
224 run — a relative target is refused; give an absolute path."
225}
226
227fn segments_in_cwd(command: &str, cwd: Option<&str>) -> Vec<(String, Option<String>)> {
230 let base = cwd
231 .filter(|c| !c.trim().is_empty())
232 .map(std::path::Path::new);
233 crate::core::command_cwd::segments_with_cwd(command, base)
234 .into_iter()
235 .map(|s| {
236 let here = s.cwd.map(|p| p.to_string_lossy().into_owned());
237 (s.segment, here)
238 })
239 .collect()
240}
241
242fn is_unix_scratch_prefix(path: &str) -> bool {
246 for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
247 if path == prefix || path.starts_with(&format!("{prefix}/")) {
248 return true;
249 }
250 }
251 false
252}
253
254fn is_scratch_path(path: &str) -> bool {
258 if is_unix_scratch_prefix(path) {
259 return true;
260 }
261 if let Ok(tmpdir) = std::env::var("TMPDIR")
262 && !tmpdir.is_empty()
263 && std::path::Path::new(path).starts_with(tmpdir.as_str())
264 {
265 return true;
266 }
267 let tmp = std::env::temp_dir();
269 if std::path::Path::new(path).starts_with(&tmp) {
270 return true;
271 }
272 false
273}
274
275#[cfg(test)]
280fn download_to_file_reason(command: &str) -> Option<String> {
281 disallowed_download(command, &[], None, None)
282}
283
284fn disallowed_download(
290 command: &str,
291 write_allow_paths: &[String],
292 project_root: Option<&str>,
293 cwd: Option<&str>,
294) -> Option<String> {
295 let base = cwd
307 .filter(|c| !c.trim().is_empty())
308 .map(std::path::Path::new);
309 let segments = crate::core::command_cwd::segments_with_cwd(command, base);
310 let known_vars =
311 crate::core::command_vars::literal_assignments_before_each_segment(command, segments.len());
312 for (index, seg_cwd) in segments.into_iter().enumerate() {
313 let seg = seg_cwd.segment;
314 let here = seg_cwd.cwd;
315 let vars = &known_vars[index];
316 let resolve = |path: &str| -> String {
317 let expanded = crate::core::command_vars::expand_leading_variable(path, vars);
318 let path = expanded.as_deref().unwrap_or(path);
319 let p = std::path::Path::new(path);
320 if p.is_absolute() || path.starts_with('/') {
323 return path.to_string();
324 }
325 match here.as_deref() {
328 Some(dir) => crate::core::command_cwd::join_in(dir, path)
329 .to_string_lossy()
330 .into_owned(),
331 None => path.to_string(),
332 }
333 };
334 let allowed = |path: &str| -> bool {
339 let target = resolve(path);
340 !target.contains(['$', '`'])
341 && (is_scratch_path(&target)
342 || is_write_allowed_redirect_target(
343 &target,
344 write_allow_paths,
345 project_root,
346 None,
347 ))
348 };
349 let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
350 let Some(first) = tokens.first() else {
351 continue;
352 };
353 let base = first.rsplit('/').next().unwrap_or(first);
354 match base {
355 "curl" => {
356 let tokens_slice = &tokens[1..];
357 for (i, tok) in tokens_slice.iter().enumerate() {
358 let target: Option<&str> = if tok == "--output" {
359 tokens_slice.get(i + 1).map(String::as_str)
360 } else if let Some(val) = tok.strip_prefix("--output=") {
361 Some(val)
362 } else if tok == "--output-dir" {
363 tokens_slice.get(i + 1).map(String::as_str)
364 } else if let Some(val) = tok.strip_prefix("--output-dir=") {
365 Some(val)
366 } else if tok.starts_with('-')
367 && !tok.starts_with("--")
368 && tok[1..].contains('o')
369 {
370 tokens_slice.get(i + 1).map(String::as_str)
372 } else if tok == "--remote-name"
373 || tok == "--remote-name-all"
374 || (tok.starts_with('-')
375 && !tok.starts_with("--")
376 && tok[1..].contains('O'))
377 {
378 Some(".")
379 } else {
380 None
381 };
382 if let Some(path) = target {
383 if allowed(path) {
384 continue;
385 }
386 return Some(format!("curl {tok} {path}"));
387 }
388 }
389 }
390 "wget" => {
391 if let Some(target) = wget_targets(&tokens[1..])
392 .into_iter()
393 .find(|target| !allowed(target))
394 {
395 return Some(format!("wget writes {target}"));
396 }
397 }
398 "dd" => {
399 for tok in &tokens[1..] {
400 if let Some(target) = tok.strip_prefix("of=")
401 && target != "/dev/null"
402 && !allowed(target)
403 {
404 return Some(format!("dd {tok}"));
405 }
406 }
407 }
408 _ => {}
409 }
410 }
411 None
412}
413
414fn wget_targets(args: &[String]) -> Vec<String> {
418 let mut document: Option<String> = None;
419 let mut prefix: Option<String> = None;
420 let mut logs = Vec::new();
421 let mut spider = false;
422 let mut i = 0;
423 while i < args.len() {
424 let tok = args[i].as_str();
425 let next = || args.get(i + 1).cloned();
426 let mut takes_next = false;
427 if tok == "--spider" {
428 spider = true;
429 } else if let Some((flag, value)) = tok.split_once('=').filter(|_| tok.starts_with("--")) {
430 match flag {
431 "--output-document" => document = Some(value.to_string()),
432 "--directory-prefix" => prefix = Some(value.to_string()),
433 "--output-file" | "--append-output" => logs.push(value.to_string()),
434 _ => {}
435 }
436 } else if matches!(
437 tok,
438 "--output-document" | "--directory-prefix" | "--output-file" | "--append-output"
439 ) {
440 takes_next = true;
441 let value = next();
442 match tok {
443 "--output-document" => document = value,
444 "--directory-prefix" => prefix = value,
445 _ => logs.extend(value),
446 }
447 } else if let Some(cluster) = tok.strip_prefix('-').filter(|c| !c.starts_with('-')) {
448 if let Some(pos) = cluster.find(['O', 'P', 'o', 'a']) {
451 let rest = &cluster[pos + 1..];
452 let value = if rest.is_empty() {
453 takes_next = true;
454 next()
455 } else {
456 Some(rest.to_string())
457 };
458 match &cluster[pos..=pos] {
459 "O" => document = value,
460 "P" => prefix = value,
461 _ => logs.extend(value),
462 }
463 }
464 }
465 i += if takes_next { 2 } else { 1 };
466 }
467 let mut targets = logs;
468 match document.as_deref() {
469 Some("-") => {}
470 Some(file) => targets.push(file.to_string()),
471 None if !spider => targets.push(prefix.unwrap_or_else(|| ".".to_string())),
472 None => {}
473 }
474 targets
475}
476
477fn is_heredoc_file_write(
481 command: &str,
482 segments: &[(String, Option<String>)],
483 write_allow_paths: &[String],
484 project_root: Option<&str>,
485) -> bool {
486 let has_heredoc = command.contains("<<");
487 if !has_heredoc {
488 return false;
489 }
490 let cmd_lower = command.to_lowercase();
491 let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
492 let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
493 if !has_known_heredoc {
494 return false;
495 }
496 segments.iter().any(|(segment, here)| {
499 disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
500 .is_some()
501 })
502}
503
504pub fn is_temp_redirect_target(target: &str) -> bool {
514 let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
515 is_write_allowed_redirect_target(target, &write_allow_paths, None, None)
518}
519
520fn is_write_allowed_redirect_target(
521 target: &str,
522 write_allow_paths: &[String],
523 project_root: Option<&str>,
524 cwd: Option<&str>,
525) -> bool {
526 let t = target.trim_start_matches(['>', '&', '|']);
528 let t = t.trim_matches(['"', '\'']);
531 if t.starts_with('$') || t.starts_with("${") {
532 return true;
534 }
535
536 if is_unix_scratch_prefix(t) {
541 return true;
542 }
543
544 let path = std::path::Path::new(t);
558 let resolved_input;
559 let path = if path.is_absolute() {
560 path
561 } else if let Some(base) = cwd.filter(|c| !c.trim().is_empty()) {
562 resolved_input = std::path::Path::new(base).join(path);
563 resolved_input.as_path()
564 } else {
565 return false;
566 };
567 let resolved = resolve_path_for_comparison(path);
568 if project_root.is_some_and(|root| {
569 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
570 }) {
571 return false;
572 }
573 write_allow_paths.iter().any(|allowed| {
574 resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
575 })
576}
577
578fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
579 use std::path::{Component, PathBuf};
580
581 let mut normalized = PathBuf::new();
582 for component in path.components() {
583 match component {
584 Component::CurDir => {}
585 Component::ParentDir => {
586 normalized.pop();
587 }
588 other => normalized.push(other.as_os_str()),
589 }
590 }
591
592 let mut unresolved = Vec::new();
593 let mut existing = normalized.clone();
594 while !existing.exists() {
595 let Some(name) = existing.file_name() else {
596 break;
597 };
598 unresolved.push(name.to_os_string());
599 if !existing.pop() {
600 break;
601 }
602 }
603 let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
604 for component in unresolved.iter().rev() {
605 resolved.push(component);
606 }
607 resolved
608}
609
610fn tee_targets(command: &str) -> Vec<String> {
611 crate::core::shell_allowlist::extract_all_commands_pub(command)
612 .into_iter()
613 .filter_map(|segment| {
614 let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
615 let first = tokens.first()?;
616 if first.rsplit('/').next().unwrap_or(first) != "tee" {
617 return None;
618 }
619 let mut after_separator = false;
620 Some(
621 tokens
622 .iter()
623 .skip(1)
624 .find(|token| {
625 if *token == "--" {
626 after_separator = true;
627 return false;
628 }
629 after_separator || !token.starts_with('-')
630 })
631 .cloned()
632 .unwrap_or_default(),
633 )
634 })
635 .collect()
636}
637
638fn disallowed_tee_target(
645 command: &str,
646 write_allow_paths: &[String],
647 project_root: Option<&str>,
648 cwd: Option<&str>,
649) -> Option<String> {
650 tee_targets(command).into_iter().find(|target| {
651 !target.is_empty()
652 && !is_write_allowed_redirect_target(target, write_allow_paths, project_root, cwd)
653 })
654}
655
656#[cfg(test)]
663fn has_file_write_redirect(
664 command: &str,
665 write_allow_paths: &[String],
666 project_root: Option<&str>,
667) -> bool {
668 disallowed_write_redirect_target(command, write_allow_paths, project_root, None).is_some()
672}
673
674fn disallowed_write_redirect_target(
683 command: &str,
684 write_allow_paths: &[String],
685 project_root: Option<&str>,
686 cwd: Option<&str>,
687) -> Option<String> {
688 let bytes = command.as_bytes();
689 let len = bytes.len();
690 let mut i = 0;
691 let mut in_single_quote = false;
692 let mut in_double_quote = false;
693
694 while i < len {
695 let c = bytes[i];
696 if c == b'\\' && !in_single_quote {
697 i += 2;
703 continue;
704 }
705 if c == b'\'' && !in_double_quote {
706 in_single_quote = !in_single_quote;
707 } else if c == b'"' && !in_single_quote {
708 in_double_quote = !in_double_quote;
709 } else if c == b'>' && !in_single_quote && !in_double_quote {
710 if i > 0 && bytes[i - 1] == b'2' {
711 i += 1;
712 continue;
713 }
714 let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
715 i + 2
716 } else {
717 i + 1
718 };
719 let rest = command[target_start..].trim_start();
724 let (rest, fd_dup) = match rest.strip_prefix('|') {
725 Some(r) => (r, false),
726 None => match rest.strip_prefix('&') {
727 Some(r) => (r, true),
728 None => (rest, false),
729 },
730 };
731 let word: String = rest
744 .chars()
745 .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
746 .collect();
747 let target = if fd_dup { format!("&{word}") } else { word };
748 if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
749 i += 1;
750 continue;
751 }
752 if let Some(fd) = target.strip_prefix('&')
755 && !fd.is_empty()
756 && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
757 {
758 i += 1;
759 continue;
760 }
761 if is_write_allowed_redirect_target(&target, write_allow_paths, project_root, cwd) {
764 i += 1;
765 continue;
766 }
767 if !target.is_empty() {
768 return Some(target);
769 }
770 }
771 i += 1;
772 }
773 None
774}
775
776pub fn normalize_command_for_shell(command: &str) -> String {
779 if !cfg!(windows) {
780 return command.to_string();
781 }
782 let (_, flag) = crate::shell::shell_and_flag();
783 if flag != "/C" {
784 return command.to_string();
785 }
786 let bytes = command.as_bytes();
787 let mut result = Vec::with_capacity(bytes.len() + 16);
788 let mut in_single = false;
789 let mut in_double = false;
790 for (i, &b) in bytes.iter().enumerate() {
791 if b == b'\'' && !in_double {
792 in_single = !in_single;
793 } else if b == b'"' && !in_single {
794 in_double = !in_double;
795 } else if b == b';' && !in_single && !in_double {
796 result.extend_from_slice(b" && ");
797 continue;
798 }
799 result.push(b);
800 let _ = i;
801 }
802 String::from_utf8(result).unwrap_or_else(|_| command.to_string())
803}
804
805pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
810 crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
811}
812
813pub fn handle_with_context(
814 command: &str,
815 output: &str,
816 exit_code: i32,
817 crp_mode: CrpMode,
818 project_root: Option<&str>,
819) -> String {
820 let mut result = handle(command, output, exit_code, crp_mode);
821
822 {
823 if let Some(root) = project_root {
824 let estimated_tokens = result.len() / 4;
825 if estimated_tokens > 500 {
826 let kernel_budget = 100;
827 if let Some(enrichment) =
828 crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
829 && !enrichment.blocks.is_empty()
830 {
831 result.push_str("\n--- kernel context ---\n");
832 result.push_str(&enrichment.blocks);
833 }
834 }
835 }
836 }
837
838 result
839}
840
841#[cfg(test)]
842mod kernel_tests {
843 use super::handle_with_context;
844 use crate::tools::CrpMode;
845
846 #[test]
847 fn handle_with_context_does_not_panic_on_short_output() {
848 let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
849 assert!(!result.is_empty(), "`result` is empty");
850 }
851}
852
853#[cfg(test)]
854fn is_search_command(command: &str) -> bool {
855 let cmd = command.trim_start();
856 cmd.starts_with("grep ")
857 || cmd.starts_with("rg ")
858 || cmd.starts_with("find ")
859 || cmd.starts_with("fd ")
860 || cmd.starts_with("ag ")
861 || cmd.starts_with("ack ")
862}
863
864#[cfg(test)]
865fn generic_compress(output: &str) -> String {
866 let output = crate::core::compressor::strip_ansi(output);
867 let lines: Vec<&str> = output
868 .lines()
869 .filter(|l| {
870 let t = l.trim();
871 !t.is_empty()
872 })
873 .collect();
874
875 if lines.len() <= 20 {
876 return lines.join("\n");
877 }
878
879 let show_count = (lines.len() / 3).min(30);
880 let half = show_count / 2;
881 let first = &lines[..half];
882 let last = &lines[lines.len() - half..];
883 let omitted = lines.len() - (half * 2);
884 format!(
885 "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
886 first.join("\n"),
887 half * 2,
888 lines.len(),
889 omitted,
890 last.join("\n")
891 )
892}
893
894pub fn contains_auth_flow(output: &str) -> bool {
898 let lower = output.to_lowercase();
899
900 const STRONG_SIGNALS: &[&str] = &[
901 "devicelogin",
902 "deviceauth",
903 "device_code",
904 "device code",
905 "device-code",
906 "verification_uri",
907 "user_code",
908 "one-time code",
909 ];
910
911 if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
912 return true;
913 }
914
915 const WEAK_SIGNALS: &[&str] = &[
916 "enter the code",
917 "enter this code",
918 "enter code:",
919 "use the code",
920 "use a web browser to open",
921 "open the page",
922 "authenticate by visiting",
923 "sign in with the code",
924 "sign in using a code",
925 "verification code",
926 "authorize this device",
927 "waiting for authentication",
928 "waiting for login",
929 "waiting for you to authenticate",
930 "open your browser",
931 "open in your browser",
932 ];
933
934 let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
935 if !has_weak_signal {
936 return false;
937 }
938
939 lower.contains("http://") || lower.contains("https://")
940}
941
942#[cfg(test)]
943mod tests;