|
| 1 | +import axios from "axios"; |
| 2 | +import { writeFile } from "fs/promises"; |
| 3 | +import Papa from "papaparse"; |
| 4 | + |
| 5 | +const INTERMEDIATE_CA_URL = |
| 6 | + "https://ccadb.my.salesforce-sites.com/mozilla/PublicAllIntermediateCertsWithPEMCSV"; |
| 7 | + |
| 8 | +const ROOT_CA_URL = |
| 9 | + "https://ccadb.my.salesforce-sites.com/mozilla/IncludedCACertificateReportPEMCSV"; |
| 10 | + |
| 11 | +/** |
| 12 | + * @param {string} url |
| 13 | + * @returns {Promise<string[]>} |
| 14 | + */ |
| 15 | +async function downloadCertificates(url) { |
| 16 | + let r; |
| 17 | + try { |
| 18 | + r = await axios.get(url); |
| 19 | + } catch (error) { |
| 20 | + throw Error(`Failed to get data: ${error}`); |
| 21 | + } |
| 22 | + |
| 23 | + const data = Papa.parse(r.data, { header: true }).data; |
| 24 | + const output = []; |
| 25 | + for (const entry of data) { |
| 26 | + // Remove quotes from beginning and end of certificate |
| 27 | + const certPem = entry["PEM Info"].slice(1, -1); |
| 28 | + const commonName = entry["Common Name or Certificate Name"]; |
| 29 | + output.push(`${commonName}\n${certPem}`); |
| 30 | + } |
| 31 | + return output; |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * @returns {Promise<string>} |
| 36 | + */ |
| 37 | +async function retrieveCABundle() { |
| 38 | + // Download at the same time |
| 39 | + const values = await Promise.all([ |
| 40 | + downloadCertificates(INTERMEDIATE_CA_URL), |
| 41 | + downloadCertificates(ROOT_CA_URL), |
| 42 | + ]); |
| 43 | + |
| 44 | + const intermediateCACerts = values[0]; |
| 45 | + const rootCACerts = values[1]; |
| 46 | + |
| 47 | + const combinedCACerts = intermediateCACerts.concat(rootCACerts); |
| 48 | + return combinedCACerts.join("\n\n"); |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * @param {string} filePath |
| 53 | + */ |
| 54 | +export async function retrieveAndStoreCABundle(filePath) { |
| 55 | + const caBundle = await retrieveCABundle(); |
| 56 | + |
| 57 | + try { |
| 58 | + await writeFile(filePath, caBundle); |
| 59 | + console.log(`Downloaded Mozilla CA bundle and saved it to ${filePath}`); |
| 60 | + } catch (error) { |
| 61 | + console.error("Error writing file:", error); |
| 62 | + return; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * |
| 68 | + * @param {string} filePath |
| 69 | + */ |
| 70 | +export async function setupCABundle(filePath) { |
| 71 | + process.env.NODE_EXTRA_CA_CERTS = filePath; |
| 72 | +} |
0 commit comments