Skip to content

Add OCPP 2.0 - #34743

Open
deidi01 wants to merge 43 commits into
evcc-io:masterfrom
deidi01:feature/ocpp20-generic
Open

deidi01 wants to merge 43 commits into
evcc-io:masterfrom
deidi01:feature/ocpp20-generic

Conversation

@deidi01

@deidi01 deidi01 commented Oct 12, 2026 •

Copy link
Copy Markdown

OCPP 2.0.1 - KEBA KeContact P30 X-Series

Based on #29169 by @andig.

Changes

  • Add KEBA KeContact P30 X-Series as product entry in ocpp20.yaml

Testing

Previously tested with own OCPP 2.0.1 infrastructure:

  • ✅ KEBA P30 X-Series connects via OCPP 2.0.1
  • ✅ Correct power metering (no 4.3kW limit)
  • ✅ RFID working
  • no phase switching possible (missing Keba module)

Hardware test with this PR's code (#29169 infrastructure) pending
due to charger hardware failure. Will update once hardware is
available again.

Closes #34728

@github-actions github-actions Bot added devices Specific device support enhancement New feature or request labels Oct 12, 2026
@deidi01
deidi01 force-pushed the feature/ocpp20-generic branch 5 times, most recently from 45c948f to daf55c1 Compare October 15, 2026 14:12
@andig andig changed the title Feature/ocpp20 generic Add OCPP 2.0 Oct 17, 2026
@andig

andig commented Oct 17, 2026

Copy link
Copy Markdown
Member

See lorenzodonini/ocpp-go#431. Wondering if we should switch to @xBlaz3kx fork which has various OCPP 2.0 fixes?

@andig

andig commented Oct 17, 2026

Copy link
Copy Markdown
Member

Note: I'd especially like to see OCPP 1.6 and 2.0 shared over the same port!

@github-actions github-actions Bot added the stale Outdated and ready to close label Oct 29, 2026
@deidi01

deidi01 commented Nov 3, 2026

Copy link
Copy Markdown
Author

Hardware Test: 2x Keba P30 X-Series with OCPP 2.0.1

Setup

  • evcc: Source build, Raspberry Pi
  • Branch: feature/ocpp20-generic
  • Commit: 8f74632
  • Chargers: 2x Keba P30 X-Series, OCPP 2.0.1 via UI template
  • Authentication: RFID

Result: MeterValues not coming through, charging does work without any problems (Vehicles: Cupra Born and Skoda Eniaq)

Both chargers continuously report:

[lp-1] ERROR charge power: measurement not available: Power.Active.Import
[lp-2] ERROR charge power: measurement not available: Power.Active.Import
[lp-1] ERROR charge total import: measurement not available: Energy.Active.Import.Register
[lp-2] ERROR charge total import: measurement not available: Energy.Active.Import.Register

Observations

  • Error occurs identically on both wallboxes
  • Error appears immediately after evcc start and persists

Suspicion

In OCPP 2.0.1, transaction-related MeterValues are delivered
via TransactionEvent(Updated), not via separate MeterValues
messages. The embedded meterValue data in OnTransactionEvent()
may not be correctly extracted or forwarded to the internal
meter object.

Environment

  • Keba Firmware: 2.0.1

@github-actions github-actions Bot removed the stale Outdated and ready to close label Nov 3, 2026
@andig

andig commented Nov 3, 2026

Copy link
Copy Markdown
Member

Great PR! I'd really prefer if we could share a single port for both protocols.

@xBlaz3kx is that something you have already done on your fork? Then I'd propose we switch to that given lorenzodonini/ocpp-go#431 hasn't really shown any activity. If it would help we could also consider giving it a home in the evcc org. I couldn't take over (sole) maintenance though.

@deidi01
deidi01 marked this pull request as ready for review November 3, 2026 11:53

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 security issue, and 29 other issues

Security issues:

  • Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections. (link)

Fixed security issues:

  • github.com/go-jose/go-jose/v4 (link)
  • github.com/xuri/excelize/v2 (link)
  • golang.org/x/net (link)
Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="charger/ocpp20/cs.go" line_range="163" />
<code_context>
+	cs.mu.Lock()
+
+	// check for configured charging station
+	reg, ok := cs.regs[station.ID()]
+	if ok {
+		cs.log.DEBUG.Printf("charging station connected: %s", station.ID())
</code_context>
<issue_to_address>
**Station IDs are trusted as identity**

When an attacker can reach the OCPP 2.0.1 listener and knows or guesses a configured station ID, a device on the OCPP network can connect using a configured station ID and be treated as that station: `NewChargingStation` matches the ID to its registration, and `OnBootNotification` accepts it without authenticating the peer. The device can submit forged status, transaction, and meter updates for the configured EVSE, which evcc then uses as charger state and measurements.

Authenticate the connecting station (for example, with configured credentials or client certificates) before binding its connection to a configured station ID.
</issue_to_address>

### Comment 2
<location path="charger/ocpp20/instance.go" line_range="53" />
<code_context>
+	getOcpp20Url,
+	getOcpp20UrlWithStationId,
+} from "@/utils/ocpp";

 const initialValues = {
 	type: ConfigType.Template,
</code_context>
<issue_to_address>
**Malicious sites can use OCPP**

When an evcc user visits a malicious page while their browser can reach the OCPP 2.0.1 port, a page opened in an evcc user's browser can connect to the OCPP 2.0.1 listener and send OCPP frames because `SetCheckOriginHandler` accepts every origin. The browser can therefore act as a cross-site proxy to impersonate a configured station and alter its reported status or meter data.

Reject cross-origin WebSocket requests, and require station authentication before accepting OCPP messages.
</issue_to_address>

### Comment 3
<location path="charger/ocpp20/cs_log.go" line_range="16" />
<code_context>
+		s = "recv" + s
+	}
+	if ok {
+		cs.log.TRACE.Println(s)
+	}
+}
</code_context>
<issue_to_address>
**RFID tokens enter trace logs**

When a charger sends a transaction event with an IDToken while TRACE logging is enabled, `cs.print` logs the raw received JSON message, including transaction events' `IDToken`, so enabling TRACE logging exposes RFID tokens in logs.

Redact sensitive fields from OCPP frames before logging them, or avoid logging raw frame contents.
</issue_to_address>

### Comment 4
<location path="charger/ocpp20/instance.go" line_range="105-106" />
<code_context>
+
+		// wait for server to start
+		for range time.Tick(10 * time.Millisecond) {
+			if dispatcher.IsRunning() {
+				break
+			}
+		}
</code_context>
<issue_to_address>
**OCPP server startup hangs**

When the configured OCPP 2.0.1 port cannot be bound or the server otherwise fails to start, `Instance` ignores the result of `csms.Start` and waits indefinitely for `dispatcher.IsRunning()`, so charger initialization and tests hang instead of reporting the listen error.

Propagate the server startup result and stop waiting when startup fails.

Also at `charger/ocpp20/instance.go:104`, `charger/ocpp20_test.go:36`.
</issue_to_address>

### Comment 5
<location path="charger/ocpp20/cs.go" line_range="155" />
<code_context>
+		cp.onTransportConnect()
+	}
+
+	return cp, init(cp)
+}
+
</code_context>
<issue_to_address>
**Failed setup blocks retries**

When the first station initialization fails and registration is retried, `RegisterChargingStation` leaves the station in `reg.cs` when `init(cp)` fails, so later registrations return the cached station without rerunning setup; transient failures leave the charger unusable or partially initialized.

Clear the cached station when initialization fails, or cache it only after initialization succeeds.
</issue_to_address>

### Comment 6
<location path="charger/ocpp20/cs.go" line_range="18" />
<code_context>
+	mu     sync.RWMutex
+	setup  sync.RWMutex                                    // serialises charging station setup
+	cs     *Station                                        // guarded by setup and CSMS mutexes
+	status map[int]*availability.StatusNotificationRequest // guarded by mu mutex
+}
+
</code_context>
<issue_to_address>
**Connectors inherit wrong status**

When multiple connectors under one EVSE report status before their EVSE listeners are created, `reg.status` stores only one notification per EVSE, and `NewEVSE` replays it without checking `ConnectorID`; a connector can initialize with another connector’s availability or occupancy state.

Cache and replay status by both EVSE ID and connector ID.

Also at `charger/ocpp20/cs_core.go:88-89`, `charger/ocpp20/evse.go:80-82`, `charger/ocpp20/cs.go:105`.
</issue_to_address>

### Comment 7
<location path="charger/ocpp20.go" line_range="98" />
<code_context>
+	}
+
+	if !sponsor.IsAuthorized() {
+		return nil, api.ErrSponsorRequired
+	}
+
</code_context>
<issue_to_address>
**Failed creation leaves listener**

When charger creation fails after `NewEVSE` registers its listener, `NewOCPP20` returns without deregistering the EVSE listener, so a retry with the same EVSE and connector is rejected as a duplicate and the abandoned listener can still receive events.

Deregister the EVSE listener on every constructor failure after registration.

Also at `charger/ocpp20.go:200`.
</issue_to_address>

### Comment 8
<location path="charger/ocpp20.go" line_range="177-179" />
<code_context>
+		return nil, err
+	}
+
+	if remoteStart {
+		idTag = lo.CoalesceOrEmpty(idTag, defaultIdTag20)
+	}
+
+	evse, err := ocpp20.NewEVSE(ctx, log, evseID, connectorID, cp, idTag, meterInterval)
</code_context>
<issue_to_address>
**Remote start never starts**

When `remotestart` is enabled and the station requires a CSMS-initiated start, `remoteStart` only supplies a fallback ID tag; no OCPP 2.0.1 handler sends `RequestStartTransaction`, so a connected vehicle remains plugged in without starting a transaction.

Send a remote-start request when the EVSE needs one, or remove the advertised option until that behavior is implemented.

Also at `templates/definition/charger/ocpp20.yaml:79`, `charger/ocpp20.go:90`.
</issue_to_address>

### Comment 9
<location path="charger/ocpp/connector_core.go" line_range="99-104" />
<code_context>
-					// freshness is measured locally: charger sample timestamps may lag (Mennekes: 6-7s)
-					conn.meterUpdated = conn.clock.Now()
-				}
+		if !meterValue.Timestamp.Time.Before(conn.meterUpdated) {
+			for _, sample := range meterValue.SampledValue {
+				sample.Value = strings.TrimSpace(sample.Value)
+				conn.measurements[getSampleKey(sample)] = sample
+				conn.meterUpdated = meterValue.Timestamp.Time
 			}
 		}
 	}
</code_context>
<issue_to_address>
**Fresh meter readings stay stale**

When charger sample timestamps lag local time, especially after `assumeMeterStopped` resets the meter state, `OnMeterValues` compares charger timestamps with `meterUpdated`, which also represents local receipt time for the watchdog; fresh readings are rejected or treated as stale, leaving measurements outdated and triggering repeated meter requests.

Track charger sample ordering separately from local receipt time, and use local receipt time for watchdog freshness.
</issue_to_address>

### Comment 10
<location path="charger/ocpp20/evse.go" line_range="154-156" />
<code_context>
+		}
+
+	case transactions.TransactionEventEnded:
+		e.log.DEBUG.Printf("evse %d: transaction ended: %s", e.id, request.TransactionInfo.TransactionID)
+		e.transaction = nil
+		e.idTag = ""
+	}
+
</code_context>
<issue_to_address>
**Old events erase active session**

When an event from an earlier transaction arrives after a newer transaction has started, `EVSE.OnTransactionEvent` applies or clears the tracked transaction without validating its transaction ID or sequence number, so a delayed event clears or overwrites the active session and evcc reports the wrong charging or authentication state.

Validate transaction IDs and sequence numbers before applying transaction events.
</issue_to_address>

### Comment 11
<location path="charger/ocpp20/evse.go" line_range="177" />
<code_context>
+func (e *EVSE) updateMeterValuesLocked(meterValues []types.MeterValue) {
+	for _, mv := range meterValues {
+		for _, sv := range mv.SampledValue {
+			e.measurements[measurementKey{sv.Measurand, sv.Phase}] = sv
+		}
+	}
</code_context>
<issue_to_address>
**Older meter samples overwrite newer**

When a station delivers an older sample after a newer sample for the same measurement, `updateMeterValuesLocked` overwrites cached measurements in arrival order without comparing sample timestamps, so delayed reports replace newer power, energy, current, or voltage readings.

Store and compare sample timestamps so older reports cannot replace newer measurements.
</issue_to_address>

### Comment 12
<location path="charger/ocpp20/evse.go" line_range="107-111" />
<code_context>
+	}
+}
+
+// WatchDog triggers meter values periodically
+func (e *EVSE) WatchDog(ctx context.Context, meterInterval time.Duration) {
+	// TODO: Implement watchdog for OCPP 2.0.1
+	// In 2.0.1, meter values typically come via TransactionEvent
+}
+
+// OnStatusNotification handles status notifications.
</code_context>
<issue_to_address>
**Meter readings stop refreshing**

When a station does not send periodic meter values on its own, `WatchDog` does nothing and is never started by `NewOCPP20`, so `meterInterval` does not trigger refreshes and power and energy readings remain stale.

Implement and start the OCPP 2.0.1 meter watchdog using the configured interval.
</issue_to_address>

### Comment 13
<location path="charger/ocpp20.go" line_range="227" />
<code_context>
+}
+
+// Status implements the api.Charger interface
+func (c *OCPP20) Status() (api.ChargeStatus, error) {
+	status, err := c.evse.Status()
+	if err != nil {
</code_context>
<issue_to_address>
**Disconnected charger shows old state**

When the station disconnects after reporting a status or transaction event, `EVSE.Status` and `OCPP20.Status` return cached EVSE data without checking the station connection, so callers continue to see the previous connected or charging state instead of a connection error.

Check the station connection before returning cached status or enabled state.

Also at `charger/ocpp20.go:279`, `charger/ocpp20/evse.go:188`, `charger/ocpp20/cs.go:212`.
</issue_to_address>

### Comment 14
<location path="charger/ocpp20.go" line_range="201" />
<code_context>
+	getOcpp20Url,
+	getOcpp20UrlWithStationId,
+} from "@/utils/ocpp";

 const initialValues = {
 	type: ConfigType.Template,
</code_context>
<issue_to_address>
**Reboot leaves profile unapplied**

When a station reboots after setup and its reported capabilities or charging profile need to be reapplied, `NewOCPP20` does not start the station reboot monitor, so later BootNotifications are not consumed to rerun setup and restore evcc’s charging profile or updated capabilities.

Start `Station.MonitorReboot` and rerun setup when the station reboots.

Also at `charger/ocpp20.go:200`.
</issue_to_address>

### Comment 15
<location path="charger/ocpp20.go" line_range="286" />
<code_context>
+		case availability.ConnectorStatusOccupied:
+			// Check if actually charging
+			if state, ok := c.evse.ChargingState(); ok {
+				return state == transactions.ChargingStateCharging, nil
+			}
+			return true, nil
</code_context>
<issue_to_address>
**Suspended charging appears disabled**

When a connected vehicle temporarily suspends charging while the connector remains occupied, `Enabled` returns false for every occupied EVSE state other than `Charging`, including `SuspendedEV`. That state means the vehicle is temporarily not requesting energy, not that evcc disabled the charger, so callers see an enabled charger as disabled and may issue an inappropriate enable/current adjustment.

Map `SuspendedEV` to enabled and distinguish it from `SuspendedEVSE` when determining whether the charger is enabled.
</issue_to_address>

### Comment 16
<location path="charger/ocpp20.go" line_range="292-301" />
<code_context>
+		}
+	}
+
+	// fallback to the "offered" measurands
+	if v, err := c.evse.GetMaxCurrent(); err == nil {
+		return v > 0, nil
+	}
+	if v, err := c.evse.GetMaxPower(); err == nil {
+		return v > 0, nil
+	}
+
+	// fallback to cached value as last resort
+	return c.enabled, nil
+}
+
</code_context>
<issue_to_address>
**Disabled charger appears enabled**

When the connector is Available, `Enable(false)` has succeeded, and the station still reports a positive offered-current or offered-power value, the available-status path falls through to offered-current or offered-power measurements before consulting `c.enabled`. Chargers that report their hardware limit while idle therefore appear enabled after `Enable(false)`, and callers see the wrong enabled state.

Return the cached enabled state for Available connectors after a charging profile has been set, before consulting offered measurements.
</issue_to_address>

### Comment 17
<location path="charger/ocpp20/evse.go" line_range="252-255" />
<code_context>
+	if sv, ok := e.measurements[measurementKey{measurand: measurand}]; ok {
+		return e.scale(sv), nil
+	}
+	for k, sv := range e.measurements {
+		if k.measurand == measurand {
+			return e.scale(sv), nil
+		}
+	}
+
</code_context>
<issue_to_address>
**Phase readings understate total**

When a station reports a measurand only as phase-specific samples and omits an aggregate sample, `getMeasurement` returns the first matching phase from a map instead of combining phase samples, so `CurrentPower` or `TotalEnergy` reports an arbitrary phase’s value rather than the EVSE total.

Combine the phase-specific samples when no aggregate measurement is available.
</issue_to_address>

### Comment 18
<location path="charger/ocpp20/evse.go" line_range="265-266" />
<code_context>
+func (e *EVSE) scale(sv types.SampledValue) float64 {
+	val := sv.Value
+
+	if sv.UnitOfMeasure != nil && sv.UnitOfMeasure.Multiplier != nil {
+		val *= math.Pow(10, float64(*sv.UnitOfMeasure.Multiplier))
+	}
+
</code_context>
<issue_to_address>
**Explicit units produce wrong readings**

When a station reports a sample in kW or kWh without an explicit multiplier, `EVSE.scale` ignores `UnitOfMeasure.Unit`, so power and energy readings are interpreted using the wrong base unit and are off by a factor of 1,000.

Normalize samples using both the explicit unit and decimal multiplier.

Also at `charger/ocpp20/evse.go:272`, `charger/ocpp20/evse.go:280`.
</issue_to_address>

### Comment 19
<location path="charger/ocpp20.go" line_range="107" />
<code_context>
+	)
+
+	// Power measurement
+	if _, err := c.evse.CurrentPower(); err == nil {
+		powerG = c.evse.CurrentPower
+	}
</code_context>
<issue_to_address>
**Late readings never expose capabilities**

When the station has not reported a measurement when `NewOCPP20FromConfig` runs its initial probes, `NewOCPP20FromConfig` adds meter and sensor interfaces only when their first reads already succeed, so later measurements never expose those capabilities and evcc continues to see them as unavailable.

Register the measurement capabilities independently of whether initial readings are available.

Also at `charger/ocpp20.go:117`, `charger/ocpp20.go:127`.
</issue_to_address>

### Comment 20
<location path="charger/ocpp/connector_core.go" line_range="45-49" />
<code_context>
-			core.ChargePointStatusSuspendedEV, core.ChargePointStatusSuspendedEVSE:
-			conn.rebooted = false
-		}
+	if applied && request.Status == core.ChargePointStatusAvailable && conn.txnId != 0 {
+		conn.log.DEBUG.Printf("clearing stale transaction %d on Available status", conn.txnId)
+		conn.txnId = 0
+		conn.idTag = ""
+		conn.assumeMeterStopped()
 	}

</code_context>
<issue_to_address>
**Reboot retains stale transaction**

When a charger reboots with a vehicle still connected and reports `Preparing` before `Available`, `OnStatusNotification` clears a tracked transaction only for `Available`, and the reboot path does not mark connectors as rebooted; the old transaction and ID tag remain, so evcc treats the new session as already authenticated.

Clear stale transaction and ID-tag state when a rebooted charger reports its post-reboot status.
</issue_to_address>

### Comment 21
<location path="charger/ocpp/connector_core.go" line_range="102-103" />
<code_context>
+		if !meterValue.Timestamp.Time.Before(conn.meterUpdated) {
+			for _, sample := range meterValue.SampledValue {
+				sample.Value = strings.TrimSpace(sample.Value)
+				conn.measurements[getSampleKey(sample)] = sample
+				conn.meterUpdated = meterValue.Timestamp.Time
 			}
 		}
</code_context>
<issue_to_address>
**Snapshot replaces live meter reading**

When a message contains the same measurand as both a live periodic reading and a transaction-boundary snapshot, with the snapshot last, `OnMeterValues` stores samples in message order under the same measurand key, so the transaction-boundary snapshot replaces the live reading and callers see stale energy or power.

Prefer the live periodic sample over a transaction-boundary snapshot when both use the same measurand.
</issue_to_address>

### Comment 22
<location path="charger/ocpp20/cs.go" line_range="179" />
<code_context>
+
+	// check for configured anonymous charging station
+	reg, ok = cs.regs[""]
+	if ok && reg.cs != nil {
+		cp := reg.cs
+		cs.log.INFO.Printf("charging station connected, registering: %s", station.ID())
</code_context>
<issue_to_address>
**Anonymous registration misses a connection**

When a station connects after the anonymous registration is published but before its station object is assigned, `NewChargingStation` ignores an anonymous registration while `reg.cs` is nil and records the station as unknown instead. `RegisterChargingStation` then creates the anonymous station without adopting that connection, so its BootNotification remains pending and setup waits for a connection that is already present.

Synchronize connection handling with registration setup, or reconcile pending unknown registrations when the anonymous station object is installed.
</issue_to_address>

### Comment 23
<location path="charger/ocpp20/evse.go" line_range="94" />
<code_context>
+}
+
+// Initialized waits for initial status notification
+func (e *EVSE) Initialized() error {
+	// wait for initial status or timeout
+	timeout := time.NewTimer(ocpp.Timeout)
</code_context>
<issue_to_address>
**Initialization waits without requesting status**

When the station does not spontaneously send an initial StatusNotification after connecting, `Initialized` only waits for a status notification, and the OCPP 2.0.1 EVSE setup path never triggers one; a station that does not send an unsolicited initial notification causes charger setup to time out despite supporting TriggerMessage.

Request a StatusNotification when no cached status is available, and retry before timing out.
</issue_to_address>

### Comment 24
<location path="charger/ocpp20/cp.go" line_range="60" />
<code_context>
+		meterC:                   make(chan struct{}, 1),
+		bootNotificationRequestC: make(chan *provisioning.BootNotificationRequest, 1),
+
+		ChargingRateUnit:        types.ChargingRateUnitAmperes,
+		HasRemoteTriggerFeature: true, // assume remote trigger feature is available
+	}
</code_context>
<issue_to_address>
**Watt-only stations reject profiles**

When the OCPP 2.0.1 station accepts only watt-based charging schedules, `NewStation` always selects amperes, and `Setup` never discovers the station's supported charging-rate unit; a station that supports only watts therefore receives an unsupported amperes profile and rejects charging limits.

Discover the station's supported charging-rate unit during setup and construct profiles using a supported unit.
</issue_to_address>

### Comment 25
<location path="assets/js/utils/ocpp.ts" line_range="12" />
<code_context>
 }

+export function getOcpp20Url(ocpp: Ocpp): string {
+  return `ws://${window.location.hostname}:${ocpp.config.port20}/`;
+}
+
</code_context>
<issue_to_address>
**Proxy URL is omitted for OCPP 2.0.1**

When an installation uses a custom external OCPP URL or reverse proxy, `getOcpp20Url` always builds a URL from the browser hostname and `port20`, ignoring the configured `externalUrl`; the charger setup instructions therefore show an unreachable endpoint when evcc is exposed through a custom host or reverse proxy.

Make the OCPP 2.0.1 URL helper honor the configured external URL, including any required station-ID suffix.
</issue_to_address>

### Comment 26
<location path="charger/ocpp20/cs_core.go" line_range="88" />
<code_context>
+	cs.mu.Lock()
+	if reg, ok := cs.regs[chargingStationId]; ok {
+		reg.mu.Lock()
+		reg.status[request.EvseID] = request
+		reg.mu.Unlock()
+	}
</code_context>
<issue_to_address>
**Late status notification rolls state back**

When a delayed status notification has an earlier timestamp than the connector’s current status, `OnStatusNotification` unconditionally replaces the cached status and fans the request out to EVSEs. An older notification delivered after a newer one therefore restores the old connector state, which callers continue to observe until another notification arrives.

Compare notification timestamps with the stored status and ignore stale updates before caching or fanning them out.
</issue_to_address>

### Comment 27
<location path="charger/ocpp20_test.go" line_range="162" />
<code_context>
+	suite.InDelta(1.5, energy, 0.001) // 1500 Wh → 1.5 kWh
+
+	// 6. evcc → station: MaxCurrent triggers SetChargingProfile (handler accepts)
+	suite.Require().NoError(c.MaxCurrent(16))
+
+	// 7. transaction ends — evse clears it
</code_context>
<issue_to_address>
**Max-current no-op passes**

When `MaxCurrent` is changed to return nil without dispatching a request, `TestE2E`'s `NoError` assertion at line 162 passes if `MaxCurrent` returns nil without sending a charging profile. The fake handler's acceptance at `charger/ocpp20_test_handler.go:156-158` is never observed or asserted, so the test does not require a request to reach the station.

Record received `SetChargingProfile` requests in the fake handler and assert that `MaxCurrent(16)` sends one with the expected limit.
</issue_to_address>

### Comment 28
<location path="templates/definition/charger/ocpp20.yaml" line_range="1" />
<code_context>
+template: ocpp20
+products:
+  - description:
</code_context>
<issue_to_address>
**Generated template docs stay stale**

When the new template is merged without regenerating the template documentation, the new charger template has no corresponding generated documentation update, so the template documentation omits this configuration.

Run `make docs` and include the generated documentation changes.
</issue_to_address>

### Comment 29
<location path="templates/definition/charger/ocpp20.yaml" line_range="66" />
<code_context>
+    description:
+      de: EVSE
+      en: EVSE
+    default: 1
+    help:
+      de: Nummer des EVSE (Electric Vehicle Supply Equipment)
</code_context>
<issue_to_address>
**Template repeats inherited settings**

The template explicitly repeats properties already inherited with the same values, leaving redundant settings in the charger definition.

Remove properties whose values already match the inherited defaults.

Also at `templates/definition/charger/ocpp20.yaml:70`, `templates/definition/charger/ocpp20.yaml:79`, `templates/definition/charger/ocpp20.yaml:83`, `templates/definition/charger/ocpp20.yaml:87`, `templates/definition/charger/ocpp20.yaml:101`, `templates/definition/charger/ocpp20.yaml:105`, `templates/definition/charger/ocpp20.yaml:110`, `templates/definition/charger/ocpp20.yaml:114`.
</issue_to_address>

### Comment 30
<location path="assets/js/utils/ocpp.ts" line_range="12" />
<code_context>
  return `ws://${window.location.hostname}:${ocpp.config.port20}/`;
</code_context>
<issue_to_address>
**security (javascript.lang.security.detect-insecure-websocket):** Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections.

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread charger/ocpp20/cs.go
cs.mu.Lock()

// check for configured charging station
reg, ok := cs.regs[station.ID()]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Station IDs are trusted as identity

When an attacker can reach the OCPP 2.0.1 listener and knows or guesses a configured station ID, a device on the OCPP network can connect using a configured station ID and be treated as that station: NewChargingStation matches the ID to its registration, and OnBootNotification accepts it without authenticating the peer. The device can submit forged status, transaction, and meter updates for the configured EVSE, which evcc then uses as charger state and measurements.

Authenticate the connecting station (for example, with configured credentials or client certificates) before binding its connection to a configured station ID.

Prompt for AI agents
In `charger/ocpp20/cs.go` at line 163:

**Station IDs are trusted as identity**

When an attacker can reach the OCPP 2.0.1 listener and knows or guesses a configured station ID, a device on the OCPP network can connect using a configured station ID and be treated as that station: `NewChargingStation` matches the ID to its registration, and `OnBootNotification` accepts it without authenticating the peer. The device can submit forged status, transaction, and meter updates for the configured EVSE, which evcc then uses as charger state and measurements.

Authenticate the connecting station (for example, with configured credentials or client certificates) before binding its connection to a configured station ID.


server := ws.NewServer()
server.SetCheckOriginHandler(func(r *http.Request) bool { return true })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Malicious sites can use OCPP

When an evcc user visits a malicious page while their browser can reach the OCPP 2.0.1 port, a page opened in an evcc user's browser can connect to the OCPP 2.0.1 listener and send OCPP frames because SetCheckOriginHandler accepts every origin. The browser can therefore act as a cross-site proxy to impersonate a configured station and alter its reported status or meter data.

Reject cross-origin WebSocket requests, and require station authentication before accepting OCPP messages.

Prompt for AI agents
In `charger/ocpp20/instance.go` at line 53:

**Malicious sites can use OCPP**

When an evcc user visits a malicious page while their browser can reach the OCPP 2.0.1 port, a page opened in an evcc user's browser can connect to the OCPP 2.0.1 listener and send OCPP frames because `SetCheckOriginHandler` accepts every origin. The browser can therefore act as a cross-site proxy to impersonate a configured station and alter its reported status or meter data.

Reject cross-origin WebSocket requests, and require station authentication before accepting OCPP messages.

Comment thread charger/ocpp20/cs_log.go
s = "recv" + s
}
if ok {
cs.log.TRACE.Println(s)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · RFID tokens enter trace logs

When a charger sends a transaction event with an IDToken while TRACE logging is enabled, cs.print logs the raw received JSON message, including transaction events' IDToken, so enabling TRACE logging exposes RFID tokens in logs.

Redact sensitive fields from OCPP frames before logging them, or avoid logging raw frame contents.

Prompt for AI agents
In `charger/ocpp20/cs_log.go` at line 16:

**RFID tokens enter trace logs**

When a charger sends a transaction event with an IDToken while TRACE logging is enabled, `cs.print` logs the raw received JSON message, including transaction events' `IDToken`, so enabling TRACE logging exposes RFID tokens in logs.

Redact sensitive fields from OCPP frames before logging them, or avoid logging raw frame contents.

From AGENTS.md L303:

- Never log sensitive information (passwords, tokens, personal data)

Comment thread charger/ocpp20/instance.go Outdated
Comment on lines +105 to +106
if dispatcher.IsRunning() {
break

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · OCPP server startup hangs

When the configured OCPP 2.0.1 port cannot be bound or the server otherwise fails to start, Instance ignores the result of csms.Start and waits indefinitely for dispatcher.IsRunning(), so charger initialization and tests hang instead of reporting the listen error.

Propagate the server startup result and stop waiting when startup fails.

Also at charger/ocpp20/instance.go:104, charger/ocpp20_test.go:36.

Prompt for AI agents
In `charger/ocpp20/instance.go` at lines 105-106:

**OCPP server startup hangs**

When the configured OCPP 2.0.1 port cannot be bound or the server otherwise fails to start, `Instance` ignores the result of `csms.Start` and waits indefinitely for `dispatcher.IsRunning()`, so charger initialization and tests hang instead of reporting the listen error.

Propagate the server startup result and stop waiting when startup fails.

Also at `charger/ocpp20/instance.go:104`, `charger/ocpp20_test.go:36`.

Comment thread charger/ocpp20/cs.go Outdated
cp.onTransportConnect()
}

return cp, init(cp)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Failed setup blocks retries

When the first station initialization fails and registration is retried, RegisterChargingStation leaves the station in reg.cs when init(cp) fails, so later registrations return the cached station without rerunning setup; transient failures leave the charger unusable or partially initialized.

Clear the cached station when initialization fails, or cache it only after initialization succeeds.

Prompt for AI agents
In `charger/ocpp20/cs.go` at line 155:

**Failed setup blocks retries**

When the first station initialization fails and registration is retried, `RegisterChargingStation` leaves the station in `reg.cs` when `init(cp)` fails, so later registrations return the cached station without rerunning setup; transient failures leave the charger unusable or partially initialized.

Clear the cached station when initialization fails, or cache it only after initialization succeeds.

Comment thread charger/ocpp20/cs_core.go
cs.mu.Lock()
if reg, ok := cs.regs[chargingStationId]; ok {
reg.mu.Lock()
reg.status[request.EvseID] = request

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Late status notification rolls state back

When a delayed status notification has an earlier timestamp than the connector’s current status, OnStatusNotification unconditionally replaces the cached status and fans the request out to EVSEs. An older notification delivered after a newer one therefore restores the old connector state, which callers continue to observe until another notification arrives.

Compare notification timestamps with the stored status and ignore stale updates before caching or fanning them out.

Prompt for AI agents
In `charger/ocpp20/cs_core.go` at line 88:

**Late status notification rolls state back**

When a delayed status notification has an earlier timestamp than the connector’s current status, `OnStatusNotification` unconditionally replaces the cached status and fans the request out to EVSEs. An older notification delivered after a newer one therefore restores the old connector state, which callers continue to observe until another notification arrives.

Compare notification timestamps with the stored status and ignore stale updates before caching or fanning them out.

Comment thread charger/ocpp20_test.go
suite.InDelta(1.5, energy, 0.001) // 1500 Wh → 1.5 kWh

// 6. evcc → station: MaxCurrent triggers SetChargingProfile (handler accepts)
suite.Require().NoError(c.MaxCurrent(16))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Max-current no-op passes

When MaxCurrent is changed to return nil without dispatching a request, TestE2E's NoError assertion at line 162 passes if MaxCurrent returns nil without sending a charging profile. The fake handler's acceptance at charger/ocpp20_test_handler.go:156-158 is never observed or asserted, so the test does not require a request to reach the station.

Record received SetChargingProfile requests in the fake handler and assert that MaxCurrent(16) sends one with the expected limit.

Prompt for AI agents
In `charger/ocpp20_test.go` at line 162:

**Max-current no-op passes**

When `MaxCurrent` is changed to return nil without dispatching a request, `TestE2E`'s `NoError` assertion at line 162 passes if `MaxCurrent` returns nil without sending a charging profile. The fake handler's acceptance at `charger/ocpp20_test_handler.go:156-158` is never observed or asserted, so the test does not require a request to reach the station.

Record received `SetChargingProfile` requests in the fake handler and assert that `MaxCurrent(16)` sends one with the expected limit.

@@ -0,0 +1,116 @@
template: ocpp20

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Generated template docs stay stale

When the new template is merged without regenerating the template documentation, the new charger template has no corresponding generated documentation update, so the template documentation omits this configuration.

Run make docs and include the generated documentation changes.

Prompt for AI agents
In `templates/definition/charger/ocpp20.yaml` at line 1:

**Generated template docs stay stale**

When the new template is merged without regenerating the template documentation, the new charger template has no corresponding generated documentation update, so the template documentation omits this configuration.

Run `make docs` and include the generated documentation changes.

From AGENTS.md L286:

- Update docs after template changes: `make docs`

description:
de: Anschluss
en: Connector
default: 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Template repeats inherited settings

The template explicitly repeats properties already inherited with the same values, leaving redundant settings in the charger definition.

Remove properties whose values already match the inherited defaults.

Also at templates/definition/charger/ocpp20.yaml:70, templates/definition/charger/ocpp20.yaml:79, templates/definition/charger/ocpp20.yaml:83, templates/definition/charger/ocpp20.yaml:87, templates/definition/charger/ocpp20.yaml:101, templates/definition/charger/ocpp20.yaml:105, templates/definition/charger/ocpp20.yaml:110, templates/definition/charger/ocpp20.yaml:114.

Prompt for AI agents
In `templates/definition/charger/ocpp20.yaml` at line 66:

**Template repeats inherited settings**

The template explicitly repeats properties already inherited with the same values, leaving redundant settings in the charger definition.

Remove properties whose values already match the inherited defaults.

Also at `templates/definition/charger/ocpp20.yaml:70`, `templates/definition/charger/ocpp20.yaml:79`, `templates/definition/charger/ocpp20.yaml:83`, `templates/definition/charger/ocpp20.yaml:87`, `templates/definition/charger/ocpp20.yaml:101`, `templates/definition/charger/ocpp20.yaml:105`, `templates/definition/charger/ocpp20.yaml:110`, `templates/definition/charger/ocpp20.yaml:114`.

From AGENTS.md L284:

- Don't restate param properties that `util/templates/defaults.yaml` already defines for that param name. Properties (description, help, type, unit, default, example, required, advanced, mask, private, usages, …) are inherited from defaults; only specify a property in a template to give it a _different_ value. Restating the same value is redundant duplication: reference the param by `name` alone.

Comment thread assets/js/utils/ocpp.ts Outdated
}

export function getOcpp20Url(ocpp: Ocpp): string {
return `ws://${window.location.hostname}:${ocpp.config.port20}/`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (javascript.lang.security.detect-insecure-websocket): Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections.

Source: opengrep

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 30 issues

Fixed security issues:

  • github.com/go-jose/go-jose/v4 (link)
  • github.com/xuri/excelize/v2 (link)
  • golang.org/x/net (link)
Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="charger/ocpp20/cs_core.go" line_range="65" />
<code_context>

 	res := &core.StartTransactionConfirmation{
 		IdTagInfo: &types.IdTagInfo{
 			Status: types.AuthorizationStatusAccepted,
 		},
-		TransactionId: txnId,
</code_context>
<issue_to_address>
**Unrecognized RFID tokens are accepted**

When a charger asks to authorize an unrecognized RFID token, `OnAuthorize` returns `Accepted` without checking the supplied IdToken against an authorization policy, so a charger treats any presented RFID token as authorized and allows its holder to start charging.

Validate incoming IdTokens against an explicit authorization policy, or make the open-authorization behavior an explicit opt-in.
</issue_to_address>

### Comment 2
<location path="charger/ocpp20/cs.go" line_range="163" />
<code_context>
+	cs.mu.Lock()
+
+	// check for configured charging station
+	reg, ok := cs.regs[station.ID()]
+	if ok {
+		cs.log.DEBUG.Printf("charging station connected: %s", station.ID())
</code_context>
<issue_to_address>
**Charging stations can be impersonated**

When an untrusted peer can reach the OCPP 2.0.1 listener and knows or guesses a configured station ID, `NewChargingStation` associates a connection with a configured station using only the client-supplied station ID, and the WebSocket server accepts every Origin. A network peer that claims that ID can submit status, transaction, and meter events as the real charger, so evcc acts on forged charger state.

Authenticate station connections with a per-station credential or client certificate, and restrict listener access to trusted networks.

Also at `charger/ocpp20/instance.go:53`.
</issue_to_address>

### Comment 3
<location path="charger/ocpp20/instance.go" line_range="51" />
<code_context>
+	once.Do(func() {
+		log := util.NewLogger("ocpp20")
+
+		server := ws.NewServer()
+		server.SetCheckOriginHandler(func(r *http.Request) bool { return true })
+
</code_context>
<issue_to_address>
**OCPP traffic is unencrypted**

When the charger connection crosses a network segment an attacker can observe or modify, the OCPP 2.0.1 listener uses plain WebSocket, so a peer on the network path can read RFID IdTokens and tamper with charger messages, including meter and transaction events.

Support and prefer TLS-protected WebSocket connections, or require a secured tunnel for this listener.

Also at `templates/definition/charger/ocpp20.yaml:25`.
</issue_to_address>

### Comment 4
<location path="charger/ocpp20/cs_core.go" line_range="61" />
<code_context>
+// authorization.CSMSHandler
+
+func (cs *CSMS) OnAuthorize(chargingStationId string, request *authorization.AuthorizeRequest) (*authorization.AuthorizeResponse, error) {
+	cs.log.TRACE.Printf("charge station %s: authorize: %+v", chargingStationId, request)
+
+	return &authorization.AuthorizeResponse{
</code_context>
<issue_to_address>
**RFID tokens appear in logs**

When TRACE logging is enabled and a charger sends an authorization request, `OnAuthorize` formats the full request, including its IdToken, into a TRACE log; when TRACE is enabled, the RFID credential is sent to log output and logstash, where log readers can obtain it.

Log only non-sensitive authorization fields or redact the IdToken before logging.
</issue_to_address>

### Comment 5
<location path="charger/ocpp20/cs.go" line_range="200" />
<code_context>
+	}
+
+	// register unknown charging station
+	cs.regs[station.ID()] = newRegistration()
+	cs.log.INFO.Printf("unknown charging station connected: %s", station.ID())
+
</code_context>
<issue_to_address>
**Unknown stations exhaust server memory**

When an untrusted peer can reach the listener and repeatedly connect using distinct station IDs, `NewChargingStation` creates and retains a registration for each previously unseen station ID; `ChargingStationDisconnected` does not remove registrations whose `cs` is nil. A reachable peer can connect with many distinct IDs and leave unbounded entries in the map and status list, eventually exhausting memory.

Reject or expire unknown registrations and bound the number of pending station IDs.
</issue_to_address>

### Comment 6
<location path="charger/ocpp20.go" line_range="178-179" />
<code_context>
+	}
+
+	if remoteStart {
+		idTag = lo.CoalesceOrEmpty(idTag, defaultIdTag20)
+	}
+
+	evse, err := ocpp20.NewEVSE(ctx, log, evseID, connectorID, cp, idTag, meterInterval)
</code_context>
<issue_to_address>
**Remote start never begins a transaction**

When the `remotestart` option is enabled and a vehicle connects, the OCPP 2.0.1 path only supplies an ID tag and never sends a `RequestStartTransaction`, so stations that require a CSMS-initiated start wait for a local start instead of starting automatically.

Send the OCPP 2.0.1 remote-start request when the option is enabled and a vehicle connects.

Also at `charger/ocpp20.go:176-177`, `templates/definition/charger/ocpp20.yaml:86`.
</issue_to_address>

### Comment 7
<location path="charger/ocpp20.go" line_range="366-367" />
<code_context>
+		Limit:       current,
+	}
+
+	if c.cp.ChargingRateUnit == types.ChargingRateUnitWatts {
+		period.Limit = math.Trunc(230.0 * current * float64(phases))
+	} else {
+		// OCPP assumes phases == 3 if not set
</code_context>
<issue_to_address>
**Charging profile sets zero power**

When the station advertises a watt-based charging rate unit and phase switching has not set a phase count, `createTxDefaultChargingProfile` multiplies the requested current by `phases` for watt-based stations, but `phases` is zero until phase switching is invoked. The resulting profile limit is zero, so `MaxCurrent` disables charging on those stations.

Use a valid default phase count or determine the actual phase count before converting current to watts.
</issue_to_address>

### Comment 8
<location path="charger/ocpp20/cp.go" line_range="60" />
<code_context>
+		meterC:                   make(chan struct{}, 1),
+		bootNotificationRequestC: make(chan *provisioning.BootNotificationRequest, 1),
+
+		ChargingRateUnit:        types.ChargingRateUnitAmperes,
+		HasRemoteTriggerFeature: true, // assume remote trigger feature is available
+	}
</code_context>
<issue_to_address>
**W-only stations reject profiles**

When a station supports charging profiles in watts but not amperes, `Station` defaults `ChargingRateUnit` to amperes, and `Setup` discovers only phase-switching support, so the generated profile always requests amperes. A station that supports charging profiles only in watts rejects the request, preventing evcc from applying its charging limit.

Discover the station's supported charging-rate unit during setup and use a supported unit when creating profiles.

Also at `charger/ocpp20/cp_setup.go:29-36`.
</issue_to_address>

### Comment 9
<location path="charger/ocpp/connector_core.go" line_range="45" />
<code_context>
-			core.ChargePointStatusSuspendedEV, core.ChargePointStatusSuspendedEVSE:
-			conn.rebooted = false
-		}
+	if applied && request.Status == core.ChargePointStatusAvailable && conn.txnId != 0 {
+		conn.log.DEBUG.Printf("clearing stale transaction %d on Available status", conn.txnId)
+		conn.txnId = 0
</code_context>
<issue_to_address>
**Reboot leaves stale session active**

When a rebooted charger reports `Preparing` before `Available`, the OCPP 1.6 boot and status handling no longer clears the pre-reboot transaction and ID tag in this sequence, so the connector treats the stale session as active and skips authentication.

Restore reboot recovery so a rebooted connector clears its stale transaction and ID tag before handling the new session.
</issue_to_address>

### Comment 10
<location path="charger/ocpp20/cs.go" line_range="155" />
<code_context>
+		cp.onTransportConnect()
+	}
+
+	return cp, init(cp)
+}
+
</code_context>
<issue_to_address>
**Failed setup is never retried**

When initial station setup returns an error, `RegisterChargingStation` leaves `reg.cs` populated when `init(cp)` fails, so a later registration returns the cached station without running setup again and the charger remains uninitialized.

Remove or reset the cached station when `init(cp)` fails so a later registration retries setup.
</issue_to_address>

### Comment 11
<location path="charger/ocpp20/instance.go" line_range="102-105" />
<code_context>
+	getOcpp20Url,
+	getOcpp20UrlWithStationId,
+} from "@/utils/ocpp";

 const initialValues = {
 	type: ConfigType.Template,
</code_context>
<issue_to_address>
**Listener startup can block forever**

When the OCPP 2.0.1 listener fails to start, such as because its port is occupied, `csms.Start` runs in a goroutine whose error is discarded, while `Instance` waits indefinitely for `dispatcher.IsRunning()`; initialization and the test suite hang instead of reporting the bind failure.

Propagate listener startup errors to `Instance` and return an error or timeout instead of waiting indefinitely.

Also at `charger/ocpp20/instance.go:101`, `charger/ocpp20_test.go:36`.
</issue_to_address>

### Comment 12
<location path="charger/ocpp20/cs_core.go" line_range="88" />
<code_context>
+	cs.mu.Lock()
+	if reg, ok := cs.regs[chargingStationId]; ok {
+		reg.mu.Lock()
+		reg.status[request.EvseID] = request
+		reg.mu.Unlock()
+	}
</code_context>
<issue_to_address>
**Connector replays a sibling's status**

When multiple connectors share an EVSE and a status arrives before the matching connector listener is created, `OnStatusNotification` caches only by EVSE ID, and `NewEVSE` replays the cached status without checking its connector ID, so a connector can start with another connector's availability and state.

Key cached statuses by both EVSE and connector ID, and replay only the matching connector's status.

Also at `charger/ocpp20/evse.go:80-82`.
</issue_to_address>

### Comment 13
<location path="charger/ocpp20/evse.go" line_range="177-180" />
<code_context>
+func (e *EVSE) updateMeterValuesLocked(meterValues []types.MeterValue) {
+	for _, mv := range meterValues {
+		for _, sv := range mv.SampledValue {
+			e.measurements[measurementKey{sv.Measurand, sv.Phase}] = sv
+		}
+	}
+	e.meterUpdated = time.Now()
+}
+
</code_context>
<issue_to_address>
**Older meter samples replace newer readings**

When an older meter report arrives after a newer sample for the same measurand and phase, `updateMeterValuesLocked` overwrites measurements in arrival order without comparing their timestamps, so delayed reports replace current power or energy readings and callers see stale values.

Compare each sample's timestamp with the stored sample and keep the newer value.
</issue_to_address>

### Comment 14
<location path="charger/ocpp20/evse.go" line_range="265-267" />
<code_context>
+func (e *EVSE) scale(sv types.SampledValue) float64 {
+	val := sv.Value
+
+	if sv.UnitOfMeasure != nil && sv.UnitOfMeasure.Multiplier != nil {
+		val *= math.Pow(10, float64(*sv.UnitOfMeasure.Multiplier))
+	}
+
+	return val
</code_context>
<issue_to_address>
**Reported power and energy are mis-scaled**

When a station reports power in kW or energy in kWh rather than W or Wh, `scale` applies the decimal multiplier but ignores the reported unit, while `TotalEnergy` divides the result by 1000 as though it were Wh; valid readings are therefore reported off by a factor of 1000.

Convert samples according to their reported unit before returning power or energy, and avoid applying the Wh-to-kWh conversion to values already in kWh.

Also at `charger/ocpp20/evse.go:274`, `charger/ocpp20/evse.go:280`.
</issue_to_address>

### Comment 15
<location path="charger/ocpp20/evse.go" line_range="252" />
<code_context>
+	if sv, ok := e.measurements[measurementKey{measurand: measurand}]; ok {
+		return e.scale(sv), nil
+	}
+	for k, sv := range e.measurements {
+		if k.measurand == measurand {
+			return e.scale(sv), nil
</code_context>
<issue_to_address>
**Phase readings are not totaled**

When a station reports active-import power only as phase-specific samples, `getMeasurement` returns the first matching phase from a map instead of combining phase values, so `CurrentPower` reports one phase rather than total power and the selected phase varies across map iterations.

Aggregate the matching phase samples when no aggregate sample is available.

Also at `charger/ocpp20/evse.go:253-254`.
</issue_to_address>

### Comment 16
<location path="charger/ocpp20.go" line_range="107" />
<code_context>
+	)
+
+	// Power measurement
+	if _, err := c.evse.CurrentPower(); err == nil {
+		powerG = c.evse.CurrentPower
+	}
</code_context>
<issue_to_address>
**Late meter samples never expose capabilities**

When the station has not sent the corresponding measurement before charger construction finishes, `NewOCPP20FromConfig` probes readings only once while building the decorators, so measurements that arrive later never add the meter capabilities and callers cannot access them through the charger API.

Expose the measurement capabilities independently of whether samples are already cached during construction.

Also at `charger/ocpp20.go:112-127`, `charger/ocpp20.go:133`, `charger/ocpp20.go:200`.
</issue_to_address>

### Comment 17
<location path="charger/ocpp20/evse.go" line_range="155" />
<code_context>
+
+	case transactions.TransactionEventEnded:
+		e.log.DEBUG.Printf("evse %d: transaction ended: %s", e.id, request.TransactionInfo.TransactionID)
+		e.transaction = nil
+		e.idTag = ""
+	}
</code_context>
<issue_to_address>
**Ended sessions retain charging power**

When a transaction ends without a final power sample and no later meter values arrive, `OnTransactionEvent` clears the transaction but leaves its last power sample cached, and `CurrentPower` continues returning that value, so callers see power from the ended session.

Clear or invalidate the cached power when handling a transaction-ended event without a final power sample.

Also at `charger/ocpp20/evse.go:108-111`, `charger/ocpp20/evse.go:156-157`, `charger/ocpp20/evse.go:274`.
</issue_to_address>

### Comment 18
<location path="charger/ocpp20/evse.go" line_range="107-111" />
<code_context>
+	}
+}
+
+// WatchDog triggers meter values periodically
+func (e *EVSE) WatchDog(ctx context.Context, meterInterval time.Duration) {
+	// TODO: Implement watchdog for OCPP 2.0.1
+	// In 2.0.1, meter values typically come via TransactionEvent
+}
+
+// OnStatusNotification handles status notifications.
</code_context>
<issue_to_address>
**Meter watchdog never refreshes readings**

When the station does not send fresh meter values on its own, `EVSE.WatchDog` is a no-op, so the configured meter interval never triggers meter-value requests and evcc keeps stale measurements.

Implement and start the OCPP 2.0.1 meter watchdog so it requests fresh meter values at the configured interval.

Also at `templates/definition/charger/ocpp20.yaml:103-104`.
</issue_to_address>

### Comment 19
<location path="charger/ocpp20/evse.go" line_range="274" />
<code_context>
+
+// CurrentPower returns the current power in W
+func (e *EVSE) CurrentPower() (float64, error) {
+	return e.getMeasurement(types.MeasurandPowerActiveImport)
+}
+
</code_context>
<issue_to_address>
**Disconnected meters stay stale**

When the station disconnects or stops sending meter updates after reporting a nonzero value, `CurrentPower` and the other measurement getters keep returning cached samples without checking station connectivity or sample age. Because `WatchDog` is unimplemented, a disconnect or stalled meter stream leaves the last readings in use indefinitely, and callers see stale power and energy instead of a timeout or zero.

Apply connectivity and meter-freshness checks to OCPP 2.0 measurement getters, and implement the watchdog or equivalent timeout handling.

Also at `charger/ocpp20/evse.go:109-110`.
</issue_to_address>

### Comment 20
<location path="charger/ocpp20/evse.go" line_range="120-121" />
<code_context>
+	e.mu.Lock()
+	defer e.mu.Unlock()
+
+	e.status = request
+	e.statusTime = time.Now()
+
+	// signal initialization (once only, safe for concurrent calls)
</code_context>
<issue_to_address>
**Older status replaces newer status**

When an older status notification is delivered after a newer one, `OnStatusNotification` unconditionally replaces the cached status, so `Status` and `Enabled` use the stale availability state.

Reject status notifications older than the currently cached notification.
</issue_to_address>

### Comment 21
<location path="charger/ocpp20/evse.go" line_range="156-157" />
<code_context>
+	case transactions.TransactionEventEnded:
+		e.log.DEBUG.Printf("evse %d: transaction ended: %s", e.id, request.TransactionInfo.TransactionID)
+		e.transaction = nil
+		e.idTag = ""
+	}
+
+	// update meter values from transaction event
</code_context>
<issue_to_address>
**Old transaction events clear the active session**

When an end event for an earlier transaction arrives after a newer transaction has started, `OnTransactionEvent` clears the current transaction and ID tag without checking the event's transaction ID or sequence number, so a delayed or repeated event erases the newer session and callers see it as inactive.

Apply transaction events only when their transaction identity and sequence are valid for the current transaction.

Also at `charger/ocpp20/evse.go:148-155`.
</issue_to_address>

### Comment 22
<location path="charger/ocpp20.go" line_range="286" />
<code_context>
+		case availability.ConnectorStatusOccupied:
+			// Check if actually charging
+			if state, ok := c.evse.ChargingState(); ok {
+				return state == transactions.ChargingStateCharging, nil
+			}
+			return true, nil
</code_context>
<issue_to_address>
**Enabled state contradicts connector state**

When the EV is suspended by the vehicle, or an Available connector still reports positive offered current after `Enable(false)`, `Enabled` reports an occupied `SuspendedEV` connector as disabled and can report an Available connector as enabled from its offered-current or offered-power readings, so callers see incorrect charging state.

Make `Enabled` use the connector and cached control state consistently instead of treating suspended charging or an available hardware offer as enabled state.

Also at `charger/ocpp20.go:292-293`.
</issue_to_address>

### Comment 23
<location path="charger/ocpp/connector_core.go" line_range="99-104" />
<code_context>
-					// freshness is measured locally: charger sample timestamps may lag (Mennekes: 6-7s)
-					conn.meterUpdated = conn.clock.Now()
-				}
+		if !meterValue.Timestamp.Time.Before(conn.meterUpdated) {
+			for _, sample := range meterValue.SampledValue {
+				sample.Value = strings.TrimSpace(sample.Value)
+				conn.measurements[getSampleKey(sample)] = sample
+				conn.meterUpdated = meterValue.Timestamp.Time
 			}
 		}
 	}
</code_context>
<issue_to_address>
**Fresh readings appear expired**

When a charger reports meter timestamps behind local time, `OnMeterValues` stores the charger timestamp in `meterUpdated`, which is also used for local freshness checks and compared with locally assigned times; fresh readings can be rejected or appear expired, leaving readings stale and retriggering meter requests.

Track local receipt time separately from the charger sample timestamp and use receipt time for watchdog freshness.
</issue_to_address>

### Comment 24
<location path="charger/ocpp/connector_core.go" line_range="103" />
<code_context>
+			for _, sample := range meterValue.SampledValue {
+				sample.Value = strings.TrimSpace(sample.Value)
+				conn.measurements[getSampleKey(sample)] = sample
+				conn.meterUpdated = meterValue.Timestamp.Time
 			}
 		}
</code_context>
<issue_to_address>
**Boundary samples overwrite live readings**

When one message contains the same measurand as both a live and a transaction-boundary sample, the meter loop stores samples in message order, so a later `Transaction.Begin` or `Transaction.End` snapshot replaces the live reading and callers see a stale boundary value.

Prefer live samples over transaction-boundary snapshots when a message contains duplicate measurands.
</issue_to_address>

### Comment 25
<location path="assets/js/components/Config/ChargerModal.vue" line_range="178" />
<code_context>
 				this.currentTemplate !== null &&
 				this.currentTemplate?.Params.some((p: TemplateParam) => p.Name === "connector") &&
+				this.currentTemplate?.Params.some((p: TemplateParam) => p.Name === "stationid") &&
+				!this.isOcpp20
+			);
+		},
</code_context>
<issue_to_address>
**OCPP 2 setup URL is hidden**

When a user selects an OCPP 2.0.1 charger template in the configuration modal, `isOcpp` is false for OCPP 2.0.1 templates, but the template description, URL field, and onboarding controls are all gated on `isOcpp`; users configuring an OCPP 2 charger therefore do not see the generated server URL or the station-ID onboarding flow.

Render the OCPP instructions and URL for either OCPP version, and allow the station-ID onboarding lookup for OCPP 2.0.1 as well.
</issue_to_address>

### Comment 26
<location path="charger/ocpp20.go" line_range="206" />
<code_context>
+// In OCPP 2.0.1, phase switching is encoded via ChargingSchedulePeriod.NumberPhases
+// in the active charging profile, so we re-send the profile with the new phase count.
+func (c *OCPP20) phases1p3p(phases int) error {
+	c.phases = phases
+
+	enabled, err := c.Enabled()
</code_context>
<issue_to_address>
**Concurrent controls send stale limits**

When phase switching and a current-limit update run concurrently, `phases1p3p` and `MaxCurrentMillis` read and write `c.phases` and `c.current` without synchronization, then send profiles independently. Concurrent calls race and can leave the station enforcing a profile with the wrong phase/current combination.

Serialize updates to the shared phase/current state and the resulting profile requests.

Also at `charger/ocpp20.go:415`.
</issue_to_address>

### Comment 27
<location path="charger/ocpp20/cs.go" line_range="148-152" />
<code_context>
+	cp = newfun()
+
+	cs.mu.Lock()
+	reg.cs = cp
+	cs.mu.Unlock()
+
+	if registered {
+		cp.onTransportConnect()
+	}
+
</code_context>
<issue_to_address>
**Connection is missed during registration**

When the charger connects between registration creation and assignment of `reg.cs`, `NewChargingStation` can find the new registration while `reg.cs` is still nil and return without calling `onTransportConnect`. `RegisterChargingStation` then stores the station but skips `onTransportConnect` because its earlier `registered` value was false, leaving `HasConnected` open and setup waiting until timeout.

Ensure a connection observed during registration is handed to the newly created station, or recheck connection state after assigning `reg.cs`.
</issue_to_address>

### Comment 28
<location path="charger/ocpp20/cs.go" line_range="173" />
<code_context>
+		}
+
+		cs.mu.Unlock()
+		cs.publish()
+		return
+	}
</code_context>
<issue_to_address>
**OCPP status updates are not broadcast**

When an OCPP 2.0.1 station connects or disconnects without an unrelated OCPP 1.6 status update, the OCPP 2.0.1 connection handlers call `publish`, but no code registers their `SetUpdated` callback. Its callback remains nil, so connect and disconnect events do not publish a new OCPP status and consumers can keep displaying the previous connection state.

Wire the OCPP 2.0.1 CSMS update callback into the same status-broadcast path as OCPP 1.6.

Also at `charger/ocpp20/cs.go:215`.
</issue_to_address>

### Comment 29
<location path="charger/ocpp20.go" line_range="87-97" />
<code_context>
+	stackLevelZero := cc.StackLevelZero != nil && *cc.StackLevelZero
+	profileKindRelative := cc.ProfileKindRelative
+
+	c, err := NewOCPP20(ctx,
+		cc.StationId, cc.EVSE, cc.Connector, cc.IdTag,
+		cc.MeterInterval,
+		stackLevelZero, profileKindRelative, cc.RemoteStart,
+		cc.PhaseSwitching,
+		cc.ConnectTimeout)
+	if err != nil {
+		return c, err
+	}
+
+	if !sponsor.IsAuthorized() {
+		return nil, api.ErrSponsorRequired
+	}
</code_context>
<issue_to_address>
**Unauthorized setup waits for charger**

When the instance is not authorized to use the sponsored charger and the station is not connected, `NewOCPP20FromConfig` constructs and waits for the charger before checking sponsorship. An unauthorized configuration therefore waits for connection or times out before reporting the sponsorship error, and can leave its station registration and EVSE listener established when it does return.

Check sponsorship authorization before starting OCPP registration or waiting for the charger.
</issue_to_address>

### Comment 30
<location path="charger/ocpp20.go" line_range="170" />
<code_context>
+			case <-cp.HasConnected():
+			}
+
+			return cp.Setup()
+		},
+	)
</code_context>
<issue_to_address>
**Reboots do not reapply station setup**

When the charging station sends another BootNotification after initial setup, the OCPP 2.0.1 charger never starts `MonitorReboot`, so the setup callback is not rerun after reboot and discovered capabilities or charging profiles are not reapplied.

Start reboot monitoring for the OCPP 2.0.1 station and rerun setup when a reboot is detected.

Also at `charger/ocpp20.go:199`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread charger/ocpp20/cs_core.go

return &authorization.AuthorizeResponse{
IdTokenInfo: types.IdTokenInfo{
Status: types.AuthorizationStatusAccepted,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Unrecognized RFID tokens are accepted

When a charger asks to authorize an unrecognized RFID token, OnAuthorize returns Accepted without checking the supplied IdToken against an authorization policy, so a charger treats any presented RFID token as authorized and allows its holder to start charging.

Validate incoming IdTokens against an explicit authorization policy, or make the open-authorization behavior an explicit opt-in.

Prompt for AI agents
In `charger/ocpp20/cs_core.go` at line 65:

**Unrecognized RFID tokens are accepted**

When a charger asks to authorize an unrecognized RFID token, `OnAuthorize` returns `Accepted` without checking the supplied IdToken against an authorization policy, so a charger treats any presented RFID token as authorized and allows its holder to start charging.

Validate incoming IdTokens against an explicit authorization policy, or make the open-authorization behavior an explicit opt-in.

Comment thread charger/ocpp20/cs.go
cs.mu.Lock()

// check for configured charging station
reg, ok := cs.regs[station.ID()]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Charging stations can be impersonated

When an untrusted peer can reach the OCPP 2.0.1 listener and knows or guesses a configured station ID, NewChargingStation associates a connection with a configured station using only the client-supplied station ID, and the WebSocket server accepts every Origin. A network peer that claims that ID can submit status, transaction, and meter events as the real charger, so evcc acts on forged charger state.

Authenticate station connections with a per-station credential or client certificate, and restrict listener access to trusted networks.

Also at charger/ocpp20/instance.go:53.

Prompt for AI agents
In `charger/ocpp20/cs.go` at line 163:

**Charging stations can be impersonated**

When an untrusted peer can reach the OCPP 2.0.1 listener and knows or guesses a configured station ID, `NewChargingStation` associates a connection with a configured station using only the client-supplied station ID, and the WebSocket server accepts every Origin. A network peer that claims that ID can submit status, transaction, and meter events as the real charger, so evcc acts on forged charger state.

Authenticate station connections with a per-station credential or client certificate, and restrict listener access to trusted networks.

Also at `charger/ocpp20/instance.go:53`.

once.Do(func() {
log := util.NewLogger("ocpp20")

server := ws.NewServer()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · OCPP traffic is unencrypted

When the charger connection crosses a network segment an attacker can observe or modify, the OCPP 2.0.1 listener uses plain WebSocket, so a peer on the network path can read RFID IdTokens and tamper with charger messages, including meter and transaction events.

Support and prefer TLS-protected WebSocket connections, or require a secured tunnel for this listener.

Also at templates/definition/charger/ocpp20.yaml:25.

Prompt for AI agents
In `charger/ocpp20/instance.go` at line 51:

**OCPP traffic is unencrypted**

When the charger connection crosses a network segment an attacker can observe or modify, the OCPP 2.0.1 listener uses plain WebSocket, so a peer on the network path can read RFID IdTokens and tamper with charger messages, including meter and transaction events.

Support and prefer TLS-protected WebSocket connections, or require a secured tunnel for this listener.

Also at `templates/definition/charger/ocpp20.yaml:25`.

Comment thread charger/ocpp20/cs_core.go
// authorization.CSMSHandler

func (cs *CSMS) OnAuthorize(chargingStationId string, request *authorization.AuthorizeRequest) (*authorization.AuthorizeResponse, error) {
cs.log.TRACE.Printf("charge station %s: authorize: %+v", chargingStationId, request)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · RFID tokens appear in logs

When TRACE logging is enabled and a charger sends an authorization request, OnAuthorize formats the full request, including its IdToken, into a TRACE log; when TRACE is enabled, the RFID credential is sent to log output and logstash, where log readers can obtain it.

Log only non-sensitive authorization fields or redact the IdToken before logging.

Prompt for AI agents
In `charger/ocpp20/cs_core.go` at line 61:

**RFID tokens appear in logs**

When TRACE logging is enabled and a charger sends an authorization request, `OnAuthorize` formats the full request, including its IdToken, into a TRACE log; when TRACE is enabled, the RFID credential is sent to log output and logstash, where log readers can obtain it.

Log only non-sensitive authorization fields or redact the IdToken before logging.

Comment thread charger/ocpp20/cs.go
}

// register unknown charging station
cs.regs[station.ID()] = newRegistration()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Unknown stations exhaust server memory

When an untrusted peer can reach the listener and repeatedly connect using distinct station IDs, NewChargingStation creates and retains a registration for each previously unseen station ID; ChargingStationDisconnected does not remove registrations whose cs is nil. A reachable peer can connect with many distinct IDs and leave unbounded entries in the map and status list, eventually exhausting memory.

Reject or expire unknown registrations and bound the number of pending station IDs.

Prompt for AI agents
In `charger/ocpp20/cs.go` at line 200:

**Unknown stations exhaust server memory**

When an untrusted peer can reach the listener and repeatedly connect using distinct station IDs, `NewChargingStation` creates and retains a registration for each previously unseen station ID; `ChargingStationDisconnected` does not remove registrations whose `cs` is nil. A reachable peer can connect with many distinct IDs and leave unbounded entries in the map and status list, eventually exhausting memory.

Reject or expire unknown registrations and bound the number of pending station IDs.

Comment thread charger/ocpp20.go
// In OCPP 2.0.1, phase switching is encoded via ChargingSchedulePeriod.NumberPhases
// in the active charging profile, so we re-send the profile with the new phase count.
func (c *OCPP20) phases1p3p(phases int) error {
c.phases = phases

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Concurrent controls send stale limits

When phase switching and a current-limit update run concurrently, phases1p3p and MaxCurrentMillis read and write c.phases and c.current without synchronization, then send profiles independently. Concurrent calls race and can leave the station enforcing a profile with the wrong phase/current combination.

Serialize updates to the shared phase/current state and the resulting profile requests.

Also at charger/ocpp20.go:415.

Prompt for AI agents
In `charger/ocpp20.go` at line 206:

**Concurrent controls send stale limits**

When phase switching and a current-limit update run concurrently, `phases1p3p` and `MaxCurrentMillis` read and write `c.phases` and `c.current` without synchronization, then send profiles independently. Concurrent calls race and can leave the station enforcing a profile with the wrong phase/current combination.

Serialize updates to the shared phase/current state and the resulting profile requests.

Also at `charger/ocpp20.go:415`.

Comment thread charger/ocpp20/cs.go Outdated
Comment on lines +148 to +152
reg.cs = cp
cs.mu.Unlock()

if registered {
cp.onTransportConnect()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Connection is missed during registration

When the charger connects between registration creation and assignment of reg.cs, NewChargingStation can find the new registration while reg.cs is still nil and return without calling onTransportConnect. RegisterChargingStation then stores the station but skips onTransportConnect because its earlier registered value was false, leaving HasConnected open and setup waiting until timeout.

Ensure a connection observed during registration is handed to the newly created station, or recheck connection state after assigning reg.cs.

Prompt for AI agents
In `charger/ocpp20/cs.go` at lines 148-152:

**Connection is missed during registration**

When the charger connects between registration creation and assignment of `reg.cs`, `NewChargingStation` can find the new registration while `reg.cs` is still nil and return without calling `onTransportConnect`. `RegisterChargingStation` then stores the station but skips `onTransportConnect` because its earlier `registered` value was false, leaving `HasConnected` open and setup waiting until timeout.

Ensure a connection observed during registration is handed to the newly created station, or recheck connection state after assigning `reg.cs`.

Comment thread charger/ocpp20/cs.go
}

cs.mu.Unlock()
cs.publish()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · OCPP status updates are not broadcast

When an OCPP 2.0.1 station connects or disconnects without an unrelated OCPP 1.6 status update, the OCPP 2.0.1 connection handlers call publish, but no code registers their SetUpdated callback. Its callback remains nil, so connect and disconnect events do not publish a new OCPP status and consumers can keep displaying the previous connection state.

Wire the OCPP 2.0.1 CSMS update callback into the same status-broadcast path as OCPP 1.6.

Also at charger/ocpp20/cs.go:215.

Prompt for AI agents
In `charger/ocpp20/cs.go` at line 173:

**OCPP status updates are not broadcast**

When an OCPP 2.0.1 station connects or disconnects without an unrelated OCPP 1.6 status update, the OCPP 2.0.1 connection handlers call `publish`, but no code registers their `SetUpdated` callback. Its callback remains nil, so connect and disconnect events do not publish a new OCPP status and consumers can keep displaying the previous connection state.

Wire the OCPP 2.0.1 CSMS update callback into the same status-broadcast path as OCPP 1.6.

Also at `charger/ocpp20/cs.go:215`.

Comment thread charger/ocpp20.go
Comment on lines +87 to +97
c, err := NewOCPP20(ctx,
cc.StationId, cc.EVSE, cc.Connector, cc.IdTag,
cc.MeterInterval,
stackLevelZero, profileKindRelative, cc.RemoteStart,
cc.PhaseSwitching,
cc.ConnectTimeout)
if err != nil {
return c, err
}

if !sponsor.IsAuthorized() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Unauthorized setup waits for charger

When the instance is not authorized to use the sponsored charger and the station is not connected, NewOCPP20FromConfig constructs and waits for the charger before checking sponsorship. An unauthorized configuration therefore waits for connection or times out before reporting the sponsorship error, and can leave its station registration and EVSE listener established when it does return.

Check sponsorship authorization before starting OCPP registration or waiting for the charger.

Prompt for AI agents
In `charger/ocpp20.go` at lines 87-97:

**Unauthorized setup waits for charger**

When the instance is not authorized to use the sponsored charger and the station is not connected, `NewOCPP20FromConfig` constructs and waits for the charger before checking sponsorship. An unauthorized configuration therefore waits for connection or times out before reporting the sponsorship error, and can leave its station registration and EVSE listener established when it does return.

Check sponsorship authorization before starting OCPP registration or waiting for the charger.

Comment thread charger/ocpp20.go Resolved

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New security issues found

Comment thread assets/js/utils/ocpp.ts Resolved
Die Ladestation muss daher evcc via Hostname (funktionierende DNS-Aufloesung erforderlich!) oder ueber die IP-Adresse auf Port 8886 erreichen koennen.
Standardmaessig wird die erste eingehende Verbindung mit einer beliebigen Stationskennung verwendet.
Um mehrere Ladestationen eindeutig zuordnen zu koennen muessen die jeweilige Stationskennung (`stationid: `) und EVSE-Nummer (`evse: `) hinterlegt werden.
Viele Ladestationen fuegen die `stationid` automatisch der Backend-URL hinzu, bei manchen muss dies manuell geschehen `ws://<evcc-host>:8886/<stationid>`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (javascript.lang.security.detect-insecure-websocket): Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections.

Source: opengrep


Voraussetzungen:
* Ggf. zuvor konfigurierte OCPP-Profile (z.B. durch eine andere Backend-Anbindung) in der Ladestationskonfiguration entfernen
* Backend-URL (CSMS) in der Ladestationskonfiguration: `ws://<evcc-host>:8886/` (eventuell noch um `stationid` erweitern)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (javascript.lang.security.detect-insecure-websocket): Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections.

Source: opengrep

Voraussetzungen:
* Ggf. zuvor konfigurierte OCPP-Profile (z.B. durch eine andere Backend-Anbindung) in der Ladestationskonfiguration entfernen
* Backend-URL (CSMS) in der Ladestationskonfiguration: `ws://<evcc-host>:8886/` (eventuell noch um `stationid` erweitern)
* Protokoll: OCPP 2.0.1, ocpp201, JSON, Websocket, ws:// o.ae.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (javascript.lang.security.detect-insecure-websocket): Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections.

Source: opengrep

The charging station needs to be able to reach evcc via the host name (functioning DNS resolution required!) or via the IP address on port 8886.
By default, the first incoming connection with any station identifier is used.
In order to be able to clearly assign several charging stations, the respective station identifier (`stationid: `) and EVSE number (`evse: `) must be configured.
Many charging stations automatically add the `station id` to the backend URL, some have to do this manually `ws://<evcc-host>:8886/<stationid>`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (javascript.lang.security.detect-insecure-websocket): Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections.

Source: opengrep


Requirements:
* If necessary, remove previously configured OCPP profiles (e.g. used for a different backend connection) in the charging station configuration
* Backend URL (CSMS) in the charging station configuration: `ws://<evcc-host>:8886/` (possibly add `stationid`)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (javascript.lang.security.detect-insecure-websocket): Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections.

Source: opengrep

Requirements:
* If necessary, remove previously configured OCPP profiles (e.g. used for a different backend connection) in the charging station configuration
* Backend URL (CSMS) in the charging station configuration: `ws://<evcc-host>:8886/` (possibly add `stationid`)
* Protocol: OCPP 2.0.1, ocpp201, JSON, Websocket, ws:// or similar

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (javascript.lang.security.detect-insecure-websocket): Insecure WebSocket Detected. WebSocket Secure (wss) should be used for all WebSocket connections.

Source: opengrep

@deidi01
deidi01 force-pushed the feature/ocpp20-generic branch from a6d9086 to 290ab06 Compare November 3, 2026 12:49
@deidi01

deidi01 commented Nov 3, 2026

Copy link
Copy Markdown
Author

Sourcery Security Findings

The 7 blocking security issues flagged by Sourcery are not new
to this PR
– they reflect the same design decisions as the
existing OCPP 1.6 implementation:

  • ws:// instead of wss://: Standard for local OCPP installations.
    The OCPP 1.6 getOcppUrl() uses the same ws:// scheme.
  • No station authentication: Same as OCPP 1.6 (OnAuthorize accepts
    all tokens). OCPP Security Profiles 2/3 (TLS + client certs) are
    not implemented in either version.
  • Template says "no encryption, no authentication": This matches the
    OCPP 1.6 template and is correct for local network setups.

TLS and station authentication are valid improvements but should be
addressed as a separate feature for both OCPP versions.

Sourcery Code Review Fixes

Addressed 14 of the Sourcery code review findings:

Intentionally left open:

deidi01 and others added 9 commits November 9, 2026 13:00
…pport

- Add StationInfo, RegisterStatusHook20, Port20 to charger/ocpp
- Fix Identify() return type to []string
- Fix gci import ordering in ocpp20.go
- Fix bool vs string comparison in ocpp20.tpl
- Fix RegisterChargepoint to clear cache on init failure
Co-authored-by: Frank van der Aa <frank@van-der-aa.net>
Co-authored-by: Qian Qin <mail@qianqin.de>
Co-authored-by: Martin Schmiedel Dopke <martin.schmiedel@gmail.com>
Co-authored-by: Nicola Corna <nicola@corna.info>
Co-authored-by: MobilettoSoft <a.bernardini.md@gmail.com>
Co-authored-by: Frits van Proosdij <fritsp@gmail.com>
Co-authored-by: dingoduffel <dirk@katalise.be>
Co-authored-by: Richard E <richard@ebbersonline.nl>
Co-authored-by: RTTTC <94727758+RTTTC@users.noreply.github.com>
Co-authored-by: shpokas <ivars.strazdins@gmail.com>
Co-authored-by: amtssp <amtssp@users.noreply.hosted.weblate.org>
Co-authored-by: Filipe Lima <flepp4ever@users.noreply.hosted.weblate.org>
Co-authored-by: Joni Lehtola <jonilehtola@users.noreply.hosted.weblate.org>
Co-authored-by: aerucu <aerucu@users.noreply.hosted.weblate.org>
Co-authored-by: Priit Jõerüüt <jrthwlate@users.noreply.hosted.weblate.org>
Co-authored-by: Martin Schmiedel Dopke <martin.schmiedel@users.noreply.hosted.weblate.org>
andig and others added 10 commits November 9, 2026 13:00
…ror when no measurement available yet

OCPP 2.0.1 meter values arrive later via TransactionEvent, not at startup.
Previously, capabilities were only registered if the initial probe succeeded,
causing permanent 'measurement not available' errors.
- evcc-io#18: normalize kilo-units (kW, kWh, kA, kV) to base units in scale()
- evcc-io#15: treat SuspendedEV as enabled in Enabled()
- evcc-io#10: validate transaction ID before applying Updated/Ended events
- evcc-io#17: sum phase-specific values when no aggregate measurement available
- evcc-io#4: add 5s timeout to OCPP 2.0.1 server startup instead of waiting forever
- evcc-io#5: cache station only after successful initialization
- evcc-io#13: check station connection before returning cached status
- evcc-io#16: return cached enabled state for Available connectors
- evcc-io#23: trigger StatusNotification if no cached status available
- evcc-io#5: cache station only after successful initialization
- evcc-io#7: cleanup on constructor failure via context cancel
- evcc-io#13: check station connection before returning cached status
- evcc-io#14: start MonitorReboot to re-apply setup after station reboot
- evcc-io#16: return cached enabled state for Available connectors
- evcc-io#23: trigger StatusNotification if no cached status available
- evcc-io#18: normalize kilo-units (kW, kWh, kA, kV) to base units
- evcc-io#15: treat SuspendedEV as enabled
- evcc-io#10: validate transaction ID before applying Updated/Ended events
- evcc-io#17: sum phase-specific values when no aggregate measurement
- evcc-io#4: add 5s timeout to OCPP 2.0.1 server startup
… end

- default to 3 phases when phases not set for watt-based charging profiles
- clear cached measurements when transaction ends to avoid stale power readings
Set reg.cs before init() to prevent deadlock where OnBootNotification
cannot find the station because reg.cs is nil, causing perpetual
Pending responses and eventual timeout.

Rollback reg.cs on init() error to preserve original error handling.
@deidi01
deidi01 force-pushed the feature/ocpp20-generic branch from 290ab06 to ccf1a51 Compare November 9, 2026 12:19
premultiply and others added 19 commits November 10, 2026 00:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

devices Specific device support enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants