UNPKG

@citrineos/util

Version:

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

184 lines 9.34 kB
"use strict"; 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SignedMeterValuesUtil = void 0; const data_1 = require("@citrineos/data"); const crypto = __importStar(require("node:crypto")); const pvutils_1 = require("pvutils"); /** * Util to process and validate signed meter values. */ class SignedMeterValuesUtil { /** * @param {IFileStorage} [fileStorage] - The `fileStorage` allows access to the configured file storage. * * @param {SystemConfig} config - The `config` contains the current system configuration settings. * * @param {Logger<ILogObj>} [logger] - The `logger` represents an instance of {@link Logger<ILogObj>}. * */ constructor(fileStorage, config, logger) { this._fileStorage = fileStorage; this._logger = logger; this._chargingStationSecurityInfoRepository = new data_1.sequelize.SequelizeChargingStationSecurityInfoRepository(config, logger); this._signedMeterValuesConfiguration = config.modules.transactions.signedMeterValuesConfiguration; } /** * Checks the validity of a meter value. * * If a meter value is unsigned, it is valid. * * If a meter value is signed, it is valid if: * - SignedMeterValuesConfig is configured * AND * - The incoming signed meter value's signing method matches the configured signing method * AND * - The incoming signed meter value's public key is empty but there is a public key stored for that charging station * OR * - The incoming signed meter value's public key isn't empty and it matches the configured public key * * @param stationId - The charging station the meter values belong to * @param meterValues - The list of meter values */ validateMeterValues(stationId, meterValues) { return __awaiter(this, void 0, void 0, function* () { for (const meterValue of meterValues) { for (const sampledValue of meterValue.sampledValue) { if (sampledValue.signedMeterValue) { const validMeterValues = yield this.validateSignedSampledValue(stationId, sampledValue.signedMeterValue); if (!validMeterValues) { return false; } } } } return true; }); } validateSignedSampledValue(stationId, signedMeterValue) { return __awaiter(this, void 0, void 0, function* () { if (signedMeterValue.publicKey && signedMeterValue.publicKey.length > 0) { const incomingPublicKeyIsValid = yield this.validateSignedMeterValueSignature(signedMeterValue); if (this._signedMeterValuesConfiguration && incomingPublicKeyIsValid) { yield this._chargingStationSecurityInfoRepository.readOrCreateChargingStationInfo(stationId, this._signedMeterValuesConfiguration.publicKeyFileId); return true; } else { return false; } } else { const chargingStationPublicKeyFileId = yield this._chargingStationSecurityInfoRepository.readChargingStationPublicKeyFileId(stationId); return yield this.validateSignedMeterValueSignature(signedMeterValue, chargingStationPublicKeyFileId); } }); } validateSignedMeterValueSignature(signedMeterValue, publicKeyFileId) { return __awaiter(this, void 0, void 0, function* () { var _a, _b, _c; const incomingPublicKeyString = signedMeterValue.publicKey; const signingMethod = signedMeterValue.signingMethod; if (!((_a = this._signedMeterValuesConfiguration) === null || _a === void 0 ? void 0 : _a.publicKeyFileId)) { this._logger.warn('Invalid signature because public key is missing from system config.'); return false; } if (publicKeyFileId && publicKeyFileId !== ((_b = this._signedMeterValuesConfiguration) === null || _b === void 0 ? void 0 : _b.publicKeyFileId)) { this._logger.warn('Invalid signature because incoming public key does not match configured public key.'); return false; } if (!publicKeyFileId && incomingPublicKeyString.length === 0) { this._logger.warn('Invalid signature because no configured public key and incoming signed meter values has no public key.'); return false; } if (((_c = this._signedMeterValuesConfiguration) === null || _c === void 0 ? void 0 : _c.signingMethod) !== signingMethod) { this._logger.warn('Invalid signature because incoming signing method does not match configured signing method.'); return false; } const configuredPublicKey = this.formatKey(yield this._fileStorage.getFile(this._signedMeterValuesConfiguration.publicKeyFileId)); if (incomingPublicKeyString.length > 0) { const signedMeterValuePublicKey = Buffer.from(signedMeterValue.publicKey, 'base64').toString(); if (configuredPublicKey !== signedMeterValuePublicKey) { return false; } } switch (signingMethod) { case 'RSASSA-PKCS1-v1_5': return yield this.validateRsaSignature(configuredPublicKey, signingMethod, signedMeterValue.encodingMethod, signedMeterValue.signedMeterData); default: this._logger.warn(`${signingMethod} is not supported for Signed Meter Values.`); return false; } }); } validateRsaSignature(configuredPublicKey, signingMethod, encodingMethod, signatureData) { return __awaiter(this, void 0, void 0, function* () { try { const cryptoPublicKey = yield crypto.subtle.importKey('spki', (0, pvutils_1.stringToArrayBuffer)(atob(configuredPublicKey)), { name: signingMethod, hash: encodingMethod }, true, ['verify']); const signatureBuffer = Buffer.from(signatureData, 'base64'); // For now, we only care that the signature could be read, regardless of the value in the signature. yield crypto.subtle.verify(signingMethod, cryptoPublicKey, signatureBuffer, signatureBuffer); return true; } catch (e) { const errorMessage = e instanceof DOMException ? e.message : JSON.stringify(e); this._logger.warn(`Error decrypting public key or verifying signature from Signed Meter Value. Error: ${errorMessage}`); return false; } }); } formatKey(key) { if (!key) { throw new Error('Public key file is missing.'); } return key .replace('-----BEGIN PUBLIC KEY-----', '') .replace('-----END PUBLIC KEY-----', '') .replace(/(\r\n|\n|\r)/gm, ''); } } exports.SignedMeterValuesUtil = SignedMeterValuesUtil; //# sourceMappingURL=SignedMeterValuesUtil.js.map