feat: comprehensive code review fixes — security, performance, quality

Backend security:
- Reject Gitea webhooks when webhook_secret is empty (was silently skipping)
- Add slowapi rate limiting on login (5/min) and setup (3/min) endpoints
- Add CORS middleware with configurable origins
- Mask telegram_webhook_secret in settings API response
- Protect system-owned command template configs from regular user modification
- Increase minimum password length to 8 characters

Backend performance:
- Batch queries in _resolve_command_context (3 queries instead of 3N)
- Concurrent album fetching with asyncio.gather in immich commands
- Singleton Jinja2 SandboxedEnvironment (reuse instead of per-render creation)
- TTLCache for rate limits (bounded memory, auto-eviction)
- Optional aiohttp session reuse in send_reply/send_media_group

Backend code quality:
- Extract dispatch_helpers.py (shared link_data loading + event filtering)
- Extract database/seeds.py from main.py (490 lines → dedicated module)
- Split immich_handler.py (415 lines) into commands/immich/ subpackage
- Replace bare except blocks with logged warnings
- Add per-provider config validation (Pydantic models)
- Truncate command input to 512 chars
- Expose usage_* and desc_* slots in capabilities and variables API

Frontend security:
- CSS.escape() for user-controlled querySelector in highlight.ts
- Client-side password min 8 chars validation on setup and password change

Frontend code quality:
- Replace any types with proper interfaces across top files
- Decompose targets/+page.svelte into TargetForm + ReceiverSection
- Fix $derived.by usage, $state mutation patterns
- Add console.warn to empty catch blocks

Frontend UX:
- Auth redirect via goto() with "Redirecting..." state
- Platform-aware Ctrl/Cmd K keyboard hint
- Remove stat-card hover transform

Frontend accessibility:
- Modal: role=dialog, aria-modal, focus trap, restore focus
- EntitySelect/IconGridSelect: listbox/option roles, aria-selected/disabled
This commit is contained in:
2026-03-23 01:59:51 +03:00
parent 31584c5d31
commit e0bae394ee
78 changed files with 2855 additions and 1658 deletions
@@ -207,7 +207,12 @@ class TemplateSlot(SQLModel, table=True):
)
id: int | None = Field(default=None, primary_key=True)
config_id: int = Field(foreign_key="template_config.id", index=True)
config_id: int = Field(
foreign_key="template_config.id",
index=True,
)
slot_name: str
template: str = Field(default="", sa_column=Column(Text, default=""))
@@ -245,7 +250,12 @@ class TargetReceiver(SQLModel, table=True):
)
id: int | None = Field(default=None, primary_key=True)
target_id: int = Field(foreign_key="notification_target.id", index=True)
target_id: int = Field(
foreign_key="notification_target.id",
index=True,
)
name: str = Field(default="")
config: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
receiver_key: str = Field(default="") # dedup key (e.g. chat_id, url, email)
@@ -283,7 +293,12 @@ class NotificationTrackerTarget(SQLModel, table=True):
index=True,
sa_column_kwargs={"name": "notification_tracker_id"},
)
target_id: int = Field(foreign_key="notification_target.id", index=True)
target_id: int = Field(
foreign_key="notification_target.id",
index=True,
)
tracking_config_id: int | None = Field(
default=None, foreign_key="tracking_config.id"
)
@@ -366,7 +381,12 @@ class CommandTemplateSlot(SQLModel, table=True):
)
id: int | None = Field(default=None, primary_key=True)
config_id: int = Field(foreign_key="command_template_config.id", index=True)
config_id: int = Field(
foreign_key="command_template_config.id",
index=True,
)
slot_name: str
locale: str = Field(default="en")
template: str = Field(default="", sa_column=Column(Text, default=""))
@@ -399,7 +419,11 @@ class CommandTrackerListener(SQLModel, table=True):
)
id: int | None = Field(default=None, primary_key=True)
command_tracker_id: int = Field(foreign_key="command_tracker.id")
command_tracker_id: int = Field(
foreign_key="command_tracker.id",
)
listener_type: str # e.g. "telegram_bot"
listener_id: int
created_at: datetime = Field(default_factory=_utcnow)
@@ -0,0 +1,324 @@
"""Database seed functions — create/update system-owned defaults on startup."""
import json
import logging
from datetime import datetime, timezone
from sqlalchemy import text
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from .engine import get_engine
from .models import (
CommandConfig,
CommandTemplateConfig,
CommandTemplateSlot,
TemplateConfig,
TemplateSlot,
TrackingConfig,
)
_LOGGER = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
async def _seed_provider_template(
session: AsyncSession,
provider_type: str,
label: str,
) -> None:
"""Seed templates for a single provider type across all locales."""
from notify_bridge_core.templates.defaults import load_default_templates
result = await session.exec(
select(TemplateConfig).where(
TemplateConfig.user_id == 0,
TemplateConfig.provider_type == provider_type,
)
)
configs = result.all()
existing_locales = {
(c.locale if c.locale else ("ru" if "(RU)" in c.name else "en")): c
for c in configs
}
for locale in ("en", "ru"):
slots = load_default_templates(locale, provider_type=provider_type)
if not slots:
continue
if locale not in existing_locales:
now = datetime.now(timezone.utc).isoformat()
name = f"Default {label} ({locale.upper()})"
desc = f"Default {label} templates ({locale.upper()})"
# Get column names to build INSERT with defaults for legacy cols
col_info = (await session.execute(
text("PRAGMA table_info(template_config)")
)).fetchall()
col_names = [c[1] for c in col_info if c[1] != "id"]
values: dict[str, object] = {}
for col in col_names:
if col == "user_id":
values[col] = 0
elif col == "provider_type":
values[col] = provider_type
elif col == "name":
values[col] = name
elif col == "description":
values[col] = desc
elif col == "created_at":
values[col] = now
elif col == "date_format":
values[col] = "%d.%m.%Y, %H:%M UTC"
elif col == "date_only_format":
values[col] = "%d.%m.%Y"
elif col == "locale":
values[col] = locale
else:
values[col] = "" # empty string for legacy columns
cols_str = ", ".join(values.keys())
placeholders = ", ".join(f":{k}" for k in values.keys())
await session.execute(
text(f"INSERT INTO template_config ({cols_str}) VALUES ({placeholders})"),
values,
)
config_id = (await session.execute(
text("SELECT last_insert_rowid()")
)).scalar()
for slot_name, template_text in slots.items():
session.add(TemplateSlot(
config_id=config_id,
slot_name=slot_name,
template=template_text,
))
else:
config = existing_locales[locale]
for slot_name, template_text in slots.items():
slot_result = await session.exec(
select(TemplateSlot).where(
TemplateSlot.config_id == config.id,
TemplateSlot.slot_name == slot_name,
)
)
existing = slot_result.first()
if existing:
existing.template = template_text
session.add(existing)
else:
session.add(TemplateSlot(
config_id=config.id,
slot_name=slot_name,
template=template_text,
))
async def _seed_provider_command_template(
session: AsyncSession,
provider_type: str,
name: str,
description: str,
) -> None:
"""Seed command templates for a single provider type across all locales."""
from notify_bridge_core.templates.command_defaults import load_default_command_templates
result = await session.exec(
select(CommandTemplateConfig).where(
CommandTemplateConfig.user_id == 0,
CommandTemplateConfig.provider_type == provider_type,
)
)
configs = result.all()
if not configs:
config = CommandTemplateConfig(
user_id=0,
provider_type=provider_type,
name=name,
description=description,
)
session.add(config)
await session.flush()
else:
config = configs[0]
for locale in ("en", "ru"):
slots = load_default_command_templates(locale, provider_type=provider_type)
if not slots:
continue
for slot_name, template_text in slots.items():
slot_result = await session.exec(
select(CommandTemplateSlot).where(
CommandTemplateSlot.config_id == config.id,
CommandTemplateSlot.slot_name == slot_name,
CommandTemplateSlot.locale == locale,
)
)
existing = slot_result.first()
if existing:
existing.template = template_text
session.add(existing)
else:
session.add(CommandTemplateSlot(
config_id=config.id,
slot_name=slot_name,
locale=locale,
template=template_text,
))
# ---------------------------------------------------------------------------
# Top-level seed functions
# ---------------------------------------------------------------------------
async def _seed_default_templates() -> None:
"""Seed or update default (system-owned) templates on startup.
Uses TemplateSlot child rows for template content.
"""
engine = get_engine()
async with AsyncSession(engine) as session:
await _seed_provider_template(session, "immich", "Immich")
await _seed_provider_template(session, "gitea", "Gitea")
await _seed_provider_template(session, "scheduler", "Scheduler")
await session.commit()
async def _seed_default_command_templates() -> None:
"""Seed or update default command response templates on startup.
Creates a single config per provider with locale-aware slots
(each slot has an EN and RU version stored as separate rows).
"""
engine = get_engine()
async with AsyncSession(engine) as session:
await _seed_provider_command_template(
session, "immich", "Default Commands", "Default Immich command templates",
)
await _seed_provider_command_template(
session, "gitea", "Default Gitea Commands", "Default Gitea command templates",
)
await session.commit()
async def _seed_default_tracking_configs() -> None:
"""Seed system-owned default tracking configs for each provider type."""
engine = get_engine()
async with AsyncSession(engine) as session:
result = await session.exec(
select(TrackingConfig).where(TrackingConfig.user_id == 0)
)
existing = {c.provider_type: c for c in result.all()}
defaults = [
{
"provider_type": "gitea",
"name": "Default Gitea",
"track_push": True,
"track_issue_opened": True,
"track_issue_closed": True,
"track_issue_commented": False,
"track_pr_opened": True,
"track_pr_closed": True,
"track_pr_merged": True,
"track_pr_commented": False,
"track_release_published": True,
},
{
"provider_type": "scheduler",
"name": "Default Scheduler",
"track_scheduled_message": True,
},
]
for cfg in defaults:
ptype = cfg["provider_type"]
if ptype in existing:
continue
session.add(TrackingConfig(user_id=0, **cfg))
await session.commit()
async def _seed_default_command_configs() -> None:
"""Seed system-owned default command configs for each provider type."""
engine = get_engine()
async with AsyncSession(engine) as session:
result = await session.exec(
select(CommandConfig).where(CommandConfig.user_id == 0)
)
existing = {c.provider_type: c for c in result.all()}
# Find system command template configs to link
tmpl_result = await session.exec(
select(CommandTemplateConfig).where(CommandTemplateConfig.user_id == 0)
)
tmpl_by_type = {t.provider_type: t.id for t in tmpl_result.all()}
defaults = [
{
"provider_type": "immich",
"name": "Default Immich",
"enabled_commands": [
"help", "status", "albums", "events", "latest",
"random", "favorites", "summary", "memory",
],
"response_mode": "media",
"default_count": 5,
"rate_limits": {"search": 30, "default": 10},
},
{
"provider_type": "gitea",
"name": "Default Gitea",
"enabled_commands": [
"help", "status", "repos", "issues", "prs", "commits",
],
"response_mode": "text",
"default_count": 10,
"rate_limits": {"api": 15, "default": 10},
},
]
for cfg in defaults:
ptype = cfg["provider_type"]
if ptype in existing:
continue
cmd_tmpl_id = tmpl_by_type.get(ptype)
await session.execute(
text(
"INSERT INTO command_config "
"(user_id, provider_type, name, icon, enabled_commands, locale, "
"response_mode, default_count, rate_limits, command_template_config_id, created_at) "
"VALUES (:uid, :pt, :name, :icon, :cmds, :locale, :rm, :dc, :rl, :ctid, :ca)"
),
{
"uid": 0,
"pt": ptype,
"name": cfg["name"],
"icon": "",
"cmds": json.dumps(cfg["enabled_commands"]),
"locale": "en",
"rm": cfg["response_mode"],
"dc": cfg["default_count"],
"rl": json.dumps(cfg["rate_limits"]),
"ctid": cmd_tmpl_id,
"ca": datetime.now(timezone.utc).isoformat(),
},
)
await session.commit()
# ---------------------------------------------------------------------------
# Public entry point
# ---------------------------------------------------------------------------
async def seed_all() -> None:
"""Run all seed functions in order."""
await _seed_default_templates()
await _seed_default_command_templates()
await _seed_default_tracking_configs()
await _seed_default_command_configs()