| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450 |
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.createHttpError = createHttpError;
- exports.parseJson = parseJson;
- exports.configureRequestOptionsFromUrl = configureRequestOptionsFromUrl;
- exports.safeGetHeader = safeGetHeader;
- exports.configureRequestOptions = configureRequestOptions;
- exports.safeStringifyJson = safeStringifyJson;
- exports.DigestTransform = exports.HttpExecutor = exports.HttpError = void 0;
- function _crypto() {
- const data = require("crypto");
- _crypto = function () {
- return data;
- };
- return data;
- }
- var _debug2 = _interopRequireDefault(require("debug"));
- function _fsExtraP() {
- const data = require("fs-extra-p");
- _fsExtraP = function () {
- return data;
- };
- return data;
- }
- function _stream() {
- const data = require("stream");
- _stream = function () {
- return data;
- };
- return data;
- }
- function _url() {
- const data = require("url");
- _url = function () {
- return data;
- };
- return data;
- }
- function _CancellationToken() {
- const data = require("./CancellationToken");
- _CancellationToken = function () {
- return data;
- };
- return data;
- }
- function _index() {
- const data = require("./index");
- _index = function () {
- return data;
- };
- return data;
- }
- function _ProgressCallbackTransform() {
- const data = require("./ProgressCallbackTransform");
- _ProgressCallbackTransform = function () {
- return data;
- };
- return data;
- }
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- const debug = (0, _debug2.default)("electron-builder");
- function createHttpError(response, description = null) {
- return new HttpError(response.statusCode || -1, `${response.statusCode} ${response.statusMessage}` + (description == null ? "" : "\n" + JSON.stringify(description, null, " ")) + "\nHeaders: " + safeStringifyJson(response.headers), description);
- }
- const HTTP_STATUS_CODES = new Map([[429, "Too many requests"], [400, "Bad request"], [403, "Forbidden"], [404, "Not found"], [405, "Method not allowed"], [406, "Not acceptable"], [408, "Request timeout"], [413, "Request entity too large"], [500, "Internal server error"], [502, "Bad gateway"], [503, "Service unavailable"], [504, "Gateway timeout"], [505, "HTTP version not supported"]]);
- class HttpError extends Error {
- constructor(statusCode, message = `HTTP error: ${HTTP_STATUS_CODES.get(statusCode) || statusCode}`, description = null) {
- super(message);
- this.statusCode = statusCode;
- this.description = description;
- this.name = "HttpError";
- }
- }
- exports.HttpError = HttpError;
- function parseJson(result) {
- return result.then(it => it == null || it.length === 0 ? null : JSON.parse(it));
- }
- class HttpExecutor {
- constructor() {
- this.maxRedirects = 10;
- }
- request(options, cancellationToken = new (_CancellationToken().CancellationToken)(), data) {
- configureRequestOptions(options);
- const encodedData = data == null ? undefined : Buffer.from(JSON.stringify(data));
- if (encodedData != null) {
- options.method = "post";
- options.headers["Content-Type"] = "application/json";
- options.headers["Content-Length"] = encodedData.length;
- }
- return this.doApiRequest(options, cancellationToken, it => it.end(encodedData));
- }
- doApiRequest(options, cancellationToken, requestProcessor, redirectCount = 0) {
- if (debug.enabled) {
- debug(`Request: ${safeStringifyJson(options)}`);
- }
- return cancellationToken.createPromise((resolve, reject, onCancel) => {
- const request = this.doRequest(options, response => {
- try {
- this.handleResponse(response, options, cancellationToken, resolve, reject, redirectCount, requestProcessor);
- } catch (e) {
- reject(e);
- }
- });
- this.addErrorAndTimeoutHandlers(request, reject);
- this.addRedirectHandlers(request, options, reject, redirectCount, options => {
- this.doApiRequest(options, cancellationToken, requestProcessor, redirectCount).then(resolve).catch(reject);
- });
- requestProcessor(request, reject);
- onCancel(() => request.abort());
- });
- } // noinspection JSUnusedLocalSymbols
- addRedirectHandlers(request, options, reject, redirectCount, handler) {// not required for NodeJS
- }
- addErrorAndTimeoutHandlers(request, reject) {
- this.addTimeOutHandler(request, reject);
- request.on("error", reject);
- request.on("aborted", () => {
- reject(new Error("Request has been aborted by the server"));
- });
- }
- handleResponse(response, options, cancellationToken, resolve, reject, redirectCount, requestProcessor) {
- if (debug.enabled) {
- debug(`Response: ${response.statusCode} ${response.statusMessage}, request options: ${safeStringifyJson(options)}`);
- } // we handle any other >= 400 error on request end (read detailed message in the response body)
- if (response.statusCode === 404) {
- // error is clear, we don't need to read detailed error description
- reject(createHttpError(response, `method: ${options.method} url: ${options.protocol || "https:"}//${options.hostname}${options.path}
- Please double check that your authentication token is correct. Due to security reasons actual status maybe not reported, but 404.
- `));
- return;
- } else if (response.statusCode === 204) {
- // on DELETE request
- resolve();
- return;
- }
- const redirectUrl = safeGetHeader(response, "location");
- if (redirectUrl != null) {
- if (redirectCount > 10) {
- reject(new Error("Too many redirects (> 10)"));
- return;
- }
- this.doApiRequest(HttpExecutor.prepareRedirectUrlOptions(redirectUrl, options), cancellationToken, requestProcessor, redirectCount).then(resolve).catch(reject);
- return;
- }
- let data = "";
- response.setEncoding("utf8");
- response.on("data", chunk => data += chunk);
- response.on("end", () => {
- try {
- if (response.statusCode != null && response.statusCode >= 400) {
- const contentType = safeGetHeader(response, "content-type");
- const isJson = contentType != null && (Array.isArray(contentType) ? contentType.find(it => it.includes("json")) != null : contentType.includes("json"));
- reject(createHttpError(response, isJson ? JSON.parse(data) : data));
- } else {
- resolve(data.length === 0 ? null : data);
- }
- } catch (e) {
- reject(e);
- }
- });
- }
- doDownload(requestOptions, destination, redirectCount, options, callback, onCancel) {
- const request = this.doRequest(requestOptions, response => {
- if (response.statusCode >= 400) {
- callback(new Error(`Cannot download "${requestOptions.protocol || "https:"}//${requestOptions.hostname}${requestOptions.path}", status ${response.statusCode}: ${response.statusMessage}`));
- return;
- }
- const redirectUrl = safeGetHeader(response, "location");
- if (redirectUrl != null) {
- if (redirectCount < this.maxRedirects) {
- this.doDownload(HttpExecutor.prepareRedirectUrlOptions(redirectUrl, requestOptions), destination, redirectCount++, options, callback, onCancel);
- } else {
- callback(new Error(`Too many redirects (> ${this.maxRedirects})`));
- }
- return;
- }
- configurePipes(options, response, destination, callback, options.cancellationToken);
- });
- this.addErrorAndTimeoutHandlers(request, callback);
- this.addRedirectHandlers(request, requestOptions, callback, redirectCount, requestOptions => {
- this.doDownload(requestOptions, destination, redirectCount++, options, callback, onCancel);
- });
- onCancel(() => request.abort());
- request.end();
- }
- addTimeOutHandler(request, callback) {
- request.on("socket", socket => {
- socket.setTimeout(60 * 1000, () => {
- callback(new Error("Request timed out"));
- request.abort();
- });
- });
- }
- static prepareRedirectUrlOptions(redirectUrl, options) {
- const newOptions = configureRequestOptionsFromUrl(redirectUrl, Object.assign({}, options));
- if (newOptions.headers != null && newOptions.headers.Authorization != null && newOptions.headers.Authorization.startsWith("token")) {
- const parsedNewUrl = new (_url().URL)(redirectUrl);
- if (parsedNewUrl.hostname.endsWith(".amazonaws.com")) {
- delete newOptions.headers.Authorization;
- }
- }
- return newOptions;
- }
- }
- exports.HttpExecutor = HttpExecutor;
- function configureRequestOptionsFromUrl(url, options) {
- const parsedUrl = (0, _url().parse)(url);
- options.protocol = parsedUrl.protocol;
- options.hostname = parsedUrl.hostname;
- if (parsedUrl.port == null) {
- if (options.port != null) {
- delete options.port;
- }
- } else {
- options.port = parsedUrl.port;
- }
- options.path = parsedUrl.path;
- return configureRequestOptions(options);
- }
- class DigestTransform extends _stream().Transform {
- constructor(expected, algorithm = "sha512", encoding = "base64") {
- super();
- this.expected = expected;
- this.algorithm = algorithm;
- this.encoding = encoding;
- this._actual = null;
- this.isValidateOnEnd = true;
- this.digester = (0, _crypto().createHash)(algorithm);
- } // noinspection JSUnusedGlobalSymbols
- get actual() {
- return this._actual;
- } // noinspection JSUnusedGlobalSymbols
- _transform(chunk, encoding, callback) {
- this.digester.update(chunk);
- callback(null, chunk);
- } // noinspection JSUnusedGlobalSymbols
- _flush(callback) {
- this._actual = this.digester.digest(this.encoding);
- if (this.isValidateOnEnd) {
- try {
- this.validate();
- } catch (e) {
- callback(e);
- return;
- }
- }
- callback(null);
- }
- validate() {
- if (this._actual == null) {
- throw (0, _index().newError)("Not finished yet", "ERR_STREAM_NOT_FINISHED");
- }
- if (this._actual !== this.expected) {
- throw (0, _index().newError)(`${this.algorithm} checksum mismatch, expected ${this.expected}, got ${this._actual}`, "ERR_CHECKSUM_MISMATCH");
- }
- return null;
- }
- }
- exports.DigestTransform = DigestTransform;
- function checkSha2(sha2Header, sha2, callback) {
- if (sha2Header != null && sha2 != null) {
- // todo why bintray doesn't send this header always
- if (sha2Header == null) {
- callback(new Error("checksum is required, but server response doesn't contain X-Checksum-Sha2 header"));
- return false;
- } else if (sha2Header !== sha2) {
- callback(new Error(`checksum mismatch: expected ${sha2} but got ${sha2Header} (X-Checksum-Sha2 header)`));
- return false;
- }
- }
- return true;
- }
- function safeGetHeader(response, headerKey) {
- const value = response.headers[headerKey];
- if (value == null) {
- return null;
- } else if (Array.isArray(value)) {
- // electron API
- return value.length === 0 ? null : value[value.length - 1];
- } else {
- return value;
- }
- }
- function configurePipes(options, response, destination, callback, cancellationToken) {
- if (!checkSha2(safeGetHeader(response, "X-Checksum-Sha2"), options.sha2, callback)) {
- return;
- }
- const streams = [];
- if (options.onProgress != null) {
- const contentLength = safeGetHeader(response, "content-length");
- if (contentLength != null) {
- streams.push(new (_ProgressCallbackTransform().ProgressCallbackTransform)(parseInt(contentLength, 10), options.cancellationToken, options.onProgress));
- }
- }
- const sha512 = options.sha512;
- if (sha512 != null) {
- streams.push(new DigestTransform(sha512, "sha512", sha512.length === 128 && !sha512.includes("+") && !sha512.includes("Z") && !sha512.includes("=") ? "hex" : "base64"));
- } else if (options.sha2 != null) {
- streams.push(new DigestTransform(options.sha2, "sha256", "hex"));
- }
- const fileOut = (0, _fsExtraP().createWriteStream)(destination);
- streams.push(fileOut);
- let lastStream = response;
- for (const stream of streams) {
- stream.on("error", error => {
- if (!cancellationToken.cancelled) {
- callback(error);
- }
- });
- lastStream = lastStream.pipe(stream);
- }
- fileOut.on("finish", () => {
- fileOut.close(callback);
- });
- }
- function configureRequestOptions(options, token, method) {
- if (method != null) {
- options.method = method;
- }
- let headers = options.headers;
- if (headers == null) {
- headers = {};
- options.headers = headers;
- }
- if (token != null) {
- headers.authorization = token.startsWith("Basic") ? token : `token ${token}`;
- }
- if (headers["User-Agent"] == null) {
- headers["User-Agent"] = "electron-builder";
- }
- if (method == null || method === "GET" || headers["Cache-Control"] == null) {
- headers["Cache-Control"] = "no-cache";
- } // do not specify for node (in any case we use https module)
- if (options.protocol == null && process.versions.electron != null) {
- options.protocol = "https:";
- }
- return options;
- }
- function safeStringifyJson(data, skippedNames) {
- return JSON.stringify(data, (name, value) => {
- if (name.endsWith("authorization") || name.endsWith("Password") || name.endsWith("PASSWORD") || name.endsWith("Token") || name.includes("password") || name.includes("token") || skippedNames != null && skippedNames.has(name)) {
- return "<stripped sensitive data>";
- }
- return value;
- }, 2);
- }
- //# sourceMappingURL=httpExecutor.js.map
|