refactor: comprehensive codebase review — security, performance, quality, UX

Security:
- Fix NUT protocol command injection (validate names against safe regex)
- Enable Jinja2 autoescape=True to prevent HTML injection via external data
- Add WebhookProviderConfig validation model

Performance:
- Shared aiohttp.ClientSession singleton (replaces 40+ per-request sessions)
- Fix 4 N+1 queries with batch IN loads (poller, scheduler, memory, broadcast)
- asyncio.gather for Gitea commands and notification dispatcher
- Add DB indexes on NotificationTrackerState.tracker_id, CommandTrackerListener
- LRU cache for compiled Jinja2 templates
- Daily EventLog cleanup job (90-day retention)
- 30s HTTP timeout on all external calls
- GROUP BY for target type counts (replaces 7 sequential queries)

Code quality:
- Extract get_owned_entity() helper (replaces 11 duplicate functions)
- Extract slot_helpers.py (load_slots, save_slots, render_template_preview)
- Extract command_utils.py (tracker lookup, last event, collection IDs)
- Extract http_session.py (shared session lifecycle)
- Provider connection validation dedup (3x → 1 helper)
- Command dispatch tables replacing if/elif chains
- Album+links fetch helper (fetch_albums_with_links)
- Provider dispatch polymorphism (list_provider_collections)
- Immutable _enrich_assets (no longer mutates in-place)
- Fix _format_assets return type + handler unpacking

Frontend:
- Fix 18+ hardcoded English strings → t() with new i18n keys (en + ru)
- Mobile "More" nav panel with provider filter and search
- Shared Button.svelte component (4 variants, 2 sizes)
- Shared ErrorBanner.svelte component (8 pages updated)
- SvelteKit goto() replacing window.location.href
- Dashboard grid fixed for 4 cards, paginator opacity consistency

Functionality:
- max_instances=1 on scheduler jobs (prevents duplicate events)
- Webhook provider in watcher (prevents error spam)
- Fix stale SQLModel reference in poller
- Gitea get_repo() direct API call
This commit is contained in:
2026-03-28 13:22:26 +03:00
parent 616b221c92
commit b803d004e1
65 changed files with 1934 additions and 1498 deletions
@@ -2,6 +2,7 @@
from __future__ import annotations
import asyncio
import logging
from dataclasses import dataclass, field
from typing import Any
@@ -68,14 +69,17 @@ class NotificationDispatcher:
Returns list of results (one per target).
"""
raw_results = await asyncio.gather(
*[self._send_to_target(event, t) for t in targets],
return_exceptions=True,
)
results = []
for target in targets:
try:
result = await self._send_to_target(event, target)
results.append(result)
except Exception as e:
_LOGGER.error("Failed to dispatch to target: %s", e)
results.append({"success": False, "error": str(e)})
for raw in raw_results:
if isinstance(raw, Exception):
_LOGGER.error("Failed to dispatch to target: %s", raw)
results.append({"success": False, "error": str(raw)})
else:
results.append(raw)
return results
def _resolve_template(
@@ -85,6 +85,20 @@ class GiteaClient:
return repos
async def get_repo(self, owner: str, repo: str) -> dict[str, Any] | None:
"""Fetch a single repository by owner/repo name."""
try:
async with self._session.get(
f"{self._url}/api/v1/repos/{owner}/{repo}",
headers=self._headers,
) as response:
if response.status == 200:
return await response.json()
_LOGGER.warning("Failed to fetch repo %s/%s: HTTP %s", owner, repo, response.status)
except aiohttp.ClientError as err:
_LOGGER.warning("Failed to fetch repo %s/%s: %s", owner, repo, err)
return None
async def get_repo_issues(
self, owner: str, repo: str, state: str = "open", limit: int = 10,
) -> list[dict[str, Any]]:
@@ -14,12 +14,28 @@ _DEFAULT_PORT = 3493
_READ_TIMEOUT = 10.0
_CONNECT_TIMEOUT = 5.0
# Allowed characters for NUT protocol identifiers (UPS names, variable names).
# Prevents command injection via newlines or special characters.
_SAFE_NAME_RE = re.compile(r"^[\w.\-]+$")
# Regex to parse VAR lines: VAR <ups> <name> "<value>"
_VAR_RE = re.compile(r'^VAR\s+(\S+)\s+(\S+)\s+"(.*)"$')
# Regex to parse UPS lines: UPS <name> "<description>"
_UPS_RE = re.compile(r'^UPS\s+(\S+)\s+"(.*)"$')
def _validate_name(value: str, label: str) -> None:
"""Validate that *value* is a safe NUT protocol identifier.
Raises ``NutClientError`` if *value* contains characters outside
``[\\w.\\-]``, which could be used for protocol command injection.
"""
if not _SAFE_NAME_RE.match(value):
raise NutClientError(
f"Invalid {label}: {value!r} contains disallowed characters"
)
class NutClientError(Exception):
"""Error communicating with NUT server."""
@@ -91,6 +107,7 @@ class NutClient:
async def list_var(self, ups_name: str) -> dict[str, str]:
"""Get all variables for a UPS device."""
_validate_name(ups_name, "UPS name")
lines = await self._list_command(f"LIST VAR {ups_name}")
variables: dict[str, str] = {}
for line in lines:
@@ -101,6 +118,8 @@ class NutClient:
async def get_var(self, ups_name: str, var_name: str) -> str:
"""Get a single variable value."""
_validate_name(ups_name, "UPS name")
_validate_name(var_name, "variable name")
response = await self._command(f"GET VAR {ups_name} {var_name}")
m = _VAR_RE.match(response)
if m:
@@ -10,7 +10,7 @@ from jinja2.sandbox import SandboxedEnvironment
_LOGGER = logging.getLogger(__name__)
_env = SandboxedEnvironment(autoescape=False)
_env = SandboxedEnvironment(autoescape=True)
def render_template(template_str: str, context: dict[str, Any]) -> str: