Skip to main content

lean_ctx/tools/
ctx_shell.rs

1use crate::tools::CrpMode;
2
3const MAX_COMMAND_BYTES: usize = 8192;
4
5/// Validates a shell command before execution. Returns Some(error_message) if
6/// the command should be rejected, None if it's safe to run.
7pub 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(
14    command: &str,
15    write_allow_paths: &[String],
16    project_root: Option<&str>,
17) -> Option<String> {
18    if command.len() > MAX_COMMAND_BYTES {
19        return Some(format!(
20            "ERROR: Command too large ({} bytes, limit {}). \
21             If you're writing file content, use the native Write/Edit tool instead. \
22             ctx_shell is for reading command output only (git, cargo, npm, etc.).",
23            command.len(),
24            MAX_COMMAND_BYTES
25        ));
26    }
27
28    // #931: strip heredoc bodies before the redirect scanner — a `>` inside a
29    // heredoc body is opaque data, not a file-write redirect.
30    let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
31    // #1768: the rule is the destination, not the size of the payload. The
32    // refusal used to justify itself with "MCP protocol corruption on large
33    // payloads" while the guard allows a megabyte into /tmp and blocks two
34    // bytes into a project file — so the stated reason argued *against* the
35    // verdict in both directions, and steered callers to retry smaller (no
36    // effect) or to avoid the sanctioned scratch capture. The reasons that
37    // actually hold are the ones #1303 and #1142 established: ctx_shell
38    // compresses what it returns, so output redirected into a file you keep
39    // can land there with compression markers instead of the command's own
40    // bytes; and a scratch capture is precisely how a large payload stays out
41    // of the MCP channel.
42    if let Some(target) =
43        disallowed_write_redirect_target(&cmd_no_heredoc, write_allow_paths, project_root)
44    {
45        return Some(format!(
46            "ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
47             not the size of the output. ctx_shell compresses what it returns, so a redirect \
48             into a file you keep can write compression markers instead of the command's own \
49             bytes, and ctx_shell never modifies project files. \
50             Use the native Write tool or ctx_patch for project files. \
51             Capturing output to a scratch path (/tmp, /var/tmp, $TMPDIR) is allowed — that \
52             keeps the output out of the MCP channel entirely."
53        ));
54    }
55
56    // #989: tee detection must run on heredoc-stripped text to avoid false
57    // positives when the word "tee" appears in heredoc/quoted payloads.
58    //
59    // #1671: the rule is the destination, not the pipe. The message used to say
60    // "tee without pipe" and then state that piped tee is allowed — so it
61    // rejected a command and, in the next sentence, described that exact
62    // command as permitted. A reviewer read it, concluded the block was correct
63    // because an alternative was offered, and closed a review with no findings.
64    // Naming the pipe also sent callers off to restructure their pipeline,
65    // which cannot help: `… | tee FILE | wc -l` is judged identically.
66    if let Some(target) = disallowed_tee_target(&cmd_no_heredoc, write_allow_paths, project_root) {
67        return Some(format!(
68            "ERROR: ctx_shell refuses `tee {target}` — the destination is inside the \
69             project, and ctx_shell is ONLY for reading command output. \
70             Piping makes no difference: the destination decides. \
71             Use the native Write tool to create/modify project files, or tee to a \
72             scratch path (/tmp, /var/tmp, $TMPDIR), which is allowed."
73        ));
74    }
75
76    if is_heredoc_file_write(command, write_allow_paths, project_root) {
77        return Some(
78            "ERROR: ctx_shell detected a heredoc writing to a file. \
79             Use the native Write tool to create/modify files. \
80             ctx_shell is ONLY for reading command output. \
81             Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
82                .to_string(),
83        );
84    }
85
86    // #1672: on the heredoc-stripped text, for the same reason as #931 and
87    // #989 above. A download flag inside a heredoc *body* is opaque data — a
88    // commit message, a doc, a fixture — and refusing the call for it blocks
89    // writing about the guard at all. This detector was simply never switched
90    // over when the other two were.
91    if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
92        return Some(format!(
93            "ERROR: ctx_shell detected a file download/write ({reason}). \
94             ctx_shell is ONLY for reading command output — redirect-free flags bypass \
95             this doctrine, so they are blocked too (GH #391). \
96             For text, fetch to stdout: curl <url> / wget -qO- <url>. \
97             For a binary (image, PDF, archive) neither stdout nor the editor's Write \
98             tool can carry the bytes — download to an absolute scratch path instead, \
99             e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661)."
100        ));
101    }
102
103    None
104}
105
106/// Well-known Unix scratch prefixes that agents use on every platform.
107/// On Windows, `/tmp/foo` is not a real absolute path, but Git Bash, WSL,
108/// and agent-generated commands routinely target it.  (#1467)
109fn is_unix_scratch_prefix(path: &str) -> bool {
110    for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
111        if path == prefix || path.starts_with(&format!("{prefix}/")) {
112            return true;
113        }
114    }
115    false
116}
117
118/// Detects download/copy tools writing directly to files via their own flags.
119/// Returns true when a path targets a scratch/temp location outside the
120/// project, where file downloads are safe (#1021).
121fn is_scratch_path(path: &str) -> bool {
122    if is_unix_scratch_prefix(path) {
123        return true;
124    }
125    if let Ok(tmpdir) = std::env::var("TMPDIR")
126        && !tmpdir.is_empty()
127        && std::path::Path::new(path).starts_with(tmpdir.as_str())
128    {
129        return true;
130    }
131    // Windows: %TEMP% / std::env::temp_dir()
132    let tmp = std::env::temp_dir();
133    if std::path::Path::new(path).starts_with(&tmp) {
134        return true;
135    }
136    false
137}
138
139/// (`curl -o`, `wget` default mode, `dd of=`) — the redirect-free equivalent of
140/// `> file`, reported as a `validate_command` bypass in GH #391.
141fn download_to_file_reason(command: &str) -> Option<String> {
142    // #1661: the scratch carve-out is written in absolute paths, but agents
143    // reach a scratch directory the way a person would — `cd <scratchpad> &&
144    // curl -o shot.png …`. Judged as the bare string `shot.png`, a target that
145    // lands squarely inside the sanctioned directory looked like a project
146    // write and was blocked, leaving no in-tool way to fetch a binary at all.
147    // Segments are paired with the directory they actually run in so a relative
148    // target is judged where it lands.
149    for seg_cwd in crate::core::command_cwd::segments_with_cwd(command, None) {
150        let seg = seg_cwd.segment;
151        let here = seg_cwd.cwd;
152        let resolve = |path: &str| -> String {
153            let p = std::path::Path::new(path);
154            // `starts_with('/')`: shell text, so a Unix-absolute target is
155            // absolute on Windows too, where `is_absolute` disagrees (#1467).
156            if p.is_absolute() || path.starts_with('/') {
157                return path.to_string();
158            }
159            // Without a known directory the target stays unresolved, which the
160            // scratch check then rejects — the guard errs closed.
161            match here.as_deref() {
162                Some(dir) => crate::core::command_cwd::join_in(dir, path)
163                    .to_string_lossy()
164                    .into_owned(),
165                None => path.to_string(),
166            }
167        };
168        let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
169        let Some(first) = tokens.first() else {
170            continue;
171        };
172        let base = first.rsplit('/').next().unwrap_or(first);
173        match base {
174            "curl" => {
175                let tokens_slice = &tokens[1..];
176                for (i, tok) in tokens_slice.iter().enumerate() {
177                    let target: Option<&str> = if tok == "--output" {
178                        tokens_slice.get(i + 1).map(String::as_str)
179                    } else if let Some(val) = tok.strip_prefix("--output=") {
180                        Some(val)
181                    } else if tok == "--output-dir" {
182                        tokens_slice.get(i + 1).map(String::as_str)
183                    } else if let Some(val) = tok.strip_prefix("--output-dir=") {
184                        Some(val)
185                    } else if tok.starts_with('-')
186                        && !tok.starts_with("--")
187                        && tok[1..].contains('o')
188                    {
189                        // -o <file>: next token is the path
190                        tokens_slice.get(i + 1).map(String::as_str)
191                    } else if tok == "--remote-name"
192                        || tok == "--remote-name-all"
193                        || (tok.starts_with('-')
194                            && !tok.starts_with("--")
195                            && tok[1..].contains('O'))
196                    {
197                        Some(".")
198                    } else {
199                        None
200                    };
201                    if let Some(path) = target {
202                        if is_scratch_path(&resolve(path)) {
203                            continue;
204                        }
205                        return Some(format!("curl {tok}"));
206                    }
207                }
208            }
209            "wget" => {
210                // wget writes a file BY DEFAULT; only stdout/no-download modes pass.
211                let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
212                    tok == "--output-document=-"
213                        || tok == "-O-"
214                        || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
215                        || ((tok == "-O" || tok == "--output-document")
216                            && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
217                        || tok == "--spider"
218                });
219                if !to_stdout {
220                    return Some(
221                        "wget downloads to a file by default; use wget -qO- <url> for stdout"
222                            .to_string(),
223                    );
224                }
225            }
226            "dd" => {
227                for tok in &tokens[1..] {
228                    if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
229                        return Some(format!("dd {tok}"));
230                    }
231                }
232            }
233            _ => {}
234        }
235    }
236    None
237}
238
239/// Returns true only for heredocs that redirect to files (the dangerous pattern).
240/// Legitimate heredoc uses (input piping, inline scripts) are allowed through.
241fn is_heredoc_file_write(
242    command: &str,
243    write_allow_paths: &[String],
244    project_root: Option<&str>,
245) -> bool {
246    let has_heredoc = command.contains("<<");
247    if !has_heredoc {
248        return false;
249    }
250    let cmd_lower = command.to_lowercase();
251    let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
252    let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
253    if !has_known_heredoc {
254        return false;
255    }
256    // #931: strip heredoc bodies so `>` / `>>` inside the body are not
257    // mistaken for file-write redirects.
258    let stripped = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
259    disallowed_write_redirect_target(&stripped, write_allow_paths, project_root).is_some()
260}
261
262/// Detects shell redirect operators (`>` or `>>`) that write to files.
263/// Ignores `>` inside quotes, after a backslash escape (`\"` must not toggle
264/// quote state, `\>` is a literal), `2>` (stderr), `/dev/null`, and
265/// comparison operators.
266/// #848: temp directory targets are read-back, not persistent writes.
267/// #848/#989: targets that are NOT persistent project-file writes.
268/// Redirecting to temp dirs, /dev/* devices, or paths containing shell
269/// variables (which we cannot resolve at parse time) is output capture,
270/// not file authoring.
271pub fn is_temp_redirect_target(target: &str) -> bool {
272    let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
273    is_write_allowed_redirect_target(target, &write_allow_paths, None)
274}
275
276fn is_write_allowed_redirect_target(
277    target: &str,
278    write_allow_paths: &[String],
279    project_root: Option<&str>,
280) -> bool {
281    // `>|` is the noclobber-override form of `>`; the `|` is not part of the path.
282    let t = target.trim_start_matches(['>', '&', '|']);
283    // #1142: agents quote scratch paths (`> "$TMPDIR/x.log"`, `> "/private/tmp/x"`);
284    // strip quotes so quoted and unquoted targets are judged identically.
285    let t = t.trim_matches(['"', '\'']);
286    if t.starts_with('$') || t.starts_with("${") {
287        // Preserve #989's escape hatch for harness-provided scratch paths.
288        return true;
289    }
290
291    // On Windows, agents often use Unix-style /tmp paths (Git Bash, WSL,
292    // or Claude generating Unix commands).  `/tmp/foo` is not absolute per
293    // std::path on Windows, so check well-known scratch prefixes before
294    // the is_absolute gate.  (#1467)
295    if is_unix_scratch_prefix(t) {
296        return true;
297    }
298
299    let path = std::path::Path::new(t);
300    if !path.is_absolute() {
301        return false;
302    }
303    let resolved = resolve_path_for_comparison(path);
304    if project_root.is_some_and(|root| {
305        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
306    }) {
307        return false;
308    }
309    write_allow_paths.iter().any(|allowed| {
310        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
311    })
312}
313
314fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
315    use std::path::{Component, PathBuf};
316
317    let mut normalized = PathBuf::new();
318    for component in path.components() {
319        match component {
320            Component::CurDir => {}
321            Component::ParentDir => {
322                normalized.pop();
323            }
324            other => normalized.push(other.as_os_str()),
325        }
326    }
327
328    let mut unresolved = Vec::new();
329    let mut existing = normalized.clone();
330    while !existing.exists() {
331        let Some(name) = existing.file_name() else {
332            break;
333        };
334        unresolved.push(name.to_os_string());
335        if !existing.pop() {
336            break;
337        }
338    }
339    let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
340    for component in unresolved.iter().rev() {
341        resolved.push(component);
342    }
343    resolved
344}
345
346fn tee_targets(command: &str) -> Vec<String> {
347    crate::core::shell_allowlist::extract_all_commands_pub(command)
348        .into_iter()
349        .filter_map(|segment| {
350            let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
351            let first = tokens.first()?;
352            if first.rsplit('/').next().unwrap_or(first) != "tee" {
353                return None;
354            }
355            let mut after_separator = false;
356            Some(
357                tokens
358                    .iter()
359                    .skip(1)
360                    .find(|token| {
361                        if *token == "--" {
362                            after_separator = true;
363                            return false;
364                        }
365                        after_separator || !token.starts_with('-')
366                    })
367                    .cloned()
368                    .unwrap_or_default(),
369            )
370        })
371        .collect()
372}
373
374/// The first `tee` destination that is not a permitted write target.
375///
376/// Returns the path so the refusal can name it (#1671). The rule is entirely
377/// about the destination — whether the `tee` is piped makes no difference — and
378/// a message that cannot name the destination ends up describing some other
379/// rule instead.
380fn disallowed_tee_target(
381    command: &str,
382    write_allow_paths: &[String],
383    project_root: Option<&str>,
384) -> Option<String> {
385    tee_targets(command).into_iter().find(|target| {
386        !target.is_empty()
387            && !is_write_allowed_redirect_target(target, write_allow_paths, project_root)
388    })
389}
390
391/// True when the command redirects into a path it may not write.
392///
393/// Test-only convenience: every production caller needs the offending target
394/// for its message and goes to [`disallowed_write_redirect_target`] directly
395/// (#1768). The assertions here only care about the verdict, and reading
396/// `.is_some()` into every one of them would obscure what they pin.
397#[cfg(test)]
398fn has_file_write_redirect(
399    command: &str,
400    write_allow_paths: &[String],
401    project_root: Option<&str>,
402) -> bool {
403    disallowed_write_redirect_target(command, write_allow_paths, project_root).is_some()
404}
405
406/// The first redirect target that is **not** write-allowed, or `None` when the
407/// command writes nowhere it may not.
408///
409/// Returns the target rather than a bare verdict so the refusal can name what
410/// tripped it (#1768) — the same reason [`disallowed_tee_target`] exists. A
411/// guard that states a rule the caller cannot map onto their own command gets
412/// read as something else (there, "piping"; here, "large payloads"), and every
413/// such misreading sends the caller somewhere that cannot help.
414fn disallowed_write_redirect_target(
415    command: &str,
416    write_allow_paths: &[String],
417    project_root: Option<&str>,
418) -> Option<String> {
419    let bytes = command.as_bytes();
420    let len = bytes.len();
421    let mut i = 0;
422    let mut in_single_quote = false;
423    let mut in_double_quote = false;
424
425    while i < len {
426        let c = bytes[i];
427        if c == b'\\' && !in_single_quote {
428            // A backslash escapes the next byte (POSIX: outside quotes and
429            // inside double quotes; inside single quotes it is literal).
430            // Without this, an escaped quote like `\"` toggled the quote
431            // state and literal `>` in quoted prose (e.g. `(root: <root>)`
432            // in a gh --body string) read as a redirect (#903).
433            i += 2;
434            continue;
435        }
436        if c == b'\'' && !in_double_quote {
437            in_single_quote = !in_single_quote;
438        } else if c == b'"' && !in_single_quote {
439            in_double_quote = !in_double_quote;
440        } else if c == b'>' && !in_single_quote && !in_double_quote {
441            if i > 0 && bytes[i - 1] == b'2' {
442                i += 1;
443                continue;
444            }
445            let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
446                i + 2
447            } else {
448                i + 1
449            };
450            // The redirect *operator* can carry one more character: `>|`
451            // overrides noclobber and `>&` duplicates a descriptor. Neither
452            // belongs to the target word, so strip it before reading the word
453            // and re-attach `&` for the fd check below.
454            let rest = command[target_start..].trim_start();
455            let (rest, fd_dup) = match rest.strip_prefix('|') {
456                Some(r) => (r, false),
457                None => match rest.strip_prefix('&') {
458                    Some(r) => (r, true),
459                    None => (rest, false),
460                },
461            };
462            // The word ends at whitespace *or* at a shell metacharacter
463            // (#1659). Stopping only at whitespace made the verdict depend on
464            // where the redirect sat: `echo a 1>/dev/null` read the target as
465            // `/dev/null` and was allowed, while `echo a 1>/dev/null; echo b`
466            // read `/dev/null;` — semicolon included, since it is not
467            // whitespace — missed the /dev/null exemption, and was blocked as a
468            // file write. `&&` happened to work only because a space precedes
469            // it. Same redirect, same shell semantics, opposite verdicts.
470            //
471            // `(` is deliberately not a terminator: it would reduce the
472            // process-substitution target `>(cmd)` to an empty word, and an
473            // empty word falls through unblocked.
474            let word: String = rest
475                .chars()
476                .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
477                .collect();
478            let target = if fd_dup { format!("&{word}") } else { word };
479            if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
480                i += 1;
481                continue;
482            }
483            // #1142: `>&1` / `>&2` duplicate a file descriptor — no file involved.
484            // (`2>&1` is already skipped by the `2>` case above.)
485            if let Some(fd) = target.strip_prefix('&')
486                && !fd.is_empty()
487                && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
488            {
489                i += 1;
490                continue;
491            }
492            // #848: allow redirects to temp directories — agents capture
493            // build output for grepping, not writing persistent files.
494            if is_write_allowed_redirect_target(&target, write_allow_paths, project_root) {
495                i += 1;
496                continue;
497            }
498            if !target.is_empty() {
499                return Some(target);
500            }
501        }
502        i += 1;
503    }
504    None
505}
506
507/// On Windows cmd.exe, `;` is not a valid command separator.
508/// Convert `cmd1; cmd2` to `cmd1 && cmd2` when running under cmd.exe.
509pub fn normalize_command_for_shell(command: &str) -> String {
510    if !cfg!(windows) {
511        return command.to_string();
512    }
513    let (_, flag) = crate::shell::shell_and_flag();
514    if flag != "/C" {
515        return command.to_string();
516    }
517    let bytes = command.as_bytes();
518    let mut result = Vec::with_capacity(bytes.len() + 16);
519    let mut in_single = false;
520    let mut in_double = false;
521    for (i, &b) in bytes.iter().enumerate() {
522        if b == b'\'' && !in_double {
523            in_single = !in_single;
524        } else if b == b'"' && !in_single {
525            in_double = !in_double;
526        } else if b == b';' && !in_single && !in_double {
527            result.extend_from_slice(b" && ");
528            continue;
529        }
530        result.push(b);
531        let _ = i;
532    }
533    String::from_utf8(result).unwrap_or_else(|_| command.to_string())
534}
535
536/// Compresses shell command output using the unified compression pipeline.
537/// Delegates to the same exit-code-aware logic used by the CLI, so a failed
538/// command (`exit_code != 0`) is preserved verbatim and successful output is
539/// compressed consistently (excluded_commands, structural routing, terse). #810.
540pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
541    crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
542}
543
544pub fn handle_with_context(
545    command: &str,
546    output: &str,
547    exit_code: i32,
548    crp_mode: CrpMode,
549    project_root: Option<&str>,
550) -> String {
551    let mut result = handle(command, output, exit_code, crp_mode);
552
553    {
554        if let Some(root) = project_root {
555            let estimated_tokens = result.len() / 4;
556            if estimated_tokens > 500 {
557                let kernel_budget = 100;
558                if let Some(enrichment) =
559                    crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
560                    && !enrichment.blocks.is_empty()
561                {
562                    result.push_str("\n--- kernel context ---\n");
563                    result.push_str(&enrichment.blocks);
564                }
565            }
566        }
567    }
568
569    result
570}
571
572#[cfg(test)]
573mod kernel_tests {
574    use super::handle_with_context;
575    use crate::tools::CrpMode;
576
577    #[test]
578    fn handle_with_context_does_not_panic_on_short_output() {
579        let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
580        assert!(!result.is_empty());
581    }
582}
583
584#[cfg(test)]
585fn is_search_command(command: &str) -> bool {
586    let cmd = command.trim_start();
587    cmd.starts_with("grep ")
588        || cmd.starts_with("rg ")
589        || cmd.starts_with("find ")
590        || cmd.starts_with("fd ")
591        || cmd.starts_with("ag ")
592        || cmd.starts_with("ack ")
593}
594
595#[cfg(test)]
596fn generic_compress(output: &str) -> String {
597    let output = crate::core::compressor::strip_ansi(output);
598    let lines: Vec<&str> = output
599        .lines()
600        .filter(|l| {
601            let t = l.trim();
602            !t.is_empty()
603        })
604        .collect();
605
606    if lines.len() <= 20 {
607        return lines.join("\n");
608    }
609
610    let show_count = (lines.len() / 3).min(30);
611    let half = show_count / 2;
612    let first = &lines[..half];
613    let last = &lines[lines.len() - half..];
614    let omitted = lines.len() - (half * 2);
615    format!(
616        "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
617        first.join("\n"),
618        half * 2,
619        lines.len(),
620        omitted,
621        last.join("\n")
622    )
623}
624
625/// Detects OAuth device code flow output that must not be compressed.
626/// Uses a two-tier approach: strong signals match alone (very specific to
627/// device code flows), weak signals require a URL/domain in the same output.
628pub fn contains_auth_flow(output: &str) -> bool {
629    let lower = output.to_lowercase();
630
631    const STRONG_SIGNALS: &[&str] = &[
632        "devicelogin",
633        "deviceauth",
634        "device_code",
635        "device code",
636        "device-code",
637        "verification_uri",
638        "user_code",
639        "one-time code",
640    ];
641
642    if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
643        return true;
644    }
645
646    const WEAK_SIGNALS: &[&str] = &[
647        "enter the code",
648        "enter this code",
649        "enter code:",
650        "use the code",
651        "use a web browser to open",
652        "open the page",
653        "authenticate by visiting",
654        "sign in with the code",
655        "sign in using a code",
656        "verification code",
657        "authorize this device",
658        "waiting for authentication",
659        "waiting for login",
660        "waiting for you to authenticate",
661        "open your browser",
662        "open in your browser",
663    ];
664
665    let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
666    if !has_weak_signal {
667        return false;
668    }
669
670    lower.contains("http://") || lower.contains("https://")
671}
672
673#[cfg(test)]
674mod tests;