Repository navigation
fix(ocpp): from-zero audit — Critical + High spec conformance and safety fixes - #1961
Conversation
…en under non-strict compliance Per OCPP 1.6 §4.2, when the Charge Point is in Pending state (having received a BootNotification response with status Pending), it SHALL NOT send request messages to the Central System unless instructed via a TriggerMessage.req. The only outbound calls permitted in Pending are: - BootNotification retries (a station-recovery mechanism the spec allows) - Trigger-driven responses (params.triggerMessage === true) - CALL_RESULT_MESSAGE responses to incoming requests internalSendMessage's gate had an escape hatch that bypassed this rule entirely: when ocppStrictCompliance === false, ANY outbound CALL was allowed in both Unknown AND Pending states. The Unknown-state allowance is defensible (transient pre-boot window, spec is not strict there), but the Pending-state allowance was a direct §4.2 violation regardless of the strict-compliance toggle. Narrow the non-strict bypass to Unknown state only. Pending state now uniformly enforces the spec's trigger-driven-only restriction, whether ocppStrictCompliance is true or false. Tests still pass (2926 pass / 0 fail); the bypass was not exercised by any test in Pending state.
…ion.req Per OCPP 1.6 §5.12, the Charge Point SHALL send a StatusNotification.req with status 'Finishing' before StopTransaction.req. The remote-stop path (remoteStopTransaction) sent Finishing at its entry, but the non-remote path (stopTransactionOnConnector called directly from ATG stop, unlockConnector, station stop, etc.) skipped this step, producing an out-of-spec StopTransaction with no preceding Finishing. Move the Finishing emission into stopTransactionOnConnector itself with an idempotent guard on the current connector status. Callers that already sent Finishing (remoteStopTransaction) see the guard short-circuit and no duplicate emission occurs; all other call paths now emit Finishing before the StopTransaction.req, matching spec. Test update: 'should send StopTransaction ... and return accepted: true' asserted requestHandler.calls[0] was 'StopTransaction'. Renamed to 'should send StatusNotification(Finishing) then StopTransaction ... (per §5.12)' and updated the assertion to check the two-message spec-compliant sequence.
…t auto-select
Per OCPP 1.6 §5.11, when RemoteStartTransaction is received without a
connectorId the Charge Point is free to pick any suitable connector.
The auto-select loop rejected connectors reserved for the requesting
idTag correctly ('!hasReservation(cs, id, requesterIdTag)' returned
false) but it let through connectors reserved for a DIFFERENT idTag —
because hasReservation checks 'is this connector reserved for THIS
specific idTag'. A connector reserved by user A could therefore be
auto-selected for a RemoteStart by user B, violating the reservation
that was granted to A.
Reformulate the predicate: a connector is eligible when it is
available, has no transaction started, AND is either not Reserved OR
Reserved for the requesting idTag (i.e. the requester owns the
reservation). The rejected path becomes 'Reserved AND not for us'.
Gates pass (typecheck / test, 2939 pass / 0 fail).
…ined) Two .catch(() => undefined) sites in AbstractUIServer silently dropped errors: - disposeMetrics: .catch after registry.clear() lost any registry cleanup failure with no trace. - runMetricsScrape: .catch resets the metricsScrapeChain to allow the next scrape to proceed even when the previous one rejected (chain- breaker pattern documented in the class JSDoc); previously the swallowed error had no log trace. Replace both with .catch((error: unknown) => logger.warn(...)) so the rejection is still absorbed (chain semantics preserved) but the failure gains an operational log entry with the module/method prefix. No new public API; no behavior change for the happy path. Gates pass (typecheck / lint).
…e.js shutdown Three fire-and-forget setTimeout sites in OCPP request services were untracked, preventing clean node.js exit when a charging station is stopped while a timer is pending: - OCPP20IncomingRequestService: scheduleEvseReset inner setTimeout (delayed EVSE reset via RESET_DELAY_MS) - OCPP20IncomingRequestService: sendQueuedSecurityEvents retry setTimeout (SECURITY_EVENT_RETRY_DELAY_MS) - OCPP16IncomingRequestService: deferred updateFirmwareSimulation setTimeout (retrieveDate-driven delay) Full per-station clearTimeout tracking would require new plumbing in OCPPIncomingRequestService (WeakMap<ChargingStation, Set<Timeout>>) and subclass stop() extensions. As an incremental step, call .unref() on each Timeout so node.js can exit even when a timer is still pending; the callback body remains a no-op on a stopped station because the inner functions (updateFirmwareSimulation, sendQueuedSecurityEvents, getEvseStatus/restoreConnectorStatus) already gate on the station lifecycle (checkChargingStationState / getEvseStatus returns undefined for stopped stations, etc.). Full clearTimeout tracking left as follow-up; this commit at minimum removes the process-block risk. Gates pass (typecheck / test, 2955 pass / 0 fail).
… definite-assignment Five private string fields on ChargingStation used the definite-assignment assertion (`!:`) even though they are only assigned in initialize(), not the constructor. If any code path accesses these fields before initialize() runs, TypeScript's type system claims safety while runtime returns undefined. Initialize the five string fields to '' in the constructor and drop the definite-assignment marker: - configurationFile - configurationFileHash - connectorsConfigurationHash - evsesConfigurationHash - templateFileHash Empty-string sentinels are safe here: reads either compare against a computed hash (fresh station mismatches on first access) or fail cleanly at the fs boundary when used as a file path. Three remaining `!` fields need a broader lifecycle-typing refactor touching ~35 files and are left for a follow-up PR: - configuredSupervisionUrl!: URL (no reasonable empty-URL sentinel) - ocppRequestService! / ocppIncomingRequestService! (depend on stationInfo.ocppVersion which is only known after initialize()) Gates pass (typecheck / test, 2955 pass / 0 fail).
SummaryThe following content is AI-generated and provides a summary of the pull request: fix(ocpp): Critical + High spec conformance and safety fixes (audit follow-up)Follow-up to #1960 landing the remaining deferred Critical and High findings from the from-zero audit. Ships 5 real fixes (1 Critical, 4 High) plus documented withdrawal of 3 audit findings confirmed as false positives. All quality gates pass: 2955 tests / 0 fail / 6 skipped. Skott circular-dependency count preserved at 61. Changes🔴 Critical Fix — C2: Pending state outbound message guard (
|
There was a problem hiding this comment.
This PR contains solid, well-motivated spec-conformance fixes. The two issues I flagged are worth attention: the remoteStopTransaction / stopTransactionOnConnector deduplication relies on implicit ordering rather than an explicit contract (making it fragile if the calling sequence ever changes), and the H6 reservation guard in RemoteStartTransaction auto-select may be unreachable dead code if Reserved connectors don't retain Operative availability — which would make that fix a no-op. All other changes (.unref() on timers, string-field initialization, error logging, and the C2 pending-state restriction) are correct and well-implemented.
PR Bot Information
Version: 1.27.0
- File Content Strategy: Full file content
- Correlation ID:
dd6a1310-795a-11f1-9836-b1aae448c537 - Event Trigger:
pull_request.opened - Agent Instructions:
- LLM:
anthropic--claude-4.6-sonnet
| const connectorStatus = chargingStation.getConnectorStatus(connectorId) | ||
| const isReservedForOther = | ||
| connectorStatus?.status === OCPP16ChargePointStatus.Reserved && | ||
| !OCPP16ServiceUtils.hasReservation(chargingStation, connectorId, commandPayload.idTag) | ||
| if ( | ||
| chargingStation.isConnectorAvailable(connectorId) && | ||
| chargingStation.getConnectorStatus(connectorId)?.transactionStarted === false && | ||
| !OCPP16ServiceUtils.hasReservation(chargingStation, connectorId, commandPayload.idTag) | ||
| connectorStatus?.transactionStarted === false && | ||
| !isReservedForOther |
There was a problem hiding this comment.
Logic Error: The isReservedForOther guard is only checked after isConnectorAvailable, but isConnectorAvailable already returns false for a Reserved connector (since its availability is not Operative). This means the entire if block can never be entered for a Reserved connector regardless of the isReservedForOther value, making the H6 fix a no-op for the connector auto-select path.
To verify: isConnectorAvailable checks connectorStatus.availability === AvailabilityType.Operative (line 824-828 of ChargingStation.ts), and a Reserved connector has its availability set as part of the ReserveNow flow. If Reserved connectors have availability !== Operative, then isConnectorAvailable already excludes them and the isReservedForOther guard is unreachable.
Should verify whether a Reserved connector retains Operative availability in this codebase. If not, the isReservedForOther check is dead code and the fix should instead be applied after the isConnectorAvailable check is replaced/widened.
Please provide feedback on the review comment by checking the appropriate box:
- 🌟 Awesome comment, a human might have missed that.
- ✅ Helpful comment
- 🤷 Neutral
- ❌ This comment is not helpful
| const connectorStatus = chargingStation.getConnectorStatus(connectorId) | ||
| if (connectorStatus?.status !== OCPP16ChargePointStatus.Finishing) { | ||
| await sendAndSetConnectorStatus(chargingStation, { | ||
| connectorId, | ||
| status: OCPP16ChargePointStatus.Finishing, | ||
| } as OCPP16StatusNotificationRequest) | ||
| } |
There was a problem hiding this comment.
Logic Error: remoteStopTransaction sends StatusNotification(Finishing) before calling stopTransactionOnConnector, which now also unconditionally sends StatusNotification(Finishing) unless the connector is already in Finishing state. The guard in stopTransactionOnConnector (connectorStatus?.status !== OCPP16ChargePointStatus.Finishing) is intended to prevent a duplicate, relying on sendAndSetConnectorStatus having already updated the connector status in memory by the time stopTransactionOnConnector runs.
While this works today (because remoteStopTransaction awaits the emission), it is fragile: the deduplication is implicit and relies on ordering rather than an explicit contract. Consider simply removing the explicit sendAndSetConnectorStatus call from remoteStopTransaction since stopTransactionOnConnector now handles it, which eliminates the dependency entirely and makes the spec compliance visible in one place only.
Please provide feedback on the review comment by checking the appropriate box:
- 🌟 Awesome comment, a human might have missed that.
- ✅ Helpful comment
- 🤷 Neutral
- ❌ This comment is not helpful
| const connectorStatus = chargingStation.getConnectorStatus(connectorId) | ||
| const isReservedForOther = | ||
| connectorStatus?.status === OCPP16ChargePointStatus.Reserved && | ||
| !OCPP16ServiceUtils.hasReservation(chargingStation, connectorId, commandPayload.idTag) | ||
| if ( | ||
| chargingStation.isConnectorAvailable(connectorId) && | ||
| chargingStation.getConnectorStatus(connectorId)?.transactionStarted === false && | ||
| !OCPP16ServiceUtils.hasReservation(chargingStation, connectorId, commandPayload.idTag) | ||
| connectorStatus?.transactionStarted === false && | ||
| !isReservedForOther |
There was a problem hiding this comment.
Logic Error: The isReservedForOther guard is evaluated only when chargingStation.isConnectorAvailable(connectorId) is true. isConnectorAvailable checks connectorStatus.availability === AvailabilityType.Operative (see ChargingStation.ts lines 824–828). A Reserved connector's status is Reserved, but if its availability field remains Operative (i.e. the reservation only changes status, not availability), then isConnectorAvailable returns true and the isReservedForOther guard correctly fires.
However, if the ReserveNow handler sets availability to anything other than Operative on reservation, then isConnectorAvailable would already return false and isReservedForOther would be unreachable dead code, making the H6 fix a no-op. Please add a code comment or test confirming which case applies — if Reserved connectors keep availability === Operative, this fix is correct; otherwise the predicate needs to be restructured (e.g. replacing isConnectorAvailable with a combined availability+reservation check).
Please provide feedback on the review comment by checking the appropriate box:
- 🌟 Awesome comment, a human might have missed that.
- ✅ Helpful comment
- 🤷 Neutral
- ❌ This comment is not helpful
The .catch swallowed-error log message added in e82cc9a claimed '${moduleName}.disposeMetrics' as its method prefix, but the enclosing method is public stop(); disposeMetrics is not a method on AbstractUIServer at all. Correct the log prefix to '${moduleName}.stop: metrics registry cleanup failed' so operational logs point at the actual method name. Gates pass (format / typecheck / lint).
…king node.js shutdown Complete H9 shutdown-unblock coverage. Commit fa2bea3 unref()d the 3 fire-and-forget setTimeout handles in the OCPP incoming-request services but left two structurally-identical setInterval idle-monitors ref()d: - scheduleEvseResetOnIdle (OCPP20IncomingRequestService.ts:3350) - scheduleResetOnIdle (OCPP20IncomingRequestService.ts:3371) Both poll on a fixed interval waiting for an idle condition before executing a reset. clearInterval fires when the idle condition is met or the target EVSE disappears; if the station stops before either, the interval blocks node.js exit exactly like the setTimeout sites did. Chain .unref() on each setInterval return value so node can exit even with the monitor pending. The callback is a no-op on a stopped station (the reset paths gate on station lifecycle). Gates pass (format / typecheck / lint).
The 5 setTimeout / setInterval sites that carry .unref() (introduced across commits fa2bea3 and 7dfc5de as part of H9) share a non-obvious safety invariant: the timer is fire-and-forget AND its callback is a no-op / self-clear on a stopped or gone station or EVSE. That combination is what makes .unref() safe here — a reader who does not reconstruct it from git history has no way to know whether the timer could observe a stale ChargingStation on late fire. Add a one-line state-describing comment above each of the five sites so the safety rationale travels with the code: - OCPP16IncomingRequestService.ts:593 (deferred UpdateFirmware) - OCPP20IncomingRequestService.ts:3322 (pending EVSE reset) - OCPP20IncomingRequestService.ts:3350 (EVSE idle-monitor) - OCPP20IncomingRequestService.ts:3371 (station idle-monitor) - OCPP20IncomingRequestService.ts:3614 (security-event retry) No behavior change. Gates pass (format / typecheck / lint).
The .catch handler introduced at e82cc9a logged 'chain reset to continue serving next scrape', but nothing about the promise chain is reset there. What actually happens: the .catch absorbs the prior rejection so its .then continuation can run for the next scrape. Rewrite the log message to describe the actual semantics ('absorbing rejection so next scrape can proceed') so operational logs are grep-able against a truthful cause description. No behavior change. Gates pass (format / typecheck / lint).
…title The renamed test at c24d04c cited '(per §5.12)', but §5.12 is RemoteStopTransaction, whereas stopTransactionOnConnector is the shared helper called from ATG stop, unlockConnector, station stop, and the remote-stop path alike. The Finishing→StopTransaction sequence was harmonized across all callers, matching the pattern the remote-stop path already used. Rewrite the parenthetical to describe the design intent verified by this test ('matches remote-stop message sequence') instead of pointing at a spec section that only covers one of the callers. No behavior change. Gates pass (format / typecheck / lint).
Summary
Follow-up to PR #1960 landing the remaining deferred Criticals and Highs from the from-zero audit, plus content-quality fixes surfaced during three iterative review rounds.
Eleven commits ship:
3 audit findings were verified as false positives (no code change). 3 audit findings remain deferred with concrete follow-up rationale.
Each commit is atomic, spec-cited where applicable, and passes the full documented quality gates. Skott circular-dependency count preserved at 61.
Commits
7c233157ocppStrictCompliance === false(§4.2)c24d04c8StatusNotification(Finishing)beforeStopTransaction.reqin the non-remote stop pathf600626dRemoteStartTransactionauto-select skips connectors reserved for a different idTag (§5.11)e82cc9a1.catch(() => undefined)in AbstractUIServerfa2bea32.unref()on 3 lifecyclesetTimeouthandles so they no longer block node.js shutdown6d5ebbb6ChargingStationfields in the constructor; drop their definite-assignment markersa72cb504stop, notdisposeMetrics) in the metrics-cleanup log prefix atAbstractUIServer.ts:4207dfc5de2setIntervalidle-monitor handles (scheduleEvseResetOnIdle,scheduleResetOnIdle) — same shutdown-blocking pattern as the setTimeout sitesa4559d09.unref()sitese8b79c1arunMetricsScrapecatch-log wording (chain reset→absorbing rejection so next scrape can proceed) to match actual.catchsemanticsca6b0182stopTransactionOnConnectortest title (§5.12 covers only remote-stop; the helper is shared with ATG / unlock / station-stop paths)Highlights
Commit 1 — C2 spec-conformance (§4.2)
OCPPRequestService.internalSendMessagehad four OR-branches gating outbound CALLs. One branch wasocppStrictCompliance === false && (inUnknownState() || inPendingState())— a blanket bypass that allowed any outgoing message in Pending, in direct violation of §4.2 ("SHALL NOT send request messages ... unless instructed via TriggerMessage.req"). Narrowed the bypass to Unknown state only. Pending now uniformly enforces the trigger-only restriction whether strict compliance is on or off. The Unknown-state allowance is preserved as a transient pre-boot convenience where the spec is not strict.Commit 2 — H2 spec-conformance (Finishing → StopTransaction sequence)
Only
remoteStopTransactionemittedStatusNotification(Finishing)beforeStopTransaction.req; the non-remotestopTransactionOnConnectorpath (ATG stop,unlockConnector, station stop, etc.) skipped it. Moved the emission intostopTransactionOnConnectoritself with an idempotent guard on the current connector status. Remote-stop callers short-circuit the guard so no duplicate is emitted; every non-remote path now matches the same two-message sequence used by the remote-stop path.Commit 3 — H6 spec-conformance (§5.11)
The
RemoteStartTransactionauto-select loop rejected connectors reserved for the requesting idTag (!hasReservation(cs, id, requesterIdTag)returnedfalsecorrectly) but let through connectors reserved for a different idTag — becausehasReservationchecks "is this connector reserved for THIS specific idTag". A connector reserved by user A could therefore be auto-selected for aRemoteStartby user B, violating A's reservation. Reformulated the predicate: eligible when available, no transaction, AND (not Reserved OR Reserved-for-requester). The rejected path becomes "Reserved AND not for us".Commit 4 — H11 silent-error logging
Two
.catch(() => undefined)sites inAbstractUIServerswallowed errors without a log trace (stop()registry cleanup +runMetricsScrapechain-breaker). Replaced with.catch((error: unknown) => logger.warn(...))— the rejection is still absorbed (chain semantics preserved) but the failure gains an operational log entry.Commits 5 + 8 — H9 shutdown-unblock (5 timer sites total)
Five untracked timer sites in OCPP incoming-request services blocked clean node.js exit when a station stopped while a timer was pending:
fa2bea32):scheduleEvseResetdelay,sendQueuedSecurityEventsretry, deferredupdateFirmwareSimulation7dfc5de2):scheduleEvseResetOnIdle,scheduleResetOnIdleidle-poll monitorsChained
.unref()on eachTimeout/Intervalso node can exit even when the handle is still pending. Callback bodies are safe because the inner functions (updateFirmwareSimulation,sendQueuedSecurityEvents,restoreConnectorStatus,isChargingStationIdle) already gate on the station lifecycle or the interval self-clears once its idle condition is met. Full per-stationclearTimeouttracking is left as follow-up — see below.Commit 6 — H10 partial (string fields)
Five private string fields on
ChargingStationused!:even though they are only assigned ininitialize(). Initialized them to''in the constructor and dropped the marker. Empty-string sentinels are safe because reads either compare against a computed hash (fresh station mismatches on first access) or fail cleanly at the fs boundary. Three non-string!fields remain — see below.Commits 7, 9, 10, 11 — review follow-ups
Content-quality corrections surfaced during three iterative from-zero reviews of the PR itself:
a72cb504) — the log message added ate82cc9a1claimed${moduleName}.disposeMetricsbut the enclosing method isstop();disposeMetricsis not a method onAbstractUIServerat all. Corrected to${moduleName}.stop.a4559d09) — the 5.unref()sites share a non-obvious safety invariant (fire-and-forget timer + station-lifecycle-idempotent callback) that a reader has no way to reconstruct without git history. A one-line state-describing comment above each site keeps the safety rationale next to the code.e8b79c1a) — therunMetricsScrapecatch-log claimed "chain reset to continue serving next scrape", but nothing about the promise chain is reset there. What actually happens: the.catchabsorbs the prior rejection so its.thencontinuation can run for the next scrape. Rewrote to match the real semantics.ca6b0182) — the renamed test atc24d04c8cited(per §5.12), but §5.12 is RemoteStopTransaction only;stopTransactionOnConnectoris the shared helper. Rewrote the parenthetical to describe the verified design intent ("matches remote-stop message sequence") instead of pointing at a spec section that only covers one caller.Audit findings verified as false positives (empirical rationale, no code change)
H4 —
ChangeAvailabilitydeferred trigger. Empirically the trigger IS wired:handleRequestChangeAvailabilitysetsconnectorStatus.availability = Inoperative(line 773) and returns Scheduled. When the transaction stops,handleResponseStopTransactioncallssendPostTransactionStatuswhich readsisConnectorAvailable(connectorId)(i.e.availability === Operative). If availability was set to Inoperative, the post-stop emission isUnavailable— that IS the deferred availability trigger. Audit finding rescinded.H5 — MeterValues in
StopTransaction.transactionData. TheSTOP_TRANSACTIONpayload builder atOCPP16RequestService.ts:240-267already embedstransactionDatawhen thetransactionDataMeterValuesconfig flag is set. The audit's specific concern (separateMeterValuesrequest whenbeginEndMeterValues && strict && !outOfOrder) is a distinct, documented feature (beginEndMeterValuestoggles Transaction.Begin/End MeterValues as lifecycle events — README-documented). Both patterns are spec-permissible; §5.12 SHOULD ≠ SHALL, and the two features are orthogonal. Audit conflated them.H8 —
console.*in production code. Every one of the 14 flagged sites has documented defensive rationale:Configuration.ts:111,164— config-load / pre-process.exit(1)(logger not yet configured)ErrorUtils.ts:28,36— uncaught / unhandledRejection process-level handlers (logger state unknown; already haslogger?.errorfallback)ErrorUtils.ts:89,91,121,145— behindparams.consoleOut === trueflag (documented escape hatch)ConfigurationValidation.ts:114— inline rationale:console.warn: logger.warn would recurse via Configuration → validateConfigurationstart.ts:14— top-level startup error handler (logger init after)WorkerUtils.ts:45-54— worker-lifecycle handlers (workers have separate logger context)None are anti-pattern uses. Audit finding rescinded.
Findings still deferred (with concrete rationale)
H7 — ~15
as unknown as Xcasts across the OCPP request / response dispatch layer. Root cause is that theRequest/Responseunion types are too wide; narrowing them per-command eliminates the casts but touches every OCPP command handler acrossOCPP16RequestService,OCPP20RequestService,OCPP16IncomingRequestService,OCPP20IncomingRequestService. Deserves its own PR dedicated to that type contract.H9 residual — the 5 timer sites now
.unref()cleanly but full per-stationclearTimeouttracking (WeakMap<ChargingStation, Set<Timeout>>) requires new plumbing onOCPPIncomingRequestServicebase class plusstop(station)overrides. Out of this PR's scope.H10 residual — 3 non-string
!fields onChargingStation:ocppRequestService!: OCPPRequestServiceandocppIncomingRequestService!: OCPPIncomingRequestService— depend onstationInfo.ocppVersion(only known afterinitialize()reads the template file), so cannot be constructed in theChargingStationconstructor.configuredSupervisionUrl!: URL— no reasonable empty-URL sentinel; needsURL | undefined+ null-checks.Full fix requires touching ~35 files (grep on
ocppRequestService./ocppIncomingRequestService./configuredSupervisionUrl.). Coherent as a follow-up PR dedicated to theChargingStationlifecycle contract.Verification
Full documented gates against the final tip of the branch (
ca6b0182):Skott circular-dependency count: 61 (preserved, no change since PR #1960).