UNPKG

@citrineos/util

Version:

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

167 lines 8.06 kB
"use strict"; // Copyright Contributors to the CitrineOS Project // // SPDX-License-Identifier: Apache 2.0 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Hubject = void 0; const tslog_1 = require("tslog"); const CertificateUtil_1 = require("../CertificateUtil"); class Hubject { constructor(config, logger) { if (!config.util.certificateAuthority.v2gCA.hubject) { throw new Error('Missing Hubject configuration'); } this._baseUrl = config.util.certificateAuthority.v2gCA.hubject.baseUrl; this._tokenUrl = config.util.certificateAuthority.v2gCA.hubject.tokenUrl; this._isoVersion = config.util.certificateAuthority.v2gCA.hubject.isoVersion; this._logger = logger ? logger.getSubLogger({ name: this.constructor.name }) : new tslog_1.Logger({ name: this.constructor.name }); } /** * Retrieves a signed certificate based on the provided CSR. * DOC: https://hubject.stoplight.io/docs/open-plugncharge/486f0b8b3ded4-simple-enroll-iso-15118-2-and-iso-15118-20 * * @param {string} csrString - The certificate signing request from SignCertificateRequest. * @return {Promise<string>} The signed certificate without header and footer. */ getSignedCertificate(csrString) { return __awaiter(this, void 0, void 0, function* () { const url = `${this._baseUrl}/cpo/simpleenroll/${this._isoVersion}`; const response = yield fetch(url, { method: 'POST', headers: { Accept: 'application/pkcs10', Authorization: yield this._getAuthorizationToken(this._tokenUrl), 'Content-Type': 'application/pkcs10', }, body: csrString, }); if (response.status !== 200) { throw new Error(`Get signed certificate response is unexpected: ${response.status}: ${yield response.text()}`); } return yield response.text(); }); } /** * Retrieves the CA certificates including sub CAs and root CA. * DOC: https://hubject.stoplight.io/docs/open-plugncharge/e246aa213bc22-obtaining-ca-certificates-iso-15118-2-and-iso-15118-20 * * @return {Promise<string>} The CA certificates. */ getCACertificates() { return __awaiter(this, void 0, void 0, function* () { const url = `${this._baseUrl}/cpo/cacerts/${this._isoVersion}`; const response = yield fetch(url, { method: 'GET', headers: { Accept: 'application/pkcs10, application/pkcs7', Authorization: yield this._getAuthorizationToken(this._tokenUrl), 'Content-Transfer-Encoding': 'application/pkcs10', }, }); if (response.status !== 200) { throw new Error(`Get CA certificates response is unexpected: ${response.status}: ${yield response.text()}`); } return yield response.text(); }); } getSignedContractData(xsdMsgDefNamespace, certificateInstallationReq) { return __awaiter(this, void 0, void 0, function* () { const url = `${this._baseUrl}/v1/ccp/signedContractData`; const response = yield fetch(url, { method: 'POST', headers: { Accept: 'application/json', Authorization: yield this._getAuthorizationToken(this._tokenUrl), 'Content-Type': 'application/json', }, body: JSON.stringify({ certificateInstallationReq: certificateInstallationReq, xsdMsgDefNamespace: xsdMsgDefNamespace, }), }); if (response.status !== 200) { const errorResponse = yield response.text(); this._logger.error(`Unexpected response ${response.status} from Hubject: ${errorResponse}`); let errorMessages = 'Failed to get signed contract data'; if (errorResponse && errorResponse.includes('errorMessages')) { errorMessages = JSON.parse(errorResponse).errorMessages; } throw new Error(errorMessages); } const contractData = JSON.parse(yield response.text()); let certificateInstallationRes; if (contractData.CCPResponse.emaidContent && contractData.CCPResponse.emaidContent.length > 0) { for (const emaidContent of contractData.CCPResponse.emaidContent) { if (emaidContent.messageDef && emaidContent.messageDef.certificateInstallationRes) { certificateInstallationRes = emaidContent.messageDef.certificateInstallationRes; } } } if (!certificateInstallationRes) { throw new Error('Failed to find CertificateInstallationRes in response.'); } return certificateInstallationRes; }); } /** * Retrieves all root certificates from Hubject. * Refer to https://hubject.stoplight.io/docs/open-plugncharge/fdc9bdfdd4fb2-get-all-root-certificates * * @return {Promise<string[]>} Array of root certificate. */ getRootCertificates() { return __awaiter(this, void 0, void 0, function* () { const url = `${this._baseUrl}/v1/root/rootCerts`; const response = yield fetch(url, { method: 'GET', headers: { Accept: 'application/json', Authorization: yield this._getAuthorizationToken(this._tokenUrl), }, }); if (response.status !== 200) { throw new Error(`Get root certificates response is unexpected: ${response.status}: ${yield response.text()}`); } const certificates = []; const rootCertificatesResponse = JSON.parse(yield response.text()); for (const root of rootCertificatesResponse.RootCertificateCollection.rootCertificates) { certificates.push((0, CertificateUtil_1.createPemBlock)('CERTIFICATE', root.caCertificate)); } return certificates; }); } _getAuthorizationToken(tokenUrl) { return __awaiter(this, void 0, void 0, function* () { const response = yield fetch(tokenUrl, { method: 'GET' }); if (!response.ok && response.status !== 304) { throw new Error(`Get token response is unexpected: ${response.status}: ${yield response.text()}`); } return this._parseBearerToken((yield response.json()).data); }); } /** * Parses the Bearer token from the input token * which is expected to be in the format of "XXXXBearer <token>\nXXXXX" * * @param {string} token - The input token string to parse. * @return {string} The parsed Bearer token string. */ _parseBearerToken(token) { let tokenValue = token.split('Bearer ')[1]; tokenValue = tokenValue.split('\n')[0]; return 'Bearer ' + tokenValue; } } exports.Hubject = Hubject; //# sourceMappingURL=hubject.js.map