UNPKG

@citrineos/util

Version:

The OCPP util module which supplies helpful utilities like cache and queue connectors, etc.

191 lines 9.75 kB
"use strict"; // Copyright Contributors to the CitrineOS Project // // SPDX-License-Identifier: Apache 2.0 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Acme = void 0; const acme = __importStar(require("acme-client")); const tslog_1 = require("tslog"); const fs_1 = __importDefault(require("fs")); const CertificateUtil_1 = require("../CertificateUtil"); class Acme { constructor(config, logger, client) { var _a, _b, _c, _d, _e; this._directoryUrl = acme.directory.letsencrypt.staging; this._preferredChain = { name: 'ISRG Root X1', file: 'isrgrootx1', }; // Key: serverId, Value: [cert chain, sub ca private key] this._securityCertChainKeyMap = new Map(); this._logger = logger ? logger.getSubLogger({ name: this.constructor.name }) : new tslog_1.Logger({ name: this.constructor.name }); config.util.networkConnection.websocketServers.forEach((server) => { if (server.securityProfile === 3) { try { this._securityCertChainKeyMap.set(server.id, [ fs_1.default.readFileSync(server.tlsCertificateChainFilePath, 'utf8'), fs_1.default.readFileSync(server.mtlsCertificateAuthorityKeyFilePath, 'utf8'), ]); } catch (error) { this._logger.error('Unable to start Certificates module due to invalid security certificates for {}: {}', server, error); throw error; } } }); this._email = (_a = config.util.certificateAuthority.chargingStationCA.acme) === null || _a === void 0 ? void 0 : _a.email; const accountKey = fs_1.default.readFileSync((_c = (_b = config.util.certificateAuthority.chargingStationCA) === null || _b === void 0 ? void 0 : _b.acme) === null || _c === void 0 ? void 0 : _c.accountKeyFilePath); const acmeEnv = (_e = (_d = config.util.certificateAuthority.chargingStationCA) === null || _d === void 0 ? void 0 : _d.acme) === null || _e === void 0 ? void 0 : _e.env; if (acmeEnv === 'production') { this._directoryUrl = acme.directory.letsencrypt.production; } this._client = client || new acme.Client({ directoryUrl: this._directoryUrl, accountKey: accountKey.toString(), }); } /** * Get LetsEncrypt Root CA certificate, ISRG Root X1. * @return {Promise<string>} The CA certificate pem. */ getRootCACertificate() { return __awaiter(this, void 0, void 0, function* () { const response = yield fetch(`https://letsencrypt.org/certs/${this._preferredChain.file}.pem`); if (!response.ok && response.status !== 304) { throw new Error(`Failed to fetch certificate: ${response.status}: ${yield response.text()}`); } return yield response.text(); }); } /** * Retrieves a signed certificate based on the provided CSR. * The returned certificate will be signed by Let's Encrypt, ISRG Root X1. * which is listed in https://ccadb.my.salesforce-sites.com/mozilla/CAAIdentifiersReport * * @param {string} csrString - The certificate signing request. * @return {Promise<string>} The signed certificate. */ signCertificateByExternalCA(csrString) { return __awaiter(this, void 0, void 0, function* () { var _a; const folderPath = '/usr/local/apps/citrineos/Server/src/assets/.well-known/acme-challenge'; const cert = yield ((_a = this._client) === null || _a === void 0 ? void 0 : _a.auto({ csr: csrString, email: this._email, termsOfServiceAgreed: true, preferredChain: this._preferredChain.name, challengePriority: ['http-01'], skipChallengeVerification: true, challengeCreateFn: (authz, challenge, keyAuthorization) => __awaiter(this, void 0, void 0, function* () { this._logger.debug('Triggered challengeCreateFn()'); const filePath = `${folderPath}/${challenge.token}`; if (!fs_1.default.existsSync(folderPath)) { fs_1.default.mkdirSync(folderPath, { recursive: true }); this._logger.debug(`Directory created: ${folderPath}`); } else { this._logger.debug(`Directory already exists: ${folderPath}`); } const fileContents = keyAuthorization; this._logger.debug(`Creating challenge response ${fileContents} for ${authz.identifier.value} at path: ${filePath}`); fs_1.default.writeFileSync(filePath, fileContents); }), challengeRemoveFn: (_authz, _challenge, _keyAuthorization) => __awaiter(this, void 0, void 0, function* () { this._logger.debug(`Triggered challengeRemoveFn(). Would remove "${folderPath}`); fs_1.default.rmSync(folderPath, { recursive: true, force: true }); }), })); if (!cert) { throw new Error('Failed to get signed certificate'); } this._logger.debug(`Certificate singed by external CA: ${cert}`); return cert; }); } /** * Get sub CA from the certificate chain. * Use it to sign certificate based on the CSR string. * * @param {string} csrString - The Certificate Signing Request (CSR) string. * @return {Promise<string>} - The signed certificate followed by sub CA in PEM format. */ getCertificateChain(csrString) { return __awaiter(this, void 0, void 0, function* () { const nextEntry = this._securityCertChainKeyMap.entries().next().value; if (!nextEntry) { throw new Error('Failed to get certificate chain, securityCertChainKeyMap is empty'); } const [serverId, [certChain, subCAPrivateKey]] = nextEntry; this._logger.debug(`Found certificate chain in server ${serverId}: ${certChain}`); const certChainArray = (0, CertificateUtil_1.parseCertificateChainPem)(certChain); if (certChainArray.length < 2) { throw new Error(`The size of the chain is ${certChainArray.length}. Sub CA certificate for signing not found`); } this._logger.info(`Found Sub CA certificate: ${certChainArray[1]}`); const signedCertPem = (0, CertificateUtil_1.createSignedCertificateFromCSR)(csrString, certChainArray[1], subCAPrivateKey).getPEM(); // Generate and return certificate chain for signed certificate certChainArray[0] = signedCertPem.replace(/\n+$/, ''); return certChainArray.join('\n'); }); } updateCertificateChainKeyMap(serverId, certificateChain, privateKey) { if (this._securityCertChainKeyMap.has(serverId)) { this._securityCertChainKeyMap.set(serverId, [certificateChain, privateKey]); this._logger.info(`Updated certificate chain key map for server ${serverId}`); } else { this._logger.error(`Server ${serverId} not found in the map`); } } } exports.Acme = Acme; //# sourceMappingURL=acme.js.map