This commit is contained in:
2026-11-27 01:40:30 +00:00
parent 16aeaa36fb
commit eb9647e4a0
63 changed files with 7975 additions and 3 deletions
+192
View File
@@ -0,0 +1,192 @@
"""Validated Bot API inputs and shared client catalog."""
from __future__ import annotations
from enum import Enum
from typing import Annotated, ClassVar, Final, Literal, final
from pydantic import BaseModel, ConfigDict, Field, model_validator
CATALOG_BYTES: Final = 524_288
ASSET_BYTES: Final = 2_097_152
DOWNLOAD_BYTES: Final = 4_194_304
TOTAL_BYTES: Final = 134_217_728
PACK_LIMIT: Final = 64
STICKER_LIMIT: Final = 2048
EMOJI_UTF16_BYTES: Final = 128
TITLE_UTF16_BYTES: Final = 512
PackId = Annotated[str, Field(pattern=r"^[A-Za-z0-9_]{1,64}$")]
AssetId = Annotated[str, Field(pattern=r"^[0-9a-f]{64}$")]
class FailureReason(Enum):
"""Static failure descriptions safe to retain without request credentials."""
CATALOG_EXCEEDS_512_KIB = "catalog exceeds 512 KiB"
CATALOG_SIZE_LIMIT_EXCEEDED = "catalog size limit exceeded"
STAGING_ROOT_IS_A_SYMLINK = "staging root is a symlink"
UNOWNED_STAGING_DIRECTORY = "unowned staging directory"
TGS_NESTING_LIMIT = "TGS nesting limit"
TGS_IMAGE_RESOURCES_UNSUPPORTED = "TGS image resources unsupported"
TGS_TEXT_RESOURCES_UNSUPPORTED = "TGS text resources unsupported"
TGS_EXPRESSIONS_UNSUPPORTED = "TGS expressions unsupported"
TGS_COMPLEXITY_LIMIT = "TGS complexity limit"
SOURCE_IMAGE_DIMENSIONS_EXCEED_512 = "source image dimensions exceed 512"
TGS_EXPANSION_EXCEEDS_2_MIB = "TGS expansion exceeds 2 MiB"
INVALID_TGS_FRAME_INTERVAL = "invalid TGS frame interval"
INVALID_TGS_ROOT = "invalid TGS root"
INVALID_DECODED_VIDEO_FRAMES = "invalid decoded video frames"
EXPECTED_STATIC_WEBP = "expected static WEBP"
PNG_EXCEEDS_2_MIB = "PNG exceeds 2 MiB"
BOT_API_RETURNED_A_DIFFERENT_PACK = "Bot API returned a different pack"
CATALOG_HAS_NO_ROOM_FOR_ANOTHER_PACK = "catalog has no room for another pack"
BOT_API_FILE_FORMAT_MISMATCH = "Bot API file format mismatch"
BOT_API_FILE_SIZE_MISMATCH = "Bot API file size mismatch"
CONVERSION_FAILED = "conversion failed"
GENERATED_ASSET_SIZE_LIMIT_EXCEEDED = "generated asset size limit exceeded"
INVALID_ATLAS_DIMENSIONS = "invalid atlas dimensions"
CATALOG_CREDENTIAL_SAFETY_VIOLATION = "catalog credential safety violation"
EMOJI_EXCEEDS_64_UTF_16_UNITS = "emoji exceeds 64 UTF-16 units"
INVALID_PACK_TITLE = "invalid pack title"
DUPLICATE_STICKER_ID = "duplicate sticker id"
DUPLICATE_PACK_ID = "duplicate pack id"
CATALOG_EXCEEDS_2048_STICKERS = "catalog exceeds 2048 stickers"
ASSET_ID_HAS_CONFLICTING_FRAME_COUNTS = "asset id has conflicting frame counts"
CONFLICTING_STICKER_FORMATS = "conflicting sticker formats"
INVALID_PACK_REFERENCE = (
"expected Telegram sticker pack short name or HTTPS addstickers URL"
)
INVALID_API_ORIGIN = "API base must be an origin without credentials or path"
INSECURE_API_ORIGIN = "HTTP API base allowed only on loopback"
INVALID_CREDENTIAL_FILE = "invalid token file"
BOT_API_REQUEST_REJECTED = "Bot API request rejected"
DOWNLOAD_SIZE_OR_TIME_LIMIT_EXCEEDED = "download size or time limit exceeded"
UNSAFE_BOT_API_FILE_PATH = "unsafe Bot API file path"
@final
class ImportFailureError(Exception):
"""Typed failure; exception traceback state must remain mutable."""
def __init__(self, reason: FailureReason) -> None:
"""Retain a typed cause while leaving traceback state mutable."""
super().__init__(reason.value)
self.reason = reason
class Frozen(BaseModel):
"""Reject extra fields and coercion in immutable catalog values."""
model_config: ClassVar[ConfigDict] = ConfigDict(
frozen=True, strict=True, extra="forbid"
)
class Sticker(Frozen):
"""Content-addressed atlas reference with client-compatible timing."""
id: AssetId
emoji: str
frames: Annotated[int, Field(ge=1, le=60)]
@model_validator(mode="after")
def check_emoji(self) -> Sticker:
"""Bound emoji length using the client's UTF-16 representation."""
if len(self.emoji.encode("utf-16-le")) > EMOJI_UTF16_BYTES:
raise ImportFailureError(FailureReason.EMOJI_EXCEEDS_64_UTF_16_UNITS)
return self
class Pack(Frozen):
"""Named sticker collection published as one cache transaction."""
id: PackId
title: str
stickers: Annotated[list[Sticker], Field(max_length=200)]
@model_validator(mode="after")
def check_pack(self) -> Pack:
"""Reject unusable titles and repeated asset references."""
if (
not self.title.strip()
or len(self.title.encode("utf-16-le")) > TITLE_UTF16_BYTES
):
raise ImportFailureError(FailureReason.INVALID_PACK_TITLE)
if len({s.id for s in self.stickers}) != len(self.stickers):
raise ImportFailureError(FailureReason.DUPLICATE_STICKER_ID)
return self
class Catalog(Frozen):
"""Versioned client manifest with globally consistent asset timing."""
version: Annotated[int, Field(ge=1, le=1)] = 1
packs: Annotated[list[Pack], Field(max_length=PACK_LIMIT)] = Field(
default_factory=list
)
@model_validator(mode="after")
def check_catalog(self) -> Catalog:
"""Bound total stickers and reject conflicting shared identities."""
if len({p.id for p in self.packs}) != len(self.packs):
raise ImportFailureError(FailureReason.DUPLICATE_PACK_ID)
if sum(len(p.stickers) for p in self.packs) > STICKER_LIMIT:
raise ImportFailureError(FailureReason.CATALOG_EXCEEDS_2048_STICKERS)
frames: dict[str, int] = {}
for pack in self.packs:
for sticker in pack.stickers:
if sticker.id in frames and frames[sticker.id] != sticker.frames:
raise ImportFailureError(
FailureReason.ASSET_ID_HAS_CONFLICTING_FRAME_COUNTS
)
frames[sticker.id] = sticker.frames
return self
class ApiModel(Frozen):
"""Parse known Bot API fields while tolerating upstream additions."""
model_config: ClassVar[ConfigDict] = ConfigDict(
frozen=True, strict=True, extra="ignore"
)
class Envelope[T](ApiModel):
"""Successful Bot API response carrying a validated result."""
ok: Literal[True]
result: T
class RemoteSticker(ApiModel):
"""Bounded source metadata used to select the conversion format."""
file_id: Annotated[str, Field(min_length=1, max_length=512)]
width: Annotated[int, Field(ge=1, le=512)]
height: Annotated[int, Field(ge=1, le=512)]
is_animated: bool
is_video: bool
emoji: Annotated[str, Field(max_length=64)] = ""
file_size: Annotated[int, Field(ge=1, le=DOWNLOAD_BYTES)] | None = None
@model_validator(mode="after")
def check_format(self) -> RemoteSticker:
"""Reject mutually exclusive animated and video flags."""
if self.is_animated and self.is_video:
raise ImportFailureError(FailureReason.CONFLICTING_STICKER_FORMATS)
return self
class RemotePack(ApiModel):
"""Bounded Bot API sticker set before downloading any files."""
name: PackId
title: Annotated[str, Field(min_length=1, max_length=256)]
stickers: Annotated[list[RemoteSticker], Field(min_length=1, max_length=200)]
class RemoteFile(ApiModel):
"""Bot API download location and optional declared size."""
file_path: Annotated[str, Field(min_length=1, max_length=512)]
file_size: Annotated[int, Field(ge=1, le=DOWNLOAD_BYTES)] | None = None