- AccessService: одноразовые приглашения (128 бит, в БД только sha256, TTL 24 ч), атомарный захват приглашения (условный UPDATE — из двух сканов одного QR проходит один), антиперебор (> 5 неудач в час — молчание), отзыв (черновик и FSM удаляются), повторное приглашение - ADMIN_IDS заводятся в БД при старте; дальше — только по приглашению - AccessMiddleware: участники из БД (+ last_seen раз в 5 мин), новичкам — только /start <токен> - «👥 Участники» для админов: список, QR (segno) + ссылка, отзыв с подтверждением - один ответ на неверный/истёкший/использованный токен — без подсказок Refs #25 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
88 lines
3.4 KiB
Python
88 lines
3.4 KiB
Python
"""Typed configuration from the environment / `.env` — one settings class per subsystem (ARCHITECTURE §2.11)."""
|
|
|
|
from pathlib import Path
|
|
from typing import Annotated, Literal
|
|
|
|
from pydantic import Field, SecretStr, field_validator
|
|
from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
|
|
|
|
_ENV = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
|
|
|
|
|
class TelegramSettings(BaseSettings):
|
|
model_config = SettingsConfigDict(**_ENV, env_prefix="TELEGRAM_")
|
|
|
|
bot_token: SecretStr
|
|
|
|
|
|
class AccessSettings(BaseSettings):
|
|
model_config = _ENV
|
|
|
|
# Bootstrap admins (SPEC A-8). Comma-separated in the env: ADMIN_IDS=1,2
|
|
admin_ids: Annotated[frozenset[int], NoDecode] = frozenset()
|
|
invite_ttl_hours: float = Field(default=24.0, gt=0)
|
|
# More failed /start <token> per hour than this — silence (SPEC A-6)
|
|
max_failed_attempts: int = Field(default=5, ge=1)
|
|
|
|
@field_validator("admin_ids", mode="before")
|
|
@classmethod
|
|
def _split_ids(cls, value: object) -> object:
|
|
if isinstance(value, str):
|
|
return frozenset(int(part) for part in value.replace(" ", "").split(",") if part)
|
|
return value
|
|
|
|
|
|
class LLMSettings(BaseSettings):
|
|
model_config = SettingsConfigDict(**_ENV, env_prefix="LLM_")
|
|
|
|
# mock: deterministic offline answers (tests, demo without network); openai_compat: any OpenAI-style API (ADR-008)
|
|
provider: Literal["mock", "openai_compat"] = "mock"
|
|
base_url: str = ""
|
|
model: str = ""
|
|
api_key: SecretStr = SecretStr("")
|
|
timeout: float = Field(default=30.0, gt=0)
|
|
max_attempts: int = Field(default=3, ge=1)
|
|
temperature: float = Field(default=0.0, ge=0, le=2)
|
|
|
|
|
|
class DatabaseSettings(BaseSettings):
|
|
model_config = SettingsConfigDict(**_ENV, env_prefix="DATABASE_")
|
|
|
|
# Compose sets a PostgreSQL URL; the default lets the bot run locally without Docker.
|
|
url: str = "sqlite+aiosqlite:///./tgit.db"
|
|
|
|
|
|
class SourceCraftSettings(BaseSettings):
|
|
model_config = SettingsConfigDict(**_ENV, env_prefix="SOURCECRAFT_")
|
|
|
|
token: SecretStr = SecretStr("")
|
|
api_url: str = "https://api.sourcecraft.tech"
|
|
uploads_repo: str = "rogachevegorushka/tgit-uploads"
|
|
# Web link to a CI run. The SPA answers 200 on any path, so the format is unverified — adjust if it 404s in UI.
|
|
run_url_template: str = "https://sourcecraft.dev/{repo}/cicd/runs/{run}"
|
|
timeout: float = Field(default=30.0, gt=0)
|
|
max_attempts: int = Field(default=5, ge=1)
|
|
|
|
|
|
class RuntimeSettings(BaseSettings):
|
|
model_config = _ENV
|
|
|
|
log_level: str = "INFO"
|
|
# Non-secret configs (texts, thresholds, prompts). Relative to the working dir: /srv/tgit in Docker.
|
|
config_dir: Path = Path("config")
|
|
# The heartbeat file is touched while the event loop is alive; the Docker healthcheck reads its age.
|
|
heartbeat_file: Path = Path("/tmp/tgit-heartbeat")
|
|
heartbeat_interval: float = Field(default=10.0, gt=0)
|
|
heartbeat_max_age: float = Field(default=30.0, gt=0)
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
model_config = _ENV
|
|
|
|
telegram: TelegramSettings = Field(default_factory=TelegramSettings)
|
|
access: AccessSettings = Field(default_factory=AccessSettings)
|
|
database: DatabaseSettings = Field(default_factory=DatabaseSettings)
|
|
llm: LLMSettings = Field(default_factory=LLMSettings)
|
|
sourcecraft: SourceCraftSettings = Field(default_factory=SourceCraftSettings)
|
|
runtime: RuntimeSettings = Field(default_factory=RuntimeSettings)
|