net-client-request.ts 18 KB

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