#!/bin/bash
# Run the WritableStream::Abort cross-world Promise leak POC.
set -eu

ARTIFACTS_DIR="$(cd "$(dirname "$0")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PORT="${PORT:-8080}"
PROFILE="$(mktemp -d /tmp/chrome-poc-profile.XXXXXX)"

cleanup() {
  [[ -n "${SERVER_PID:-}" ]] && kill "$SERVER_PID" 2>/dev/null || true
  rm -rf "$PROFILE"
}
trap cleanup EXIT

# Start the HTTP server (serves POC files + /gen/ mojom JS bindings).
cd "$ARTIFACTS_DIR"
python3 server.py &
SERVER_PID=$!
sleep 1

# Launch Chrome.
#   --enable-blink-features=MojoJS,MojoJSTest : enable MojoInterfaceInterceptor
#       so the page can substitute a fake SerialService for real hardware.
#       This does not alter the vulnerable code path; it only replaces the
#       browser-side serial backend.
#   --load-extension : load the victim content-script (isolated world).
LOG="$ARTIFACTS_DIR/chrome-output.log"
timeout 25 "$CHROME" \
  --headless=new \
  --no-sandbox \
  --disable-gpu \
  --no-first-run --no-default-browser-check \
  --enable-logging=stderr --v=0 \
  --enable-blink-features=MojoJS,MojoJSTest \
  --disable-extensions-except="$ARTIFACTS_DIR/extension" \
  --load-extension="$ARTIFACTS_DIR/extension" \
  --user-data-dir="$PROFILE" \
  "http://127.0.0.1:${PORT}/poc.html" >"$LOG" 2>&1 || true

echo "==== POC console output (filtered) ===="
grep -E '\[POC\]|\[CS\]' "$LOG" | sed -E 's/^\[[0-9:.\/]+INFO:CONSOLE:[0-9]+\] //' || true
echo "======================================="
if grep -q 'RESULT: VULNERABLE' "$LOG"; then
  echo "STATUS: VULNERABLE"
  exit 0
elif grep -q 'RESULT: NOT VULNERABLE' "$LOG"; then
  echo "STATUS: NOT VULNERABLE"
  exit 1
else
  echo "STATUS: INDETERMINATE (see $LOG)"
  exit 2
fi
