Fixes to OCPP command payload validation:
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPResponseService.ts
1 import Ajv, { type JSONSchemaType } from 'ajv';
2 import ajvFormats from 'ajv-formats';
3
4 import OCPPError from '../../exception/OCPPError';
5 import type { JsonType } from '../../types/JsonType';
6 import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
7 import type { RequestCommand } from '../../types/ocpp/Requests';
8 import logger from '../../utils/Logger';
9 import type ChargingStation from '../ChargingStation';
10 import { OCPPServiceUtils } from './OCPPServiceUtils';
11
12 const moduleName = 'OCPPResponseService';
13
14 export default abstract class OCPPResponseService {
15 private static instance: OCPPResponseService | null = null;
16 private readonly version: OCPPVersion;
17 private readonly ajv: Ajv;
18
19 protected constructor(version: OCPPVersion) {
20 this.version = version;
21 this.ajv = new Ajv({
22 multipleOfPrecision: 2,
23 });
24 ajvFormats(this.ajv);
25 this.responseHandler.bind(this);
26 this.validateResponsePayload.bind(this);
27 }
28
29 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
30 if (OCPPResponseService.instance === null) {
31 OCPPResponseService.instance = new this();
32 }
33 return OCPPResponseService.instance as T;
34 }
35
36 protected validateResponsePayload<T extends JsonType>(
37 chargingStation: ChargingStation,
38 commandName: RequestCommand,
39 schema: JSONSchemaType<T>,
40 payload: T
41 ): boolean {
42 if (chargingStation.getPayloadSchemaValidation() === false) {
43 return true;
44 }
45 const validate = this.ajv.compile(schema);
46 if (validate(payload)) {
47 return true;
48 }
49 logger.error(
50 `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Command '${commandName}' response PDU is invalid: %j`,
51 validate.errors
52 );
53 throw new OCPPError(
54 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
55 'Response PDU is invalid',
56 commandName,
57 JSON.stringify(validate.errors, null, 2)
58 );
59 }
60
61 protected emptyResponseHandler() {
62 /* This is intentional */
63 }
64
65 public abstract responseHandler(
66 chargingStation: ChargingStation,
67 commandName: RequestCommand,
68 payload: JsonType,
69 requestPayload: JsonType
70 ): Promise<void>;
71 }