- // ==UserScript==
- // @name Itsnotlupus' MiddleMan
- // @namespace Itsnotlupus Industries
- // @version 1.1
- // @description inspect/intercept/modify any network requests
- // @author Itsnotlupus
- // @license MIT
- // ==/UserScript==
-
- const middleMan = (function(window) {
-
- /**
- * A small class that lets you register middleware for Fetch/XHR traffic.
- *
- */
- class MiddleMan {
- routes = {
- Request: {},
- Response: {}
- };
- regexps = {};
-
- addHook(route, {requestHandler, responseHandler}) {
- if (requestHandler) {
- this.routes.Request[route]??=[];
- this.routes.Request[route].push(requestHandler);
- }
- if (responseHandler) {
- this.routes.Response[route]??=[];
- this.routes.Response[route].push(responseHandler);
- }
- this.regexps[route]??=this.routeToRegexp(route);
- }
-
- removeHook(route, {requestHandler, responseHandler}) {
- if (requestHandler && this.routes.Request[route]?.includes(requestHandler)) {
- const i = this.routes.Request[route].indexOf(requestHandler);
- this.routes.Request[route].splice(i,1);
- }
- if (responseHandler && this.routes.Response[route]?.includes(responseHandler)) {
- const i = this.routes.Response[route].indexOf(responseHandler);
- this.routes.Response[route].splice(i,1);
- }
- }
-
- // 2 modes: start with '/' => full regexp, otherwise we only recognize '*" as a wildcard.
- routeToRegexp(path) {
- const r = path instanceof RegExp ? path :
- path.startsWith('/') ?
- path.split('/').slice(1,-1).join('') :
- ['^', ...path.split(/([*])/).map((chunk, i) => i%2==0 ? chunk.replace(/([^a-zA-Z0-9])/g, "\\$1") : '.'+chunk), '$'].join('');
- return new RegExp(r);
- }
-
- /**
- * Call this with a Request or a Response, and it'll loop through
- * each relevant hook to inspect and/or transform it.
- */
- async process(obj) {
- const { constructor: type, constructor: { name } } = obj;
- const routes = this.routes[name], hooks = [];
- Object.keys(routes).forEach(k => {
- if (obj.url.match(this.regexps[k])) hooks.push(...routes[k]);
- });
- for (const hook of hooks) {
- if (obj instanceof type) obj = await hook(obj.clone()) ?? obj;
- }
- return obj;
- }
- }
-
- // The only instance we'll need
- const middleMan = new MiddleMan;
-
- // A wrapper for fetch() that plugs into middleMan.
- const _fetch = window.fetch;
- async function fetch(resource, options) {
- const request = new Request(resource, options);
- const result = await middleMan.process(request);
- const response = result instanceof Request ? await _fetch(result) : result;
- return middleMan.process(response);
- }
-
- /**
- * Polyfill a subset of EventTarget, for the sole purpose of being used in the XHR polyfill below.
- * Primarily exists to allow Safari to extend it without tripping on itself.
- * Various liberties were taken.
- */
- class EventTarget {
- #listeners = {};
- #events = {};
- #setEvent(name, f) {
- if (this.#events[name]) this.removeEventListener(name, this.#events[name]);
- this.#events[name] = typeof f == 'function' ? f : null;
- if (this.#events[name]) this.addEventListener(name, this.#events[name]);
- }
- #getEvent(name) {
- return this.#events[name];
- }
- constructor(events = []) {
- events.forEach(name => {
- Object.defineProperty(this, "on"+name, {
- get() { return this.#getEvent(name); },
- set(f) { this.#setEvent(name, f); }
- });
- });
- }
- addEventListener(type, listener, options = {}) {
- if (options === true) { options = { capture: true }; }
- this.#listeners[type]??=[];
- this.#listeners[type].push({ listener, options });
- options.signal?.addEventListener?.('abort', () => this.removeEventListener(type, listener, options));
- }
- removeEventListener(type, listener, options = {}) {
- if (options === true) { options = { capture: true }; }
- if (!this.#listeners[type]) return;
- const index = this.#listeners[type].findIndex(slot => slot.listener === listener && slot.options.capture === options.capture);
- if (index > -1) {
- this.#listeners[type].splice(index,1);
- }
- }
- dispatchEvent(event) {
- // no capturing, no bubbling, no preventDefault, no stopPropagation, and a general disdain for most of the intended featureset.
- const listeners = this.#listeners[event.type];
- if (!listeners) return;
- // since I can't set event.target, or generally do anything useful with an Event instance, let's Proxy it.
- let immediateStop = false;
- const eventProxy = new Proxy(event, {
- get: (target, prop) => {
- switch (prop) {
- case "target":
- case "currentTarget":
- return this;
- case "isTrusted":
- return true; // you betcha
- case "stopImmediatePropagation":
- return () => immediateStop = true;
- default:
- return Reflect.get(target, prop);
- }
- }
- });
- listeners.forEach(async ({listener, options}) => {
- if (immediateStop) return;
- if (options.once) this.removeEventListener(eventProxy.type, listener, options);
- try {
- listener.call(this, eventProxy);
- } catch (e) {
- // I think it's impossible to match EventTarget::dispatchEvent throwing behavior in pure JS. oh well. fudge the timing and keep on trucking.
- await 0;
- throw e;
- }
- });
- return true;
- }
- }
-
- /**
- * An XMLHttpRequest polyfill written on top of fetch().
- * Nothing special here, but this allows MiddleMan to work on XHR too.
- *
- * A few gotchas:
- * - This is not spec-compliant. In many ways. https://xhr.spec.whatwg.org/
- * - xhr.upload is not implemented. we'll throw an exception if someone tries to use it.
- * - synchronous xhr is not implemented. all my homies hate sync xhr anyway.
- * - no test coverage. But I tried it on 2 sites and it didn't explode, so.. pretty good.
- */
- class XMLHttpRequest extends EventTarget {
- #readyState;
-
- #requestOptions = {};
- #requestURL;
- #abortController;
- #timeout;
- #responseType = '';
- #mimeTypeOverride = null;
-
- #response;
- #responseText;
- #responseXML;
- #responseAny;
-
- #dataLengthComputable = false;
- #dataLoaded = 0;
- #dataTotal = 0;
-
- #errorEvent;
-
- UNSENT = 0;
- OPENED = 1;
- HEADERS_RECEIVED = 2;
- LOADING = 3;
- DONE = 4;
- static UNSENT = 0;
- static OPENED = 1;
- static HEADERS_RECEIVED = 2;
- static LOADING = 3;
- static DONE = 4;
-
- constructor() {
- super(['abort','error','load','loadend','loadstart','progress','readystatechange','timeout']);
- this.#readyState = 0;
- }
-
- get readyState() {
- return this.#readyState;
- }
- #assertReadyState(...validValues) {
- if (!validValues.includes(this.#readyState)) {
- throw new Error("Failed to take action on XMLHttpRequest: Invalid state.");
- }
- }
- #updateReadyState(value) {
- this.#readyState = value;
- this.#emitEvent("readystatechange");
- }
-
- // Request setup
- open(method, url, async, user, password) {
- this.#assertReadyState(0,1);
- this.#requestOptions.method = method.toString().toUpperCase();
- this.#requestOptions.headers = new Headers()
- this.#requestURL = url;
- this.#abortController = null;
- this.#timeout = 0;
- this.#mimeTypeOverride = null;
- this.#response = null;
- this.#responseText = '';
- this.#responseAny = null;
- this.#responseXML = null;
- this.#dataLengthComputable = false;
- this.#dataLoaded = 0;
- this.#dataTotal = 0;
-
- if (async === false) {
- throw new Error("Synchronous XHR is not supported.");
- }
- if (user || password) {
- this.#requestOptions.headers.set('Authorization', 'Basic '+btoa(`${user??''}:${password??''}`));
- }
- this.#updateReadyState(1);
- }
- setRequestHeader(header, value) {
- this.#assertReadyState(1);
- this.#requestOptions.headers.set(header, value);
- }
- overrideMimeType(mimeType) {
- this.#mimeTypeOverride = mimeType;
- }
- set responseType(type) {
- if (!["","arraybuffer","blob","document","json","text"].includes(type)) {
- console.warn(`The provided value '${type}' is not a valid enum value of type XMLHttpRequestResponseType.`);
- return;
- }
- this.#responseType = type;
- }
- get responseType() {
- return this.#responseType;
- }
- set timeout(value) {
- const ms = isNaN(Number(value)) ? 0 : Math.floor(Number(value));
- this.#timeout = value;
- }
- get timeout() {
- return this.#timeout;
- }
- get upload() {
- throw new Error("XMLHttpRequestUpload is not implemented.");
- }
- set withCredentials(flag) {
- this.#requestOptions.credentials = flag ? "include" : "omit";
- }
- get withCredentials() {
- return this.#requestOptions.credentials == "include";
- }
- async send(body = null) {
- this.#assertReadyState(1);
- if (this.#requestOptions.method != 'GET' && this.#requestOptions.method != 'HEAD') {
- this.#requestOptions.body = body instanceof Document ? body.documentElement.outerHTML : body;
- }
- const request = new Request(this.#requestURL, this.#requestOptions);
- this.#abortController = new AbortController();
- const signal = this.#abortController.signal;
- if (this.#timeout) {
- setTimeout(()=> this.#timedOut(), this.#timeout);
- }
- this.#emitEvent("loadstart");
- let response;
- try {
- response = await fetch(request, { signal });
- this.#updateReadyState(2);
- const isNotCompressed = response.type == 'basic' && !response.headers.get('content-encoding');
- if (isNotCompressed) {
- this.#dataTotal = response.headers.get('content-length') ?? 0;
- this.#dataLengthComputable = this.#dataTotal !== 0;
- }
- await this.#processResponse(response);
- } catch (e) {
- return this.#error();
- }
- }
- abort() {
- this.#abortController?.abort();
- this.#errorEvent = "abort";
- }
- #timedOut() {
- this.#abortController?.abort();
- this.#errorEvent = "timeout";
- }
- #error() {
- // abort and timeout end up here.
- this.#response = new Response('');
- this.#responseText = ''
- this.#responseAny = null;
- this.#dataLoaded = 0;
- this.#updateReadyState(4);
- this.#emitEvent(this.#errorEvent ?? "error");
- this.#emitEvent("loadend");
- this.#errorEvent = null;
- }
- async #processResponse(response) {
- this.#response = response;
- this.#trackProgress(response.clone());
- switch (this.#responseType) {
- case 'arraybuffer':
- try {
- this.#responseAny = await response.arrayBuffer();
- } catch {
- this.#responseAny = null;
- }
- break;
- case 'blob':
- try {
- this.#responseAny = await response.blob();
- } catch {
- this.#responseAny = null;
- }
- break;
- case 'document': {
- this.#responseText = await response.text();
- const mimeType = this.#mimeTypeOverride ?? this.#response.headers.get('content-type')?.split(';')[0].trim() ?? 'text/xml';
- try {
- const parser = new DOMParser();
- const doc = parser.parseFromString(this.#responseText, mimeType);
- this.#responseAny = this.#responseXML = doc;
- } catch {
- this.#responseAny = null;
- }
- break;
- }
- case 'json':
- try {
- this.#responseAny = await response.json();
- } catch {
- this.#responseAny = null;
- }
- break;
- case '':
- case 'text':
- default:
- this.#responseAny = this.#responseText = await response.text();
- break;
- }
- this.#updateReadyState(4);
- this.#emitEvent("load");
- this.#emitEvent("loadend");
- }
- async #trackProgress(response) {
- // count the bytes to update #dataLoaded, and add text into #responseText if appropriate
- const isText = this.#responseType == 'text' || (this.#responseType == '' && !response.headers.get('content-type').startsWith('text/xml'));
- const decoder = new TextDecoder();
-
- const reader = response.body.getReader();
- const handleChunk = ({ done, value }) => {
- if (done) return;
- this.#dataLoaded += value.length;
- if (isText) {
- this.#responseText += decoder.decode(value);
- this.#responseAny = this.#responseText;
- }
- this.#emitEvent('progress');
- reader.read().then(handleChunk).catch(()=>0);
- };
- reader.read().then(handleChunk).catch(()=>0);
- }
- // Response access
- getResponseHeader(header) {
- return this.#response?.headers.get(header) ?? null;
- }
- getAllResponseHeaders() {
- return [...this.#response?.headers.entries()??[]].map(([key,value]) => `${key}: ${value}\r\n`).join('');
- }
- get response() {
- return this.#responseAny;
- }
- get responseText() {
- if (this.#responseType != 'text' && this.#responseType != '') {
- throw new Error(`Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was '${this.#responseType}').`);
- }
- return this.#responseText;
- }
- get responseXML() {
- if (this.#responseType != 'document' && this.#responseType != '') {
- throw new Error(`Failed to read the 'responseXML' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'document' (was '${this.#responseType}').`);
- }
- return this.#responseXML;
- }
- get responseURL() {
- return this.#response?.url;
- }
- get status() {
- return this.#response?.status ?? 0;
- }
- get statusText() {
- return this.#response?.statusText ?? '';
- }
-
- // event dispatching resiliency
- async #emitEvent(name) {
- this.dispatchEvent(new ProgressEvent(name, {
- lengthComputable: this.#dataLengthComputable,
- loaded: this.#dataLoaded,
- total: this.#dataTotal
- }));
- }
- // I've got the perfect disguise..
- get [Symbol.toStringTag]() {
- return 'XMLHttpRequest';
- }
- static toString = ()=> 'function XMLHttpRequest() { [native code] }';
- }
-
- window.XMLHttpRequest = XMLHttpRequest;
- window.fetch = fetch;
-
- return middleMan;
-
- })(globalThis.unsafeWindow ?? window);