xhr-utils.js
13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"use strict";
const fs = require("fs");
const { EventEmitter } = require("events");
const { URL } = require("whatwg-url");
const parseDataURL = require("data-urls");
const DOMException = require("domexception/webidl2js-wrapper");
const ProgressEvent = require("../generated/ProgressEvent");
const agentFactory = require("../helpers/agent-factory");
const Request = require("../helpers/http-request");
const FormData = require("form-data");
const { fireAnEvent } = require("../helpers/events");
const headerListSeparatorRegexp = /,[ \t]*/;
const simpleMethods = new Set(["GET", "HEAD", "POST"]);
const simpleHeaders = new Set(["accept", "accept-language", "content-language", "content-type"]);
const preflightHeaders = new Set([
"access-control-expose-headers",
"access-control-allow-headers",
"access-control-allow-credentials",
"access-control-allow-origin"
]);
const READY_STATES = exports.READY_STATES = Object.freeze({
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
});
function getRequestHeader(requestHeaders, header) {
const lcHeader = header.toLowerCase();
const keys = Object.keys(requestHeaders);
let n = keys.length;
while (n--) {
const key = keys[n];
if (key.toLowerCase() === lcHeader) {
return requestHeaders[key];
}
}
return null;
}
function updateRequestHeader(requestHeaders, header, newValue) {
const lcHeader = header.toLowerCase();
const keys = Object.keys(requestHeaders);
let n = keys.length;
while (n--) {
const key = keys[n];
if (key.toLowerCase() === lcHeader) {
requestHeaders[key] = newValue;
}
}
}
function dispatchError(xhr) {
const errMessage = xhr.properties.error;
requestErrorSteps(xhr, "error", DOMException.create(xhr._globalObject, [errMessage, "NetworkError"]));
if (xhr._ownerDocument) {
const error = new Error(errMessage);
error.type = "XMLHttpRequest"; // TODO this should become "resource loading" when XHR goes through resource loader
xhr._ownerDocument._defaultView._virtualConsole.emit("jsdomError", error);
}
}
function validCORSHeaders(xhr, response, flag, properties, origin) {
const acaoStr = response.headers["access-control-allow-origin"];
const acao = acaoStr ? acaoStr.trim() : null;
if (acao !== "*" && acao !== origin) {
properties.error = "Cross origin " + origin + " forbidden";
dispatchError(xhr);
return false;
}
const acacStr = response.headers["access-control-allow-credentials"];
const acac = acacStr ? acacStr.trim() : null;
if (flag.withCredentials && acac !== "true") {
properties.error = "Credentials forbidden";
dispatchError(xhr);
return false;
}
return true;
}
function validCORSPreflightHeaders(xhr, response, flag, properties) {
if (!validCORSHeaders(xhr, response, flag, properties, properties.origin)) {
return false;
}
const acahStr = response.headers["access-control-allow-headers"];
const acah = new Set(acahStr ? acahStr.trim().toLowerCase().split(headerListSeparatorRegexp) : []);
const forbiddenHeaders = acah.has("*") ?
[] :
Object.keys(flag.requestHeaders).filter(header => {
const lcHeader = header.toLowerCase();
return !simpleHeaders.has(lcHeader) && !acah.has(lcHeader);
});
if (forbiddenHeaders.length > 0) {
properties.error = "Headers " + forbiddenHeaders + " forbidden";
dispatchError(xhr);
return false;
}
return true;
}
function requestErrorSteps(xhr, event, exception) {
const { flag, properties, upload } = xhr;
xhr.readyState = READY_STATES.DONE;
properties.send = false;
setResponseToNetworkError(xhr);
if (flag.synchronous) {
throw exception;
}
fireAnEvent("readystatechange", xhr);
if (!properties.uploadComplete) {
properties.uploadComplete = true;
if (properties.uploadListener) {
fireAnEvent(event, upload, ProgressEvent, { loaded: 0, total: 0, lengthComputable: false });
fireAnEvent("loadend", upload, ProgressEvent, { loaded: 0, total: 0, lengthComputable: false });
}
}
fireAnEvent(event, xhr, ProgressEvent, { loaded: 0, total: 0, lengthComputable: false });
fireAnEvent("loadend", xhr, ProgressEvent, { loaded: 0, total: 0, lengthComputable: false });
}
function setResponseToNetworkError(xhr) {
const { properties } = xhr;
properties.responseBuffer =
properties.responseCache =
properties.responseTextCache =
properties.responseXMLCache = null;
properties.responseHeaders = {};
xhr.status = 0;
xhr.statusText = "";
}
// return a "request" client object or an event emitter matching the same behaviour for unsupported protocols
// the callback should be called with a "request" response object or an event emitter matching the same behaviour too
function createClient(xhr) {
const { flag, properties } = xhr;
const urlObj = new URL(flag.uri);
const uri = urlObj.href;
const ucMethod = flag.method.toUpperCase();
const { requestManager } = flag;
if (urlObj.protocol === "file:") {
const response = new EventEmitter();
response.statusCode = 200;
response.rawHeaders = [];
response.headers = {};
const filePath = urlObj.pathname
.replace(/^file:\/\//, "")
.replace(/^\/([a-z]):\//i, "$1:/")
.replace(/%20/g, " ");
const client = new EventEmitter();
const readableStream = fs.createReadStream(filePath, { encoding: null });
readableStream.on("data", chunk => {
response.emit("data", chunk);
client.emit("data", chunk);
});
readableStream.on("end", () => {
response.emit("end");
client.emit("end");
});
readableStream.on("error", err => {
client.emit("error", err);
});
client.abort = function () {
readableStream.destroy();
client.emit("abort");
};
if (requestManager) {
const req = {
abort() {
properties.abortError = true;
xhr.abort();
}
};
requestManager.add(req);
const rmReq = requestManager.remove.bind(requestManager, req);
client.on("abort", rmReq);
client.on("error", rmReq);
client.on("end", rmReq);
}
process.nextTick(() => client.emit("response", response, urlObj.href));
return client;
}
if (urlObj.protocol === "data:") {
const response = new EventEmitter();
const client = new EventEmitter();
let buffer;
try {
const parsed = parseDataURL(uri);
const contentType = parsed.mimeType.toString();
buffer = Buffer.from(parsed.body);
response.statusCode = 200;
response.rawHeaders = ["Content-Type", contentType];
response.headers = { "content-type": contentType };
} catch (err) {
process.nextTick(() => client.emit("error", err));
return client;
}
client.abort = () => {
// do nothing
};
process.nextTick(() => {
client.emit("response", response, urlObj.href);
process.nextTick(() => {
response.emit("data", buffer);
client.emit("data", buffer);
response.emit("end");
client.emit("end");
});
});
return client;
}
const agents = agentFactory(flag.proxy, flag.strictSSL);
const requestHeaders = {};
for (const header in flag.requestHeaders) {
requestHeaders[header] = flag.requestHeaders[header];
}
if (getRequestHeader(flag.requestHeaders, "referer") === null) {
requestHeaders.Referer = flag.referrer;
}
if (getRequestHeader(flag.requestHeaders, "user-agent") === null) {
requestHeaders["User-Agent"] = flag.userAgent;
}
if (getRequestHeader(flag.requestHeaders, "accept-language") === null) {
requestHeaders["Accept-Language"] = "en";
}
if (getRequestHeader(flag.requestHeaders, "accept") === null) {
requestHeaders.Accept = "*/*";
}
const crossOrigin = flag.origin !== urlObj.origin;
if (crossOrigin) {
requestHeaders.Origin = flag.origin;
}
const options = { rejectUnauthorized: flag.strictSSL, agents, followRedirects: true };
if (flag.auth) {
options.user = flag.auth.user || "";
options.pass = flag.auth.pass || "";
}
if (flag.cookieJar && (!crossOrigin || flag.withCredentials)) {
options.cookieJar = flag.cookieJar;
}
const { body } = flag;
const hasBody = body !== undefined &&
body !== null &&
body !== "" &&
!(ucMethod === "HEAD" || ucMethod === "GET");
if (hasBody && getRequestHeader(flag.requestHeaders, "content-type") === null) {
requestHeaders["Content-Type"] = "text/plain;charset=UTF-8";
}
function doRequest() {
try {
let requestBody = body;
let len = 0;
if (hasBody) {
if (flag.formData) {
// TODO: implement https://html.spec.whatwg.org/#multipart-form-data
// directly instead of using an external library
requestBody = new FormData();
for (const entry of body) {
requestBody.append(entry.name, entry.value, entry.options);
}
len = requestBody.getLengthSync();
requestHeaders["Content-Type"] = `multipart/form-data; boundary=${requestBody.getBoundary()}`;
} else {
if (typeof body === "string") {
len = Buffer.byteLength(body);
} else {
len = body.length;
}
requestBody = Buffer.isBuffer(requestBody) ? requestBody : Buffer.from(requestBody);
}
requestHeaders["Content-Length"] = len;
}
requestHeaders["Accept-Encoding"] = "gzip, deflate";
const requestClient = new Request(uri, options, { method: flag.method, headers: requestHeaders });
if (hasBody) {
if (flag.formData) {
requestBody.on("error", err => {
requestClient.emit("error", err);
requestClient.abort();
});
requestClient.pipeRequest(requestBody);
} else {
requestClient.write(requestBody);
}
}
return requestClient;
} catch (e) {
const eventEmitterclient = new EventEmitter();
process.nextTick(() => eventEmitterclient.emit("error", e));
eventEmitterclient.end = () => {};
return eventEmitterclient;
}
}
let client;
const nonSimpleHeaders = Object.keys(flag.requestHeaders)
.filter(header => !simpleHeaders.has(header.toLowerCase()));
if (crossOrigin && (!simpleMethods.has(ucMethod) || nonSimpleHeaders.length > 0 || properties.uploadListener)) {
client = new EventEmitter();
const preflightRequestHeaders = {};
for (const header in requestHeaders) {
// the only existing request headers the cors spec allows on the preflight request are Origin and Referer
const lcHeader = header.toLowerCase();
if (lcHeader === "origin" || lcHeader === "referer") {
preflightRequestHeaders[header] = requestHeaders[header];
}
}
preflightRequestHeaders["Access-Control-Request-Method"] = flag.method;
if (nonSimpleHeaders.length > 0) {
preflightRequestHeaders["Access-Control-Request-Headers"] = nonSimpleHeaders.join(", ");
}
preflightRequestHeaders["User-Agent"] = flag.userAgent;
flag.preflight = true;
const rejectUnauthorized = flag.strictSSL;
const preflightClient = new Request(
uri,
{ agents, followRedirects: false },
{ method: "OPTIONS", headers: preflightRequestHeaders, rejectUnauthorized }
);
preflightClient.on("response", resp => {
// don't send the real request if the preflight request returned an error
if (resp.statusCode < 200 || resp.statusCode > 299) {
client.emit("error", new Error("Response for preflight has invalid HTTP status code " + resp.statusCode));
return;
}
// don't send the real request if we aren't allowed to use the headers
if (!validCORSPreflightHeaders(xhr, resp, flag, properties)) {
setResponseToNetworkError(xhr);
return;
}
// Set request gzip option right before headers are set
const realClient = doRequest();
realClient.on("response", (...args) => client.emit("response", ...args));
realClient.on("data", chunk => client.emit("data", chunk));
realClient.on("end", () => client.emit("end"));
realClient.on("abort", () => client.emit("abort"));
realClient.on("request", req => {
client.headers = realClient.headers;
client.emit("request", req);
});
realClient.on("redirect", (...args) => {
client.emit("redirect", ...args);
});
realClient.on("error", err => {
client.emit("error", err);
});
client.abort = () => {
realClient.abort();
};
setImmediate(() => realClient.end());
});
preflightClient.on("error", err => {
client.emit("error", err);
});
client.abort = () => {
preflightClient.abort();
};
setImmediate(() => preflightClient.end());
} else {
client = doRequest();
setImmediate(() => client.end());
}
if (requestManager) {
const req = {
abort() {
properties.abortError = true;
xhr.abort();
}
};
requestManager.add(req);
const rmReq = requestManager.remove.bind(requestManager, req);
client.on("abort", rmReq);
client.on("error", rmReq);
client.on("end", rmReq);
}
return client;
}
exports.headerListSeparatorRegexp = headerListSeparatorRegexp;
exports.simpleHeaders = simpleHeaders;
exports.preflightHeaders = preflightHeaders;
exports.getRequestHeader = getRequestHeader;
exports.updateRequestHeader = updateRequestHeader;
exports.dispatchError = dispatchError;
exports.validCORSHeaders = validCORSHeaders;
exports.requestErrorSteps = requestErrorSteps;
exports.setResponseToNetworkError = setResponseToNetworkError;
exports.createClient = createClient;