Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
b4b5bf1
refactor(controls): say once who the control mode lets operate the panel
cayossarian Nov 18, 2026
f9997bb
feat(websocket): tell the topology's asker whether they may operate t…
cayossarian Nov 18, 2026
804410e
docs(websocket-api): document the topology's control_access
cayossarian Nov 18, 2026
a95484f
feat(websocket): report a user whose permissions allow no control as …
cayossarian Nov 18, 2026
65ebb3d
docs(websocket-api): document read_only and the panel's breaker posit…
cayossarian Nov 18, 2026
5c7b76a
docs: say that the card disables controls for a user who may not oper…
cayossarian Nov 18, 2026
b9c3013
docs(websocket-api): document the topology's panel_entities
cayossarian Nov 18, 2026
91bbfa4
refactor(controls): name the mode's refusals ControlModeRefusal, and …
cayossarian Nov 18, 2026
441156c
test(controls): pin the order the gate refuses in
cayossarian Nov 18, 2026
12abfcd
test(controls): hold the topology and the gate to the policy setup gi…
cayossarian Nov 18, 2026
301d182
test(websocket): hold read_only to Core's refusal of the priority sel…
cayossarian Nov 18, 2026
754cef0
docs(controls): say what keeps the gate and the topology agreeing, an…
cayossarian Nov 18, 2026
2d3dada
docs: state the topology's empty spaces, panel roles and the README's…
cayossarian Nov 18, 2026
11c775a
docs(websocket-api): say which controls each control_access reason co…
cayossarian Nov 18, 2026
d2e634d
build: bundle the card that disables the controls a user may not operate
cayossarian Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -714,7 +714,9 @@ see [Recommended deployment](#recommended-deployment), where network topology an
**Choosing `Nobody` is reversible.** The control entities stop being created and read as unavailable, but their registry entries, names, areas and
customizations are kept, so turning the option back on restores exactly the entities you had. The control lock comes back armed or disarmed as you left it, with
any auto-relock still due at the same moment, and armed if Home Assistant no longer holds its last state. The shipped SPAN Panel card and dashboard offer no
breaker switch or priority while `Nobody` is chosen, and other dashboards show those entities unavailable.
breaker switch or priority while `Nobody` is chosen, and other dashboards show those entities unavailable. For a user who may not operate the panel — anyone but
an administrator while `Administrators only` is chosen, or an account whose Home Assistant permissions allow control of none of its relay and priority controls
— the card and dashboard show those controls disabled.

### The record of what was commanded

Expand Down
99 changes: 99 additions & 0 deletions custom_components/span_panel/control_access.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Whether the user asking may operate the panel, as `span_panel/panel_topology` reports it.

The card disables a panel's relay and priority controls for a user this says may
not operate them, so it answers from the two rules that would refuse that user
and restates neither:

- **The control mode**, `ControlPolicy.refusal_for`, which the gate enforces on
every command. It comes first, because it is the integration's own answer
and holds for every control the entry has.
- **The user's Home Assistant permissions.** Core refuses an entity service
call from a user who is not an administrator, raising `Unauthorized` at the
first entity it names that `user.permissions.check_entity(entity_id,
POLICY_CONTROL)` does not allow, and administrators are not checked at all
(`helpers/service.py`). That happens before any entity, and so before the
gate, is asked, which is why the gate never answers it and this module has
to.

`control_access` asks the mode, then the permissions, and reports the first
refusal.
"""

from __future__ import annotations

from collections.abc import Collection
from enum import StrEnum
from typing import TYPE_CHECKING, TypedDict

from homeassistant.auth.permissions.const import POLICY_CONTROL

from .control_gate import ControlModeRefusal, ControlPolicy

if TYPE_CHECKING:
from homeassistant.auth.models import User


class PermissionRefusal(StrEnum):
"""Why the user's own Home Assistant permissions keep them from operating the panel.

A wire value beside `ControlModeRefusal`'s, in the same
`control_access.reason` field. Separate because Core decides it, not the
control mode, and the gate never refuses for it.
"""

READ_ONLY = "read_only"
"""The user may control none of the panel's circuit controls, as a Read Only user may control nothing."""


type ControlAccessReason = ControlModeRefusal | PermissionRefusal
"""Every reason `control_access` can give: the control mode's, then Core's permissions'."""


class ControlAccessRecord(TypedDict):
"""Whether the user asking may operate the panel, and if not, why.

`may_operate` is true exactly where `reason` is null. Neither says whether
the control lock is armed, which changes while the card is open and which
the card reads from the lock's own switch. A WebSocket connection always
has a logged-in user, so whether control without one is allowed never comes
into it.
"""

may_operate: bool
reason: ControlAccessReason | None


def control_access(
policy: ControlPolicy, user: User, circuit_controls: Collection[str]
) -> ControlAccessRecord:
"""Return whether `user` may operate the panel whose policy is `policy`.

`circuit_controls` is the entity id of every relay switch and priority
select the topology offers for the panel's circuits. The permissions are
checked against those, and only those, because they are what the card
disables on this answer: a user able to control only the control lock's
switch, or an EVSE's, could still operate none of them.

`read_only` is reported where there is at least one such control and the
user may control none of them. Where they may control some, the card keeps
its controls and Core refuses the rest, one at a time, as it would anywhere
else -- the answer is one flag for the whole panel, and a user who can
operate something is not told they can operate nothing. Where the panel
offers no circuit control there is nothing to disable and nothing for Core
to refuse, so the permissions are not reported.
"""
reason: ControlAccessReason | None = policy.refusal_for(is_admin=user.is_admin)
if reason is None:
reason = _permission_refusal(user, circuit_controls)
return ControlAccessRecord(may_operate=reason is None, reason=reason)


def _permission_refusal(user: User, circuit_controls: Collection[str]) -> PermissionRefusal | None:
"""Core's answer for `user` over `circuit_controls`, by the check its entity services make."""
if user.is_admin or not circuit_controls:
return None
if any(
user.permissions.check_entity(entity_id, POLICY_CONTROL) for entity_id in circuit_controls
):
return None
return PermissionRefusal.READ_ONLY
74 changes: 66 additions & 8 deletions custom_components/span_panel/control_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,23 @@ class ControlMode(StrEnum):
"""


class ControlModeRefusal(StrEnum):
"""Why the control mode refuses a caller, judged by who the caller is.

The values are wire values: `span_panel/panel_topology` reports them to the
card as `control_access.reason`, beside the one Home Assistant's own
permissions give, which `control_access` adds. They are not the gate's
translation keys, which name the refusal a service caller is shown and are
free to be worded for that reader.
"""

CONTROL_DISABLED = "control_disabled"
"""The mode is `disabled`, so no one may operate the panel."""

ADMIN_ONLY = "admin_only"
"""The mode is `admin_only` and the caller is not an administrator."""


@dataclass(frozen=True, slots=True)
class ControlCaller:
"""Who issued the command currently being published, if anyone.
Expand Down Expand Up @@ -171,6 +188,32 @@ def lock_enabled(self) -> bool:
"""
return self.lock_timeout_minutes is not None and self.mode is not ControlMode.DISABLED

def refusal_for(self, *, is_admin: bool | None) -> ControlModeRefusal | None:
"""Why the control mode refuses this caller, or None where it does not.

The one statement of who the mode lets operate the panel. The gate
enforces it on every command, and `span_panel/panel_topology` reports it
for whoever is viewing the card, so the controls the card offers and the
commands the gate lets through are decided by one rule rather than two
copies of it. `test_topology_control_access.py` runs both, the gate
through a real setup too, and holds them to the same answer.

`is_admin` is None for a caller with no logged-in user. `disabled`
refuses that caller as it refuses everyone. `admin_only` does not judge
it, there being no user to judge: whether a command with no user is let
through is `allow_contextless`'s question, which the gate asks on its
own.

Nothing here is about the moment. Whether the control lock is armed
changes while a page is open, and the relay debounce is about one
circuit's last command; the gate asks both itself.
"""
if self.mode is ControlMode.DISABLED:
return ControlModeRefusal.CONTROL_DISABLED
if self.mode is ControlMode.ADMIN_ONLY and is_admin is False:
return ControlModeRefusal.ADMIN_ONLY
return None

@classmethod
def default(cls) -> ControlPolicy:
"""Return the policy an entry with no control options configured has.
Expand Down Expand Up @@ -386,13 +429,19 @@ async def before_publish(self, command: ControlCommand) -> None:
context = caller.context if caller is not None else None
user_id = context.user_id if context is not None else None

# Judged once, by the rule the topology reports to the card, and acted
# on below in this method's own order: `disabled` before everything
# else, `admin_only` after the lock and contextless checks and before
# the relay debounce.
refusal = self._policy.refusal_for(is_admin=await self._caller_is_admin(user_id))

# First, because it is the entry-wide answer and the most useful thing
# to be told. Not creating the entities is what a user sees, but it is
# not a choke point: a command arriving by any other route -- a service
# this integration grows later, a code path that forgets the helper --
# would otherwise be published by an entry whose owner switched control
# off. That is the promise this module opens with.
if self._policy.mode is ControlMode.DISABLED:
if refusal is ControlModeRefusal.CONTROL_DISABLED:
self._refuse(
"control_disabled",
"Control of this SPAN panel is switched off in its options. "
Expand All @@ -413,13 +462,11 @@ async def before_publish(self, command: ControlCommand) -> None:
parent_id=context.parent_id if context is not None else None,
)

if self._policy.mode is ControlMode.ADMIN_ONLY and user_id is not None:
user = await self._hass.auth.async_get_user(user_id)
if user is None or not user.is_admin:
self._refuse(
"admin_only_control",
"Only a Home Assistant administrator may operate this SPAN panel.",
)
if refusal is ControlModeRefusal.ADMIN_ONLY:
self._refuse(
"admin_only_control",
"Only a Home Assistant administrator may operate this SPAN panel.",
)

if command.property_id == RELAY_PROPERTY:
self._refuse_a_debounced_relay(command)
Expand Down Expand Up @@ -461,6 +508,17 @@ async def after_publish(self, command: ControlCommand, outcome: PublishOutcome)

# -- internals ----------------------------------------------------------

async def _caller_is_admin(self, user_id: str | None) -> bool | None:
"""Whether the caller is an administrator, or None when there is no logged-in user.

A user id that no longer resolves -- a user deleted since the call was
made -- is not an administrator.
"""
if user_id is None:
return None
user = await self._hass.auth.async_get_user(user_id)
return user is not None and user.is_admin

def _refuse_a_debounced_relay(self, command: ControlCommand) -> None:
"""Refuse a relay command that follows too closely on the last one.

Expand Down
129 changes: 89 additions & 40 deletions custom_components/span_panel/frontend/dist/span-panel-card.js

Large diffs are not rendered by default.

117 changes: 83 additions & 34 deletions custom_components/span_panel/frontend/dist/span-panel.js

Large diffs are not rendered by default.

31 changes: 26 additions & 5 deletions custom_components/span_panel/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

from collections.abc import Collection, Mapping
from typing import TYPE_CHECKING, Any, TypedDict
from typing import TYPE_CHECKING, Any, Final, TypedDict

from homeassistant.components import websocket_api
from homeassistant.config_entries import ConfigEntryState
Expand All @@ -13,6 +13,7 @@
from span_panel_api import shared_meter_groups

from .const import DOMAIN
from .control_access import control_access
from .control_gate import ControlMode
from .current_monitor import MonitoredCircuit, monitored_circuits
from .energy_orientation import circuit_is_generation
Expand Down Expand Up @@ -110,7 +111,10 @@ async def handle_panel_topology(
each circuit and device, the ratings current monitoring judges each circuit
against, and the registry IDs that tie them together; no host, credential
or certificate is in it. Whether a control it names may be operated is
decided by the control policy when the control is used, not here.
decided by the control policy and by Home Assistant's permissions when the
control is used, not here; `control_access` carries their answer for the
user asking, so the card can disable the controls that user would be
refused. See `control_access`.

The caller passes the HA device registry ID for the **main SPAN panel**
device only (not a sub-device or a circuit's device). Returns panel
Expand Down Expand Up @@ -191,6 +195,9 @@ async def handle_panel_topology(

# Build circuits section.
circuits: dict[str, dict[str, Any]] = {}
# Every relay switch and priority select offered below, which
# `control_access` checks the user's permissions against.
circuit_controls: list[str] = []
for circuit_id, circuit in snapshot.circuits.items():
if circuit_id not in circuit_ids:
continue
Expand All @@ -200,6 +207,10 @@ async def handle_panel_topology(
own_device = circuit_device(
device_registry, snapshot.serial_number, circuit_id, config_entry_id=config_entry_id
)
offered = _offered_roles(
entity_map.get(circuit_id, {}), circuit, runtime_data.control_policy.mode
)
circuit_controls.extend(offered[role] for role in _CONTROL_ROLES if role in offered)
circuits[circuit_id] = {
# The circuit's own device, a child of the panel's, by its registry
# id; null where the circuit has none. A consumer reads the name and
Expand Down Expand Up @@ -257,9 +268,7 @@ async def handle_panel_topology(
# circuit, because a consumer rendering from this record has no
# other way to tell a pinned priority from an absent one.
"is_never_backup": None if circuit.measures_outside_panel else circuit.is_never_backup,
"entities": _offered_roles(
entity_map.get(circuit_id, {}), circuit, runtime_data.control_policy.mode
),
"entities": offered,
}

# Build sub-devices section from devices linked via via_device_id.
Expand Down Expand Up @@ -325,6 +334,14 @@ async def handle_panel_topology(
# circuit's `package_ratings_form` says whether it takes a copy, and in
# which form.
"monitoring_rating_offered": not describes_breakers,
# Whether the user asking may operate the panel: by the policy the
# gate holds, then by their own permissions over the controls offered
# above. The policy is the gate's own object: setup hands one policy
# to the gate and to the runtime data, and an options change reloads
# both.
"control_access": control_access(
runtime_data.control_policy, connection.user, circuit_controls
),
"circuits": circuits,
# Each shared meter by the key its members carry in `shared_meter_group`.
"shared_meter_groups": meter_groups,
Expand Down Expand Up @@ -413,6 +430,10 @@ def _solar_block(
return None


_CONTROL_ROLES: Final = ("switch", "select")
"""The roles that name a circuit control: its relay switch and its priority select."""


def _offered_roles(
roles: Mapping[str, str], circuit: SpanCircuitSnapshot, mode: ControlMode
) -> dict[str, str]:
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/topology/main32_r202633.json
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,10 @@
}
},
"config_entry_id": "entry-main32_r202633",
"control_access": {
"may_operate": true,
"reason": null
},
"device_id": "nt-0000-panel",
"device_name": "Span Panel",
"firmware": "spanos3/r202633/02",
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/topology/main32_r202639-battery-unvalued.json
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,10 @@
}
},
"config_entry_id": "entry-main32_r202639-battery-unvalued",
"control_access": {
"may_operate": true,
"reason": null
},
"device_id": "nt-9874-s7rxt",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/topology/main32_r202639-no-battery.json
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,10 @@
}
},
"config_entry_id": "entry-main32_r202639-no-battery",
"control_access": {
"may_operate": true,
"reason": null
},
"device_id": "nt-9874-s7rxt",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,10 @@
}
},
"config_entry_id": "entry-main32_r202639-unpublished-readings",
"control_access": {
"may_operate": true,
"reason": null
},
"device_id": "nt-9874-s7rxt",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/topology/main32_r202639.json
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,10 @@
}
},
"config_entry_id": "entry-main32_r202639",
"control_access": {
"may_operate": true,
"reason": null
},
"device_id": "nt-9874-s7rxt",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/topology/r202639-a.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@
}
},
"config_entry_id": "entry-r202639-a",
"control_access": {
"may_operate": true,
"reason": null
},
"device_id": "xg-3940-9ooto",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
Expand Down
4 changes: 4 additions & 0 deletions tests/fixtures/topology/r202639-b.json
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,10 @@
}
},
"config_entry_id": "entry-r202639-b",
"control_access": {
"may_operate": true,
"reason": null
},
"device_id": "xg-1155-18fkf",
"device_name": "Span Panel",
"firmware": "spanos3/r202639/03",
Expand Down
Loading
Loading