ajhsu / blog

The external storage of my brain.
3 stars 0 forks source link

MITM for XMLHttpRequest #35

Open ajhsu opened 7 years ago

ajhsu commented 7 years ago

Source

The implementation was originated from Jasper's gist.

Implementation

const responseTransform = requestURL => response => {
  // Original request url
  console.log(requestURL);
  // Deep clone from response
  const nextResponse = JSON.parse(JSON.stringify(response));
  // do what you want with response
  if (nextResponse.results_json) {
    nextResponse.results_json.search_results.map(r => {
      r.listing.name = '顆顆';
    });
  }
  return nextResponse;
};

// XMLHttpRequest MITM attack implementation
(function() {
  const XHR = window.XMLHttpRequest;
  function nextXHR() {
    const xhr = new XHR();
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        const response = responseTransform(xhr.responseURL)(
          xhr.responseText !== '' ? JSON.parse(xhr.responseText) : {}
        );
        // Unlock and overwrite the responseText
        Object.defineProperty(xhr, 'responseText', {
          writable: true
        });
        xhr.responseText = JSON.stringify(response);
      }
    };
    return xhr;
  }
  window.XMLHttpRequest = nextXHR;
})();