net-client-request.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. import * as url from 'url';
  2. import { Readable, Writable } from 'stream';
  3. import { app } from 'electron/main';
  4. import type { ClientRequestConstructorOptions, UploadProgress } from 'electron/main';
  5. const {
  6. isValidHeaderName,
  7. isValidHeaderValue,
  8. createURLLoader
  9. } = process._linkedBinding('electron_browser_net');
  10. const { Session } = process._linkedBinding('electron_browser_session');
  11. const kHttpProtocols = new Set(['http:', 'https:']);
  12. // set of headers that Node.js discards duplicates for
  13. // see https://nodejs.org/api/http.html#http_message_headers
  14. const discardableDuplicateHeaders = new Set([
  15. 'content-type',
  16. 'content-length',
  17. 'user-agent',
  18. 'referer',
  19. 'host',
  20. 'authorization',
  21. 'proxy-authorization',
  22. 'if-modified-since',
  23. 'if-unmodified-since',
  24. 'from',
  25. 'location',
  26. 'max-forwards',
  27. 'retry-after',
  28. 'etag',
  29. 'last-modified',
  30. 'server',
  31. 'age',
  32. 'expires'
  33. ]);
  34. class IncomingMessage extends Readable {
  35. _shouldPush: boolean = false;
  36. _data: (Buffer | null)[] = [];
  37. _responseHead: NodeJS.ResponseHead;
  38. _resume: (() => void) | null = null;
  39. constructor (responseHead: NodeJS.ResponseHead) {
  40. super();
  41. this._responseHead = responseHead;
  42. }
  43. get statusCode () {
  44. return this._responseHead.statusCode;
  45. }
  46. get statusMessage () {
  47. return this._responseHead.statusMessage;
  48. }
  49. get headers () {
  50. const filteredHeaders: Record<string, string | string[]> = {};
  51. const { headers, rawHeaders } = this._responseHead;
  52. for (const [name, values] of Object.entries(headers)) {
  53. filteredHeaders[name] = discardableDuplicateHeaders.has(name) ? values[0] : values.join(', ');
  54. }
  55. const cookies = rawHeaders.filter(({ key }) => key.toLowerCase() === 'set-cookie').map(({ value }) => value);
  56. // keep set-cookie as an array per Node.js rules
  57. // see https://nodejs.org/api/http.html#http_message_headers
  58. if (cookies.length) { filteredHeaders['set-cookie'] = cookies; }
  59. return filteredHeaders;
  60. }
  61. get rawHeaders () {
  62. const rawHeadersArr: string[] = [];
  63. const { rawHeaders } = this._responseHead;
  64. for (const header of rawHeaders) {
  65. rawHeadersArr.push(header.key, header.value);
  66. }
  67. return rawHeadersArr;
  68. }
  69. get httpVersion () {
  70. return `${this.httpVersionMajor}.${this.httpVersionMinor}`;
  71. }
  72. get httpVersionMajor () {
  73. return this._responseHead.httpVersion.major;
  74. }
  75. get httpVersionMinor () {
  76. return this._responseHead.httpVersion.minor;
  77. }
  78. get rawTrailers () {
  79. throw new Error('HTTP trailers are not supported');
  80. }
  81. get trailers () {
  82. throw new Error('HTTP trailers are not supported');
  83. }
  84. _storeInternalData (chunk: Buffer | null, resume: (() => void) | null) {
  85. // save the network callback for use in _pushInternalData
  86. this._resume = resume;
  87. this._data.push(chunk);
  88. this._pushInternalData();
  89. }
  90. _pushInternalData () {
  91. while (this._shouldPush && this._data.length > 0) {
  92. const chunk = this._data.shift();
  93. this._shouldPush = this.push(chunk);
  94. }
  95. if (this._shouldPush && this._resume) {
  96. // Reset the callback, so that a new one is used for each
  97. // batch of throttled data. Do this before calling resume to avoid a
  98. // potential race-condition
  99. const resume = this._resume;
  100. this._resume = null;
  101. resume();
  102. }
  103. }
  104. _read () {
  105. this._shouldPush = true;
  106. this._pushInternalData();
  107. }
  108. }
  109. /** Writable stream that buffers up everything written to it. */
  110. class SlurpStream extends Writable {
  111. _data: Buffer;
  112. constructor () {
  113. super();
  114. this._data = Buffer.alloc(0);
  115. }
  116. _write (chunk: Buffer, encoding: string, callback: () => void) {
  117. this._data = Buffer.concat([this._data, chunk]);
  118. callback();
  119. }
  120. data () { return this._data; }
  121. }
  122. class ChunkedBodyStream extends Writable {
  123. _pendingChunk: Buffer | undefined;
  124. _downstream?: NodeJS.DataPipe;
  125. _pendingCallback?: (error?: Error) => void;
  126. _clientRequest: ClientRequest;
  127. constructor (clientRequest: ClientRequest) {
  128. super();
  129. this._clientRequest = clientRequest;
  130. }
  131. _write (chunk: Buffer, encoding: string, callback: () => void) {
  132. if (this._downstream) {
  133. this._downstream.write(chunk).then(callback, callback);
  134. } else {
  135. // the contract of _write is that we won't be called again until we call
  136. // the callback, so we're good to just save a single chunk.
  137. this._pendingChunk = chunk;
  138. this._pendingCallback = callback;
  139. // The first write to a chunked body stream begins the request.
  140. this._clientRequest._startRequest();
  141. }
  142. }
  143. _final (callback: () => void) {
  144. this._downstream!.done();
  145. callback();
  146. }
  147. startReading (pipe: NodeJS.DataPipe) {
  148. if (this._downstream) {
  149. throw new Error('two startReading calls???');
  150. }
  151. this._downstream = pipe;
  152. if (this._pendingChunk) {
  153. const doneWriting = (maybeError: Error | void) => {
  154. // If the underlying request has been aborted, we honestly don't care about the error
  155. // all work should cease as soon as we abort anyway, this error is probably a
  156. // "mojo pipe disconnected" error (code=9)
  157. if (this._clientRequest._aborted) return;
  158. const cb = this._pendingCallback!;
  159. delete this._pendingCallback;
  160. delete this._pendingChunk;
  161. cb(maybeError || undefined);
  162. };
  163. this._downstream.write(this._pendingChunk).then(doneWriting, doneWriting);
  164. }
  165. }
  166. }
  167. type RedirectPolicy = 'manual' | 'follow' | 'error';
  168. const kAllowNonHttpProtocols = Symbol('kAllowNonHttpProtocols');
  169. export function allowAnyProtocol (opts: ClientRequestConstructorOptions): ClientRequestConstructorOptions {
  170. return {
  171. ...opts,
  172. [kAllowNonHttpProtocols]: true
  173. } as any;
  174. }
  175. type ExtraURLLoaderOptions = {
  176. redirectPolicy: RedirectPolicy;
  177. headers: Record<string, { name: string, value: string | string[] }>;
  178. allowNonHttpProtocols: boolean;
  179. }
  180. function parseOptions (optionsIn: ClientRequestConstructorOptions | string): NodeJS.CreateURLLoaderOptions & ExtraURLLoaderOptions {
  181. // eslint-disable-next-line node/no-deprecated-api
  182. const options: any = typeof optionsIn === 'string' ? url.parse(optionsIn) : { ...optionsIn };
  183. let urlStr: string = options.url;
  184. if (!urlStr) {
  185. const urlObj: url.UrlObject = {};
  186. const protocol = options.protocol || 'http:';
  187. urlObj.protocol = protocol;
  188. if (options.host) {
  189. urlObj.host = options.host;
  190. } else {
  191. if (options.hostname) {
  192. urlObj.hostname = options.hostname;
  193. } else {
  194. urlObj.hostname = 'localhost';
  195. }
  196. if (options.port) {
  197. urlObj.port = options.port;
  198. }
  199. }
  200. if (options.path && / /.test(options.path)) {
  201. // The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
  202. // with an additional rule for ignoring percentage-escaped characters
  203. // but that's a) hard to capture in a regular expression that performs
  204. // well, and b) possibly too restrictive for real-world usage. That's
  205. // why it only scans for spaces because those are guaranteed to create
  206. // an invalid request.
  207. throw new TypeError('Request path contains unescaped characters');
  208. }
  209. // eslint-disable-next-line node/no-deprecated-api
  210. const pathObj = url.parse(options.path || '/');
  211. urlObj.pathname = pathObj.pathname;
  212. urlObj.search = pathObj.search;
  213. urlObj.hash = pathObj.hash;
  214. urlStr = url.format(urlObj);
  215. }
  216. const redirectPolicy = options.redirect || 'follow';
  217. if (!['follow', 'error', 'manual'].includes(redirectPolicy)) {
  218. throw new Error('redirect mode should be one of follow, error or manual');
  219. }
  220. if (options.headers != null && typeof options.headers !== 'object') {
  221. throw new TypeError('headers must be an object');
  222. }
  223. const urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { redirectPolicy: RedirectPolicy, headers: Record<string, { name: string, value: string | string[] }>, allowNonHttpProtocols: boolean } = {
  224. method: (options.method || 'GET').toUpperCase(),
  225. url: urlStr,
  226. redirectPolicy,
  227. headers: {},
  228. body: null as any,
  229. useSessionCookies: options.useSessionCookies,
  230. credentials: options.credentials,
  231. origin: options.origin,
  232. referrerPolicy: options.referrerPolicy,
  233. cache: options.cache,
  234. allowNonHttpProtocols: Object.hasOwn(options, kAllowNonHttpProtocols)
  235. };
  236. const headers: Record<string, string | string[]> = options.headers || {};
  237. for (const [name, value] of Object.entries(headers)) {
  238. if (!isValidHeaderName(name)) {
  239. throw new Error(`Invalid header name: '${name}'`);
  240. }
  241. if (!isValidHeaderValue(value.toString())) {
  242. throw new Error(`Invalid value for header '${name}': '${value}'`);
  243. }
  244. const key = name.toLowerCase();
  245. urlLoaderOptions.headers[key] = { name, value };
  246. }
  247. if (options.session) {
  248. if (!(options.session instanceof Session)) { throw new TypeError('`session` should be an instance of the Session class'); }
  249. urlLoaderOptions.session = options.session;
  250. } else if (options.partition) {
  251. if (typeof options.partition === 'string') {
  252. urlLoaderOptions.partition = options.partition;
  253. } else {
  254. throw new TypeError('`partition` should be a string');
  255. }
  256. }
  257. return urlLoaderOptions;
  258. }
  259. export class ClientRequest extends Writable implements Electron.ClientRequest {
  260. _started: boolean = false;
  261. _firstWrite: boolean = false;
  262. _aborted: boolean = false;
  263. _chunkedEncoding: boolean | undefined;
  264. _body: Writable | undefined;
  265. _urlLoaderOptions: NodeJS.CreateURLLoaderOptions & { headers: Record<string, { name: string, value: string | string[] }> };
  266. _redirectPolicy: RedirectPolicy;
  267. _followRedirectCb?: () => void;
  268. _uploadProgress?: { active: boolean, started: boolean, current: number, total: number };
  269. _urlLoader?: NodeJS.URLLoader;
  270. _response?: IncomingMessage;
  271. constructor (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
  272. super({ autoDestroy: true });
  273. if (!app.isReady()) {
  274. throw new Error('net module can only be used after app is ready');
  275. }
  276. if (callback) {
  277. this.once('response', callback);
  278. }
  279. const { redirectPolicy, ...urlLoaderOptions } = parseOptions(options);
  280. const urlObj = new URL(urlLoaderOptions.url);
  281. if (!urlLoaderOptions.allowNonHttpProtocols && !kHttpProtocols.has(urlObj.protocol)) {
  282. throw new Error('ClientRequest only supports http: and https: protocols');
  283. }
  284. if (urlLoaderOptions.credentials === 'same-origin' && !urlLoaderOptions.origin) { throw new Error('credentials: same-origin requires origin to be set'); }
  285. this._urlLoaderOptions = urlLoaderOptions;
  286. this._redirectPolicy = redirectPolicy;
  287. }
  288. get chunkedEncoding () {
  289. return this._chunkedEncoding || false;
  290. }
  291. set chunkedEncoding (value: boolean) {
  292. if (this._started) {
  293. throw new Error('chunkedEncoding can only be set before the request is started');
  294. }
  295. if (typeof this._chunkedEncoding !== 'undefined') {
  296. throw new Error('chunkedEncoding can only be set once');
  297. }
  298. this._chunkedEncoding = !!value;
  299. if (this._chunkedEncoding) {
  300. this._body = new ChunkedBodyStream(this);
  301. this._urlLoaderOptions.body = (pipe: NodeJS.DataPipe) => {
  302. (this._body! as ChunkedBodyStream).startReading(pipe);
  303. };
  304. }
  305. }
  306. setHeader (name: string, value: string) {
  307. if (typeof name !== 'string') {
  308. throw new TypeError('`name` should be a string in setHeader(name, value)');
  309. }
  310. if (value == null) {
  311. throw new Error('`value` required in setHeader("' + name + '", value)');
  312. }
  313. if (this._started || this._firstWrite) {
  314. throw new Error('Can\'t set headers after they are sent');
  315. }
  316. if (!isValidHeaderName(name)) {
  317. throw new Error(`Invalid header name: '${name}'`);
  318. }
  319. if (!isValidHeaderValue(value.toString())) {
  320. throw new Error(`Invalid value for header '${name}': '${value}'`);
  321. }
  322. const key = name.toLowerCase();
  323. this._urlLoaderOptions.headers[key] = { name, value };
  324. }
  325. getHeader (name: string) {
  326. if (name == null) {
  327. throw new Error('`name` is required for getHeader(name)');
  328. }
  329. const key = name.toLowerCase();
  330. const header = this._urlLoaderOptions.headers[key];
  331. return header && header.value as any;
  332. }
  333. removeHeader (name: string) {
  334. if (name == null) {
  335. throw new Error('`name` is required for removeHeader(name)');
  336. }
  337. if (this._started || this._firstWrite) {
  338. throw new Error('Can\'t remove headers after they are sent');
  339. }
  340. const key = name.toLowerCase();
  341. delete this._urlLoaderOptions.headers[key];
  342. }
  343. _write (chunk: Buffer, encoding: BufferEncoding, callback: () => void) {
  344. this._firstWrite = true;
  345. if (!this._body) {
  346. this._body = new SlurpStream();
  347. this._body.on('finish', () => {
  348. this._urlLoaderOptions.body = (this._body as SlurpStream).data();
  349. this._startRequest();
  350. });
  351. }
  352. // TODO: is this the right way to forward to another stream?
  353. this._body.write(chunk, encoding, callback);
  354. }
  355. _final (callback: () => void) {
  356. if (this._body) {
  357. // TODO: is this the right way to forward to another stream?
  358. this._body.end(callback);
  359. } else {
  360. // end() called without a body, go ahead and start the request
  361. this._startRequest();
  362. callback();
  363. }
  364. }
  365. _startRequest () {
  366. this._started = true;
  367. const stringifyValues = (obj: Record<string, { name: string, value: string | string[] }>) => {
  368. const ret: Record<string, string> = {};
  369. for (const k of Object.keys(obj)) {
  370. const kv = obj[k];
  371. ret[kv.name] = kv.value.toString();
  372. }
  373. return ret;
  374. };
  375. this._urlLoaderOptions.referrer = this.getHeader('referer') || '';
  376. this._urlLoaderOptions.origin = this._urlLoaderOptions.origin || this.getHeader('origin') || '';
  377. this._urlLoaderOptions.hasUserActivation = this.getHeader('sec-fetch-user') === '?1';
  378. this._urlLoaderOptions.mode = this.getHeader('sec-fetch-mode') || '';
  379. this._urlLoaderOptions.destination = this.getHeader('sec-fetch-dest') || '';
  380. const opts = { ...this._urlLoaderOptions, extraHeaders: stringifyValues(this._urlLoaderOptions.headers) };
  381. this._urlLoader = createURLLoader(opts);
  382. this._urlLoader.on('response-started', (event, finalUrl, responseHead) => {
  383. const response = this._response = new IncomingMessage(responseHead);
  384. this.emit('response', response);
  385. });
  386. this._urlLoader.on('data', (event, data, resume) => {
  387. this._response!._storeInternalData(Buffer.from(data), resume);
  388. });
  389. this._urlLoader.on('complete', () => {
  390. if (this._response) { this._response._storeInternalData(null, null); }
  391. });
  392. this._urlLoader.on('error', (event, netErrorString) => {
  393. const error = new Error(netErrorString);
  394. if (this._response) this._response.destroy(error);
  395. this._die(error);
  396. });
  397. this._urlLoader.on('login', (event, authInfo, callback) => {
  398. const handled = this.emit('login', authInfo, callback);
  399. if (!handled) {
  400. // If there were no listeners, cancel the authentication request.
  401. callback();
  402. }
  403. });
  404. this._urlLoader.on('redirect', (event, redirectInfo, headers) => {
  405. const { statusCode, newMethod, newUrl } = redirectInfo;
  406. if (this._redirectPolicy === 'error') {
  407. this._die(new Error('Attempted to redirect, but redirect policy was \'error\''));
  408. } else if (this._redirectPolicy === 'manual') {
  409. let _followRedirect = false;
  410. this._followRedirectCb = () => { _followRedirect = true; };
  411. try {
  412. this.emit('redirect', statusCode, newMethod, newUrl, headers);
  413. } finally {
  414. this._followRedirectCb = undefined;
  415. if (!_followRedirect && !this._aborted) {
  416. this._die(new Error('Redirect was cancelled'));
  417. }
  418. }
  419. } else if (this._redirectPolicy === 'follow') {
  420. // Calling followRedirect() when the redirect policy is 'follow' is
  421. // allowed but does nothing. (Perhaps it should throw an error
  422. // though...? Since the redirect will happen regardless.)
  423. try {
  424. this._followRedirectCb = () => {};
  425. this.emit('redirect', statusCode, newMethod, newUrl, headers);
  426. } finally {
  427. this._followRedirectCb = undefined;
  428. }
  429. } else {
  430. this._die(new Error(`Unexpected redirect policy '${this._redirectPolicy}'`));
  431. }
  432. });
  433. this._urlLoader.on('upload-progress', (event, position, total) => {
  434. this._uploadProgress = { active: true, started: true, current: position, total };
  435. this.emit('upload-progress', position, total); // Undocumented, for now
  436. });
  437. this._urlLoader.on('download-progress', (event, current) => {
  438. if (this._response) {
  439. this._response.emit('download-progress', current); // Undocumented, for now
  440. }
  441. });
  442. }
  443. followRedirect () {
  444. if (this._followRedirectCb) {
  445. this._followRedirectCb();
  446. } else {
  447. throw new Error('followRedirect() called, but was not waiting for a redirect');
  448. }
  449. }
  450. abort () {
  451. if (!this._aborted) {
  452. process.nextTick(() => { this.emit('abort'); });
  453. }
  454. this._aborted = true;
  455. this._die();
  456. }
  457. _die (err?: Error) {
  458. // Node.js assumes that any stream which is ended is no longer capable of emitted events
  459. // which is a faulty assumption for the case of an object that is acting like a stream
  460. // (our urlRequest). If we don't emit here, this causes errors since we *do* expect
  461. // that error events can be emitted after urlRequest.end().
  462. if ((this as any)._writableState.destroyed && err) {
  463. this.emit('error', err);
  464. }
  465. this.destroy(err);
  466. if (this._urlLoader) {
  467. this._urlLoader.cancel();
  468. if (this._response) this._response.destroy(err);
  469. }
  470. }
  471. getUploadProgress (): UploadProgress {
  472. return this._uploadProgress ? { ...this._uploadProgress } : { active: false, started: false, current: 0, total: 0 };
  473. }
  474. }