sonarqube-scanner
Version:
SonarQube/SonarCloud Scanner for the JavaScript world
183 lines (182 loc) • 7.76 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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__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.getHttpAgents = getHttpAgents;
exports.resetAxios = resetAxios;
exports.initializeAxios = initializeAxios;
exports.fetch = fetch;
exports.download = download;
/*
* sonar-scanner-npm
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* 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 Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
const axios_1 = __importDefault(require("axios"));
const node_fs_1 = __importDefault(require("node:fs"));
const hpagent_1 = require("hpagent");
const node_https_1 = __importDefault(require("node:https"));
const node_forge_1 = __importDefault(require("node-forge"));
const stream = __importStar(require("node:stream"));
const node_util_1 = require("node:util");
const logging_1 = require("./logging");
const proxy_1 = require("./proxy");
const types_1 = require("./types");
const finished = (0, node_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 node_fs_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 node_fs_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 node_https_1.default.Agent({ ...httpsAgentOptions });
}
return agents;
}
function resetAxios() {
_axiosInstances = null;
}
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,
}),
};
}
}
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);
}
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 = node_fs_1.default.createWriteStream(destPath);
const streamPipeline = (0, node_util_1.promisify)(stream.pipeline);
await streamPipeline(response.data, writer);
response.data.pipe(writer);
await finished(writer);
}