d131ba461c
Lint & Test / test (push) Successful in 20s
Security - Default scripts_management, callbacks_management, links_management, and media_folders_management to False so a leaked token cannot escalate to RCE through admin CRUD endpoints. - TokenSpec + scope hierarchy (read | control | admin); legacy bare-string api_tokens entries promote to admin for back-compat. Management endpoints now require admin scope. - WebSocket subprotocol auth (Sec-WebSocket-Protocol: media-server.token.<T>) preferred over ?token= query so the token no longer lands in URL/history/ Referer; query fallback retained for HA integration back-compat. - Origin allow-list check on the WS endpoint (CSWSH defence). - In-process token-bucket rate limiter: 5/min for failed auths, 10/min for /api/scripts/execute and /api/callbacks/execute. - shell=False subprocess path (shlex.split) + per-parameter regex `pattern` in ScriptParameterConfig to harden shell=true scripts against parameter injection (Windows cmd.exe env-var expansion). - CSP gains form-action, worker-src, manifest-src directives. - Refuse cors_origins=["*"] at startup; strip token=... from uvicorn access logs; validate Gitea release tag against strict SemVer regex. - noopener noreferrer + no-referrer referrerpolicy on every outbound link. - icacls hardening of config.yaml on Windows (current user + SYSTEM + Administrators only); 0600 still enforced on POSIX. - WS volume handler clamps input and never drops the socket on bad messages. Performance - Album-art read in windows_media gated by track key — was decoding the WinRT thumbnail twice per second regardless of track changes. - /api/media/artwork returns content-derived ETag + Cache-Control so the browser sends If-None-Match and gets 304s on track repeats. - Foreground-service ctypes argtypes hoisted to one-time module init (was re-declaring ~14 prototypes per probe). - display_service _static_cache keyed by (edid_hash, ...) tuple with eviction of disappeared monitors — fixes stale capabilities on hot-plug swaps where the new topology has the same monitor count. - Visualizer rAF loop paused on document.hidden, resumed on visible. Reliability / bug fixes - Lifespan rewritten as try/yield/finally so a partial-startup failure cannot orphan background tasks or executors. - _run_callback in routes/media.py keeps a strong task ref (GC-safe) and uses the dedicated callback executor instead of the default pool. - macos_media.set_volume() no longer always returns True. - TrayManager._restart_requested initialised in __init__; set before signalling exit so the main thread observes it correctly. - Missing static_dir now logs a WARNING instead of silent UI disable. UX / accessibility / PWA - manifest.json theme_color and background_color match the Studio Reference base (#0E0D0B); added id and scope for PWA installability. - ARIA on mini-player icon buttons; inner SVGs marked aria-hidden. - OS mediaSession API wired so headset / lockscreen / Bluetooth buttons drive play/pause/next/prev/seek and show track metadata + artwork. Observability - X-Request-ID middleware (accept upstream id if it matches a safe regex, otherwise UUID4); request_id_var added to ContextVars and included in every log line alongside the token label. - Audit log (append-only JSONL) for every script + callback execution, including the on_play/on_pause/etc. event callbacks. Background-thread writer; queue capped; flushed in lifespan teardown. Deployment - proxy_headers + forwarded_allow_ips plumbed through Settings → uvicorn.Config for reverse-proxy installs. - HTTPS support via ssl_certfile + ssl_keyfile (+ optional password); startup refuses to launch with only one of the pair set. - Thumbnail cache moved from project-root .cache to %LOCALAPPDATA%/media-server/cache (Windows) and $XDG_CACHE_HOME/media-server/thumbnails (POSIX). Tests - 35 new tests across auth scopes, rate limiter, browser path traversal (../ NUL UNC absolute), script-param validation incl. regex, Gitea tag whitelist, config atomic write + POSIX perms. 47 passed / 4 skipped.
87 lines
2.9 KiB
Python
87 lines
2.9 KiB
Python
"""Gitea release provider implementation."""
|
|
|
|
import json
|
|
import logging
|
|
import re
|
|
import urllib.error
|
|
import urllib.request
|
|
from typing import Optional
|
|
|
|
from .release_provider import ReleaseInfo, ReleaseProvider
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Default repository coordinates
|
|
_DEFAULT_BASE_URL = "https://git.dolgolyov-family.by"
|
|
_DEFAULT_OWNER = "alexei.dolgolyov"
|
|
_DEFAULT_REPO = "media-player-server"
|
|
|
|
# Restrictive tag whitelist — prevents a hostile Gitea response (or MITM) from
|
|
# injecting `..`, slashes, or URL-altering characters into the release URL we
|
|
# broadcast to clients. SemVer + pre-release suffix only.
|
|
_TAG_RE = re.compile(r"^v?\d+\.\d+\.\d+(?:[\w.\-+]{0,32})?$")
|
|
|
|
|
|
class GiteaReleaseProvider(ReleaseProvider):
|
|
"""Fetches the latest release from a Gitea repository."""
|
|
|
|
def __init__(
|
|
self,
|
|
base_url: str = _DEFAULT_BASE_URL,
|
|
owner: str = _DEFAULT_OWNER,
|
|
repo: str = _DEFAULT_REPO,
|
|
timeout: float = 10.0,
|
|
) -> None:
|
|
self._api_url = f"{base_url}/api/v1/repos/{owner}/{repo}/releases"
|
|
self._release_page_url = f"{base_url}/{owner}/{repo}/releases/tag"
|
|
self._timeout = timeout
|
|
|
|
async def get_latest_release(self) -> Optional[ReleaseInfo]:
|
|
"""Fetch the latest stable release from Gitea API.
|
|
|
|
Returns:
|
|
ReleaseInfo for the latest non-prerelease, or None on failure.
|
|
"""
|
|
import asyncio
|
|
|
|
try:
|
|
data = await asyncio.to_thread(self._fetch_releases)
|
|
except Exception as e:
|
|
logger.warning("Failed to check for updates: %s", e)
|
|
return None
|
|
|
|
if not data:
|
|
return None
|
|
|
|
# Find the first non-prerelease, non-draft release
|
|
for release in data:
|
|
if release.get("draft") or release.get("prerelease"):
|
|
continue
|
|
|
|
tag = release.get("tag_name", "")
|
|
if not isinstance(tag, str) or not _TAG_RE.match(tag):
|
|
logger.warning("Rejecting malformed release tag from upstream: %r", tag)
|
|
continue
|
|
version = tag.lstrip("v")
|
|
if not version:
|
|
continue
|
|
|
|
return ReleaseInfo(
|
|
version=version,
|
|
url=f"{self._release_page_url}/{tag}",
|
|
prerelease=False,
|
|
)
|
|
|
|
logger.debug("No stable releases found")
|
|
return None
|
|
|
|
def _fetch_releases(self) -> list[dict]:
|
|
"""Synchronous HTTP fetch of releases (run in thread)."""
|
|
url = f"{self._api_url}?limit=5"
|
|
req = urllib.request.Request(url, headers={"Accept": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=self._timeout) as resp:
|
|
return json.loads(resp.read().decode())
|
|
except (urllib.error.URLError, urllib.error.HTTPError, json.JSONDecodeError, OSError) as e:
|
|
raise RuntimeError(f"Gitea API request failed: {e}") from e
|