requests.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import { blob2base64, sendTabCmd, string2uint8array } from '#/common';
  2. import { forEachEntry, forEachValue, objectPick } from '#/common/object';
  3. import ua from '#/common/ua';
  4. import cache from './cache';
  5. import { commands } from './message';
  6. import {
  7. FORBIDDEN_HEADER_RE, VM_VERIFY, requests, toggleHeaderInjector, verify,
  8. } from './requests-core';
  9. Object.assign(commands, {
  10. /** @return {void} */
  11. HttpRequest(opts, src) {
  12. const { tab: { id: tabId }, frameId } = src;
  13. const { id, eventsToNotify } = opts;
  14. requests[id] = {
  15. id,
  16. tabId,
  17. eventsToNotify,
  18. xhr: new XMLHttpRequest(),
  19. };
  20. // Returning will show JS exceptions during init phase in the tab console
  21. return httpRequest(opts, src, res => requests[id] && (
  22. sendTabCmd(tabId, 'HttpRequested', res, { frameId })
  23. ));
  24. },
  25. /** @return {void} */
  26. AbortRequest(id) {
  27. const req = requests[id];
  28. if (req) {
  29. req.xhr.abort();
  30. clearRequest(req);
  31. }
  32. },
  33. RevokeBlob(url) {
  34. const timer = cache.pop(`xhrBlob:${url}`);
  35. if (timer) {
  36. clearTimeout(timer);
  37. URL.revokeObjectURL(url);
  38. }
  39. },
  40. });
  41. /* 1MB takes ~20ms to encode/decode so it doesn't block the process of the extension and web page,
  42. * which lets us and them be responsive to other events or user input. */
  43. const CHUNK_SIZE = 1e6;
  44. async function blob2chunk(response, index) {
  45. return blob2base64(response, index * CHUNK_SIZE, CHUNK_SIZE);
  46. }
  47. function blob2objectUrl(response) {
  48. const url = URL.createObjectURL(response);
  49. cache.put(`xhrBlob:${url}`, setTimeout(commands.RevokeBlob, 60e3, url), 61e3);
  50. return url;
  51. }
  52. /** @param {VMHttpRequest} req */
  53. function xhrCallbackWrapper(req) {
  54. let lastPromise = Promise.resolve();
  55. let contentType;
  56. let dataSize;
  57. let numChunks;
  58. let response;
  59. let responseText;
  60. let responseHeaders;
  61. let sent = false;
  62. const { id, blobbed, chunked, xhr } = req;
  63. // Chrome encodes messages to UTF8 so they can grow up to 4x but 64MB is the message size limit
  64. const getChunk = blobbed && blob2objectUrl || chunked && blob2chunk;
  65. const getResponseHeaders = () => {
  66. const headers = req.responseHeaders || xhr.getAllResponseHeaders();
  67. if (responseHeaders !== headers) {
  68. responseHeaders = headers;
  69. return { responseHeaders };
  70. }
  71. };
  72. return (evt) => {
  73. if (!contentType) {
  74. contentType = xhr.getResponseHeader('Content-Type') || 'application/octet-stream';
  75. }
  76. if (xhr.response !== response) {
  77. response = xhr.response;
  78. sent = false;
  79. try {
  80. responseText = xhr.responseText;
  81. if (responseText === response) responseText = ['same'];
  82. } catch (e) {
  83. // ignore if responseText is unreachable
  84. }
  85. if ((blobbed || chunked) && response) {
  86. dataSize = response.size;
  87. numChunks = chunked && Math.ceil(dataSize / CHUNK_SIZE) || 1;
  88. }
  89. }
  90. const { type } = evt;
  91. const shouldNotify = req.eventsToNotify.includes(type);
  92. // only send response when XHR is complete
  93. const shouldSendResponse = xhr.readyState === 4 && shouldNotify && !sent;
  94. if (!shouldNotify && type !== 'loadend') {
  95. return;
  96. }
  97. lastPromise = lastPromise.then(async () => {
  98. await req.cb({
  99. blobbed,
  100. chunked,
  101. contentType,
  102. dataSize,
  103. id,
  104. numChunks,
  105. type,
  106. data: shouldNotify && {
  107. finalUrl: req.url || xhr.responseURL,
  108. ...getResponseHeaders(),
  109. ...objectPick(xhr, ['readyState', 'status', 'statusText']),
  110. ...('loaded' in evt) && objectPick(evt, ['lengthComputable', 'loaded', 'total']),
  111. response: shouldSendResponse
  112. ? numChunks && await getChunk(response, 0) || response
  113. : null,
  114. responseText: shouldSendResponse
  115. ? responseText
  116. : null,
  117. },
  118. });
  119. if (shouldSendResponse) {
  120. for (let i = 1; i < numChunks; i += 1) {
  121. await req.cb({
  122. id,
  123. chunk: {
  124. pos: i * CHUNK_SIZE,
  125. data: await getChunk(response, i),
  126. last: i + 1 === numChunks,
  127. },
  128. });
  129. }
  130. }
  131. if (type === 'loadend') {
  132. clearRequest(req);
  133. }
  134. });
  135. };
  136. }
  137. /**
  138. * @param {Object} opts
  139. * @param {chrome.runtime.MessageSender | browser.runtime.MessageSender} src
  140. * @param {function} cb
  141. */
  142. async function httpRequest(opts, src, cb) {
  143. const { tab } = src;
  144. const { incognito } = tab;
  145. const { anonymous, id, overrideMimeType, xhrType, url } = opts;
  146. const req = requests[id];
  147. if (!req || req.cb) return;
  148. req.cb = cb;
  149. req.anonymous = anonymous;
  150. const { xhr } = req;
  151. const vmHeaders = [];
  152. // Firefox can send Blob/ArrayBuffer directly
  153. const willStringifyBinaries = xhrType && !IS_FIREFOX;
  154. const chunked = willStringifyBinaries && incognito;
  155. const blobbed = willStringifyBinaries && !incognito;
  156. const [body, contentType] = decodeBody(opts.data);
  157. // Chrome can't fetch Blob URL in incognito so we use chunks
  158. req.blobbed = blobbed;
  159. req.chunked = chunked;
  160. // Firefox doesn't send cookies, https://github.com/violentmonkey/violentmonkey/issues/606
  161. // Both Chrome & FF need explicit routing of cookies in containers or incognito
  162. let shouldSendCookies = !anonymous && (incognito || IS_FIREFOX);
  163. xhr.open(opts.method || 'GET', url, true, opts.user || '', opts.password || '');
  164. xhr.setRequestHeader(VM_VERIFY, id);
  165. if (contentType) xhr.setRequestHeader('Content-Type', contentType);
  166. opts.headers::forEachEntry(([name, value]) => {
  167. if (FORBIDDEN_HEADER_RE.test(name)) {
  168. vmHeaders.push({ name, value });
  169. } else {
  170. xhr.setRequestHeader(name, value);
  171. }
  172. if (shouldSendCookies) {
  173. shouldSendCookies = !/^cookie$/i.test(name);
  174. }
  175. });
  176. xhr.responseType = willStringifyBinaries && 'blob' || xhrType || 'text';
  177. xhr.timeout = Math.max(0, Math.min(0x7FFF_FFFF, opts.timeout)) || 0;
  178. if (overrideMimeType) xhr.overrideMimeType(overrideMimeType);
  179. if (shouldSendCookies) {
  180. req.noNativeCookie = true;
  181. for (const store of await browser.cookies.getAllCookieStores()) {
  182. if (store.tabIds.includes(tab.id)) {
  183. if (IS_FIREFOX ? store.id !== 'firefox-default' : store.id !== '0') {
  184. /* Cookie routing. For the main store we rely on the browser.
  185. * The ids are hard-coded as `stores` may omit the main store if no such tabs are open. */
  186. req.storeId = store.id;
  187. }
  188. break;
  189. }
  190. }
  191. const now = Date.now() / 1000;
  192. const cookies = (await browser.cookies.getAll({
  193. url,
  194. storeId: req.storeId,
  195. ...ua.firefox >= 59 && { firstPartyDomain: null },
  196. })).filter(c => c.session || c.expirationDate > now); // FF reports expired cookies!
  197. if (cookies.length) {
  198. vmHeaders.push({
  199. name: 'cookie',
  200. value: cookies.map(c => `${c.name}=${c.value};`).join(' '),
  201. });
  202. }
  203. }
  204. toggleHeaderInjector(id, vmHeaders);
  205. const callback = xhrCallbackWrapper(req);
  206. req.eventsToNotify.forEach(evt => { xhr[`on${evt}`] = callback; });
  207. xhr.onloadend = callback; // always send it for the internal cleanup
  208. xhr.send(body);
  209. }
  210. /** @param {VMHttpRequest} req */
  211. function clearRequest({ id, coreId }) {
  212. delete verify[coreId];
  213. delete requests[id];
  214. toggleHeaderInjector(id, false);
  215. }
  216. export function clearRequestsByTabId(tabId) {
  217. requests::forEachValue(req => {
  218. if (req.tabId === tabId) {
  219. commands.AbortRequest(req.id);
  220. }
  221. });
  222. }
  223. /** Polyfill for Chrome's inability to send complex types over extension messaging */
  224. function decodeBody([body, type, wasBlob]) {
  225. if (type === 'query') {
  226. type = 'application/x-www-form-urlencoded';
  227. } else if (type != null) {
  228. // 5x times faster than fetch() which wastes time on inter-process communication
  229. const res = string2uint8array(atob(body.slice(body.indexOf(',') + 1)));
  230. if (!wasBlob) {
  231. type = body.match(/^data:(.+?);base64/)[1].replace(/(boundary=)[^;]+/,
  232. // using a function so it runs only if "boundary" was found
  233. (_, p1) => p1 + String.fromCharCode(...res.slice(2, res.indexOf(13))));
  234. }
  235. body = res;
  236. }
  237. return [body, type];
  238. }
  239. // In Firefox with production code of Violentmonkey, scripts can be injected before `tabs.onUpdated` is fired.
  240. // Ref: https://github.com/violentmonkey/violentmonkey/issues/1255
  241. browser.tabs.onRemoved.addListener(clearRequestsByTabId);