#!/usr/bin/env bash
# scan-agent-config.sh  -  config-hygiene gate for the shipped agent surface.
#
# Audits the config the pipeline SHIPS (install templates, preferences template,
# agent definitions, MCP helper scripts) for security problems before release:
#   HIGH   - hardcoded secrets; hook commands that eval/execute inspected input;
#            permission bypass flags baked into a shipped template.
#   MEDIUM - unpinned/remote-install supply-chain patterns (curl|bash, MCP and
#            package-runner launches whose selector floats or can be
#            repointed, plain-http MCP servers); blanket Bash(*) permission allow.
#
# Read-only. Never prints a secret value (reports file + rule only). Self-contained
# (no external scanner dependency; node runs the MCP launch classifier).
# Exit 1 if any HIGH finding, else 0.
#
# A first-party, dependency-free gate over this repo's own shipped surface.

set -uo pipefail

# BEGIN GENERATED: secret-patterns
# Written by pipeline/scripts/gen-secret-patterns.mjs from
# pipeline/schemas/secret-patterns.json; edit the JSON and regenerate.
SECRET_PATTERNS_ERE='((^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{36,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])github_pat_[A-Za-z0-9_]{50,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xox[abprs]-[A-Za-z0-9-]{10,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])(AKIA|ASIA)[0-9A-Z]{16})|((^|[^A-Za-z0-9_])AIza[0-9A-Za-z_-]{35}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-(proj-)?[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-ant-[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])fig[a-z]_[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])npm_[A-Za-z0-9]{36}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])glpat-[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])[sr]k_live_[A-Za-z0-9]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])pplx-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])hf_[A-Za-z0-9]{30,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])gsk_[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-or-v1-[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xapp-[0-9]+-[A-Za-z0-9]{8,}-[0-9]{8,}-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}([^A-Za-z0-9_-]|$))|((^|[^A-Za-z0-9_])SK[0-9a-f]{32}([^A-Za-z0-9_]|$))|("type"[[:space:]]*:[[:space:]]*"service_account")|((^|[^A-Za-z0-9_])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}([^A-Za-z0-9_]|$))|(-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----)|((^|[^A-Za-z0-9_])[a-z][a-z0-9+.-]{0,31}://[^[:space:]/:@]{1,255}:[^[:space:]/@]+@)'
SECRET_PATTERNS_ERE_ICASE='(aws_?secret_?access_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9/+=]{40}([^A-Za-z0-9/+=]|$))|(aws_?session_?token["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9/+=]{100,})|((^|[^A-Za-z0-9_])Authorization:[[:space:]]*(Bearer|Basic)[[:space:]]+[A-Za-z0-9._~+/=-]{16,})'
# END GENERATED: secret-patterns

# ROOT defaults to the repo root; SCAN_ROOT overrides it (used by the smoke test
# to point at a fixture tree of planted-bad configs).
#
# Two layouts, and this script ships into the second one. From the checkout, $0
# is <repo>/pipeline/scripts/... and `../..` is the repo. From an install it is
# ~/.claude/scripts/... and `../..` is the HOME directory, where none of the
# shipped config paths exist - the scan then found zero files and called itself
# clean. Same defect class as the one skill-siblings.mjs carried, so it gets the
# same two-candidate resolution: try the repo layout, fall back to the install.
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
if [ -n "${SCAN_ROOT:-}" ]; then
  ROOT="$SCAN_ROOT"
else
  _here="$(cd "$(dirname "$0")" && pwd)"
  _repo="$(cd "$_here/../.." && pwd)"
  if [ -d "$_repo/pipeline/agents" ]; then
    ROOT="$_repo"
  else
    ROOT="$HOME/.claude"
  fi
fi

HIGH=0; MED=0
high() { HIGH=$((HIGH+1)); echo "  [HIGH]   $1"; }
med()  { MED=$((MED+1));  echo "  [MEDIUM] $1"; }

# Shipped config surface (globs expanded safely; missing paths are skipped).
TARGETS=()
add() { [ -e "$1" ] && TARGETS+=("$1"); }
# The same surface under either layout: `pipeline/`-prefixed in the checkout,
# flat under ~/.claude once installed.
if [ -d "$ROOT/pipeline/agents" ]; then
  add "$ROOT/install/templates/claude-hooks.json"
  add "$ROOT/install/templates/copilot-instructions.md"
  add "$ROOT/pipeline/preferences-template.json"
  for f in "$ROOT"/pipeline/agents/*.md; do add "$f"; done
  # (figma component skills + their scripts now live in the ai-*-toolkit
  #  marketplace plugin, not in this repo, so there is nothing figma to scan here.)
  add "$ROOT/pipeline/scripts/agent-guard.sh"
  add "$ROOT/pipeline/scripts/pre-commit-check.sh"
else
  # settings.json is deliberately NOT in this list. It is the USER's file, not
  # something the pipeline ships, and their own permission choices are theirs to
  # make - scanning it turned a personal setting into a release blocker.
  for f in "$ROOT"/templates/*; do add "$f"; done
  for f in "$ROOT"/agents/*.md; do add "$f"; done
  add "$ROOT/scripts/agent-guard.sh"
  add "$ROOT/scripts/pre-commit-check.sh"
fi

rel() { echo "${1#$ROOT/}"; }

echo "→ scanning ${#TARGETS[@]} shipped config files (root: $ROOT)"

# Zero targets is a resolution failure, not a clean bill: `"${TARGETS[@]}"` on an
# empty array is also an unbound-variable error under bash 3.2 with `set -u`, so
# the script died here instead of saying what went wrong.
if [ "${#TARGETS[@]}" -eq 0 ]; then
  echo "  [HIGH]   no shipped config file found under $ROOT - nothing was scanned"
  echo "→ config hygiene: 1 HIGH, 0 MEDIUM"
  exit 1
fi

for f in "${TARGETS[@]}"; do
  [ -f "$f" ] || continue
  r="$(rel "$f")"

  # --- HIGH: hardcoded secrets (the generated shapes; report file, not value)
  if grep -EqI -e "$SECRET_PATTERNS_ERE" "$f" 2>/dev/null ||
    grep -EiqI -e "$SECRET_PATTERNS_ERE_ICASE" "$f" 2>/dev/null; then
    high "hardcoded secret / token in $r"
  fi

  # --- HIGH: permission bypass baked into a shipped template
  if grep -Eq 'skipDangerousModePermissionPrompt"?[[:space:]]*:[[:space:]]*true|--dangerously-skip-permissions|"permissions"[[:space:]]*:[[:space:]]*"?(allow-all|bypass)' "$f" 2>/dev/null; then
    high "permission bypass flag in shipped template: $r"
  fi

  # --- MEDIUM: blanket Bash allow
  if grep -Eq '"Bash\(\*\)"|"Bash\(:\*\)"|Bash\(\*:\*\)' "$f" 2>/dev/null; then
    med "blanket Bash(*) permission in $r"
  fi

  # --- MEDIUM: remote-install supply-chain patterns
  if grep -Eq 'curl[^|]*\|[[:space:]]*(sudo[[:space:]]+)?(ba)?sh|wget[^|]*\|[[:space:]]*(ba)?sh' "$f" 2>/dev/null; then
    med "pipe-to-shell remote install (curl|bash) in $r"
  fi
done

# --- MCP launch selectors: classified offline by mcp-config-audit.mjs. An MCP
# config is judged per server; any other file is searched for package-runner
# and container launches. floating/mutable selectors and plain-http servers
# come back MEDIUM, literal secrets in a server's env, headers, args or URL
# come back HIGH. A pinned launch is not reported. An audit that exits
# non-zero is HIGH: its findings, whatever they were, did not come back.
AUDIT="$SCRIPT_DIR/mcp-config-audit.mjs"
if [ -f "$AUDIT" ] && command -v node >/dev/null 2>&1; then
  audit_rc=0
  audit_out="$(node "$AUDIT" --scanner --root "$ROOT" "${TARGETS[@]}" 2>/dev/null)" || audit_rc=$?
  while IFS=$'\t' read -r level msg; do
    case "$level" in
      HIGH) high "$msg" ;;
      MEDIUM) med "$msg" ;;
    esac
  done <<<"$audit_out"
  if [ "$audit_rc" -ne 0 ]; then
    high "MCP launch audit failed (exit $audit_rc) - launch selectors were not checked"
  fi
else
  high "MCP launch audit unavailable (node or $AUDIT missing) - launch selectors were not checked"
fi

# --- HIGH: hook commands must only invoke vetted scripts, never inline eval -----
HOOKS="$ROOT/install/templates/claude-hooks.json"
if [ -f "$HOOKS" ] && command -v python3 >/dev/null 2>&1; then
  bad="$(python3 - "$HOOKS" <<'PY' 2>/dev/null || true
import json, re, sys
try:
    t = json.load(open(sys.argv[1]))
except Exception:
    sys.exit(0)
bad = []
for _event, entries in (t.get("hooks") or {}).items():
    for e in entries:
        for h in e.get("hooks", []):
            c = h.get("command", "")
            # Allow only `bash "$HOME/.claude/scripts/<name>"` (the path quoted
            # so a HOME with a space still runs it, or unquoted) plus plain long
            # flags. SessionEnd needs one: capture-flush takes --if-stale so a
            # session end does not re-flush a run that already finished. What
            # stays banned is everything that could turn a flag into a second
            # command - no spaces inside a token, no quotes beyond the pair
            # around the path, no metacharacters, and the eval/substitution
            # check below still runs on the whole string.
            if not re.fullmatch(
                r'bash (?:"\$HOME/\.claude/scripts/[A-Za-z0-9._-]+"|\$HOME/\.claude/scripts/[A-Za-z0-9._-]+)(?: --[a-z0-9][a-z0-9-]*)*',
                c.strip()):
                bad.append(c)
            if re.search(r'\beval\b|\$\(|`|[;&|><]', c):
                bad.append(c)
print("\n".join(bad))
PY
)"
  if [ -n "$bad" ]; then
    high "hooks template has a non-vetted or eval-bearing hook command"
  fi
fi

echo ""
echo "══ config-hygiene: $HIGH high, $MED medium ══"
if [ "$HIGH" -gt 0 ]; then
  echo "FAIL: high-severity config findings must be fixed before release."
  exit 1
fi
exit 0
