#!/bin/bash
# Secretless Guard — PreToolUse hook for Claude Code
# Blocks file access to secrets before they enter AI context.
# Managed by secretless-ai. Do not edit manually.
# Written by secretless-ai <version>

set -euo pipefail

# Match bytewise, not by the ambient locale.
#
# In a UTF-8 locale grep decodes each line as characters, and a line carrying an
# invalid byte sequence cannot be decoded, so any pattern using a bracket
# expression stops matching on that line while a plain literal pattern still
# does. That is an evasion: appending one invalid byte to a secret-reading
# command made the bracket-expression guards below fall silent. LC_ALL=C removes
# the decoding step, so a command cannot change how it is matched by carrying
# undecodable bytes, and matching no longer varies with the developer's locale.
export LC_ALL=C

# NOTE ON TEMPORARY FILES. bash 3.2, the /bin/bash of macOS, writes the text of
# every here-document and here-string to a temporary file, and bash 5 does so
# for a long one. When that file cannot be written (a full disk, a sandbox that
# refuses the write), the command it feeds does not run, and set -e does not
# stop the script. So this script feeds no command that way, and its verdict
# does not depend on a temporary file: the text it carries is assigned in
# single quotes, the candidate paths are split at line breaks, and grep reads a
# text through a pipe (text_matches below), whose failure makes the script exit
# 2, the code the hook protocol reads as a refusal.

INPUT=$(cat)
# Each field is optional depending on the tool (a Bash call has no file_path; a
# Read call has no command), so a non-matching grep is normal, not an error. The
# trailing `|| true` keeps a no-match from returning non-zero and tripping
# `set -euo pipefail` — without it the whole Bash-command branch below was dead:
# every Bash call died at the FILE_PATH line (grep found no file_path) before any
# command guard ran. Regression: release-test 2026-07-16.
# Parse tool_name with a real JSON parser when one is available, for the same
# reason the command extraction below does. The grep is the fallback for hosts
# without python3, and it takes spaces or tabs on each side of the colon. It
# matched only '"tool_name":"…"', so a payload with a space after the colon, as
# a pretty-printer writes it, gave an empty TOOL_NAME there, the Bash branch
# below was skipped, and every command guard failed OPEN. That is the same
# dead-branch class as the 2026-07-16 FILE_PATH regression, reached through
# formatting rather than through `set -euo pipefail`. A line break between a
# key and its colon is still not read without python3.
TOOL_NAME=""
if command -v python3 >/dev/null 2>&1; then
  # Emit ONLY a non-empty string. str() of a number, bool or dict would produce
  # a non-empty WRONG value ('123', 'True', "{'a': 1}"), which suppresses the
  # grep fallback below and leaves the guard reading a field that isn't there.
  TOOL_NAME=$(printf '%s' "$INPUT" | python3 -c 'import json,sys
try:
    v = json.load(sys.stdin).get("tool_name")
    sys.stdout.write(v if isinstance(v, str) else "")
except Exception:
    pass' 2>/dev/null || true)
fi
if [ -z "$TOOL_NAME" ]; then
  TOOL_NAME=$(echo "$INPUT" | grep -oE '"tool_name"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | cut -d'"' -f4 || true)
fi

# Extract file path from tool input (handles Read, Grep, Glob, Edit, Write).
# Same compact-JSON brittleness as TOOL_NAME above: a pretty-printed payload
# left FILE_PATH empty and the file guard never ran. Parse properly when
# python3 is available, keep the greps as the fallback, and let them take
# spaces or tabs on each side of the colon as the TOOL_NAME grep does.
# Collect EVERY candidate path, not just the first. The structured parse reads
# the documented top-level fields; the greps additionally sweep the whole
# payload, so a nested shape (MultiEdit-style edit lists, MCP tool payloads)
# whose secret path is not at the top level is still seen. Checking the union
# is what keeps the structured parse from NARROWING the older grep behaviour.
# Only non-empty strings are emitted, for the same reason as TOOL_NAME above.
FILE_PATH_CANDIDATES=""
if command -v python3 >/dev/null 2>&1; then
  FILE_PATH_CANDIDATES=$(printf '%s' "$INPUT" | python3 -c 'import json,sys
def walk(o):
    if isinstance(o, dict):
        for k, v in o.items():
            if k in ("file_path", "path") and isinstance(v, str) and v:
                yield v
            else:
                yield from walk(v)
    elif isinstance(o, list):
        for v in o:
            yield from walk(v)
try:
    sys.stdout.write("\n".join(walk(json.load(sys.stdin))))
except Exception:
    pass' 2>/dev/null || true)
fi
FILE_PATH_CANDIDATES=$(printf '%s\n%s\n%s\n'   "$FILE_PATH_CANDIDATES"   "$(echo "$INPUT" | grep -oE '"file_path"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4 || true)"   "$(echo "$INPUT" | grep -oE '"path"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4 || true)"   | grep -v '^$' | sort -u || true)
FILE_PATH=$(printf '%s' "$FILE_PATH_CANDIDATES" | head -1 || true)

# For Bash tool, check the command for secret access patterns
if [ "$TOOL_NAME" = "Bash" ]; then
  # Extract the command with a real JSON parser when one is available. The old
  # grep 'command":"[^"]*"' stopped at the FIRST double quote, so any command
  # containing a quote (`x="" ; cat .env`, `eval "$(secretless-ai env)"`) was
  # truncated before the dangerous part and slipped past every guard below.
  # python3's json module handles the escaping correctly; the grep is only a
  # fallback for hosts without python3 (there the native permissions.deny rules
  # remain the enforcing layer). Regression: adressed 2026-07-16 (issue #99).
  COMMAND=""
  FILE_READ_SCAN=""
  if command -v python3 >/dev/null 2>&1; then
    # surrogatepass so a lone surrogate in the command can't raise mid-write and
    # leave us empty; write bytes so no encoding step can fail.
    COMMAND=$(printf '%s' "$INPUT" | python3 -c 'import json,sys
try:
    ti = (json.load(sys.stdin).get("tool_input") or {})
    sys.stdout.buffer.write((ti.get("command") or "").encode("utf-8","surrogatepass"))
except Exception:
    pass' 2>/dev/null || true)
    # The text the two secret-file-read rules below match: the command with the
    # text of one inert write left out (cat > FILE <<'DELIM', or printf or echo
    # of single-quoted text into a file), so a note that names a secret file is
    # not refused as a read of one. Empty for every other command, and on any
    # error, and then the whole command is scanned. -I keeps a module in the
    # working directory from standing in for the standard library.
    if [ -n "$COMMAND" ]; then
      FILE_READ_SCAN=$(printf '%s' "$COMMAND" | python3 -I -c 'import re,sys
WORD = r"(?:\x27[^\x27]*\x27|[A-Za-z0-9_%+,./:=@~-])+"
TOKEN = re.compile(r"[ \t]+|>>?|" + WORD)
PLAIN = re.compile(r"[A-Za-z0-9_%+,./:=@~-]+\Z")
SECRET = re.compile(r"\.(env|key|pem|p12|pfx|crt)([^A-Za-z0-9]|\Z)", re.I)
HEREDOC = re.compile(r"([^<]*)<<[ \t]*\x27([A-Za-z0-9_.-]+)\x27([^<]*)\Z")
def words(s):
    out, i = [], 0
    while i < len(s):
        m = TOKEN.match(s, i)
        if not m:
            return None
        if m.group().strip(" \t"):
            out.append(m.group())
        i = m.end()
    return out
def sink(ws):
    ops = [i for i, w in enumerate(ws) if w in (">", ">>")]
    if len(ops) != 1 or ops[0] + 1 >= len(ws):
        return False
    t = ws[ops[0] + 1]
    return PLAIN.match(t) is not None and SECRET.search(t) is None
def scan_text(cmd):
    lines = cmd.split("\n")
    m = HEREDOC.match(lines[0])
    if m:
        ws = words(m.group(1) + " " + m.group(3))
        if ws is None or len(ws) != 3 or ws[0] != "cat" or not sink(ws):
            return None
        delim = m.group(2)
        if delim not in lines[1:]:
            return None
        end = lines.index(delim, 1)
        if "".join(lines[end + 1:]).strip():
            return None
        return lines[0] + "\n" + delim
    ws = words(cmd.strip(" \t\n"))
    if not ws or ws[0] not in ("printf", "echo") or not sink(ws):
        return None
    return re.sub(r"\x27[^\x27]*\x27", chr(39) * 2, cmd)
try:
    out = scan_text(sys.stdin.buffer.read().decode("utf-8", "surrogateescape"))
    if out:
        sys.stdout.buffer.write(out.encode("utf-8", "surrogateescape"))
except Exception:
    pass' 2>/dev/null || true)
    fi
  fi
  # Fail CLOSED: if python is absent OR its extraction produced nothing (parse
  # error, odd input), fall back to the grep extraction rather than leaving
  # COMMAND empty — an empty COMMAND would skip every guard below. The grep
  # reads the JSON string up to its closing quote, stepping over each escape, so
  # an escaped quote inside the command does not end it. It used to stop at the
  # first `\"`, and `echo "$GITHUB_TOKEN"` or `x=""; cat .env` reached the
  # rules below as `echo \` and `x=\`. The escapes stay as the payload writes
  # them: a quote is `\"`, a line break `\n`, a tab `\t`, a backslash `\\`.
  # Spaces or tabs may stand on each side of the colon, as for TOOL_NAME. The
  # key, the colon and the quotes are cut off by parameter expansion: through
  # the first colon, which the key and the blanks before it do not hold, then
  # through the next quote, the one that opens the value, and the closing quote
  # last, so this needs no program beyond grep and head.
  COMMAND_FORM=text
  if [ -z "$COMMAND" ]; then
    COMMAND_FORM=json
    COMMAND=$(echo "$INPUT" | grep -oE '"command"[[:space:]]*:[[:space:]]*"([^"\\]|\\.)*"' | head -1 || true)
    COMMAND=${COMMAND#*:}
    COMMAND=${COMMAND#*'"'}
    COMMAND=${COMMAND%'"'}
  fi
  # NOTE ON LINE CONTINUATIONS. bash removes a backslash-newline pair before it
  # splits a command into words, so `cat \` on one line and a secret path on
  # the next is the same read as the one-line form. Every arm below matches a
  # line at a time, and admitted the split form while it refused the one-line
  # form. So before any arm runs, the hook judges the command with every pair
  # removed, by running itself on that text, and a deny there is the verdict.
  # Then it judges the command as written, as before, so the joined text can
  # only add a denial: a continuation that bash would not join, inside single
  # quotes or at the end of a comment, could otherwise hide a read that the
  # text as written shows. Removing the pair inside single quotes, where bash
  # keeps it, can likewise only refuse more, and that over-approximation is
  # meant. With python3 the command is text and the pair is a backslash and a
  # line break. Without it the command is the JSON string, where the pair is
  # the escapes `\\` and `\n`; an escape is removed whole, after an even run
  # of backslashes only, so an escaped backslash followed by the letter n is not
  # taken for one. Removing a pair can leave a new one, a backslash before it
  # and a line break after it, so pairs are removed until none is left: with
  # python3 in one pass, which drops a line break together with the backslash
  # the text kept so far ends in, and without it by the sed loop. bash's own
  # substitution is not used for this: on bash 3.2, the /bin/bash of macOS, one
  # pass over a few thousand backslashes takes seconds. The run on the joined
  # text gets the argument --joined-run and does not join again, so the hook
  # runs itself at most once, however the pairs nest. If the run on the joined
  # text fails, the command is refused.
  CONTINUATION_NL='
'
  JOINED_INPUT=""
  if [ "${1:-}" = --joined-run ]; then
    : # this run judges text that is already joined
  elif [ "$COMMAND_FORM" = text ]; then
    case "$COMMAND" in
      *"\\$CONTINUATION_NL"*)
        JOINED_INPUT=$(printf '%s' "$COMMAND" | python3 -I -c 'import json,sys
joined = bytearray()
for byte in sys.stdin.buffer.read():
    if byte == 10 and joined and joined[-1] == 92:
        joined.pop()
    else:
        joined.append(byte)
sys.stdout.write(json.dumps({"tool_name": "Bash", "tool_input": {"command": joined.decode("utf-8", "surrogateescape")}}))' 2>/dev/null) || JOINED_INPUT="failed"
        ;;
    esac
  else
    JOINED=$(printf '%s\n' "$COMMAND" \
      | sed -E -e ':join' -e 's/(^|[^\\])((\\\\)*)\\\\\\n/\1\2/' -e 't join' 2>/dev/null) || JOINED="$COMMAND"
    if [ "$JOINED" != "$COMMAND" ]; then
      JOINED_INPUT=$(printf '{"tool_name":"Bash","tool_input":{"command":"%s"}}' "$JOINED")
    fi
  fi
  if [ -n "$JOINED_INPUT" ]; then
    JOINED_VERDICT=""
    if [ "$JOINED_INPUT" = failed ] \
      || ! JOINED_VERDICT=$(printf '%s' "$JOINED_INPUT" | "$BASH" "$0" --joined-run 2>/dev/null); then
      JOINED_VERDICT='{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked command the guard could not judge with its line continuations joined. Safe path: write the command on one line."}}'
    fi
    if [ -n "$JOINED_VERDICT" ]; then
      printf '%s\n' "$JOINED_VERDICT"
      exit 0
    fi
  fi
  if [ -z "$FILE_READ_SCAN" ]; then
    FILE_READ_SCAN="$COMMAND"
  fi
  # The text a command rule matched, for its deny reason, so the reason names
  # what tripped it: the first span of $3 that the boundary $1 followed by the
  # rule $2 matches, run on to the end of its word, cut to 160 characters, and
  # starting where $2 starts. The boundary is up to two characters (a `\n`
  # escape), and the fewest are dropped, so `\tail .env` keeps its verb. Every
  # character JSON cannot carry raw becomes ?, and quotes and backslashes are
  # escaped, so the reason stays one JSON document whatever the command holds.
  matched_text() {
    local m c
    m=$(printf '%s\n' "$3" | grep -oiE "$1$2[^[:space:]]*" | head -1 || true)
    for c in "$m" "${m:1}" "${m:2}"; do
      if printf '%s\n' "$c" | grep -qiE "^$2"; then m=$c; break; fi
    done
    printf '%s\n' "$m" \
      | tr -c '[:print:]\n' '?' | cut -c1-160 | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' || true
  }
  # Whether grep with the options $1 finds the pattern $2 in the text $3, read
  # as grep -q reads its input. The text goes through a pipe, not a here-string
  # (NOTE ON TEMPORARY FILES). grep -q stops at its first match and the writer
  # can die of SIGPIPE, so pipefail is off in the subshell and its status is
  # grep's own: 0 for a match, 1 for none. Any other status means the rule was
  # not checked, and the guard exits 2, which the hook protocol reads as a
  # refusal.
  text_matches() {
    local rc=0
    (set +o pipefail; printf '%s\n' "$3" | grep -q "$1" -- "$2") || rc=$?
    if [ "$rc" -le 1 ]; then
      return "$rc"
    fi
    echo "Secretless: blocked a call the guard could not check: grep exited $rc." >&2
    exit 2
  }
  # NOTE ON TEMPLATE FILES. The command guard refuses `cat <name>.env.example`
  # even though the file-path guard below allows template files, so the two
  # layers disagree about committed placeholders. That is a known, deliberate
  # over-block, NOT an oversight.
  #
  # The obvious fix — subtract template-suffixed tokens from the command before
  # matching — was implemented, tested against a 50-command corpus, and then
  # REVERTED, because it is a credential bypass. This guard is a denylist over
  # command TEXT, and its only evidence is the literal secret path appearing
  # after a verb. Removing that literal hands the attacker the deletion:
  #
  #     cat "$(basename <name>.env.example .example)"
  #
  # reconstructs the real path from the very token the scrub erased, needs no
  # preconditions (basename is pure string manipulation, the template need not
  # exist), and was measured reading a real secret. Requiring the extension
  # match at the end of the token fails the same way, because the template token
  # still never matches. Any textual exemption for the template NAME permits
  # deriving the real name from it.
  #
  # Closing the disagreement safely needs the guard to resolve the path a
  # command would actually open, rather than pattern-matching its text. Until
  # then, over-blocking a placeholder file is the correct trade against leaking
  # a real one.
  #
  # NOTE ON ENVIRONMENT ACCESSORS. `process.env`, `import.meta.env` and
  # `Deno.env` contain the `.env` token, so `grep -c "process\.env" app.ts`,
  # the first command of any audit of how a codebase reads its configuration,
  # was refused as a secret-file read (#119). An accessor is rewritten to a
  # neutral form before the file-read arm below ONLY inside the pattern argument
  # of grep, egrep, fgrep or git grep: the first word after option groups that
  # take no argument (none of e f A B C m d D), or the word after a lone -e.
  # Everywhere else the text is untouched, because a file called process.env
  # is a name.env file, which this guard treats as a secret file: a file
  # argument (`grep API_KEY process.env`), the word after -f, and every other
  # command (`cat process.env`) still block.
  #
  # The shape below is strict, so that the word it exempts is the one argument
  # grep reads as its pattern. The pattern word is quoted in one piece or made
  # of plain characters, so brace or glob expansion cannot split it into a
  # pattern plus a file. After it come only plain words and `--`: grep
  # permutes its options, and a later -e or -f, quoted or not, turns the first
  # word into a file argument. The exemption is also withheld from any command
  # carrying ; & > < $, a backtick or a control character, and from a pipe
  # into anything but head, wc, sort or uniq with options only, because grep
  # PRINTS the accessor: `grep -o "process.env" README.md | cut -c8- | xargs
  # cat` rebuilds `.env` from its output, the derivation NOTE ON TEMPLATE
  # FILES describes. The interpreter one-liner arm keeps the original text.
  FILE_READ_COMMAND="$COMMAND"
  SEARCH_WITHHELD='[;&<>$`[:cntrl:]]'
  SEARCH_SHAPE='^([[:blank:]]*(grep|egrep|fgrep|git[[:blank:]]+grep)([[:blank:]]+-[a-cg-ln-zE-Z0-9]+)*[[:blank:]]+(-e[[:blank:]]+)?)("([^"\]|[\][^"])*"|'\''[^'\'']*'\''|([A-Za-z0-9_./]|[\][A-Za-z0-9_./])+)(([[:blank:]]+(--|[A-Za-z0-9_./*?@%+=:,][A-Za-z0-9_./*?@%+=:,-]*))*[[:blank:]]*([|][[:blank:]]*(head|wc|sort|uniq)([[:blank:]]+-[A-Za-z0-9]+)*[[:blank:]]*)*)$'
  if [ -n "$SEARCH_WITHHELD" ] && [ -n "$SEARCH_SHAPE" ] \
    && ! [[ $COMMAND =~ $SEARCH_WITHHELD ]] && [[ $COMMAND =~ $SEARCH_SHAPE ]]; then
    SEARCH_HEAD=${BASH_REMATCH[1]-}
    SEARCH_PATTERN=${BASH_REMATCH[5]-}
    SEARCH_TAIL=${BASH_REMATCH[8]-}
    # The three parts must rebuild the command exactly, or nothing is exempt.
    if [ -n "$SEARCH_PATTERN" ] && [ "$SEARCH_HEAD$SEARCH_PATTERN$SEARCH_TAIL" = "$COMMAND" ]; then
      SEARCH_PATTERN=$(printf '%s\n' "$SEARCH_PATTERN" | sed -E 's#(^|[^A-Za-z0-9_$./])(process|import\\?\.meta|Deno)\\?\.env#\1\2_env#g' 2>/dev/null) || SEARCH_PATTERN=""
      [ -z "$SEARCH_PATTERN" ] || FILE_READ_COMMAND="$SEARCH_HEAD$SEARCH_PATTERN$SEARCH_TAIL"
    fi
  fi
  # OPERATION BEFORE TEXT. What the guard CAN remove is text that names no file
  # the command opens: a plain grep's pattern and a heredoc's body. The analyzer
  # prints the command without them, and only when it understands the whole
  # command; otherwise SCAN_TEXT stays the full command. File operands are never
  # removed, so the template over-block above is unchanged. The arms below that
  # read SCAN_TEXT match the reduced text; the data-directory arm, the arms for
  # process listings, a bare env and git credentials, and custom rules read the
  # full command.
  #
  # NOTE ON ENVIRONMENT PRINTS. The same program first parses the whole command
  # into its simple commands, across ; && || | & and line breaks, subshells,
  # command and process substitution, backquotes, brace groups, if/for/while/case
  # bodies, here-documents, wrappers (sudo, env, xargs, nice, nohup, time,
  # command, builtin, exec, watch, timeout, find -exec) and nested shells (bash,
  # sh, zsh or dash -c, eval, a shell reading a here-document or a pipe from
  # echo), and refuses, with ENV-PRINT and a reason, every one that prints the
  # environment:
  #   - set, unless its first word is a literal option and no option turns on
  #     tracing or allexport (x, v, a, k, -o xtrace and the like); set -e,
  #     set -euo pipefail and set +e pass, a bare set or set "$X" does not;
  #     zsh setopt and unsetopt naming xtrace, verbose or allexport;
  #   - env with no program after its options and assignments; printenv in
  #     every form; compgen;
  #   - export, readonly, declare, typeset and local unless every argument is
  #     NAME=value or NAME and no option is -p, -f, -F or -m. declare, typeset
  #     and local with a bare NAME and no option print that variable in zsh, so
  #     they need an assignment or an option;
  #   - a python, node, bun, deno, ruby, perl, php, awk or jq program that names
  #     the whole environment (os.environ with no subscript or .get, process.env
  #     with no property, ENV, %ENV, getenv(), ENVIRON, Deno.env.toObject());
  #   - docker inspect unless --format names no Env field, docker/kubectl exec
  #     and run of any of the above, tmux show-environment, launchctl getenv,
  #     print and export, systemctl show-environment, npm run env.
  # A command it cannot parse is refused too (an unclosed quote, a construct
  # outside the grammar, a program name or nested-shell string that comes from
  # an expansion), because a command the guard cannot read is the one it cannot
  # vouch for. ps, pgrep and /proc/*/environ keep their own arm below. Run with
  # -I so a module in the working directory cannot stand in for re or json.
  SCAN_TEXT="$COMMAND"
  ENV_VERDICT=""
  if command -v python3 >/dev/null 2>&1; then
    # Assigned, not read from a here-document (NOTE ON TEMPORARY FILES), so the
    # analyzer that runs is always this text, never a value from the environment.
    GUARD_ANALYZER='import json, re, sys

SAFE = {"grep", "egrep", "fgrep", "cat", "head", "tail", "wc", "cut", "tr",
        "tee", "sort", "uniq", "mkdir", "echo", "printf"}
GREPS = {"grep", "egrep", "fgrep"}
NOARG = set("abcEFGHhIiLlnoqRrsUvwxZz")
LONG_NOARG = {
    "--count", "--files-with-matches", "--files-without-match", "--ignore-case",
    "--line-number", "--recursive", "--no-filename", "--with-filename",
    "--only-matching", "--quiet", "--silent", "--invert-match", "--word-regexp",
    "--line-regexp", "--extended-regexp", "--fixed-strings", "--basic-regexp",
    "--no-messages", "--byte-offset", "--text", "--null", "--line-buffered",
    "--color", "--colour",
}
LONG_GLOB = ("--include=", "--exclude=", "--exclude-dir=")
LONG_VALUE = ("--color=", "--colour=", "--max-count=", "--context=",
              "--after-context=", "--before-context=", "--binary-files=")
PLAIN = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.,:/@%+=-")
BLANKS = (" ", "\t")
OPS = ("&>>", "<<<", "<<-", "&&", "||", ";;", "|&", "<<", ">>", ">|", "<&", ">&",
       "<>", "&>", "|", "&", ";", "<", ">")
SEPARATORS = ("|", "||", "&&", ";", "&", "|&")
REDIRECTS = ("&>>", "<<<", "<<-", "<<", ">>", ">|", "<&", ">&", "<>", "&>", "<", ">")
SQ, DQ, BSL, BTK = chr(39), chr(34), chr(92), chr(96)


class Bail(Exception):
    pass


class Word:
    def __init__(self, start, end, value, plain):
        self.start, self.end, self.value, self.plain = start, end, value, plain


def read_word(cmd, i):
    n = len(cmd)
    start, val, plain = i, [], True
    while i < n:
        c = cmd[i]
        if c in BLANKS or c == "\n" or c in "|&;<>":
            break
        if c in "(){}$" or c == BTK:
            raise Bail
        if c == SQ:
            j = cmd.find(SQ, i + 1)
            if j < 0:
                raise Bail
            val.append(cmd[i + 1:j])
            i = j + 1
            continue
        if c == DQ:
            i += 1
            while True:
                if i >= n:
                    raise Bail
                d = cmd[i]
                if d == DQ:
                    i += 1
                    break
                if d == "$" or d == BTK:
                    raise Bail
                if d == BSL and i + 1 < n and cmd[i + 1] in ("$", BTK, DQ, BSL, "\n"):
                    if cmd[i + 1] != "\n":
                        val.append(cmd[i + 1])
                    i += 2
                    continue
                val.append(d)
                i += 1
            continue
        if c == BSL:
            if i + 1 >= n:
                raise Bail
            if cmd[i + 1] != "\n":
                val.append(cmd[i + 1])
            i += 2
            continue
        if c == "#" and i == start:
            raise Bail
        if c not in PLAIN or (c in "=~" and i == start):
            plain = False
        val.append(c)
        i += 1
    return Word(start, i, "".join(val), plain), i


def read_body(cmd, i, delim, dash, quoted, bodies):
    n, start = len(cmd), i
    while i < n:
        j = cmd.find("\n", i)
        end = n if j < 0 else j
        line = cmd[i:end]
        if (line.lstrip("\t") if dash else line) == delim:
            body = cmd[start:i]
            if not quoted and any(ch in body for ch in ("$", BTK, BSL)):
                raise Bail
            bodies.append((start, i))
            return n if j < 0 else j + 1
        if j < 0:
            break
        i = j + 1
    raise Bail


def tokenize(cmd):
    n, i = len(cmd), 0
    commands, current, pending, bodies = [], [], [], []
    expect_delim = None
    while i < n:
        c = cmd[i]
        if c in BLANKS:
            i += 1
            continue
        if c == BSL and i + 1 < n and cmd[i + 1] == "\n":
            i += 2
            continue
        if c == "\n":
            if expect_delim is not None:
                raise Bail
            if current:
                commands.append(current)
                current = []
            i += 1
            for delim, dash, quoted in pending:
                i = read_body(cmd, i, delim, dash, quoted, bodies)
            pending = []
            continue
        if c in "|&;<>":
            if c == "<":
                # zsh reads <1-5> and <-> as a numeric glob, not a redirection
                j = i + 1
                while j < n and cmd[j].isdigit():
                    j += 1
                if j < n and cmd[j] == "-":
                    j += 1
                    while j < n and cmd[j].isdigit():
                        j += 1
                    if j < n and cmd[j] == ">":
                        raise Bail
            op = next(o for o in OPS if cmd.startswith(o, i))
            if expect_delim is not None or op == ";;":
                raise Bail
            if op in SEPARATORS:
                if not current:
                    raise Bail
                commands.append(current)
                current = []
            else:
                current.append(("op", i, op))
                if op in ("<<", "<<-"):
                    expect_delim = op == "<<-"
            i += len(op)
            continue
        word, j = read_word(cmd, i)
        if expect_delim is not None:
            if not word.value or "\n" in word.value:
                raise Bail
            quoted = any(q in cmd[i:j] for q in (SQ, DQ, BSL))
            pending.append((word.value, expect_delim, quoted))
            expect_delim = None
        current.append(("word", word))
        i = j
    if pending or expect_delim is not None:
        raise Bail
    if current:
        commands.append(current)
    return commands, bodies


def grep_patterns(args):
    patterns, positional, explicit, end_opts, k = [], [], False, False, 0
    while k < len(args):
        w = args[k]
        v = w.value
        if not end_opts and v == "--":
            if positional:
                raise Bail
            end_opts = True
            k += 1
            continue
        if end_opts or not v.startswith("-") or v == "-":
            positional.append(w)
            k += 1
            continue
        if positional:
            raise Bail
        nxt = args[k + 1] if k + 1 < len(args) else None
        if v.startswith("--"):
            if v.startswith(LONG_GLOB):
                k += 1
                continue
            if not w.plain:
                raise Bail
            if v in LONG_NOARG or v.startswith(LONG_VALUE):
                k += 1
            elif v.startswith("--regexp="):
                explicit = True
                patterns.append(w)
                k += 1
            elif v == "--regexp":
                if nxt is None or not nxt.plain:
                    raise Bail
                explicit = True
                patterns.append(nxt)
                k += 2
            elif v.startswith("--file="):
                explicit = True
                k += 1
            elif v == "--file":
                if nxt is None:
                    raise Bail
                explicit = True
                k += 2
            else:
                raise Bail
            continue
        if not w.plain:
            raise Bail
        body = v[1:]
        if body.isdigit():
            k += 1
            continue
        step = 1
        for idx, ch in enumerate(body):
            rest = body[idx + 1:]
            if ch in NOARG:
                continue
            if ch in "ABCm":
                if rest:
                    if not rest.isdigit():
                        raise Bail
                elif ch == "C" or nxt is None or not nxt.value.isdigit():
                    raise Bail
                else:
                    step = 2
            elif ch == "e":
                explicit = True
                if rest:
                    patterns.append(w)
                elif nxt is None or not nxt.plain:
                    raise Bail
                else:
                    patterns.append(nxt)
                    step = 2
            elif ch == "f":
                explicit = True
                if not rest:
                    if nxt is None:
                        raise Bail
                    step = 2
            else:
                raise Bail
            break
        k += step
    if not explicit:
        if not positional or not positional[0].plain:
            raise Bail
        patterns.append(positional[0])
    return patterns


def reducible_spans(cmd):
    commands, bodies = tokenize(cmd)
    spans = [(s, e, "") for s, e in bodies]
    for tokens in commands:
        words, k = [], 0
        while k < len(tokens):
            if tokens[k][0] == "op":
                if tokens[k][2] not in REDIRECTS:
                    raise Bail
                if k + 1 >= len(tokens) or tokens[k + 1][0] != "word":
                    raise Bail
                k += 2
                continue
            w = tokens[k][1]
            if (w.value.isdigit() and cmd[w.start:w.end] == w.value and k + 1 < len(tokens)
                    and tokens[k + 1][0] == "op" and tokens[k + 1][1] == w.end):
                k += 1
                continue
            words.append(w)
            k += 1
        if not words:
            continue
        name = words[0]
        if cmd[name.start:name.end] != name.value or name.value not in SAFE:
            raise Bail
        if name.value in GREPS:
            spans.extend((p.start, p.end, SQ + SQ) for p in grep_patterns(words[1:]))
        elif name.value not in ("echo", "printf"):
            if any(w.value.startswith("--") and w.value != "--" for w in words[1:]):
                raise Bail
    return spans


# ENVIRONMENT PRINTS. Everything below parses the WHOLE command into its simple
# commands and judges each one by what it runs; see NOTE ON ENVIRONMENT PRINTS.
SENT = chr(0xE000)
NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
ASSIGN_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])?\+?=")
ARRAY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])?\+?=\Z")
CLUSTER_RE = re.compile(r"[-+][A-Za-z]+\Z")
BRACE_RE = re.compile(r"\{[^{}]*(,|\.\.)[^{}]*\}")
ANSI_RE = re.compile(r"x([0-9A-Fa-f]{1,2})|u([0-9A-Fa-f]{1,4})|U([0-9A-Fa-f]{1,8})|([0-7]{1,3})|c(.)")
WORD_END = " \t\n|&;<>()"
RESERVED_SKIP = {"{", "}", "then", "do", "else", "if", "elif", "while", "until",
                 "!", "fi", "done", "esac", "coproc"}
MAX_DEPTH = 16


class Unparsed(Exception):
    def __init__(self, src, pos, why, fix):
        Exception.__init__(self, why)
        self.src, self.pos, self.why, self.fix = src, pos, why, fix


class Refuse(Exception):
    def __init__(self, reason):
        Exception.__init__(self, reason)
        self.reason = reason


# A word: its value has SENT where an expansion stands, so a word is literal
# only when its value holds no SENT and no unquoted glob or brace.
class PW:
    def __init__(self, start, value=""):
        self.start, self.end, self.value, self.quoted, self.glob = start, start, value, False, False


# A simple command, with the text it reads on its input when the command line
# shows that text (a here-document, a here-string, or a pipe from echo).
class PC:
    def __init__(self, src):
        self.src, self.words, self.start, self.end = src, [], None, None
        self.stdin, self.pipe_from, self.kind, self.display = [], None, "simple", None

    def text(self):
        if self.display is not None:
            return self.display
        return "" if self.start is None else self.src[self.start:self.end].strip()


def lit(w):
    return None if (SENT in w.value or w.glob) else w.value


class Parser:
    def __init__(self, s, depth, out):
        if depth > MAX_DEPTH:
            raise Unparsed(s, 0, "commands nested more deeply than the guard reads",
                           "run the inner command on its own")
        self.s, self.n, self.i, self.depth, self.out = s, len(s), 0, depth, out
        self.pending, self.nest = [], 0

    def fail(self, why, fix, pos=None):
        raise Unparsed(self.s, self.i if pos is None else pos, why, fix)

    def at(self, k=0):
        j = self.i + k
        return self.s[j] if j < self.n else ""

    def skip_blanks(self):
        while self.i < self.n:
            c = self.s[self.i]
            if c in BLANKS:
                self.i += 1
            elif c == BSL and self.at(1) == "\n":
                self.i += 2
            else:
                break

    def skip_comment(self):
        j = self.s.find("\n", self.i)
        self.i = self.n if j < 0 else j

    def skip_ws(self):
        while True:
            self.skip_blanks()
            if self.at() == "\n":
                self.i += 1
                if self.pending:
                    self.read_heredocs()
            elif self.at() == "#":
                self.skip_comment()
            else:
                return

    def word_here(self, word):
        if not self.s.startswith(word, self.i):
            return False
        j = self.i + len(word)
        return j >= self.n or self.s[j] in WORD_END

    def read_word(self, paren_ok=False):
        w = PW(self.i)
        val, bare = [], []
        while self.i < self.n:
            c = self.s[self.i]
            if c in BLANKS or c == "\n":
                break
            if c in "<>" and self.at(1) == "(" and self.i == w.start:
                self.i += 2
                self.parse_list(")")
                val.append(SENT)
                bare.append("_")
                continue
            if c == "(":
                if self.i > w.start and ARRAY_RE.match("".join(val)):
                    self.read_array()
                    val.append(SENT)
                    bare.append("_")
                    continue
                if (self.i == w.start and not paren_ok) or re.match(r"\([ \t]*\)", self.s[self.i:self.i + 8]):
                    break
                self.read_glob_group()
                w.glob = True
                val.append(SENT)
                bare.append("_")
                continue
            if c in "|&;<>)":
                break
            if c == SQ:
                j = self.s.find(SQ, self.i + 1)
                if j < 0:
                    self.fail("a single quote that is never closed", "close the quote")
                val.append(self.s[self.i + 1:j])
                bare.append("_")
                w.quoted = True
                self.i = j + 1
            elif c == DQ:
                self.i += 1
                val.append(self.read_dq())
                bare.append("_")
                w.quoted = True
            elif c == BSL:
                if self.i + 1 >= self.n:
                    val.append(BSL)
                    self.i += 1
                    continue
                d = self.s[self.i + 1]
                self.i += 2
                if d != "\n":
                    val.append(d)
                    bare.append("_")
                    w.quoted = True
            elif c == "$":
                val.append(self.read_dollar(False))
                bare.append("_")
            elif c == BTK:
                val.append(self.read_backtick(False))
                bare.append("_")
            else:
                if c in "*?[":
                    w.glob = True
                val.append(c)
                bare.append(c)
                self.i += 1
        w.end = self.i
        w.value = "".join(val)
        if BRACE_RE.search("".join(bare)):
            w.glob = True
        return w

    def read_array(self):
        self.i += 1
        while True:
            self.skip_ws()
            if self.i >= self.n:
                self.fail("an array assignment whose ( is never closed", "close the parenthesis")
            if self.s[self.i] == ")":
                self.i += 1
                return
            start = self.i
            self.read_word()
            if self.i == start:
                self.fail("an array assignment the guard cannot read", "assign the values one by one")

    def read_glob_group(self):
        start, depth = self.i, 0
        while self.i < self.n:
            c = self.s[self.i]
            if c == "(":
                depth += 1
            elif c == ")":
                depth -= 1
                if depth == 0:
                    self.i += 1
                    group = self.s[start:self.i]
                    if re.search(r"[^A-Za-z0-9_.|*?!@^~#,/:\[\]()=%-]", group) or \
                            ("|" not in group and re.search(r"[e+]", group)):
                        self.fail("a parenthesized glob the guard cannot read",
                                  "list the files without a glob qualifier or pattern group", start)
                    return
            elif c in BLANKS or c in "\n$;&<>" or c in (BTK, SQ, DQ, BSL):
                break
            self.i += 1
        self.fail("a ( the guard cannot read as a subshell or a glob",
                  "put the subshell at the start of a command", start)

    def read_dq(self):
        val = []
        while True:
            if self.i >= self.n:
                self.fail("a double quote that is never closed", "close the quote")
            c = self.s[self.i]
            if c == DQ:
                self.i += 1
                return "".join(val)
            if c == BSL and self.at(1) in ("$", BTK, DQ, BSL, "\n"):
                if self.at(1) != "\n":
                    val.append(self.at(1))
                self.i += 2
            elif c == "$":
                val.append(self.read_dollar(True))
            elif c == BTK:
                val.append(self.read_backtick(True))
            else:
                val.append(c)
                self.i += 1

    def read_dollar(self, in_dq):
        start, nxt = self.i, self.at(1)
        if nxt == "(":
            if self.at(2) == "(":
                mark, outlen = self.i, len(self.out)
                self.i += 3
                if self.try_arith():
                    return SENT
                self.i = mark
                del self.out[outlen:]
            self.i += 2
            self.parse_list(")")
            return SENT
        if nxt == "{":
            self.i += 2
            depth = 1
            while True:
                if self.i >= self.n:
                    self.fail("a parameter expansion that is never closed", "close the brace", start)
                c = self.s[self.i]
                if c == BSL:
                    self.i += 2
                elif c == SQ and not in_dq:
                    j = self.s.find(SQ, self.i + 1)
                    if j < 0:
                        self.fail("a single quote that is never closed", "close the quote")
                    self.i = j + 1
                elif c == DQ:
                    self.i += 1
                    self.read_dq()
                elif c == "$" and self.at(1) == "{":
                    depth += 1
                    self.i += 2
                elif c == "$":
                    self.read_dollar(in_dq)
                elif c == BTK:
                    self.read_backtick(in_dq)
                elif c == "}":
                    depth -= 1
                    self.i += 1
                    if depth == 0:
                        return SENT
                else:
                    self.i += 1
        if nxt == SQ and not in_dq:
            self.i += 2
            return self.read_ansi()
        if nxt == DQ and not in_dq:
            self.i += 2
            return self.read_dq()
        if nxt and (nxt.isalnum() or nxt == "_"):
            self.i += 2
            if not nxt.isdigit():
                while self.i < self.n and (self.s[self.i].isalnum() or self.s[self.i] == "_"):
                    self.i += 1
            return SENT
        if nxt and nxt in "@*#?-$!":
            self.i += 2
            return SENT
        self.i += 1
        return "$"

    def read_ansi(self):
        val = []
        simple = {"a": "\a", "b": "\b", "e": chr(27), "E": chr(27), "f": "\f", "n": "\n",
                  "r": "\r", "t": "\t", "v": "\v", BSL: BSL, SQ: SQ, DQ: DQ, "?": "?"}
        while True:
            if self.i >= self.n:
                self.fail("a $'\'' quote that is never closed", "close the quote")
            c = self.s[self.i]
            if c == SQ:
                self.i += 1
                return "".join(val)
            if c != BSL:
                val.append(c)
                self.i += 1
                continue
            d = self.at(1)
            if d in simple:
                val.append(simple[d])
                self.i += 2
                continue
            m = ANSI_RE.match(self.s, self.i + 1)
            if m:
                if m.group(5) is not None:
                    val.append(chr(ord(m.group(5)) & 31))
                elif m.group(4) is not None:
                    val.append(chr(int(m.group(4), 8) & 255))
                else:
                    val.append(chr(min(int(m.group(1) or m.group(2) or m.group(3), 16), 0x10FFFF)))
                self.i = m.end()
                continue
            val.append(BSL)
            self.i += 1

    def read_backtick(self, in_dq):
        start = self.i
        self.i += 1
        inner = []
        while True:
            if self.i >= self.n:
                self.fail("a backquote that is never closed", "close the backquote", start)
            c = self.s[self.i]
            if c == BTK:
                self.i += 1
                break
            if c == BSL and (self.at(1) in ("$", BTK, BSL) or (in_dq and self.at(1) == DQ)):
                inner.append(self.at(1))
                self.i += 2
                continue
            inner.append(c)
            self.i += 1
        Parser("".join(inner), self.depth + 1, self.out).parse_list(None)
        return SENT

    # Reads (( ... )) arithmetic up to its closing )); False when the text is
    # not arithmetic, and then the caller reads it as nested subshells.
    def try_arith(self):
        depth = 0
        try:
            while self.i < self.n:
                c = self.s[self.i]
                if c == "(":
                    depth += 1
                    self.i += 1
                elif c == ")":
                    if depth == 0:
                        if self.at(1) == ")":
                            self.i += 2
                            return True
                        return False
                    depth -= 1
                    self.i += 1
                elif c == "$":
                    self.read_dollar(False)
                elif c == BTK:
                    self.read_backtick(False)
                elif c == DQ:
                    self.i += 1
                    self.read_dq()
                elif c == SQ:
                    j = self.s.find(SQ, self.i + 1)
                    if j < 0:
                        return False
                    self.i = j + 1
                elif c == BSL:
                    self.i += 2
                else:
                    self.i += 1
        except Unparsed:
            return False
        return False

    def read_delim(self):
        val, quoted = [], False
        while self.i < self.n:
            c = self.s[self.i]
            if c in BLANKS or c in "\n|&;<>()":
                break
            if c in (SQ, DQ):
                j = self.s.find(c, self.i + 1)
                if j < 0:
                    self.fail("a quote that is never closed", "close the quote")
                val.append(self.s[self.i + 1:j])
                quoted, self.i = True, j + 1
            elif c == BSL:
                val.append(self.at(1))
                quoted = True
                self.i += 2
            else:
                val.append(c)
                self.i += 1
        if not "".join(val):
            self.fail("a here-document with no delimiter", "name the delimiter after <<")
        return "".join(val), quoted

    def read_heredocs(self):
        pending, self.pending = self.pending, []
        for delim, dash, quoted, owner in pending:
            start, body_end = self.i, self.n
            while self.i < self.n:
                j = self.s.find("\n", self.i)
                end = self.n if j < 0 else j
                line = self.s[self.i:end]
                nxt = self.n if j < 0 else j + 1
                if (line.lstrip("\t") if dash else line) == delim:
                    body_end = self.i
                    self.i = nxt
                    break
                self.i = nxt
            body = self.s[start:body_end]
            if not quoted:
                body = Parser(body, self.depth + 1, self.out).expand_body()
            owner.stdin.append(body)

    def expand_body(self):
        val = []
        while self.i < self.n:
            c = self.s[self.i]
            if c == BSL and self.at(1) in ("$", BTK, BSL, "\n"):
                if self.at(1) != "\n":
                    val.append(self.at(1))
                self.i += 2
            elif c == "$":
                val.append(self.read_dollar(True))
            elif c == BTK:
                val.append(self.read_backtick(True))
            else:
                val.append(c)
                self.i += 1
        return "".join(val)

    def finish(self, cmd):
        if cmd is not None and cmd.words:
            self.out.append(cmd)
        return None

    def parse_list(self, closer, case_item=False):
        self.nest += 1
        if self.nest > 48:
            self.fail("commands nested more deeply than the guard reads", "run the inner command on its own")
        try:
            return self.parse_list_body(closer, case_item)
        finally:
            self.nest -= 1

    def parse_list_body(self, closer, case_item):
        cmd, pipe_from = None, None
        while True:
            self.skip_blanks()
            if self.i >= self.n:
                self.finish(cmd)
                if self.pending:
                    self.read_heredocs()
                if closer:
                    self.fail("a ( or $( that is never closed", "close the parenthesis")
                return None
            c = self.s[self.i]
            if c == "\n":
                cmd, pipe_from = self.finish(cmd), None
                self.i += 1
                if self.pending:
                    self.read_heredocs()
                continue
            if c == "#" and (self.i == 0 or self.s[self.i - 1] in " \t\n;&|()"):
                self.skip_comment()
                continue
            if c == ")":
                if closer == ")":
                    self.finish(cmd)
                    self.i += 1
                    return None
                self.fail("a ) with no ( before it", "remove the stray parenthesis")
            if c in "|&;":
                op = next(o for o in (";;&", ";;", ";&", "||", "|&", "&&", "&>>", "&>", "|", "&", ";")
                          if self.s.startswith(o, self.i))
                if op in ("&>", "&>>"):
                    if cmd is None:
                        cmd = PC(self.s)
                        cmd.pipe_from = pipe_from
                    self.read_redirect(cmd, op)
                    continue
                if op in (";;", ";&", ";;&"):
                    if not case_item:
                        self.fail("a ;; outside a case statement", "remove the extra semicolon")
                    self.finish(cmd)
                    self.i += len(op)
                    return op
                prev = cmd
                cmd = self.finish(cmd)
                pipe_from = prev if op in ("|", "|&") else None
                self.i += len(op)
                continue
            if c in "<>" and self.at(1) != "(":
                if cmd is None:
                    cmd = PC(self.s)
                    cmd.pipe_from = pipe_from
                self.read_redirect(cmd, None)
                continue
            if c == "(" and cmd is not None and len(cmd.words) == 1 and not cmd.words[0].quoted and \
                    cmd.words[0].value == "time":
                cmd.words, cmd.start = [], None
            at_start = cmd is None or (not cmd.words and cmd.kind == "simple")
            if at_start and c == "(":
                if self.at(1) == "(":
                    mark, outlen = self.i, len(self.out)
                    self.i += 2
                    if self.try_arith():
                        cmd = PC(self.s)
                        cmd.kind = "compound"
                        continue
                    self.i = mark
                    del self.out[outlen:]
                self.i += 1
                self.parse_list(")")
                cmd = PC(self.s)
                cmd.kind = "compound"
                continue
            if at_start and case_item and self.word_here("esac"):
                self.finish(cmd)
                return "esac"
            if c == "(" and cmd is not None and len(cmd.words) == 1 and cmd.kind == "simple":
                j = self.i + 1
                while j < self.n and self.s[j] in BLANKS:
                    j += 1
                if j < self.n and self.s[j] == ")":
                    self.i = j + 1
                    cmd = PC(self.s)
                    continue
            start = self.i
            w = self.read_word(paren_ok=cmd is not None and bool(cmd.words))
            if self.i == start:
                self.fail("a character the guard cannot read here", "rewrite the command more simply")
            if not w.quoted and self.at() in ("<", ">") and self.at(1) != "(" and \
                    (w.value.isdigit() or re.match(r"\{[A-Za-z_][A-Za-z0-9_]*\}\Z", w.value)):
                continue
            if cmd is None or cmd.kind == "compound":
                cmd = PC(self.s)
                cmd.pipe_from = pipe_from
            if cmd.kind == "for":
                if not w.quoted and w.value == "do":
                    cmd = self.finish(cmd)
                continue
            if not cmd.words and not w.quoted:
                v = w.value
                if v in RESERVED_SKIP:
                    continue
                if v == "case":
                    self.parse_case()
                    cmd = PC(self.s)
                    cmd.kind = "compound"
                    continue
                if v in ("for", "select"):
                    self.skip_blanks()
                    if self.s.startswith("((", self.i):
                        self.i += 2
                        if not self.try_arith():
                            self.fail("a for (( )) loop the guard cannot read", "loop over a word list")
                    cmd.kind = "for"
                    continue
                if v == "[[":
                    self.parse_cond()
                    cmd = PC(self.s)
                    cmd.kind = "compound"
                    continue
                if v == "function":
                    self.skip_blanks()
                    self.read_word()
                    self.skip_blanks()
                    if self.s.startswith("()", self.i):
                        self.i += 2
                    continue
            if cmd.start is None:
                cmd.start = start
            cmd.words.append(w)
            cmd.end = self.i

    def read_redirect(self, cmd, op):
        if op is None:
            op = next(o for o in ("<<<", "<<-", "<<", ">>", ">|", "<&", ">&", "<>", "<", ">")
                      if self.s.startswith(o, self.i))
        if cmd.start is None:
            cmd.start = self.i
        self.i += len(op)
        self.skip_blanks()
        if op in ("<<", "<<-"):
            delim, quoted = self.read_delim()
            self.pending.append((delim, op == "<<-", quoted, cmd))
        else:
            if self.i >= self.n or self.s[self.i] in "\n|&;)":
                self.fail("a redirection with no target", "name the file after the redirection")
            w = self.read_word()
            if op == "<<<":
                cmd.stdin.append(w.value + "\n")
        cmd.end = self.i

    def parse_case(self):
        self.skip_ws()
        self.read_word()
        self.skip_ws()
        if not self.word_here("in"):
            self.fail("a case statement the guard cannot read", "write it as if statements")
        self.i += 2
        while True:
            self.skip_ws()
            if self.i >= self.n:
                self.fail("a case statement with no esac", "close it with esac")
            if self.word_here("esac"):
                self.i += 4
                return
            if self.s[self.i] == "(":
                self.i += 1
            while True:
                self.skip_blanks()
                if self.i >= self.n:
                    self.fail("a case pattern with no )", "close the pattern with )")
                c = self.s[self.i]
                if c == ")":
                    self.i += 1
                    break
                if c == "|":
                    self.i += 1
                    continue
                start = self.i
                self.read_word(paren_ok=True)
                if self.i == start:
                    self.fail("a case pattern the guard cannot read", "write it as if statements")
            end = self.parse_list(None, case_item=True)
            if end == "esac":
                self.i += 4
                return
            if end is None:
                self.fail("a case statement with no esac", "close it with esac")

    def parse_cond(self):
        while True:
            self.skip_ws()
            if self.i >= self.n:
                self.fail("a [[ test with no ]]", "close it with ]]")
            if self.word_here("]]"):
                self.i += 2
                return
            if self.s.startswith("&&", self.i) or self.s.startswith("||", self.i):
                self.i += 2
                continue
            if self.s[self.i] in "()!<>":
                self.i += 1
                continue
            start = self.i
            self.read_word(paren_ok=True)
            if self.i == start:
                self.fail("a [[ test the guard cannot read", "use [ ] or test")


def parse_all(text, depth):
    out = []
    Parser(text, depth, out).parse_list(None)
    return out


def shown(text):
    t = "".join(ch if 32 <= ord(ch) < 127 or ord(ch) > 159 else "?" for ch in text.replace(SENT, "$"))
    return t if len(t) <= 160 else t[:157] + "..."


SAFE_TEST = '\''check that a variable is set without printing its value, [ -n "$NAME" ] && echo set'\''
SET_LETTERS = {
    "x": "traces each later command with its variables expanded.",
    "v": "prints each later command line as the shell reads it.",
    "a": "exports every variable set after it to each program run.",
    "k": "turns NAME=value arguments into environment assignments.",
    "A": "with no name prints every array with its values.",
}
SET_SAFE = "set only with a literal option, set -e, set -u or set -o pipefail"


def refuse(cmd, what, safe):
    raise Refuse("Secretless: blocked a command that can print the environment, credentials included. Matched " +
                 BTK + shown(cmd.text()) + BTK + ": " + what + " Safe path: " + safe + ".")


def cmd_name(w):
    base = w.value.rsplit("/", 1)[-1]
    if base in ("[", "[["):
        return base
    if SENT in base or (w.glob and re.search(r"[*?\[{]", base)):
        return None
    if base.startswith("=") and not w.quoted:
        base = base[1:]
    return base.lower()


def opt_skip(args, k, with_arg, long_arg=()):
    while k < len(args):
        v = args[k].value
        if v == "--":
            return k + 1
        if not v.startswith("-") or v == "-" or SENT in v:
            return k
        if v.startswith("--"):
            k += 2 if ("=" not in v and v in long_arg) else 1
            continue
        step = 1
        for idx, ch in enumerate(v[1:]):
            if ch in with_arg:
                if idx == len(v) - 2:
                    step = 2
                break
        k += step
    return k


def word(value):
    return PW(0, value)


def strip_assign(words):
    k = 0
    while k < len(words) and ASSIGN_RE.match(words[k].value):
        k += 1
    return words[k:]


def unescape(t):
    table = {"n": "\n", "t": "\t", "r": "\r", BSL: BSL, "a": "\a", "b": "\b", "f": "\f", "v": "\v"}

    def one(m):
        g = m.group(1)
        if g[0] == "0" and len(g) > 1:
            return chr(int(g[1:], 8) & 255)
        if g[0] == "x" and len(g) > 1:
            return chr(int(g[1:], 16))
        return table.get(g, BSL + g)
    return re.sub(r"\\(0[0-7]{0,3}|x[0-9A-Fa-f]{1,2}|.)", one, t, flags=re.S)


def literal_out(prod):
    """What a cat of a here-document, or an echo or printf of literal words, writes; else None."""
    words = strip_assign(prod.words)
    if not words:
        return None
    name = cmd_name(words[0])
    args = [w.value for w in words[1:]]
    if name == "cat" and prod.stdin and all(a.startswith("-") for a in args):
        return prod.stdin[-1]
    if name == "echo":
        while args and re.match(r"-[neE]+\Z", args[0]):
            args = args[1:]
        return unescape(" ".join(args)) + "\n"
    if name == "printf" and args:
        fmt, rest, out = unescape(args[0]), args[1:], []
        for _ in range(64):
            used = False
            for p in re.split(r"(%%|%[-+ #0-9.]*[a-zA-Z])", fmt):
                if p == "%%":
                    out.append("%")
                elif p.startswith("%") and len(p) > 1:
                    used = True
                    out.append(unescape(rest.pop(0)) if rest else "")
                else:
                    out.append(p)
            if not rest or not used:
                break
        return "".join(out)
    return None


def stdin_text(cmd):
    """The text a command reads on its input when the command line shows it, else None."""
    if cmd.stdin:
        return cmd.stdin[-1]
    if cmd.pipe_from is not None:
        return literal_out(cmd.pipe_from)
    return None


def judge_text(cmd, text, depth, what):
    if SENT in text:
        refuse(cmd, what + " carries an expansion, so the guard cannot read the commands it runs.",
               "pass values as arguments, bash -c " + SQ + '\''cmd "$1"'\'' + SQ + '\'' _ "$VALUE"'\'')
    for sub in parse_all(text, depth + 1):
        sub.display = cmd.text()
        judge(sub, sub.words, depth + 1)


SHELLS = {"bash", "sh", "zsh", "dash", "ksh", "mksh", "ash", "yash", "posh"}
DECLARE = {"export", "readonly", "declare", "typeset", "local"}
TRACE_NAMES = ("xtrace", "verbose", "allexport", "keyword")


def judge(cmd, words, depth):
    words = strip_assign(words)
    if not words or cmd.kind != "simple":
        return
    name = cmd_name(words[0])
    if name is None:
        refuse(cmd, "the program name comes from an expansion, so the guard cannot tell which program runs.",
               "name the program literally")
    args = words[1:]
    if name in ("sudo", "doas"):
        k = opt_skip(args, 0, "ugCDhprtTUc", ("--user", "--group", "--prompt", "--chdir", "--host", "--role",
                                               "--type", "--other-user", "--close-from", "--command-timeout"))
        if any(re.match(r"-[A-Za-z]*[elvkKV]", a.value) or a.value in ("--edit", "--list", "--validate")
               for a in args[:k]):
            return
        return judge(cmd, args[k:], depth)
    if name in ("nohup", "builtin", "noglob", "nocorrect", "busybox", "unbuffer", "chronic"):
        return judge(cmd, args, depth)
    if name in ("stdbuf", "setsid", "caffeinate", "ionice"):
        return judge(cmd, args[opt_skip(args, 0, {"stdbuf": "ioe", "caffeinate": "tw", "ionice": "cnp"}.get(name, ""),
                                        ("--input", "--output", "--error", "--class", "--classdata")):], depth)
    if name == "su":
        k = 0
        while k < len(args):
            v = args[k].value
            if v in ("-c", "--command"):
                if k + 1 < len(args):
                    judge_text(cmd, args[k + 1].value, depth, "the string su -c runs")
                return
            if v.startswith("--command="):
                return judge_text(cmd, v.split("=", 1)[1], depth, "the string su -c runs")
            k += 2 if v in ("-s", "--shell", "-g", "--group") else 1
        return
    if name == "alias":
        for a in args:
            if "=" in a.value and not a.value.startswith("-"):
                judge_text(cmd, a.value.split("=", 1)[1], depth, "the alias body")
        return
    if name == "trap":
        k = opt_skip(args, 0, "")
        if k < len(args) and args[k].value not in ("-", "") and len(args) > k + 1:
            judge_text(cmd, args[k].value, depth, "the trap action")
        return
    if name == "command":
        k = opt_skip(args, 0, "")
        if any(re.match(r"-[a-zA-Z]*[vV]", a.value) for a in args[:k]):
            return
        return judge(cmd, args[k:], depth)
    if name == "exec":
        return judge(cmd, args[opt_skip(args, 0, "a"):], depth)
    if name == "nice":
        return judge(cmd, args[opt_skip(args, 0, "n", ("--adjustment",)):], depth)
    if name == "time":
        return judge(cmd, args[opt_skip(args, 0, "fo", ("--format", "--output")):], depth)
    if name == "timeout":
        return judge(cmd, args[opt_skip(args, 0, "sk", ("--signal", "--kill-after")) + 1:], depth)
    if name == "xargs":
        k = opt_skip(args, 0, "IadELnPsRSJ", ("--arg-file", "--delimiter", "--eof", "--max-lines", "--max-args",
                                              "--max-procs", "--max-chars", "--process-slot-var"))
        return judge(cmd, args[k:], depth)
    if name == "watch":
        k = opt_skip(args, 0, "n", ("--interval",))
        if any(re.match(r"-[a-wyz]*x", a.value) or a.value == "--exec" for a in args[:k]):
            return judge(cmd, args[k:], depth)
        if k < len(args):
            judge_text(cmd, " ".join(a.value for a in args[k:]), depth, "the command watch runs")
        return
    if name == "find":
        k = 0
        while k < len(args):
            if args[k].value in ("-exec", "-execdir", "-ok", "-okdir"):
                j = k + 1
                while j < len(args) and args[j].value not in (";", "+"):
                    j += 1
                judge(cmd, args[k + 1:j], depth)
                k = j
            k += 1
        return
    if name == "env":
        return judge_env(cmd, args, depth)
    if name in SHELLS:
        return judge_shell(cmd, name, args, depth)
    if name == "eval":
        if args:
            judge_text(cmd, " ".join(a.value for a in args), depth, "the text eval runs")
        return
    if name in ("source", "."):
        if args and (SENT in args[0].value or args[0].value in ("/dev/stdin", "/dev/fd/0")):
            text = None if SENT in args[0].value else stdin_text(cmd)
            if text is None:
                refuse(cmd, "it runs shell code the guard cannot read before it runs.", "run the commands directly")
            judge_text(cmd, text, depth, "the text source runs")
        return
    if name == "set":
        return judge_set(cmd, args)
    if name in ("setopt", "unsetopt"):
        for a in args:
            n = a.value.lower().replace("_", "")
            if SENT in n or n in TRACE_NAMES or (n.startswith("no") and n[2:] in TRACE_NAMES):
                refuse(cmd, name + " " + a.value + " can turn on tracing or export every variable in zsh.",
                       "leave tracing off; setopt pipefail and setopt errexit are allowed")
        return
    if name == "printenv":
        refuse(cmd, "printenv prints the whole environment, or the value of each variable it names.", SAFE_TEST)
    if name == "compgen":
        refuse(cmd, "compgen lists shell variables, functions and names.", SAFE_TEST)
    if name in DECLARE:
        return judge_declare(cmd, name, args)
    fam = interp_family(name)
    if fam:
        return judge_interp(cmd, fam, args)
    if name in ("docker", "podman"):
        return judge_docker(cmd, args, depth)
    if name in ("docker-compose", "podman-compose"):
        return judge_compose(cmd, args, depth)
    if name == "kubectl":
        return judge_kubectl(cmd, args, depth)
    if name == "tmux":
        if any(a.value == "showenv" or a.value.startswith("show-e") for a in args):
            refuse(cmd, "tmux show-environment prints the environment of the tmux server or session.", SAFE_TEST)
        return
    if name == "launchctl":
        if args and args[0].value in ("getenv", "print", "export"):
            refuse(cmd, "launchctl " + args[0].value + " prints environment values.", SAFE_TEST)
        return
    if name == "systemctl":
        if any(a.value == "show-environment" for a in args):
            refuse(cmd, "systemctl show-environment prints the service manager environment.", SAFE_TEST)
        return
    if name == "npm":
        k = opt_skip(args, 0, "")
        if k < len(args) and args[k].value in ("run", "run-script", "rum", "urn"):
            j = opt_skip(args, k + 1, "")
            if j < len(args) and args[j].value == "env":
                refuse(cmd, "npm run env prints the whole environment npm gives a script.", SAFE_TEST)


def judge_env(cmd, args, depth):
    k = 0
    while k < len(args):
        v = args[k].value
        if SENT in v:
            break
        if v == "--":
            k += 1
            break
        if re.match(r"-[iv0]+\Z", v) or v in ("-", "--ignore-environment", "--null", "--debug"):
            k += 1
        elif v in ("-u", "--unset", "-C", "--chdir", "-P"):
            k += 2
        elif re.match(r"-[iv0]*[uCP].|--unset=|--chdir=", v):
            k += 1
        elif re.match(r"-[iv0]*S|--split-string", v):
            if v == "--split-string" or v.endswith("S"):
                text, rest = (args[k + 1].value if k + 1 < len(args) else ""), args[k + 2:]
            else:
                text, rest = (v.split("=", 1)[1] if v.startswith("--") else v[v.index("S") + 1:]), args[k + 1:]
            if SENT in text:
                refuse(cmd, "the string env -S splits carries an expansion.", "write the program after env literally")
            return judge_env(cmd, [word(t) for t in text.split()] + list(rest), depth)
        elif v.startswith(("--block-signal", "--default-signal", "--ignore-signal", "--list-signal-handling")):
            k += 1
        elif v.startswith("-"):
            refuse(cmd, "env has an option the guard does not know, so it cannot tell whether a program follows.",
                   "use env -u NAME or env NAME=value before the program it runs")
        else:
            break
    while k < len(args) and ASSIGN_RE.match(args[k].value):
        k += 1
    if k >= len(args):
        refuse(cmd, "env with no program after its options and assignments prints the whole environment.",
               "use env only as a prefix that runs a program (env -u NAME cmd), or " + SAFE_TEST)
    judge(cmd, args[k:], depth)


def judge_shell(cmd, name, args, depth):
    k, code_flag, reads_stdin = 0, False, False
    while k < len(args):
        v = args[k].value
        if SENT in v:
            break
        if v in ("--", "-"):
            k += 1
            break
        if v in ("--rcfile", "--init-file"):
            k += 2
            continue
        if v in ("--verbose", "--debugger"):
            refuse(cmd, name + " " + v + " prints the commands it runs.", "run the shell without it")
        if v.startswith("--"):
            k += 1
            continue
        if not CLUSTER_RE.match(v):
            break
        if v[0] == "-" and ("x" in v or "v" in v):
            refuse(cmd, name + " " + v + " traces each command with its variables expanded.",
                   "run the shell without -x or -v")
        k += 1
        if "o" in v[1:] or "O" in v[1:]:
            if k < len(args) and args[k].value.lower().replace("_", "") in TRACE_NAMES:
                refuse(cmd, name + " -o " + args[k].value + " traces commands or exports every variable.",
                       "run the shell without that option")
            k += 1
        code_flag = code_flag or "c" in v[1:]
        reads_stdin = reads_stdin or "s" in v[1:]
    if code_flag:
        if k < len(args):
            judge_text(cmd, args[k].value, depth, "the string " + name + " -c runs")
        return
    if k < len(args) and not reads_stdin:
        return
    text = stdin_text(cmd)
    if text is not None:
        judge_text(cmd, text, depth, "the text " + name + " reads on its input")


def judge_set(cmd, args):
    if not args:
        refuse(cmd, "a bare set prints every shell variable.", SET_SAFE)
    first = lit(args[0])
    if first is None or not CLUSTER_RE.match(first):
        refuse(cmd, "set prints every variable unless its first word is a literal option such as -e, and a word "
                    "that is an expansion may expand to nothing.", SET_SAFE)
    want_name = False
    for w in args:
        v = lit(w)
        if v is None:
            refuse(cmd, "a set word that is an expansion may turn on tracing.", "write every set option literally")
        if want_name:
            n = v.lower().replace("_", "")
            if n in TRACE_NAMES or (n.startswith("no") and n[2:] in TRACE_NAMES):
                refuse(cmd, "set -o " + v + " traces commands with their variables expanded, or exports every "
                            "variable.", SET_SAFE)
            want_name = False
            continue
        if v == "--":
            break
        if CLUSTER_RE.match(v):
            bad = [ch for ch in v[1:] if ch in SET_LETTERS]
            if bad:
                refuse(cmd, "set " + v[0] + bad[0] + " " + SET_LETTERS[bad[0]], SET_SAFE)
            want_name = "o" in v[1:]
            continue
        if v[:1] in ("-", "+"):
            refuse(cmd, "set " + v + " is not an option the guard reads.", SET_SAFE)
        break
    if want_name:
        refuse(cmd, "set -o with no option name prints every shell option.", SET_SAFE)


def judge_declare(cmd, name, args):
    names, opts, after = 0, "", False
    for w in args:
        v = w.value
        if SENT in v.split("=", 1)[0]:
            refuse(cmd, name + " has an argument that is an expansion, which may be an option that prints "
                               "variables.", "write each name literally, " + name + " NAME=value")
        if not after and v == "--":
            after = True
            continue
        if not after and v[:1] in ("-", "+"):
            if re.search(r"[pfFm]", v[1:]):
                refuse(cmd, name + " " + v + " prints variables or functions with their values.", SAFE_TEST)
            opts += v[1:] or v
            continue
        if ASSIGN_RE.match(v):
            names += 1
            continue
        if NAME_RE.match(v):
            if name in ("declare", "typeset", "local") and not opts:
                refuse(cmd, name + " " + v + " with no option prints the variable with its value in zsh when it is "
                                            "already set.", "assign it, " + name + " " + v + "=value; to check it, " +
                       SAFE_TEST)
            names += 1
            continue
        refuse(cmd, name + " has an argument that is neither NAME=value nor NAME.", "write each name literally")
    if names == 0:
        refuse(cmd, "a bare " + name + " lists variables with their values.",
               "assign one, " + name + " NAME=value; to check a variable, " + SAFE_TEST)


PY_WHOLE = [re.compile(r"\benvironb?\b(?!\s*\[)(?!\s*\.\s*get\s*\()")]
JS_TAIL = r"(?!\s*(\?\.|\.)\s*[A-Za-z_$])(?!\s*(\?\.)?\s*\[)"
JS_WHOLE = [re.compile(r"\bprocess\s*(\?\.|\.)\s*env\b" + JS_TAIL),
            re.compile(r"\bprocess\s*(\?\.)?\s*\[\s*[" + SQ + DQ + BTK + r"]env[" + SQ + DQ + BTK + r"]\s*\]" + JS_TAIL),
            re.compile(r"\brequire\s*\(\s*[" + SQ + DQ + BTK + r"](node:)?process[" + SQ + DQ + BTK +
                       r"]\s*\)\s*(\?\.|\.)\s*env\b" + JS_TAIL),
            re.compile(r"\bDeno\s*\.\s*env\s*\.\s*toObject\b"),
            re.compile(r"\bBun\s*\.\s*env\b" + JS_TAIL)]
WHOLE_ENV = {
    "python": PY_WHOLE, "node": JS_WHOLE, "bun": JS_WHOLE, "deno": JS_WHOLE,
    "ruby": [re.compile(r"\bENV\b(?!\s*\[)(?!\s*\.\s*fetch\b)")],
    "perl": [re.compile(r"%(main)?(::)?ENV\b")],
    "php": [re.compile(r"\bgetenv\s*\(\s*\)"), re.compile(r"\$_(ENV|SERVER)\b(?!\s*\[)")],
    "awk": [re.compile(r"\bENVIRON\b(?!\s*\[)")],
    "jq": [re.compile(r"(^|[^.\w$" + SQ + DQ + r"])env\b(?!\s*[." + SQ + DQ + r"])"),
           re.compile(r"\$ENV\b(?!\s*[.\[])")],
}


def interp_family(name):
    if re.match(r"(python|pypy)(\d+(\.\d+)*)?\Z", name):
        return "python"
    if name in ("node", "nodejs"):
        return "node"
    if name in ("awk", "gawk", "mawk", "nawk"):
        return "awk"
    return name if name in ("bun", "deno", "ruby", "perl", "php", "jq") else None


def cluster_codes(args, k, spec):
    """Read the option cluster at args[k]: (program texts it names, next index)."""
    code_flags, attached, separate, digits = spec
    body, i = args[k].value[1:], 0
    while i < len(body):
        ch, rest = body[i], body[i + 1:]
        if ch in code_flags:
            if rest:
                return [rest], k + 1
            return ([args[k + 1].value] if k + 1 < len(args) else []), k + 2
        if ch in separate:
            return [], (k + 1 if rest else k + 2)
        if ch in attached:
            return [], k + 1
        i += 1
        if ch in digits:
            while i < len(body) and body[i].isdigit():
                i += 1
    return [], k + 1


def program_texts(fam, args, cmd):
    """The program texts an interpreter call runs; None when it runs a file the guard does not read."""
    codes, k = [], 0
    if fam == "deno":
        while k < len(args) and args[k].value.startswith("-"):
            k += 1
        if k >= len(args) or args[k].value != "eval":
            return None
        k = opt_skip(args, k + 1, "", ("--ext",))
        return [args[k].value] if k < len(args) else None
    if fam in ("awk", "jq"):
        while k < len(args):
            v = args[k].value
            if v == "--":
                k += 1
                break
            if SENT in v or not v.startswith("-") or v == "-":
                break
            if fam == "jq" and v in ("--arg", "--argjson", "--slurpfile", "--rawfile"):
                k += 3
            elif fam == "awk" and v in ("-e", "--source"):
                codes.append(args[k + 1].value if k + 1 < len(args) else "")
                k += 2
            elif fam == "awk" and v.startswith("--source="):
                codes.append(v.split("=", 1)[1])
                k += 1
            elif v in ("-f", "--file", "--from-file") or v.startswith(("--file=", "--from-file=")):
                return codes or None
            elif v in ("-F", "-v", "--field-separator", "--assign", "--indent", "-L"):
                k += 2
            else:
                k += 1
        if k < len(args):
            codes.append(args[k].value)
        return codes or None
    spec = {"python": ("c", "", "WX", ""), "node": ("ep", "", "r", ""), "bun": ("ep", "", "r", ""),
            "ruby": ("e", "xTWK", "rICEF", "0"), "perl": ("eE", "MmdDCxi", "I", "l0"),
            "php": ("rRBE", "", "dcz", "")}[fam]
    while k < len(args):
        v = args[k].value
        if SENT in v or not v.startswith("-"):
            break
        if v == "--":
            k += 1
            break
        if v == "-":
            t = stdin_text(cmd)
            return [t] if t is not None else None
        if fam == "python" and re.match(r"-[A-Za-z]*m", v) and "c" not in v.split("m")[0]:
            return codes or None
        if fam == "php" and v == "-f":
            return codes or None
        if v.startswith("--"):
            name, eq, val = v.partition("=")
            if fam in ("node", "bun") and name in ("--eval", "--print"):
                if eq:
                    codes.append(val)
                    k += 1
                else:
                    codes.append(args[k + 1].value if k + 1 < len(args) else "")
                    k += 2
                continue
            k += 2 if (fam in ("node", "bun") and not eq and name in ("--require", "--import", "--loader",
                                                                       "--experimental-loader")) else 1
            continue
        if fam in ("node", "bun") and re.match(r"-[ep]+\Z", v):
            codes.append(args[k + 1].value if k + 1 < len(args) else "")
            k += 2
            continue
        found, k = cluster_codes(args, k, spec)
        codes.extend(found)
        if found and fam == "python":
            return codes
    if codes:
        return codes
    if k >= len(args):
        t = stdin_text(cmd)
        return [t] if t is not None else None
    return None


def judge_interp(cmd, fam, args):
    codes = program_texts(fam, args, cmd)
    if not codes:
        return
    text = "\n".join(codes)
    if SENT in text and not text.replace(SENT, "").strip():
        refuse(cmd, "the program text comes from an expansion, so the guard cannot read it.",
               "write the program text literally")
    for p in WHOLE_ENV[fam]:
        m = p.search(text)
        if m:
            raise Refuse("Secretless: blocked script command that reads environment variables. Matched " + BTK +
                         shown(cmd.text()) + BTK + ": a " + fam + " program that names the whole environment (" +
                         shown(m.group(0).strip()) + "), so what it prints can hold every variable, credentials "
                         "included. Safe path: read one variable that holds no secret by name (os.environ.get(" +
                         DQ + "NAME" + DQ + "), process.env.NAME), or " + SAFE_TEST + ".")


RUN_FLAGS = set("ditPT")
RUN_LONG_FLAGS = {"--rm", "--init", "--privileged", "--read-only", "--tty", "--interactive", "--detach",
                  "--publish-all", "--sig-proxy", "--no-healthcheck", "--oom-kill-disable", "--no-deps",
                  "--service-ports", "--use-aliases", "--build", "--quiet-pull", "--no-TTY", "--remove-orphans"}


def skip_run_opts(args, k):
    while k < len(args):
        v = args[k].value
        if v == "--":
            return k + 1
        if not v.startswith("-") or SENT in v:
            return k
        if v.startswith("--"):
            k += 1 if ("=" in v or v in RUN_LONG_FLAGS) else 2
        else:
            k += 1 if all(ch in RUN_FLAGS for ch in v[1:]) else 2
    return k


def judge_docker(cmd, args, depth):
    k = opt_skip(args, 0, "Hcl", ("--host", "--context", "--config", "--log-level", "--tlscacert", "--tlscert",
                                  "--tlskey"))
    if k >= len(args):
        return
    sub = args[k].value
    if sub in ("container", "image", "service") and k + 1 < len(args):
        k, sub = k + 1, args[k + 1].value
    if sub == "compose":
        return judge_compose(cmd, args[k + 1:], depth)
    if sub in ("exec", "run", "create"):
        return judge(cmd, args[skip_run_opts(args, k + 1) + 1:], depth)
    if sub != "inspect":
        return
    rest, fmt, j = args[k + 1:], None, 0
    while j < len(rest):
        v = rest[j].value
        if v in ("-f", "--format"):
            fmt = rest[j + 1].value if j + 1 < len(rest) else ""
            j += 2
            continue
        if v.startswith("--format="):
            fmt = v.split("=", 1)[1]
        elif v.startswith("-f") and not v.startswith("--"):
            fmt = v[2:]
        j += 1
    if fmt is None:
        refuse(cmd, "docker inspect with no --format prints the whole configuration, Env included.",
               "name the fields you need, docker inspect --format " + SQ + "{{.State.Status}}" + SQ + " NAME")
    if SENT in fmt or re.search(r"env", fmt, re.I) or \
            re.search(r"(^|[^A-Za-z0-9_.])\.(Config|ContainerConfig|Spec|TaskTemplate|ContainerSpec)?(?![A-Za-z0-9_.])", fmt):
        refuse(cmd, "the docker inspect template names the Env field or a field that holds it.",
               "name fields that hold no environment, --format " + SQ + "{{.State.Status}}" + SQ)


def judge_compose(cmd, args, depth):
    k = opt_skip(args, 0, "fp", ("--file", "--project-name", "--project-directory", "--env-file", "--profile",
                                 "--ansi", "--progress", "--parallel"))
    if k < len(args) and args[k].value in ("exec", "run"):
        judge(cmd, args[skip_run_opts(args, k + 1) + 1:], depth)


def judge_kubectl(cmd, args, depth):
    vals = [a.value for a in args]
    if "exec" not in vals:
        return
    k = vals.index("exec")
    if "--" in vals[k:]:
        return judge(cmd, args[vals.index("--", k) + 1:], depth)
    j = k + 1
    while j < len(args) and vals[j].startswith("-"):
        j += 1 if ("=" in vals[j] or re.match(r"-[itq]+\Z", vals[j]) or
                   vals[j] in ("--stdin", "--tty", "--quiet")) else 2
    judge(cmd, args[j + 1:], depth)


def env_print_verdict(text):
    """A deny reason when the command can print the environment or cannot be parsed, else None."""
    try:
        for c in parse_all(text, 0):
            judge(c, c.words, 0)
    except Refuse as r:
        return r.reason
    except Unparsed as u:
        return ("Secretless: blocked a command the guard cannot parse. Unparsed at " + BTK +
                shown(u.src[u.pos:u.pos + 60]) + BTK + ": " + u.why + ". A command the guard cannot read may print "
                "the environment, so it is refused. Safe path: " + u.fix + ", or split it into simpler commands.")
    except RecursionError:
        return ("Secretless: blocked a command the guard cannot parse: it nests more deeply than the guard reads. "
                "Safe path: split it into simpler commands.")
    return None


# The first line of output is the verdict: ENV-PRINT: and a JSON string, the
# deny reason; OK: and the reduced command; or PASS: when the command prints no
# environment and nothing in it can be reduced.
def main():
    try:
        cmd = sys.stdin.buffer.read().decode("utf-8")
    except Exception:
        sys.stdout.write("ENV-PRINT:" + json.dumps("Secretless: blocked a command that is not UTF-8 text, which "
                                                   "the guard cannot parse. Safe path: write the command in UTF-8."))
        return
    try:
        verdict = env_print_verdict(cmd)
    except Exception:
        verdict = ("Secretless: blocked a command the guard failed to parse. A command the guard cannot read may "
                   "print the environment, so it is refused. Safe path: split it into simpler commands.")
    if verdict:
        sys.stdout.write("ENV-PRINT:" + json.dumps(verdict))
        return
    try:
        spans = sorted(reducible_spans(cmd))
    except Exception:
        sys.stdout.write("PASS:")
        return
    out, last = [], 0
    for start, end, repl in spans:
        out.append(cmd[last:start])
        out.append(repl)
        last = end
    out.append(cmd[last:])
    sys.stdout.buffer.write(("OK:" + "".join(out)).encode("utf-8"))


main()

'
    REDUCED=$(printf '%s' "$COMMAND" | python3 -I -c "$GUARD_ANALYZER" 2>/dev/null || true)
    case "$REDUCED" in
      ENV-PRINT:*)
        printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":%s}}\n' "${REDUCED#ENV-PRINT:}"
        exit 0
        ;;
      OK:*) ENV_VERDICT=parsed; SCAN_TEXT="${REDUCED#OK:}" ;;
      PASS:*) ENV_VERDICT=parsed ;;
    esac
  fi
  # Block commands that dump secret files (expanded to cover grep, awk, sed, strings, xxd).
  # A match is refused only when it survives all three exemptions above: the
  # accessor rewrite, the analyzer's reduction and the inert-write scan each
  # remove only text that names no file the command opens, so a match any one
  # of them removes was never a file read. The reason quotes the match in the
  # command as written, not in the analyzer's reduced text.
  #
  # The reader-verb pattern is the slow part of this rule: over one line of a
  # few MB, macOS grep takes seconds per pass, while a grep for the secret-file
  # name alone takes a small part of that. secret_read_lines prints the lines of
  # $1 this rule matches. Its first grep keeps the lines that name a secret
  # file, which every line the rule matches does, so the reader verb is matched
  # on those lines only, and the reason is quoted from them. A text the same as
  # one already matched is not matched again. Neither grep takes -q: each reads
  # its input to the end, so echo is never cut off by a grep that stopped early.
  # With grep -q, a long command whose secret read came on an early line was
  # admitted: grep matched and exited, echo was killed writing the rest, and
  # under pipefail the test failed.
  secret_read_lines() {
    echo "$1" | grep -iE '\.(env|key|pem|p12|pfx|crt)([^A-Za-z0-9}]|[}]([^}]|$)|$)' \
      | grep -iE '(^|[^A-Za-z0-9_.-]|\\[nt])((g|gz|z|bz|xz|lz4?|zstd)?(cat|less|more|[acefhrsuv]?grep)|(pcre2?|zip|pdf)grep|(lol|c|md|so|net)cat|(md|j)less|(g|multi|color|log|x)?tail|g?head|[gmn]?awk|g?sed|g?strings|xxd|type)(\s|\\+t)+.*\.(env|key|pem|p12|pfx|crt)([^A-Za-z0-9}]|[}]([^}]|$)|$)' || true
  }
  FILE_READ_MATCH=$(secret_read_lines "$FILE_READ_SCAN")
  if [ -n "$FILE_READ_MATCH" ] \
    && { [ "$FILE_READ_COMMAND" = "$FILE_READ_SCAN" ] || [ -n "$(secret_read_lines "$FILE_READ_COMMAND")" ]; } \
    && { [ "$SCAN_TEXT" = "$FILE_READ_SCAN" ] || [ "$SCAN_TEXT" = "$FILE_READ_COMMAND" ] \
      || [ -n "$(secret_read_lines "$SCAN_TEXT")" ]; }; then
    printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked command that reads secret files. Matched `%s`: a reader verb, then a secret-file name. This guard matches command text and cannot tell a filename from a search pattern, so a committed template (like .env.example) or a pattern that merely contains a secret-file token is blocked too. Safe path: open committed template files with the Read tool and search with the Grep tool instead of Bash. To write a note that names a secret file, use cat > FILE with a single-quoted heredoc delimiter, or printf or echo of single-quoted text into a file."}}\n' \
      "$(matched_text '(^|[^A-Za-z0-9_.-]|\\[nt])' '((g|gz|z|bz|xz|lz4?|zstd)?(cat|less|more|[acefhrsuv]?grep)|(pcre2?|zip|pdf)grep|(lol|c|md|so|net)cat|(md|j)less|(g|multi|color|log|x)?tail|g?head|[gmn]?awk|g?sed|g?strings|xxd|type)(\s|\\+t)+.*\.(env|key|pem|p12|pfx|crt)([^A-Za-z0-9}]|[}]([^}]|$)|$)' "$FILE_READ_MATCH")"
    exit 0
  fi
  # Block python/node one-liners that read secret files. Same dead-end as the arm
  # above had: a one-liner that only COMPILES a regex naming a secret-file token
  # (node -e with new RegExp, python3 -c with re.compile) opens nothing and is
  # refused all the same, because this is a denylist over command TEXT. The
  # decision has to stand — see NOTE ON TEMPLATE FILES — so the reason carries the
  # ambiguity and the route out.
  if echo "$SCAN_TEXT" | grep -qiE '(python3?|node)(\s|\\+t)+-(c|e).*\.(env|key|pem|p12|pfx|crt)([^A-Za-z0-9}]|[}]([^}]|$)|$)' \
    && echo "$FILE_READ_SCAN" | grep -qiE '(python3?|node)(\s|\\+t)+-(c|e).*\.(env|key|pem|p12|pfx|crt)([^A-Za-z0-9}]|[}]([^}]|$)|$)'; then
    # Node names the environment process.env, which ends in `.env`, so a
    # one-liner reading a variable was refused here as a secret-file read, and
    # `node -e` reading GITHUB_TOKEN was told it named a secret file. The
    # decision stands, since process.env holds every variable; the reason names
    # what matched. With each process.env set aside, a secret-file name still
    # left is a file; otherwise the one-liner reads the environment. If sed is
    # missing, nothing matches and an environment reason is given: still a deny.
    #
    # When the analyzer parsed the command (NOTE ON ENVIRONMENT PRINTS), it has
    # already refused a one-liner that names the whole environment, so a
    # process.env read here that names a property in every place, such as
    # process.env.HOME, is let through. A process.env with no property after it
    # is still refused here, which also covers one the analyzer did not reach
    # (a one-liner inside an ssh argument). Without python3 the deny stands.
    if echo "$FILE_READ_SCAN" | sed -E 's/process(\??)\.env/process\1_env/g' \
      | grep -qiE '(python3?|node)(\s|\\+t)+-(c|e).*\.(env|key|pem|p12|pfx|crt)([^A-Za-z0-9}]|[}]([^}]|$)|$)'; then
      printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked script command that reads secret files. Matched `%s`: a python or node one-liner that names a secret file. This guard matches command text and cannot tell a filename from a search pattern, so a one-liner that merely names a secret-file token inside a regex is blocked too. Safe path: open committed template files with the Read tool and search with the Grep tool instead of Bash."}}\n' \
        "$(matched_text '' '(python3?|node)(\s|\\+t)+-(c|e).*\.(env|key|pem|p12|pfx|crt)([^A-Za-z0-9}]|[}]([^}]|$)|$)' "$FILE_READ_SCAN")"
      exit 0
    elif echo "$FILE_READ_SCAN" | grep -qiE '(python3?|node)(\s|\\+t)+-(c|e).*(os\.environ|process\.env).*(SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_KEY|TOKEN|PRIVATE_KEY|VAULT|CREDENTIAL|DATABASE_URL|CONNECTION_STRING)'; then
      printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked script command that reads secret environment variables. Matched `%s`: a python or node one-liner that reads os.environ or process.env and names a secret variable. What the one-liner prints reaches this conversation. Safe path: pass the variable by name to the command that needs it, without printing it."}}\n' \
        "$(matched_text '' '(python3?|node)(\s|\\+t)+-(c|e).*(os\.environ|process\.env).*(SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_KEY|TOKEN|PRIVATE_KEY|VAULT|CREDENTIAL|DATABASE_URL|CONNECTION_STRING)' "$FILE_READ_SCAN")"
      exit 0
    elif [ -z "$ENV_VERDICT" ] || text_matches -E 'process\??\.env([^.?A-Za-z0-9_$[]|$)' "$FILE_READ_SCAN"; then
      printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked script command that reads environment variables. Matched `%s`: a python or node one-liner that names process.env, the Node environment, which holds every variable, credentials included. This guard cannot tell which variable this one-liner reads or whether it prints them all, so a variable that holds no secret is blocked too. Safe path: read one variable that holds no secret by property name, process.env.NAME, in a one-liner run directly by node; to check a secret, test it with the shell test -n instead of printing it."}}\n' \
        "$(matched_text '' '(python3?|node)(\s|\\+t)+-(c|e).*process\??\.env' "$FILE_READ_SCAN")"
      exit 0
    fi
  fi
  # Block python/node one-liners that read env vars containing secrets
  if echo "$SCAN_TEXT" | grep -qiE '(python3?|node)(\s|\\+t)+-(c|e).*(os\.environ|process\.env).*(SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_KEY|TOKEN|PRIVATE_KEY|VAULT|CREDENTIAL|DATABASE_URL|CONNECTION_STRING)'; then
    printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked script command that reads secret environment variables. Matched `%s`: a python or node one-liner that reads os.environ or process.env and names a secret variable. What the one-liner prints reaches this conversation. Safe path: pass the variable by name to the command that needs it, without printing it."}}\n' \
      "$(matched_text '' '(python3?|node)(\s|\\+t)+-(c|e).*(os\.environ|process\.env).*(SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_KEY|TOKEN|PRIVATE_KEY|VAULT|CREDENTIAL|DATABASE_URL|CONNECTION_STRING)' "$SCAN_TEXT")"
    exit 0
  fi
  # Block eval-based env var extraction
  if echo "$SCAN_TEXT" | grep -qiE '(eval(\s|\\+t)+echo|\$\{!).*\$\{?[A-Za-z0-9_]*(SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_KEY|TOKEN|PRIVATE_KEY|VAULT|CREDENTIAL|DATABASE_URL|CONNECTION_STRING)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked eval-based secret extraction"}}'
    exit 0
  fi
  # Block commands that echo secret env vars. The variable name may carry any
  # prefix: $ANTHROPIC_API_KEY and ${GITHUB_TOKEN} count, not just $API_KEY.
  if echo "$SCAN_TEXT" | grep -qiE '(echo|printenv)(\s|\\+t)+[^;&|]*\$\{?[A-Za-z0-9_]*(SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_KEY|TOKEN|PRIVATE_KEY|VAULT|CREDENTIAL|DATABASE_URL|CONNECTION_STRING)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked command that exposes secret environment variables"}}'
    exit 0
  fi
  # printenv takes a bare NAME with no `$`, so the arm above never sees it. The
  # name may be quoted, `printenv "GITHUB_TOKEN"`, and without python3 a double
  # quote reaches this rule as `\"`.
  if echo "$SCAN_TEXT" | grep -qiE 'printenv(\s|\\+t)+(-[A-Za-z0]+(\s|\\+t)+)*(\\*["'"'"'])?[A-Za-z0-9_]*(SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_KEY|TOKEN|PRIVATE_KEY|VAULT|CREDENTIAL|DATABASE_URL|CONNECTION_STRING)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked command that exposes secret environment variables"}}'
    exit 0
  fi
  # Bare `printenv` prints the whole environment, which is the same disclosure as
  # naming every secret variable at once. `env` is NOT matched here: it is
  # overwhelmingly used as a prefix (`env -u VAR cmd`), so its dump form has its
  # own arm below that tells the two apart. printenv may also start after a `\n`
  # escape and end at `;`, `&` or a `\n` escape: without python3 a line break
  # reaches this rule as `\n`, and a command after printenv does not change
  # what it prints, so `printenv; echo done` dumps the environment too. A pipe
  # after it is not matched: what `printenv | wc -l` shows is the output of
  # the next program. A quote right after the word also ends it, after any
  # backslashes: in `printf 'x\nprintenv' | sh` the shell runs the line printf
  # writes, and without python3 a double quote reaches this rule as `\"`. A
  # quote after a space opens an argument (`printenv "PATH"`), so it does not
  # count, and only the end takes a quote, so `grep -n 'printenv' src` passes.
  if echo "$SCAN_TEXT" | grep -qiE '(^|[;&|]|\\+n)(\s|\\+t)*printenv((\s|\\+t)*(-0(\s|\\+t)*)?($|[;&]|\\+n)|\\*["'"'"'])'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked full environment dump via printenv"}}'
    exit 0
  fi
  # Process listings that print environments or full command lines (#187).
  # Refusing printenv alone left the other routes open: `ps -E` (and the BSD `e`
  # modifier) prints a process environment outright, `/proc/<pid>/environ` holds
  # it, and a full command line carries it for a process that rewrites its title
  # (`npm exec` does), so `pgrep -l`/`-a`, `ps ... ww` and `ps -o command`
  # print it too. The patterns are matched case-sensitively, because `ps -e`
  # (every process, on macOS and Linux) and `ps -E` (the environment) differ only
  # in case; command names are bracketed instead, so `PS` on a case-insensitive
  # disk is still caught. `ps` and `pgrep` are matched in command position (line
  # start, after a separator, `(` or a backtick, after sudo/xargs/watch-style
  # prefixes, or as a path like /bin/ps), so `docker compose ps web` and a commit
  # message that mentions ps are not refused.
  #
  # A plain listing (`ps aux`, `ps -ef`) prints the command column too and is
  # NOT matched: it is the everyday process listing, and refusing it is how a
  # guard gets switched off. Matched are the forms that ask for the environment,
  # for unlimited width or for the command column by name. When output is not a
  # terminal, macOS ps already uses unlimited width, so there `ps aux` prints
  # the same lines as `ps auxww`; that gap is known, not closed.
  #   1. pgrep with -l/-a in a flag cluster, or --list-name/--list-full. The
  #      cluster is restricted to pgrep's own flag letters, so a pattern such as
  #      `pgrep -f "java -jar"` is not mistaken for one.
  #   2. ps with E or ww in a dashed cluster, or e or ww in a dashless (BSD
  #      style) first argument: `ps -E`, `ps -axww`, `ps eww <pid>`, `ps auxww`.
  #   3. ps -o/-O/--format (or BSD `o`) naming command, args or cmd; comm,
  #      ucomm and ucmd print the program name without its arguments.
  #   4. Any reference to a /proc environ file.
  if echo "$COMMAND" | grep -qE \
      -e '(^|[;&|({`])\s*((sudo|command|exec|nohup|time|nice|xargs|watch)(\s+-[^[:space:]]*)*\s+)*([^[:space:];&|()]*/)?[Pp][Gg][Rr][Ee][Pp](\s[^;&|]*)?\s(-[acfilnoqvwxAIS]*[la][acfilnoqvwxAIS]*([^A-Za-z0-9_-]|$)|--list-(name|full))' \
      -e '(^|[;&|({`])\s*((sudo|command|exec|nohup|time|nice|xargs|watch)(\s+-[^[:space:]]*)*\s+)*([^[:space:];&|()]*/)?[Pp][Ss]((\s[^;&|]*)?\s-[A-Za-z]*(E|ww)|\s+[A-Za-z]*(e|ww)[A-Za-z]*([^A-Za-z0-9_-]|$))' \
      -e '(^|[;&|({`])\s*((sudo|command|exec|nohup|time|nice|xargs|watch)(\s+-[^[:space:]]*)*\s+)*([^[:space:];&|()]*/)?[Pp][Ss]((\s[^;&|]*)?\s(-[A-Za-z]*[oO]|--format)|\s+[A-Za-z]*[oO])([^;&|]*[^A-Za-z0-9_])?(command|args|cmd)([^A-Za-z0-9_]|$)' \
      -e '/proc/.*environ([^A-Za-z0-9_]|$)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked process listing that can print environment variables or full command lines, which can hold the credentials of other processes. Safe path: pgrep -f <pattern> prints process IDs only, and ps -p <pid> -o pid,comm prints the program name without its arguments."}}'
    exit 0
  fi
  # A bare `env` prints the whole environment, the same disclosure as a bare
  # printenv. `env` followed only by its own options and NAME=value assignments
  # runs no command and so prints the environment (`env -u X`, `env FOO=1`,
  # `env | grep KEY`); once a command word follows (`env -u X git push`,
  # `/usr/bin/env node`) it is a prefix and is allowed.
  if echo "$COMMAND" | grep -qE '(^|[;&|({`])\s*((sudo|command|exec|nohup|time|nice|xargs|watch)(\s+-[^[:space:]]*)*\s+)*([^[:space:];&|()]*/)?[Ee][Nn][Vv](\s+(-[iv0]+|-|--(ignore-environment|null|debug)|-u\s*[A-Za-z_][A-Za-z0-9_]*|--unset[=[:space:]]\s*[A-Za-z_][A-Za-z0-9_]*|[A-Za-z_][A-Za-z0-9_]*=[^[:space:];&|]*))*\s*($|[;&|)}`<>]|[0-9]+>)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked full environment dump via env. Safe path: env as a prefix that runs a command (env -u NAME cmd) is not blocked; to check that a variable is set without printing its value, use [ -n \"$NAME\" ] && echo set."}}'
    exit 0
  fi
  # Block secretless-ai secret extraction with --force
  if echo "$SCAN_TEXT" | grep -qiE 'secretless-ai(\s|\\+t)+secret(\s|\\+t)+get.*--force'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked forced secret extraction"}}'
    exit 0
  fi
  # Block reading a git hosting token through a credential helper. The
  # git-credential helper's get action prints the stored token for git to read,
  # and git credential fill asks every configured helper and prints what they
  # answer. Git runs the helper itself when it needs the token, so no agent
  # call of either is needed. Matched under any command prefix (npx, a host
  # CLI's), and get only as a whole word, so --host get.example.com is not.
  if echo "$COMMAND" | grep -qiE '(^|[^a-zA-Z0-9_-])git-credential\s+(.*\s)?get([^a-zA-Z0-9_.-]|$)|(^|[^a-zA-Z0-9_-])git(-|\s+(.*\s)?)credential\s+fill([^a-zA-Z0-9_-]|$)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked reading a git credential. git-credential get and git credential fill print the stored token; git asks the helper itself when it needs one. Safe path: run the git command that needs the token (git fetch, git clone) directly."}}'
    exit 0
  fi
  # Block secretless-ai run with env/printenv to dump injected secrets. The
  # trailing boundary keeps env/printenv a whole word so "-- envsubst" (a legit
  # templating program) is not caught.
  if echo "$SCAN_TEXT" | grep -qiE 'secretless-ai(\s|\\+t)+run.*--(\s|\\+t)*(env|printenv)([^a-zA-Z0-9_]|$)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked secret dump via secretless-ai run"}}'
    exit 0
  fi
  # Block secretless-ai vault exec with env/printenv (same shape as run -- env,
  # for the identity vault's injected namespace credential).
  if echo "$SCAN_TEXT" | grep -qiE 'secretless-ai(\s|\\+t)+vault(\s|\\+t)+exec.*--(\s|\\+t)*(env|printenv)([^a-zA-Z0-9_]|$)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked secret dump via secretless-ai vault exec"}}'
    exit 0
  fi
  # Block the full-store plaintext dump: secretless-ai env prints every stored
  # secret as export statements. The shell-profile eval hook never runs through
  # the agent, so no agent invocation of it is legitimate.
  # `env` as a whole subcommand: followed by any non-identifier char (space,
  # `)` in `$(secretless-ai env)`, `;`, `|`, a quote) or end of string — but
  # NOT a word char, so `environment` does not match.
  if echo "$SCAN_TEXT" | grep -qiE 'secretless-ai(\s|\\+t)+env([^a-zA-Z0-9_]|$)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked full secret-store dump via secretless-ai env"}}'
    exit 0
  fi
  # Block every reader of the secretless data directory except secretless-ai
  # itself. This arm used to list reading verbs (cat, head, awk, ...) and so
  # allowed every reader it did not name: python3, node, ruby and perl
  # one-liners and a plain shell redirect (`< ~/.secretless-ai/config.json`)
  # all read the store through it, and no list of verbs can name every program
  # that opens a file. The rule is now an allowlist: a command naming the
  # directory is refused unless the WHOLE command is one plain secretless-ai
  # invocation.
  #
  # "Plain" is what keeps the allowlist from being a prefix test. The command
  # must be one line holding the program name and words made only of letters,
  # digits and `_ . / ~ : = @ + , -`. That leaves out every shell operator that
  # can start a second program (`; & | < > ( )`, a backquote, `$`, a line
  # break) and every quote and backslash, so the words the shell runs are the
  # words matched here and `"run"` or `r\un` cannot hide a subcommand. `run` and
  # `vault exec` start a program of the caller's choice, so a command carrying
  # either word is refused too. A copy reached by another name
  # (`./secretless-ai`, `node dist/cli.js`) is not on the list.
  #
  # The search-pattern over-block is kept: a source search FOR the directory
  # name (grep -rn for the literal string) reads no store and is refused anyway,
  # so the reason names it and points at the tools whose path guard can tell the
  # difference.
  # This arm reads the full command, not SCAN_TEXT, so the analyzer's reduction
  # (OPERATION BEFORE TEXT) does not lift that over-block or let a heredoc body
  # name the directory.
  if echo "$COMMAND" | grep -qiE '\.secretless-ai|\.opena2a/secretless-ai'; then
    SECRETLESS_ONLY=0
    case "$COMMAND" in
      *$'\n'*) ;;
      *)
        if printf '%s' "$COMMAND" | grep -qE '^[[:blank:]]*(npx[[:blank:]]+(-y[[:blank:]]+|--yes[[:blank:]]+)?)?secretless-ai(@[A-Za-z0-9._-]+)?([[:blank:]]+[A-Za-z0-9_./~:=@+,-]+)*[[:blank:]]*$'; then
          # The words are plain here, so a case match finds them. It is not a
          # negated grep on purpose: under pipefail, a writer killed by SIGPIPE
          # after grep -q exits early would turn that negation into an allow.
          case " $COMMAND " in
            *[[:blank:]][Rr][Uu][Nn][[:blank:]]*|*[[:blank:]][Ee][Xx][Ee][Cc][[:blank:]]*) ;;
            *) SECRETLESS_ONLY=1 ;;
          esac
        fi
        ;;
    esac
    if [ "$SECRETLESS_ONLY" -eq 0 ]; then
      echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked access to secretless data directory. Only one plain secretless-ai command may name it; any other program, a shell redirect, or a command that chains, substitutes or starts another program is refused. This guard matches command text and cannot tell a filename from a search pattern, so a command that merely searches source for the directory name is blocked too. Safe path: open files with the Read tool and search with the Grep tool instead of Bash."}}'
      exit 0
    fi
  fi
  # Without python3, or when the analyzer printed no verdict, nothing parsed the
  # command (NOTE ON ENVIRONMENT PRINTS), so a command that runs one of the
  # programs that can print the environment is refused on its name alone: set,
  # env, printenv, export, declare, typeset, local, readonly, compgen, ps, pgrep,
  # tmux and docker inspect, in command position (line start, after a separator,
  # `(`, a backquote or `!`, after a `\n` or `\t` escape, after eval or a
  # shell's -c, behind a wrapper or a directory). The arms above keep their own
  # reasons; this one names the missing parse and its fix. The command reaches
  # grep through text_matches, so a writer that dies of SIGPIPE does not hide a
  # match, and no temporary file is needed (NOTE ON TEMPORARY FILES).
  if [ -z "$ENV_VERDICT" ] && text_matches -iE '(^|[;&|({`!]|\\+[nt]|(eval|-[A-Za-z]*c)\s+(\\*["'"'"'])?)\s*((sudo|doas|command|builtin|exec|nohup|time|nice|xargs|watch)(\s+-[^[:space:]]*)*\s+)*([^[:space:];&|()]*/)?(set|env|printenv|export|declare|typeset|local|readonly|compgen|ps|pgrep|tmux|docker(\s+-[^[:space:]]+)*\s+((container|image)\s+)?inspect)([[:space:];&|)}<>`"'"'"']|\\|$)' "$COMMAND"; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked a command that may print the environment. python3 is missing or did not run, so the guard cannot parse this command, and without a parse a command that runs set, env, printenv, export, declare, typeset, local, readonly, compgen, ps, pgrep, tmux or docker inspect is refused. Fix: install python3 (macOS: xcode-select --install; Debian or Ubuntu: sudo apt-get install python3), then run the command again."}}'
    exit 0
  fi
  # Custom env var patterns (from .secretless-rules.yaml)
  if echo "$COMMAND" | grep -qiE '(echo|printenv)\s+.*\$(ACME_.*)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked custom env var pattern"}}'
    exit 0
  fi
  if echo "$COMMAND" | grep -qiE '(python3?|node)\s+-(c|e).*(os\.environ|process\.env).*(ACME_.*)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked custom env var extraction"}}'
    exit 0
  fi
  # Custom bash command patterns (from .secretless-rules.yaml)
  if echo "$COMMAND" | grep -qiE '(acme-cli.*get.*)'; then
    echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Secretless: blocked custom bash pattern"}}'
    exit 0
  fi
  exit 0
fi

# Skip if no file path found
if [ -z "$FILE_PATH_CANDIDATES" ]; then
  exit 0
fi

# Classify one path against the file rules: CLASS becomes template, blocked or
# clear, and REASON names the matching rule when blocked.
classify_path() {
  # Normalize path for matching (case-insensitive: server.KEY and prod.ENV must match too)
  local LOWER_BASENAME LOWER_PATH
  LOWER_BASENAME=$(basename "$1" | tr '[:upper:]' '[:lower:]')
  LOWER_PATH=$(echo "$1" | tr '[:upper:]' '[:lower:]')
  CLASS=clear

  # Allow committed template/example files (.env.example, config.sample, etc.) — these
  # hold placeholders, not real secrets, and are meant to be read/edited/committed.
  # Checked BEFORE any block logic so it wins over the .env extension/dotfile rules below.
  case "$LOWER_BASENAME" in
    *.example|*.sample|*.template|*.dist) CLASS=template; return 0 ;;
  esac

  # Block by secret file extension as a suffix: server.key, prod.env, id_rsa.pem, terraform.tfstate
  if echo "$LOWER_BASENAME" | grep -qE '\.(env|key|pem|p12|pfx|crt|tfstate|tfvars|acmekey)$'; then CLASS=blocked; REASON="secret file extension"; fi
  # Block .env dotfile families (.env, .env.local, .envrc, .env.production)
  case "$LOWER_BASENAME" in
    .env|.env.*|.envrc) CLASS=blocked; REASON=".env" ;;
    .npmrc|.pypirc|.git-credentials|.netrc|.acme-config) CLASS=blocked; REASON="$LOWER_BASENAME" ;;
  esac
  # Block by path fragment anywhere in the path (credentials, .ssh/, secrets/, ...)
  case "$LOWER_PATH" in
    *credentials/*|*.aws/credentials*|*.ssh/*|*.docker/config.json*|*secrets/*|*.opena2a/secretless-ai/*|*.secretless-ai/*|*acme-vault/*|*/srv/acme/creds/*.json*) CLASS=blocked; REASON="secret path" ;;
  esac
  return 0
}

deny_file() {
  echo "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"$1\"}}"
  exit 0
}

# True when a component of $1, a parent directory or the last one, is a
# symlink. Walks the path as it was given, so a relative path is checked under
# the working directory without the working directory's own components.
path_has_link() {
  local rest="$1" acc="" comp
  case "$rest" in /*) acc=/; rest="${rest#/}" ;; esac
  while [ -n "$rest" ]; do
    case "$rest" in
      */*) comp="${rest%%/*}"; rest="${rest#*/}" ;;
      *) comp="$rest"; rest="" ;;
    esac
    [ -n "$comp" ] || continue
    case "$acc" in
      ''|*/) acc="$acc$comp" ;;
      *) acc="$acc/$comp" ;;
    esac
    [ -L "$acc" ] && return 0
  done
  return 1
}

# Print the physical path a tool opens for $1: every symlink followed, in the
# parent directories and in the last component. Written with cd -P and
# single-step readlink because realpath and readlink -f are missing from older
# macOS. Fails on a symlink loop or a directory that cannot be entered. A last
# component that does not exist yet (a Write of a new file) is kept as named,
# under its resolved parent.
resolve_path() {
  local p="$1" dir base target hops=0
  while [ "$hops" -lt 40 ]; do
    hops=$((hops + 1))
    case "$p" in
      */*) dir="${p%/*}"; base="${p##*/}" ;;
      *) dir=.; base="$p" ;;
    esac
    [ -n "$dir" ] || dir=/
    case "$base" in
      ''|.|..) (cd -P -- "$p" 2>/dev/null && pwd -P) || return 1; return 0 ;;
    esac
    dir=$(cd -P -- "$dir" 2>/dev/null && pwd -P) || return 1
    [ "$dir" = / ] && dir=""
    if [ -L "$dir/$base" ]; then
      target=$(readlink -- "$dir/$base") || return 1
      case "$target" in
        /*) p="$target" ;;
        *) p="$dir/$target" ;;
      esac
    else
      printf '%s\n' "$dir/$base"
      return 0
    fi
  done
  return 1
}

# Check EVERY candidate path. A payload carrying both a benign top-level path
# and a secret one nested deeper must block on the secret one, so the loop only
# skips a template candidate rather than exiting on it. The list is split at its
# line breaks with globbing off, so each candidate is one line as given and a *
# in it stays a character, and no here-document feeds the loop (NOTE ON
# TEMPORARY FILES). The + form of the expansion keeps set -u on bash 3.2 from
# reading an empty list as unset.
split_candidates() {
  local IFS='
'
  set -f
  CANDIDATE_LIST=($1)
  set +f
}
CANDIDATE_LIST=()
split_candidates "$FILE_PATH_CANDIDATES"
for CANDIDATE in ${CANDIDATE_LIST[@]+"${CANDIDATE_LIST[@]}"}; do
  [ -z "$CANDIDATE" ] && continue

  # The name the tool was given: a secret name is refused whatever it points at.
  classify_path "$CANDIDATE"
  if [ "$CLASS" = blocked ]; then
    deny_file "Secretless: blocked access to secret file matching pattern '$REASON'"
  fi

  # The file the tool would open. The rules above read the NAME, and a symlink
  # carries any name: config.env.example -> .env passed as a template while the
  # Read returned the real .env, and a repository can ship such a link. So the
  # resolved path is classified again, template exemption first, exactly as the
  # name was. A link that exists but cannot be resolved (dangling, a loop, an
  # unreadable directory) is refused, because what it reaches is unknown.
  RESOLVED=""
  if [ -L "$CANDIDATE" ] || [ -e "$CANDIDATE" ]; then
    if ! RESOLVED=$(resolve_path "$CANDIDATE") || [ ! -e "$CANDIDATE" ]; then
      deny_file "Secretless: blocked a symbolic link whose target cannot be resolved"
    fi
  else
    # Not there yet (a Write of a new file), but a parent directory can still
    # be a link into a secret store. Nothing to read if the parent is missing.
    RESOLVED=$(resolve_path "$CANDIDATE") || RESOLVED=""
  fi
  # Only a path that passes through a link is judged by what it reaches. The
  # resolved path is absolute, and the path-fragment rules (secrets/, .ssh/,
  # credentials/) match anywhere in it, so a path with no link in any component
  # is judged by its name alone: a relative path is not judged by the working
  # directory it is joined to, and a project kept under a directory named
  # secrets/ still reads its own src/app.js by relative path. A link in that
  # project is judged by its absolute target, which names secrets/, so it is
  # refused even when it reaches a plain file there.
  if [ -n "$RESOLVED" ] && path_has_link "$CANDIDATE"; then
    classify_path "$RESOLVED"
    if [ "$CLASS" = blocked ]; then
      deny_file "Secretless: blocked access to secret file matching pattern '$REASON' at the path this one resolves to"
    fi
  fi
done

exit 0
