@sonar/scan
Version:
SonarQube/SonarCloud Scanner for the JavaScript world
177 lines (176 loc) • 7.69 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.download = exports.fetch = exports.initializeAxios = exports.resetAxios = exports.getHttpAgents = void 0;
/*
* sonar-scanner-npm
* Copyright (C) 2022-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
const axios_1 = __importDefault(require("axios"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const hpagent_1 = require("hpagent");
const https_1 = __importDefault(require("https"));
const node_forge_1 = __importDefault(require("node-forge"));
const stream = __importStar(require("stream"));
const util_1 = require("util");
const logging_1 = require("./logging");
const proxy_1 = require("./proxy");
const types_1 = require("./types");
const finished = (0, util_1.promisify)(stream.finished);
/**
* Axios instances (private to this module).
* One for sonar host (with auth), one for external requests
*/
let _axiosInstances = null;
async function extractTruststoreCerts(p12Base64, password = '') {
// P12/PFX file -> DER -> ASN.1 -> PKCS12
const der = node_forge_1.default.util.decode64(p12Base64);
const asn1 = node_forge_1.default.asn1.fromDer(der);
const p12 = node_forge_1.default.pkcs12.pkcs12FromAsn1(asn1, password);
// Extract the CA certificates as PEM for Node
const bags = p12.getBags({ bagType: node_forge_1.default.pki.oids.certBag });
const ca = [];
for (const entry of bags[node_forge_1.default.pki.oids.certBag] ?? []) {
if (entry.cert) {
ca.push(node_forge_1.default.pki.certificateToPem(entry.cert));
}
}
(0, logging_1.log)(logging_1.LogLevel.DEBUG, `${ca.length} CA certificates found in truststore`);
return ca;
}
async function getHttpAgents(properties) {
const agents = {};
const proxyUrl = (0, proxy_1.getProxyUrl)(properties);
// Accumulate https agent options
const httpsAgentOptions = {};
// Truststore
const truststorePath = properties[types_1.ScannerProperty.SonarScannerTruststorePath];
if (truststorePath) {
(0, logging_1.log)(logging_1.LogLevel.DEBUG, `Using truststore at ${truststorePath}`);
const p12Base64 = await fs_extra_1.default.promises.readFile(truststorePath, { encoding: 'base64' });
try {
const certs = await extractTruststoreCerts(p12Base64, properties[types_1.ScannerProperty.SonarScannerTruststorePassword]);
httpsAgentOptions.ca = certs;
}
catch (e) {
(0, logging_1.log)(logging_1.LogLevel.WARN, `Failed to load truststore: ${e}`);
}
}
// Key store
const keystorePath = properties[types_1.ScannerProperty.SonarScannerKeystorePath];
if (keystorePath) {
(0, logging_1.log)(logging_1.LogLevel.DEBUG, `Using keystore at ${keystorePath}`);
httpsAgentOptions.pfx = await fs_extra_1.default.promises.readFile(keystorePath);
httpsAgentOptions.passphrase = properties[types_1.ScannerProperty.SonarScannerKeystorePassword] ?? '';
}
if (proxyUrl) {
agents.httpsAgent = new hpagent_1.HttpsProxyAgent({ proxy: proxyUrl.toString(), ...httpsAgentOptions });
agents.httpAgent = new hpagent_1.HttpProxyAgent({ proxy: proxyUrl.toString() });
agents.proxy = false; // SCANNPM-58 Avoid conflicts between axios's proxy option and custom http(s) agents
}
else if (Object.keys(httpsAgentOptions).length > 0) {
// Only create an agent if there are options
agents.httpsAgent = new https_1.default.Agent({ ...httpsAgentOptions });
}
return agents;
}
exports.getHttpAgents = getHttpAgents;
function resetAxios() {
_axiosInstances = null;
}
exports.resetAxios = resetAxios;
async function initializeAxios(properties) {
const token = properties[types_1.ScannerProperty.SonarToken];
const baseURL = properties[types_1.ScannerProperty.SonarScannerApiBaseUrl];
const agents = await getHttpAgents(properties);
const timeout = Math.floor(parseInt(properties[types_1.ScannerProperty.SonarScannerResponseTimeout], 10) || 0) * 1000;
if (!_axiosInstances) {
_axiosInstances = {
internal: axios_1.default.create({
baseURL,
headers: token ? { Authorization: `Bearer ${token}` } : {},
timeout,
...agents,
}),
external: axios_1.default.create({
timeout,
...agents,
}),
};
}
}
exports.initializeAxios = initializeAxios;
function fetch(config) {
if (!_axiosInstances) {
throw new Error('Axios instance is not initialized');
}
// Use external instance for absolute URLs
if (!config.url?.startsWith('/')) {
(0, logging_1.log)(logging_1.LogLevel.DEBUG, `Not using axios instance for ${config.url}`);
return _axiosInstances.external.request(config);
}
return _axiosInstances.internal.request(config);
}
exports.fetch = fetch;
async function download(url, destPath, overrides) {
(0, logging_1.log)(logging_1.LogLevel.DEBUG, `Downloading ${url} to ${destPath}`);
const response = await fetch({
url,
method: 'GET',
responseType: 'stream',
headers: {
Accept: 'application/octet-stream',
},
...overrides,
});
(0, logging_1.log)(logging_1.LogLevel.INFO, 'Download starting...');
response.data.on('end', () => {
(0, logging_1.log)(logging_1.LogLevel.INFO, 'Download complete');
});
const writer = fs_extra_1.default.createWriteStream(destPath);
const streamPipeline = (0, util_1.promisify)(stream.pipeline);
await streamPipeline(response.data, writer);
response.data.pipe(writer);
await finished(writer);
}
exports.download = download;