some
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
# Telegram sticker importer
|
||||
|
||||
Server-side CLI. No deployment, Telegram messages or player interaction.
|
||||
Only `getStickerSet`, `getFile` and file downloads are used. Real Telegram
|
||||
credential verification is pending; tests use an independent HTTP fixture
|
||||
and generated WEBP, vector TGS and alpha VP9 WEBM.
|
||||
|
||||
From repository root:
|
||||
|
||||
```sh
|
||||
mkdir -p /tmp/wowmine-stickers-importer
|
||||
nix build --impure --expr \
|
||||
'import ./script/wowmine-stickers/importer/default.nix {}' \
|
||||
--out-link /tmp/wowmine-stickers-importer/result
|
||||
/tmp/wowmine-stickers-importer/result/bin/wowmine-stickers-import \
|
||||
--token-file /operator/provided/bot-token \
|
||||
--pack https://t.me/addstickers/PackShortName --output /srv/sticker-cache
|
||||
|
||||
nix-shell --impure script/wowmine-stickers/importer/shell.nix --run \
|
||||
'python -m pytest -q -o cache_dir=/tmp/wowmine-stickers-importer/pytest-cache --basetemp=/tmp/wowmine-stickers-importer/tests script/wowmine-stickers/importer/tests'
|
||||
```
|
||||
|
||||
Python runtime attrs: `python3Packages.pillow`, `python3Packages.lottie`
|
||||
(python-lottie 0.7.2), `python3Packages.cairosvg` (Cairo renderer),
|
||||
`python3Packages.pydantic`, `python3Packages.typer`, `python3Packages.httpx`; executable attr:
|
||||
`ffmpeg` (includes ffprobe and libvpx). Test/check attrs: `python3Packages.pytest`,
|
||||
`ruff`, `basedpyright`. Both Nix files pin repository's Nixpkgs revision
|
||||
`bfc1b8a4574108ceef22f02bafcf6611380c100d`; accept explicit `pkgs` override.
|
||||
HTTPX 0.28.1 is selected explicitly because this pinned Nixpkgs provides it;
|
||||
httpx2 is absent. No packages install into shared Python environments.
|
||||
|
||||
Token comes only from the explicit file (max 256 bytes). Keep file readable only
|
||||
by importer operator. CLI prints structured status, never response
|
||||
content, token, traceback or credential-bearing URL. Tokens are not subprocess
|
||||
arguments. Environment proxies and HTTP redirects are disabled. `--api-base`
|
||||
supports an operator's local Bot API server: HTTPS origin or loopback HTTP,
|
||||
without path, query or user information. Returned file paths must be safe
|
||||
relative paths; absolute paths from Bot API `--local` mode are intentionally
|
||||
rejected. Configure local server to serve relative file downloads over HTTP.
|
||||
Only configured origin receives token; pack URLs are parsed, never fetched.
|
||||
|
||||
Catalog exactly matches shared version 1 schema:
|
||||
|
||||
```json
|
||||
{"version":1,"packs":[{"id":"PackShortName","title":"Pack title","stickers":[{"id":"lowercase64hexSHA256","emoji":"","frames":1}]}]}
|
||||
```
|
||||
|
||||
`id` is SHA-256 of actual PNG bytes; assets live at `assets/<id>.png`.
|
||||
Every PNG contains deterministic text chunk `wowmine_frames` with decimal
|
||||
frame count. Identical pixels at different timings therefore have distinct
|
||||
hash identities. Catalog also rejects conflicting frame counts for one hash.
|
||||
RGBA cells are aspect-preserving, centered, transparent 128x128. Atlas is
|
||||
row-major, `min(8,frames)` columns, enough rows; unused cells stay transparent.
|
||||
Static WEBP produces one frame. TGS and VP8/VP9 WEBM sample at 20 fps, retaining
|
||||
at most first 60 frames (three seconds). VPX software decoder preserves alpha.
|
||||
Opaque source pixels remain opaque. TGS renders through python-lottie/Cairo;
|
||||
external/embedded raster images, text/font resources and expressions are rejected.
|
||||
Complex effects unsupported by python-lottie may not match Telegram perfectly.
|
||||
|
||||
Limits: PNG 2 MiB, catalog 512 KiB, 64 packs, 200 stickers/pack, 2048 overall.
|
||||
Title max 256 and emoji max 64 UTF-16 code units, matching Java.
|
||||
Identical PNGs within imported pack retain first emoji. Existing duplicate pack
|
||||
IDs or sticker hashes inside a pack reject catalog. Import replaces one pack by
|
||||
canonical Telegram name, preserving other packs. Existing catalog fields are
|
||||
strictly parsed; unknown fields reject. Empty existing packs/catalog are allowed.
|
||||
|
||||
Additional safety budgets: 4 MiB/download; 128 MiB total network bytes and
|
||||
generated PNG bytes per import; Bot API response 512 KiB; source dimensions
|
||||
at most 512x512; TGS expanded JSON 2 MiB, depth 32, 50,000 nodes, rate at most
|
||||
120 fps and frame timeline at most 7200. Reads/connects time out after 10/5
|
||||
seconds, requests enforce 30 seconds checked per received chunk (a pending
|
||||
socket read adds at most 10 seconds). Worker wall time 45 seconds, CPU 35
|
||||
seconds, address space 768 MiB, file size 8 MiB; ffmpeg decode 30 seconds.
|
||||
Imports are sequential; no retries. Bounded conversions run without token
|
||||
input, network protocols or arbitrary file resource loading.
|
||||
|
||||
Pack URL/name is untrusted ordinary-player input. No OP requirement exists in
|
||||
this CLI; main server owns authorization policy, queue, rate limits and request
|
||||
deduplication. `--api-base`, `--token-file` and `--output` are operator configuration,
|
||||
never player-controlled. Invoke with an argument array, never a shell string.
|
||||
|
||||
Status is JSON Lines: stdout emits `{"status":"fetching"}`, then
|
||||
`{"status":"converting","completed":0,"total":3}` before each conversion and
|
||||
`{"status":"complete","pack":"PackShortName","stickers":3}` after publication.
|
||||
Counts in progress track source stickers; final count is unique PNGs.
|
||||
Exit 0 means complete. Runtime errors emit
|
||||
`{"status":"error","code":"import_failed"}` on stderr and exit 1.
|
||||
Whole-job deadline emits code `job_timeout` instead. Fetch/conversion deadline
|
||||
is 270 seconds, leaving server's proposed 300-second kill deadline cleanup
|
||||
headroom. Deadline disarms for atomic publication and bounded final cleanup.
|
||||
300 seconds cannot guarantee importing every 200-sticker animated pack:
|
||||
individual conversion CPU caps alone permit 200 * 35 = 7000 CPU seconds.
|
||||
Keep 300 seconds if timeout failures are acceptable; do not promise every
|
||||
public pack finishes within that budget.
|
||||
Argument syntax errors remain Typer usage errors (exit 2); server must provide
|
||||
all required options. No exception text or remote metadata enters error status.
|
||||
|
||||
Output directory is trusted operator-owned local storage; keep other writers
|
||||
out. **Single-writer contract:** main server serializes all imports globally.
|
||||
Importer does not provide a queue or concurrent writer coordination.
|
||||
Import stages in `.wowmine-stickers-importer-v1/job-*`, publishes hash assets
|
||||
then fsyncs and atomically replaces catalog. Input/conversion/validation failures
|
||||
retain old catalog. Capacity checks run before conversion when definitely full,
|
||||
and complete 2048-entry validation happens before publishing any asset.
|
||||
|
||||
Owned staging has a format marker and per-job asset journal written atomically
|
||||
before publication. Normal failure cleans staging and any journaled unreferenced
|
||||
assets. Next import recovers interrupted jobs before allocating new staging.
|
||||
Replacement reclaims obsolete assets of replaced packs. Every deletion excludes
|
||||
all IDs referenced by current catalog; a candidate must also have matching
|
||||
SHA-256 contents and be a regular non-symlink file. Files absent from ownership
|
||||
journals and other directories are preserved, including unrelated files inside
|
||||
cache. Output's marked staging namespace is reserved for importer scratch.
|
||||
Malformed journals or invalid catalog stop recovery rather than guess ownership.
|
||||
Failed recovery leaves its journal and prevents further staging growth.
|
||||
|
||||
Managed cache contains at most 2048 referenced PNGs (2 MiB each), plus bounded
|
||||
in-flight pack (128 MiB generated PNG budget, one 4 MiB input and one transient
|
||||
atlas). Interruption may leave journaled unreferenced blobs, reclaimed on next
|
||||
import. This bound excludes unrelated pre-existing operator files, which importer
|
||||
must not delete. No global garbage collection of unknown hash-named files occurs.
|
||||
Process interruption before catalog rename keeps old catalog; power-loss
|
||||
durability of directory entries is filesystem-dependent.
|
||||
|
||||
Sources consulted: official Bot API `getStickerSet`/`getFile` method docs and
|
||||
python-lottie Cairo exporter API; installed `Animation.load(lottiedict)` and
|
||||
`export_png(animation, fp, frame=0, dpi=96)` signatures verified.
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Single-writer cache transaction with an owned recovery journal."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from tempfile import mkdtemp
|
||||
from typing import TYPE_CHECKING, Annotated, Final, Literal
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from models import (
|
||||
ASSET_BYTES,
|
||||
CATALOG_BYTES,
|
||||
AssetId,
|
||||
Catalog,
|
||||
FailureReason,
|
||||
Frozen,
|
||||
ImportFailureError,
|
||||
Pack,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
OWNER: Final = b"wowmine-stickers-importer-v1\n"
|
||||
JOB_NAME: Final = re.compile(r"job-[a-z0-9_]{8}")
|
||||
|
||||
|
||||
def load_catalog(path: Path) -> Catalog:
|
||||
"""Read bounded catalog before trusting any asset ownership or references."""
|
||||
if not path.exists():
|
||||
return Catalog()
|
||||
with path.open("rb") as source:
|
||||
raw = source.read(CATALOG_BYTES + 1)
|
||||
if len(raw) > CATALOG_BYTES:
|
||||
raise ImportFailureError(FailureReason.CATALOG_EXCEEDS_512_KIB)
|
||||
return Catalog.model_validate_json(raw)
|
||||
|
||||
|
||||
class Journal(Frozen):
|
||||
"""Only IDs recorded before publication may be reclaimed."""
|
||||
|
||||
version: Literal[1] = 1
|
||||
assets: Annotated[list[AssetId], Field(max_length=2248)]
|
||||
|
||||
|
||||
def reclaim(stage: Path, output: Path) -> None:
|
||||
"""Reclaim owned jobs while retaining live IDs, symlinks and unrelated files."""
|
||||
catalog = load_catalog(output / "catalog.json")
|
||||
live = {s.id for pack in catalog.packs for s in pack.stickers}
|
||||
journal_path = stage / "journal.json"
|
||||
if journal_path.is_file():
|
||||
with journal_path.open("rb") as source:
|
||||
raw = source.read(CATALOG_BYTES + 1)
|
||||
journal = Journal.model_validate_json(raw)
|
||||
for asset_id in set(journal.assets) - live:
|
||||
asset = output / "assets" / (asset_id + ".png")
|
||||
if asset.is_file() and not asset.is_symlink():
|
||||
with asset.open("rb") as source:
|
||||
png = source.read(ASSET_BYTES + 1)
|
||||
if (
|
||||
len(png) <= ASSET_BYTES
|
||||
and hashlib.sha256(png).hexdigest() == asset_id
|
||||
):
|
||||
asset.unlink()
|
||||
# Reserved job directories contain importer scratch only.
|
||||
shutil.rmtree(stage)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Cache:
|
||||
"""Stage and publish one pack, under server's global single-writer lock."""
|
||||
|
||||
output: Path
|
||||
stage: Path
|
||||
|
||||
def publish(self, pack: Pack) -> None:
|
||||
"""Validate whole merged catalog before publishing even one asset."""
|
||||
old = load_catalog(self.output / "catalog.json")
|
||||
merged = Catalog(packs=[p for p in old.packs if p.id != pack.id] + [pack])
|
||||
raw = merged.model_dump_json().encode()
|
||||
if len(raw) > CATALOG_BYTES:
|
||||
raise ImportFailureError(FailureReason.CATALOG_SIZE_LIMIT_EXCEEDED)
|
||||
ids = {s.id for p in old.packs for s in p.stickers} | {
|
||||
s.id for s in pack.stickers
|
||||
}
|
||||
temporary = self.stage / "journal.new"
|
||||
_ = temporary.write_text(Journal(assets=sorted(ids)).model_dump_json())
|
||||
_ = temporary.replace(self.stage / "journal.json")
|
||||
assets = self.output / "assets"
|
||||
assets.mkdir(exist_ok=True)
|
||||
for sticker in pack.stickers:
|
||||
_ = (self.stage / (sticker.id + ".png")).replace(
|
||||
assets / (sticker.id + ".png")
|
||||
)
|
||||
temporary = self.stage / "catalog.new"
|
||||
with temporary.open("wb") as target:
|
||||
_ = target.write(raw)
|
||||
target.flush()
|
||||
os.fsync(target.fileno())
|
||||
_ = temporary.replace(self.output / "catalog.json")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def transaction(output: Path) -> Iterator[Cache]:
|
||||
"""Recover only importer-owned staging before allocating another job."""
|
||||
_ = load_catalog(output / "catalog.json")
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
root = output / ".wowmine-stickers-importer-v1"
|
||||
if root.is_symlink():
|
||||
raise ImportFailureError(FailureReason.STAGING_ROOT_IS_A_SYMLINK)
|
||||
root.mkdir(exist_ok=True)
|
||||
marker = root / "owner"
|
||||
if not marker.exists():
|
||||
if any(root.iterdir()):
|
||||
raise ImportFailureError(FailureReason.UNOWNED_STAGING_DIRECTORY)
|
||||
_ = marker.write_bytes(OWNER)
|
||||
with marker.open("rb") as source:
|
||||
if source.read(len(OWNER) + 1) != OWNER:
|
||||
raise ImportFailureError(FailureReason.UNOWNED_STAGING_DIRECTORY)
|
||||
for child in root.iterdir():
|
||||
if JOB_NAME.fullmatch(child.name) and child.is_dir() and not child.is_symlink():
|
||||
reclaim(child, output)
|
||||
stage = Path(mkdtemp(prefix="job-", dir=root))
|
||||
try:
|
||||
yield Cache(output, stage)
|
||||
finally:
|
||||
reclaim(stage, output)
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Credential-free conversion worker; caller bounds CPU, memory and wall time."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import io
|
||||
import math
|
||||
import resource
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import ClassVar, Final, Literal, assert_never
|
||||
|
||||
from lottie.exporters.cairo import export_png
|
||||
from lottie.objects import Animation
|
||||
from PIL import Image
|
||||
from PIL.PngImagePlugin import PngInfo
|
||||
from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter
|
||||
|
||||
from models import ASSET_BYTES, FailureReason, ImportFailureError
|
||||
|
||||
CELL: Final = 128
|
||||
SOURCE_SIDE: Final = 512
|
||||
TGS_BYTES: Final = 2_097_152
|
||||
TGS_DEPTH: Final = 32
|
||||
TGS_NODES: Final = 50_000
|
||||
TEXT_LAYER: Final = 5
|
||||
Format = Literal["webp", "tgs", "webm"]
|
||||
JSON_VALUE: Final = TypeAdapter[JsonValue](JsonValue)
|
||||
|
||||
|
||||
class Timing(BaseModel):
|
||||
"""Bounded vector dimensions and finite animation interval."""
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(strict=True)
|
||||
w: int = Field(ge=1, le=512)
|
||||
h: int = Field(ge=1, le=512)
|
||||
fr: float = Field(gt=0, le=120, allow_inf_nan=False)
|
||||
ip: float = Field(ge=0, le=7200, allow_inf_nan=False)
|
||||
op: float = Field(gt=0, le=7200, allow_inf_nan=False)
|
||||
|
||||
|
||||
def check_vector(value: JsonValue, depth: int = 0) -> int:
|
||||
"""Reject resources and excessive nesting before rendering vector JSON."""
|
||||
if depth > TGS_DEPTH:
|
||||
raise ImportFailureError(FailureReason.TGS_NESTING_LIMIT)
|
||||
nodes = 1
|
||||
match value:
|
||||
case dict():
|
||||
if isinstance(value.get("p"), str) or isinstance(value.get("u"), str):
|
||||
raise ImportFailureError(FailureReason.TGS_IMAGE_RESOURCES_UNSUPPORTED)
|
||||
if "fonts" in value or "chars" in value or value.get("ty") == TEXT_LAYER:
|
||||
raise ImportFailureError(FailureReason.TGS_TEXT_RESOURCES_UNSUPPORTED)
|
||||
if isinstance(value.get("x"), str):
|
||||
raise ImportFailureError(FailureReason.TGS_EXPRESSIONS_UNSUPPORTED)
|
||||
children = value.values()
|
||||
case list():
|
||||
children = value
|
||||
case str() | int() | float() | None:
|
||||
return nodes
|
||||
case _:
|
||||
assert_never(value)
|
||||
for child in children:
|
||||
nodes += check_vector(child, depth + 1)
|
||||
if nodes > TGS_NODES:
|
||||
raise ImportFailureError(FailureReason.TGS_COMPLEXITY_LIMIT)
|
||||
return nodes
|
||||
|
||||
|
||||
def normalize(image: Image.Image) -> Image.Image:
|
||||
"""Fit a bounded source into one transparent client atlas cell."""
|
||||
if not (1 <= image.width <= SOURCE_SIDE and 1 <= image.height <= SOURCE_SIDE):
|
||||
raise ImportFailureError(FailureReason.SOURCE_IMAGE_DIMENSIONS_EXCEED_512)
|
||||
frame = image.convert("RGBA")
|
||||
frame.thumbnail((CELL, CELL), Image.Resampling.LANCZOS)
|
||||
cell = Image.new("RGBA", (CELL, CELL))
|
||||
cell.alpha_composite(frame, ((CELL - frame.width) // 2, (CELL - frame.height) // 2))
|
||||
return cell
|
||||
|
||||
|
||||
def vector_frames(source: Path) -> list[Image.Image]:
|
||||
"""Render bounded TGS input at 20 FPS for at most 60 frames."""
|
||||
with gzip.open(source, "rb") as compressed:
|
||||
raw = compressed.read(TGS_BYTES + 1)
|
||||
if len(raw) > TGS_BYTES:
|
||||
raise ImportFailureError(FailureReason.TGS_EXPANSION_EXCEEDS_2_MIB)
|
||||
value = JSON_VALUE.validate_json(raw)
|
||||
_ = check_vector(value)
|
||||
timing = Timing.model_validate(value)
|
||||
if timing.op <= timing.ip:
|
||||
raise ImportFailureError(FailureReason.INVALID_TGS_FRAME_INTERVAL)
|
||||
if not isinstance(value, dict):
|
||||
raise ImportFailureError(FailureReason.INVALID_TGS_ROOT)
|
||||
animation = Animation.load(value)
|
||||
count = min(60, math.ceil((timing.op - timing.ip) * 20 / timing.fr))
|
||||
frames: list[Image.Image] = []
|
||||
for index in range(count):
|
||||
with io.BytesIO() as png:
|
||||
export_png(animation, png, timing.ip + index * timing.fr / 20)
|
||||
_ = png.seek(0)
|
||||
with Image.open(png) as image:
|
||||
frames.append(normalize(image))
|
||||
return frames
|
||||
|
||||
|
||||
class VideoStream(BaseModel):
|
||||
"""Accepted WebM video stream dimensions and decoder family."""
|
||||
|
||||
model_config: ClassVar[ConfigDict] = ConfigDict(strict=True)
|
||||
width: int = Field(ge=1, le=512)
|
||||
height: int = Field(ge=1, le=512)
|
||||
codec_name: Literal["vp8", "vp9"]
|
||||
|
||||
|
||||
class VideoProbe(BaseModel):
|
||||
"""Require exactly one selected video stream from ffprobe."""
|
||||
|
||||
streams: list[VideoStream] = Field(min_length=1, max_length=1)
|
||||
|
||||
|
||||
def executable(name: Literal["ffmpeg", "ffprobe"]) -> str:
|
||||
"""Resolve required decoders on the wrapper's configured runtime path."""
|
||||
path = shutil.which(name)
|
||||
if path is None:
|
||||
raise ImportFailureError(FailureReason.CONVERSION_FAILED)
|
||||
return path
|
||||
|
||||
|
||||
def video_frames(source: Path) -> list[Image.Image]:
|
||||
"""Decode bounded local WebM frames without enabling network protocols."""
|
||||
probe = subprocess.run(
|
||||
[
|
||||
executable("ffprobe"),
|
||||
"-v",
|
||||
"error",
|
||||
"-protocol_whitelist",
|
||||
"file",
|
||||
"-f",
|
||||
"matroska",
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=width,height,codec_name",
|
||||
"-of",
|
||||
"json",
|
||||
str(source),
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
stream = VideoProbe.model_validate_json(probe.stdout).streams[0]
|
||||
match stream.codec_name:
|
||||
case "vp8":
|
||||
decoder = "libvpx"
|
||||
case "vp9":
|
||||
decoder = "libvpx-vp9"
|
||||
case _:
|
||||
assert_never(stream.codec_name)
|
||||
result = subprocess.run(
|
||||
[
|
||||
executable("ffmpeg"),
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
"-threads",
|
||||
"1",
|
||||
"-protocol_whitelist",
|
||||
"file",
|
||||
"-c:v",
|
||||
decoder,
|
||||
"-f",
|
||||
"matroska",
|
||||
"-i",
|
||||
str(source),
|
||||
"-an",
|
||||
"-sn",
|
||||
"-dn",
|
||||
"-vf",
|
||||
",".join(
|
||||
(
|
||||
"fps=20",
|
||||
f"scale={CELL}:{CELL}:force_original_aspect_ratio=decrease",
|
||||
f"pad={CELL}:{CELL}:(ow-iw)/2:(oh-ih)/2:color=black@0",
|
||||
"format=rgba",
|
||||
)
|
||||
),
|
||||
"-frames:v",
|
||||
"60",
|
||||
"-threads",
|
||||
"1",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-pix_fmt",
|
||||
"rgba",
|
||||
"pipe:1",
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
)
|
||||
stride = CELL * CELL * 4
|
||||
if (
|
||||
not result.stdout
|
||||
or len(result.stdout) % stride
|
||||
or len(result.stdout) > stride * 60
|
||||
):
|
||||
raise ImportFailureError(FailureReason.INVALID_DECODED_VIDEO_FRAMES)
|
||||
return [
|
||||
Image.frombytes("RGBA", (CELL, CELL), result.stdout[start : start + stride])
|
||||
for start in range(0, len(result.stdout), stride)
|
||||
]
|
||||
|
||||
|
||||
def convert(source: Path, kind: Format, destination: Path) -> int:
|
||||
"""Write an atlas whose PNG identity includes its frame count."""
|
||||
match kind:
|
||||
case "webp":
|
||||
with Image.open(source) as image:
|
||||
if image.format != "WEBP" or getattr(image, "n_frames", 1) != 1:
|
||||
raise ImportFailureError(FailureReason.EXPECTED_STATIC_WEBP)
|
||||
frames = [normalize(image)]
|
||||
case "tgs":
|
||||
frames = vector_frames(source)
|
||||
case "webm":
|
||||
frames = video_frames(source)
|
||||
case _:
|
||||
assert_never(kind)
|
||||
columns = min(8, len(frames))
|
||||
atlas = Image.new("RGBA", (columns * CELL, math.ceil(len(frames) / columns) * CELL))
|
||||
for index, frame in enumerate(frames):
|
||||
atlas.paste(frame, ((index % columns) * CELL, (index // columns) * CELL))
|
||||
metadata = PngInfo()
|
||||
metadata.add_text("wowmine_frames", str(len(frames)))
|
||||
atlas.save(destination, format="PNG", optimize=False, pnginfo=metadata)
|
||||
if destination.stat().st_size > ASSET_BYTES:
|
||||
raise ImportFailureError(FailureReason.PNG_EXCEEDS_2_MIB)
|
||||
return len(frames)
|
||||
|
||||
|
||||
def worker() -> None:
|
||||
"""Only validated format literals enter conversion."""
|
||||
resource.setrlimit(resource.RLIMIT_AS, (805306368, 805306368))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (35, 35))
|
||||
resource.setrlimit(resource.RLIMIT_FSIZE, (8388608, 8388608))
|
||||
kind = TypeAdapter[Format](Format).validate_python(sys.argv[2])
|
||||
_ = sys.stdout.write(f"{convert(Path(sys.argv[1]), kind, Path(sys.argv[3]))}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
worker()
|
||||
@@ -0,0 +1,14 @@
|
||||
{ pkgs ? import (builtins.getFlake
|
||||
"github:nixos/nixpkgs/bfc1b8a4574108ceef22f02bafcf6611380c100d").outPath {}
|
||||
}:
|
||||
let
|
||||
python = pkgs.python3.withPackages (ps: with ps; [
|
||||
pillow lottie cairosvg pydantic typer httpx
|
||||
]);
|
||||
in pkgs.writeShellApplication {
|
||||
name = "wowmine-stickers-import";
|
||||
runtimeInputs = [ python pkgs.ffmpeg ];
|
||||
text = ''
|
||||
exec python ${./.}/import_pack.py "$@"
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.13"
|
||||
# dependencies = ["pillow", "lottie", "cairosvg", "pydantic>=2", "typer", "httpx"]
|
||||
# ///
|
||||
# How to run: prefer Nix wrapper (README.md); python import_pack.py --help.
|
||||
"""Import a Telegram sticker pack without disclosing bot credentials."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Annotated, Final
|
||||
|
||||
import typer
|
||||
from PIL import Image
|
||||
|
||||
from cache import load_catalog, transaction
|
||||
from models import (
|
||||
ASSET_BYTES,
|
||||
PACK_LIMIT,
|
||||
STICKER_LIMIT,
|
||||
TOTAL_BYTES,
|
||||
Envelope,
|
||||
FailureReason,
|
||||
ImportFailureError,
|
||||
Pack,
|
||||
RemoteFile,
|
||||
RemotePack,
|
||||
Sticker,
|
||||
)
|
||||
from telegram import Telegram, pack_name, read_token
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from types import FrameType
|
||||
|
||||
ROOT: Final = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
class JobTimeoutError(Exception):
|
||||
"""Import exceeded server-compatible whole-job deadline."""
|
||||
|
||||
|
||||
def deadline_expired(_signum: int, _frame: FrameType | None) -> None:
|
||||
"""Interrupt the CLI when its whole-job timer expires."""
|
||||
raise JobTimeoutError
|
||||
|
||||
|
||||
def render_atlas(source: Path, kind: str, destination: Path) -> int:
|
||||
"""Run the bounded conversion worker and reap its entire process group."""
|
||||
with subprocess.Popen(
|
||||
[
|
||||
sys.executable,
|
||||
str(ROOT / "convert.py"),
|
||||
str(source),
|
||||
kind,
|
||||
str(destination),
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
) as worker:
|
||||
try:
|
||||
stdout, _ = worker.communicate(timeout=45)
|
||||
finally:
|
||||
# Kill entire worker group, including a still-running decoder.
|
||||
try:
|
||||
os.killpg(worker.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
_ = worker.poll()
|
||||
if worker.returncode != 0:
|
||||
raise ImportFailureError(FailureReason.CONVERSION_FAILED)
|
||||
return int(stdout)
|
||||
|
||||
|
||||
def import_pack(api: Telegram, name: str, output: Path) -> Pack:
|
||||
"""Download, convert and atomically publish one credential-free pack."""
|
||||
stickers: list[Sticker] = []
|
||||
seen: set[str] = set()
|
||||
generated_bytes = 0
|
||||
with transaction(output) as cache:
|
||||
stage = cache.stage
|
||||
remote = (
|
||||
Envelope[RemotePack]
|
||||
.model_validate_json(api.method("getStickerSet", "name", name))
|
||||
.result
|
||||
)
|
||||
if remote.name.casefold() != name.casefold():
|
||||
raise ImportFailureError(FailureReason.BOT_API_RETURNED_A_DIFFERENT_PACK)
|
||||
old = load_catalog(output / "catalog.json")
|
||||
remaining = [p for p in old.packs if p.id != remote.name]
|
||||
if (
|
||||
len(remaining) >= PACK_LIMIT
|
||||
or sum(len(p.stickers) for p in remaining) >= STICKER_LIMIT
|
||||
):
|
||||
raise ImportFailureError(FailureReason.CATALOG_HAS_NO_ROOM_FOR_ANOTHER_PACK)
|
||||
for completed, item in enumerate(remote.stickers):
|
||||
info = (
|
||||
Envelope[RemoteFile]
|
||||
.model_validate_json(
|
||||
api.method("getFile", "file_id", item.file_id),
|
||||
)
|
||||
.result
|
||||
)
|
||||
kind = "tgs" if item.is_animated else "webm" if item.is_video else "webp"
|
||||
if not info.file_path.lower().endswith("." + kind):
|
||||
raise ImportFailureError(FailureReason.BOT_API_FILE_FORMAT_MISMATCH)
|
||||
data = api.download(info.file_path)
|
||||
if any(
|
||||
size is not None and size != len(data)
|
||||
for size in (info.file_size, item.file_size)
|
||||
):
|
||||
raise ImportFailureError(FailureReason.BOT_API_FILE_SIZE_MISMATCH)
|
||||
source = stage / ("input." + kind)
|
||||
_ = source.write_bytes(data)
|
||||
typer.echo(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "converting",
|
||||
"completed": completed,
|
||||
"total": len(remote.stickers),
|
||||
}
|
||||
)
|
||||
)
|
||||
atlas_path = stage / "atlas.png"
|
||||
frames = render_atlas(source, kind, atlas_path)
|
||||
png = atlas_path.read_bytes()
|
||||
generated_bytes += len(png)
|
||||
if len(png) > ASSET_BYTES or generated_bytes > TOTAL_BYTES:
|
||||
raise ImportFailureError(
|
||||
FailureReason.GENERATED_ASSET_SIZE_LIMIT_EXCEEDED
|
||||
)
|
||||
sticker = Sticker(
|
||||
id=hashlib.sha256(png).hexdigest(), emoji=item.emoji, frames=frames
|
||||
)
|
||||
columns = min(8, frames)
|
||||
with Image.open(atlas_path) as image:
|
||||
if image.format != "PNG" or image.size != (
|
||||
columns * 128,
|
||||
((frames + columns - 1) // columns) * 128,
|
||||
):
|
||||
raise ImportFailureError(FailureReason.INVALID_ATLAS_DIMENSIONS)
|
||||
image.verify()
|
||||
if sticker.id not in seen:
|
||||
seen.add(sticker.id)
|
||||
_ = atlas_path.rename(stage / (sticker.id + ".png"))
|
||||
stickers.append(sticker)
|
||||
pack = Pack(id=remote.name, title=remote.title, stickers=stickers)
|
||||
if api.token in pack.model_dump_json() or api.token in old.model_dump_json():
|
||||
raise ImportFailureError(FailureReason.CATALOG_CREDENTIAL_SAFETY_VIOLATION)
|
||||
# Do not turn a committed catalog into a reported timeout during cleanup.
|
||||
_ = signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
cache.publish(pack)
|
||||
return pack
|
||||
|
||||
|
||||
def main(
|
||||
token_file: Annotated[
|
||||
Path, typer.Option(help="Explicit bot token file; never read from environment.")
|
||||
],
|
||||
pack: Annotated[
|
||||
str, typer.Option(help="Telegram short name or HTTPS addstickers URL.")
|
||||
],
|
||||
output: Annotated[
|
||||
Path, typer.Option(help="Catalog and content-addressed asset cache.")
|
||||
],
|
||||
api_base: Annotated[
|
||||
str, typer.Option(help="Bot API origin; HTTP only for loopback local servers.")
|
||||
] = "https://api.telegram.org",
|
||||
) -> None:
|
||||
"""Emit the CLI status protocol without exposing credential-bearing errors."""
|
||||
# Transport and validation errors can contain secrets; never echo their text.
|
||||
previous = signal.signal(signal.SIGALRM, deadline_expired)
|
||||
try:
|
||||
_ = signal.setitimer(signal.ITIMER_REAL, 270)
|
||||
name = pack_name(pack)
|
||||
token = read_token(token_file)
|
||||
typer.echo('{"status":"fetching"}')
|
||||
with Telegram(api_base, token) as api:
|
||||
imported = import_pack(api, name, output)
|
||||
typer.echo(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "complete",
|
||||
"pack": imported.id,
|
||||
"stickers": len(imported.stickers),
|
||||
}
|
||||
)
|
||||
)
|
||||
except JobTimeoutError:
|
||||
typer.echo('{"status":"error","code":"job_timeout"}', err=True)
|
||||
raise typer.Exit(1) from None
|
||||
except Exception: # noqa: BLE001 # noqa: BROAD_EXCEPT_OK (credential-safe CLI boundary)
|
||||
typer.echo('{"status":"error","code":"import_failed"}', err=True)
|
||||
raise typer.Exit(1) from None
|
||||
finally:
|
||||
_ = signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
_ = signal.signal(signal.SIGALRM, previous)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
typer.run(main)
|
||||
@@ -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
|
||||
@@ -0,0 +1,22 @@
|
||||
[project]
|
||||
name = "wowmine-stickers-importer"
|
||||
version = "0.1.0"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = ["pillow", "lottie", "cairosvg", "pydantic>=2", "typer", "httpx"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = ["."]
|
||||
addopts = "--strict-config --strict-markers"
|
||||
|
||||
[tool.basedpyright]
|
||||
typeCheckingMode = "all"
|
||||
pythonVersion = "3.13"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["ALL"]
|
||||
# Choose D211/D212 where docstring rules conflict; the formatter owns commas.
|
||||
ignore = ["D203", "D213", "COM812"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
known-first-party = ["cache", "convert", "import_pack", "models", "telegram", "tests"]
|
||||
known-third-party = ["lottie"]
|
||||
@@ -0,0 +1,12 @@
|
||||
{ pkgs ? import (builtins.getFlake
|
||||
"github:nixos/nixpkgs/bfc1b8a4574108ceef22f02bafcf6611380c100d").outPath {}
|
||||
}:
|
||||
pkgs.mkShell {
|
||||
packages = [
|
||||
(pkgs.python3.withPackages (ps: with ps; [
|
||||
pillow lottie cairosvg pydantic typer httpx pytest
|
||||
]))
|
||||
pkgs.ffmpeg pkgs.ruff pkgs.basedpyright
|
||||
];
|
||||
PYTHONDONTWRITEBYTECODE = "1";
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Single-origin, bounded Bot API transport. Never expose response diagnostics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING, Final, Self, final
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
|
||||
from models import (
|
||||
CATALOG_BYTES,
|
||||
DOWNLOAD_BYTES,
|
||||
TOTAL_BYTES,
|
||||
FailureReason,
|
||||
ImportFailureError,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
from types import TracebackType
|
||||
|
||||
TOKEN: Final = re.compile(r"[0-9]{1,20}:[A-Za-z0-9_-]{20,128}")
|
||||
NAME: Final = re.compile(r"[A-Za-z0-9_]{1,64}")
|
||||
FILE_PATH: Final = re.compile(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_.-]+)+")
|
||||
TOKEN_BYTES: Final = 256
|
||||
REQUEST_SECONDS: Final = 30
|
||||
|
||||
|
||||
def pack_name(value: str) -> str:
|
||||
"""Accept only short names or credential-free Telegram addstickers links."""
|
||||
if NAME.fullmatch(value):
|
||||
return value
|
||||
parsed = urlsplit(value)
|
||||
if (
|
||||
parsed.scheme == "https"
|
||||
and parsed.netloc in {"t.me", "telegram.me"}
|
||||
and not parsed.query
|
||||
and not parsed.fragment
|
||||
and parsed.path.startswith("/addstickers/")
|
||||
):
|
||||
name = parsed.path.removeprefix("/addstickers/")
|
||||
if NAME.fullmatch(name):
|
||||
return name
|
||||
raise ImportFailureError(FailureReason.INVALID_PACK_REFERENCE)
|
||||
|
||||
|
||||
def api_origin(value: str) -> str:
|
||||
"""Require one credential-free origin, allowing HTTP only on loopback."""
|
||||
parsed = urlsplit(value)
|
||||
if (
|
||||
parsed.username is not None
|
||||
or parsed.password is not None
|
||||
or not parsed.hostname
|
||||
or parsed.path not in {"", "/"}
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
or parsed.scheme not in {"https", "http"}
|
||||
):
|
||||
raise ImportFailureError(FailureReason.INVALID_API_ORIGIN)
|
||||
if parsed.scheme == "http" and parsed.hostname not in {
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
"::1",
|
||||
}:
|
||||
raise ImportFailureError(FailureReason.INSECURE_API_ORIGIN)
|
||||
# Force port validation before any credential is used.
|
||||
_ = parsed.port
|
||||
return value.rstrip("/")
|
||||
|
||||
|
||||
def read_token(path: Path) -> str:
|
||||
"""Read one bounded, syntactically valid credential from an explicit file."""
|
||||
with path.open("rb") as source:
|
||||
raw = source.read(TOKEN_BYTES + 1)
|
||||
if len(raw) > TOKEN_BYTES:
|
||||
raise ImportFailureError(FailureReason.INVALID_CREDENTIAL_FILE)
|
||||
token = raw.decode("ascii").strip()
|
||||
if TOKEN.fullmatch(token) is None:
|
||||
raise ImportFailureError(FailureReason.INVALID_CREDENTIAL_FILE)
|
||||
return token
|
||||
|
||||
|
||||
@final
|
||||
class Telegram:
|
||||
"""Mutable byte accounting belongs to one sequential import."""
|
||||
|
||||
def __init__(self, origin: str, token: str) -> None:
|
||||
"""Own a sequential transport without redirects or environment trust."""
|
||||
self.origin = api_origin(origin)
|
||||
self.token = token
|
||||
self.total = 0
|
||||
self.client = httpx.Client(
|
||||
timeout=httpx.Timeout(10, connect=5),
|
||||
limits=httpx.Limits(max_connections=1, max_keepalive_connections=1),
|
||||
follow_redirects=False,
|
||||
trust_env=False,
|
||||
headers={"Accept-Encoding": "identity"},
|
||||
)
|
||||
|
||||
def __enter__(self) -> Self:
|
||||
"""Return this import's transport."""
|
||||
return self
|
||||
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type: type[BaseException] | None,
|
||||
exc: BaseException | None,
|
||||
traceback: TracebackType | None,
|
||||
) -> None:
|
||||
"""Close the transport after success or failure."""
|
||||
self.client.close()
|
||||
|
||||
def request(self, suffix: str, limit: int) -> bytes:
|
||||
"""Bound raw response bytes, total transfer bytes and elapsed time."""
|
||||
start = time.monotonic()
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
with self.client.stream("GET", self.origin + suffix) as response:
|
||||
if (
|
||||
response.status_code != HTTPStatus.OK
|
||||
or response.headers.get("content-encoding", "identity") != "identity"
|
||||
):
|
||||
raise ImportFailureError(FailureReason.BOT_API_REQUEST_REJECTED)
|
||||
for chunk in response.iter_raw():
|
||||
size += len(chunk)
|
||||
self.total += len(chunk)
|
||||
if (
|
||||
size > limit
|
||||
or self.total > TOTAL_BYTES
|
||||
or time.monotonic() - start > REQUEST_SECONDS
|
||||
):
|
||||
raise ImportFailureError(
|
||||
FailureReason.DOWNLOAD_SIZE_OR_TIME_LIMIT_EXCEEDED
|
||||
)
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks)
|
||||
|
||||
def method(self, method: str, parameter: str, value: str) -> bytes:
|
||||
"""Encode method parameters as query data on the configured origin."""
|
||||
# Values are encoded as query data, never interpreted as a URL/path.
|
||||
query = str(httpx.QueryParams({parameter: value}))
|
||||
return self.request(f"/bot{self.token}/{method}?{query}", CATALOG_BYTES)
|
||||
|
||||
def download(self, path: str) -> bytes:
|
||||
"""Fetch a bounded file only after rejecting traversal and URL syntax."""
|
||||
if FILE_PATH.fullmatch(path) is None or any(
|
||||
p in {".", ".."} for p in path.split("/")
|
||||
):
|
||||
raise ImportFailureError(FailureReason.UNSAFE_BOT_API_FILE_PATH)
|
||||
return self.request(f"/file/bot{self.token}/{path}", DOWNLOAD_BYTES)
|
||||
@@ -0,0 +1 @@
|
||||
"""Importer boundary tests."""
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Wire fixture and independent conversion assets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import io
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Final, override
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
from pydantic import JsonValue
|
||||
|
||||
TOKEN: Final = "123456:FixtureCredential_Only_0123456789"
|
||||
ROOT: Final = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Reply:
|
||||
"""Immutable wire response for one fixture route."""
|
||||
|
||||
body: bytes
|
||||
status: int = 200
|
||||
location: str = ""
|
||||
|
||||
|
||||
def encoded(value: JsonValue) -> bytes:
|
||||
"""Serialize independent fixture JSON into a wire response."""
|
||||
return json.dumps(value).encode()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def api_server(
|
||||
routes: dict[str, Reply], received: list[str] | None = None
|
||||
) -> Iterator[str]:
|
||||
"""Serve fixture routes on loopback without logging request credentials."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None:
|
||||
if received is not None:
|
||||
received.append(self.path)
|
||||
parsed = urlsplit(self.path)
|
||||
key = parsed.path.rsplit("/", 1)[-1]
|
||||
if key == "getFile":
|
||||
key = parse_qs(parsed.query)["file_id"][0]
|
||||
reply = routes.get(key, Reply(b"", 404))
|
||||
self.send_response(reply.status)
|
||||
if reply.location:
|
||||
self.send_header("Location", reply.location)
|
||||
self.send_header("Content-Length", str(len(reply.body)))
|
||||
self.end_headers()
|
||||
try:
|
||||
_ = self.wfile.write(reply.body)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
return # Expected when bounded client rejects oversized fixture.
|
||||
|
||||
@override
|
||||
def log_message(self, format: str, *args: str | int) -> None:
|
||||
return # Never log credential-bearing fixture paths.
|
||||
|
||||
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
yield f"http://127.0.0.1:{server.server_port}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
|
||||
|
||||
def routes_for(assets: dict[str, bytes]) -> dict[str, Reply]:
|
||||
"""Describe source files using Bot API envelopes and download routes."""
|
||||
stickers: list[JsonValue] = []
|
||||
routes: dict[str, Reply] = {}
|
||||
for index, (filename, data) in enumerate(assets.items()):
|
||||
file_id = f"file{index}"
|
||||
stickers.append(
|
||||
{
|
||||
"file_id": file_id,
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"is_animated": filename.endswith(".tgs"),
|
||||
"is_video": filename.endswith(".webm"),
|
||||
"emoji": "😀",
|
||||
"file_size": len(data),
|
||||
}
|
||||
)
|
||||
routes[file_id] = Reply(
|
||||
encoded(
|
||||
{
|
||||
"ok": True,
|
||||
"result": {
|
||||
"file_path": "stickers/" + filename,
|
||||
"file_size": len(data),
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
routes[filename] = Reply(data)
|
||||
routes["getStickerSet"] = Reply(
|
||||
encoded(
|
||||
{
|
||||
"ok": True,
|
||||
"result": {
|
||||
"name": "FixturePack",
|
||||
"title": "Fixture pack",
|
||||
"stickers": stickers,
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
return routes
|
||||
|
||||
|
||||
def vector_data() -> JsonValue:
|
||||
"""Describe a moving solid layer independently of the converter."""
|
||||
return {
|
||||
"v": "5.5.2",
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 30,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"layers": [
|
||||
{
|
||||
"ty": 1,
|
||||
"ind": 1,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"st": 0,
|
||||
"sw": 128,
|
||||
"sh": 128,
|
||||
"sc": "#00ff00",
|
||||
"ks": {
|
||||
"o": {"a": 0, "k": 100},
|
||||
"r": {"a": 0, "k": 0},
|
||||
"p": {
|
||||
"a": 1,
|
||||
"k": [
|
||||
{
|
||||
"t": 0,
|
||||
"s": [64, 192],
|
||||
"e": [320, 192],
|
||||
"i": {"x": 1, "y": 1},
|
||||
"o": {"x": 0, "y": 0},
|
||||
},
|
||||
{"t": 30, "s": [320, 192]},
|
||||
],
|
||||
},
|
||||
"a": {"a": 0, "k": [0, 0]},
|
||||
"s": {"a": 0, "k": [100, 100]},
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def make_conversion_assets() -> dict[str, bytes]:
|
||||
"""Generate source media shared by CLI tests and the isolated game API fixture."""
|
||||
image = Image.new("RGBA", (256, 128))
|
||||
ImageDraw.Draw(image).rectangle((64, 32, 191, 95), fill=(255, 0, 0, 255))
|
||||
with io.BytesIO() as buffer:
|
||||
image.save(buffer, format="WEBP", lossless=True)
|
||||
webp = buffer.getvalue()
|
||||
frames: list[bytes] = []
|
||||
for index in range(80):
|
||||
image = Image.new("RGBA", (128, 128))
|
||||
ImageDraw.Draw(image).rectangle(
|
||||
(index % 64, 32, index % 64 + 31, 63), fill=(0, 0, 255, 255)
|
||||
)
|
||||
frames.append(image.tobytes())
|
||||
ffmpeg = shutil.which("ffmpeg")
|
||||
if ffmpeg is None:
|
||||
pytest.fail("ffmpeg is required to generate independent video fixtures")
|
||||
video = subprocess.run(
|
||||
[
|
||||
ffmpeg,
|
||||
"-v",
|
||||
"error",
|
||||
"-nostdin",
|
||||
"-threads",
|
||||
"1",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
"-pixel_format",
|
||||
"rgba",
|
||||
"-video_size",
|
||||
"128x128",
|
||||
"-framerate",
|
||||
"20",
|
||||
"-i",
|
||||
"pipe:0",
|
||||
"-c:v",
|
||||
"libvpx-vp9",
|
||||
"-threads",
|
||||
"1",
|
||||
"-pix_fmt",
|
||||
"yuva420p",
|
||||
"-auto-alt-ref",
|
||||
"0",
|
||||
"-f",
|
||||
"webm",
|
||||
"pipe:1",
|
||||
],
|
||||
input=b"".join(frames),
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=30,
|
||||
).stdout
|
||||
return {
|
||||
"static.webp": webp,
|
||||
"vector.tgs": gzip.compress(encoded(vector_data())),
|
||||
"video.webm": video,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def conversion_assets() -> dict[str, bytes]:
|
||||
"""Provide the same independent source media to parametrized import checks."""
|
||||
return make_conversion_assets()
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Hostile wire responses and invalid committed catalogs for CLI scenarios."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, assert_never
|
||||
|
||||
from tests.conftest import TOKEN, Reply, encoded
|
||||
|
||||
WireFailure = Literal[
|
||||
"traversal",
|
||||
"absolute",
|
||||
"encoded_path",
|
||||
"redirect_api",
|
||||
"redirect_file",
|
||||
"oversize_download",
|
||||
"bad_json",
|
||||
"api_error",
|
||||
]
|
||||
CatalogFailure = Literal[
|
||||
"duplicate_packs", "bad_catalog", "catalog_bytes", "pack_limit", "overall_limit"
|
||||
]
|
||||
Failure = (
|
||||
WireFailure
|
||||
| CatalogFailure
|
||||
| Literal[
|
||||
"dimensions",
|
||||
"expansion",
|
||||
"external_tgs",
|
||||
"credential_metadata",
|
||||
"late_conversion",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def reject_wire(routes: dict[str, Reply], failure: WireFailure) -> None:
|
||||
"""Replace a fixture route with the requested hostile Bot API response."""
|
||||
match failure:
|
||||
case "traversal" | "absolute" | "encoded_path":
|
||||
path = {
|
||||
"traversal": "stickers/../secret.webp",
|
||||
"absolute": "https://evil.test/file.webp",
|
||||
"encoded_path": "stickers/%2e%2e/file.webp",
|
||||
}[failure]
|
||||
routes["file0"] = Reply(
|
||||
encoded({"ok": True, "result": {"file_path": path}})
|
||||
)
|
||||
case "redirect_api" | "redirect_file":
|
||||
key = "getStickerSet" if failure == "redirect_api" else "static.webp"
|
||||
routes[key] = Reply(b"", 302, "https://evil.test/" + TOKEN)
|
||||
case "oversize_download":
|
||||
routes["static.webp"] = Reply(b"x" * 4_194_305)
|
||||
case "bad_json":
|
||||
routes["getStickerSet"] = Reply(b"{broken " + TOKEN.encode())
|
||||
case "api_error":
|
||||
routes["getStickerSet"] = Reply(
|
||||
encoded({"ok": False, "description": TOKEN})
|
||||
)
|
||||
case _:
|
||||
assert_never(failure)
|
||||
|
||||
|
||||
def invalid_catalog(failure: CatalogFailure) -> bytes:
|
||||
"""Encode one independently constructed invalid on-disk catalog."""
|
||||
match failure:
|
||||
case "duplicate_packs":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{"id": "Old", "title": "One", "stickers": []},
|
||||
{"id": "Old", "title": "Two", "stickers": []},
|
||||
],
|
||||
}
|
||||
)
|
||||
case "bad_catalog":
|
||||
return b"{invalid"
|
||||
case "catalog_bytes":
|
||||
return b" " * 524_289
|
||||
case "pack_limit":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{"id": f"Old{i}", "title": "Old", "stickers": []}
|
||||
for i in range(64)
|
||||
],
|
||||
}
|
||||
)
|
||||
case "overall_limit":
|
||||
return encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": f"Old{i}",
|
||||
"title": "Old",
|
||||
"stickers": [
|
||||
{"id": f"{j:064x}", "emoji": "", "frames": 1}
|
||||
for j in range(128)
|
||||
],
|
||||
}
|
||||
for i in range(16)
|
||||
],
|
||||
}
|
||||
)
|
||||
case _:
|
||||
assert_never(failure)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Disk ownership and interrupted-job recovery through the real CLI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import selectors
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, Literal, assert_never
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from tests.conftest import ROOT, TOKEN, api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def png(color: str) -> bytes:
|
||||
"""Encode a deterministic opaque asset for cache ownership scenarios."""
|
||||
with io.BytesIO() as buffer:
|
||||
Image.new("RGBA", (128, 128), color).save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_recovery_and_replacement_reclaim_only_owned_unreferenced_assets(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
) -> None:
|
||||
"""Retain shared and unrelated files while reclaiming stale owned assets."""
|
||||
cache = tmp_path / "cache"
|
||||
assets = cache / "assets"
|
||||
assets.mkdir(parents=True)
|
||||
ids: list[str] = []
|
||||
for color in ("red", "green", "blue", "yellow"):
|
||||
data = png(color)
|
||||
asset_id = hashlib.sha256(data).hexdigest()
|
||||
_ = (assets / (asset_id + ".png")).write_bytes(data)
|
||||
ids.append(asset_id)
|
||||
_ = (assets / "unrelated.txt").write_text("keep")
|
||||
_ = (cache / "catalog.json").write_bytes(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": "FixturePack",
|
||||
"title": "Old",
|
||||
"stickers": [
|
||||
{"id": ids[0], "emoji": "", "frames": 1},
|
||||
{"id": ids[1], "emoji": "", "frames": 1},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "KeepMe",
|
||||
"title": "Protected",
|
||||
"stickers": [
|
||||
{"id": ids[0], "emoji": "", "frames": 1},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
root = cache / ".wowmine-stickers-importer-v1"
|
||||
job = root / "job-12345678"
|
||||
job.mkdir(parents=True)
|
||||
_ = (root / "owner").write_bytes(b"wowmine-stickers-importer-v1\n")
|
||||
_ = (job / "journal.json").write_bytes(
|
||||
encoded({"version": 1, "assets": [ids[0], ids[2]]})
|
||||
)
|
||||
_ = (job / "input.webp").write_bytes(b"stale input")
|
||||
_ = (root / "unrelated.txt").write_text("keep too")
|
||||
with api_server(
|
||||
routes_for({"static.webp": conversion_assets["static.webp"]})
|
||||
) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert (assets / (ids[0] + ".png")).read_bytes() == png("red")
|
||||
assert not (assets / (ids[1] + ".png")).exists()
|
||||
assert not (assets / (ids[2] + ".png")).exists()
|
||||
assert (assets / (ids[3] + ".png")).read_bytes() == png("yellow")
|
||||
assert (assets / "unrelated.txt").read_text() == "keep"
|
||||
assert (root / "unrelated.txt").read_text() == "keep too"
|
||||
assert sorted(p.name for p in root.iterdir()) == ["owner", "unrelated.txt"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("interrupt", [signal.SIGKILL, signal.SIGALRM])
|
||||
def test_interrupted_job_retains_catalog_and_next_import_recovers_staging(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
interrupt: Literal[signal.Signals.SIGKILL, signal.Signals.SIGALRM],
|
||||
) -> None:
|
||||
"""Recover killed or timed-out jobs without changing the committed catalog."""
|
||||
token = tmp_path / "token"
|
||||
_ = token.write_text(TOKEN)
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
original = b'{"version":1,"packs":[]}'
|
||||
_ = (cache / "catalog.json").write_bytes(original)
|
||||
command = (
|
||||
[os.environ["IMPORTER_BINARY"]]
|
||||
if "IMPORTER_BINARY" in os.environ
|
||||
else [
|
||||
sys.executable,
|
||||
str(ROOT / "import_pack.py"),
|
||||
]
|
||||
)
|
||||
with api_server(routes_for(conversion_assets)) as origin:
|
||||
with subprocess.Popen(
|
||||
[
|
||||
*command,
|
||||
"--token-file",
|
||||
str(token),
|
||||
"--pack",
|
||||
"FixturePack",
|
||||
"--output",
|
||||
str(cache),
|
||||
"--api-base",
|
||||
origin,
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
bufsize=0,
|
||||
) as child:
|
||||
assert child.stdout is not None
|
||||
with selectors.DefaultSelector() as selector:
|
||||
_ = selector.register(child.stdout, selectors.EVENT_READ)
|
||||
assert selector.select(timeout=10)
|
||||
assert child.stdout.readline() == b'{"status":"fetching"}\n'
|
||||
assert selector.select(timeout=10)
|
||||
assert b'"status": "converting"' in child.stdout.readline()
|
||||
child.send_signal(interrupt)
|
||||
stdout, stderr = child.communicate(timeout=10)
|
||||
match interrupt:
|
||||
case signal.SIGKILL:
|
||||
assert child.returncode == -signal.SIGKILL
|
||||
case signal.SIGALRM:
|
||||
assert child.returncode == 1
|
||||
assert stderr == b'{"status":"error","code":"job_timeout"}\n'
|
||||
case _:
|
||||
assert_never(interrupt)
|
||||
assert TOKEN.encode() not in stdout + stderr
|
||||
assert (cache / "catalog.json").read_bytes() == original
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert sorted(
|
||||
p.name for p in (cache / ".wowmine-stickers-importer-v1").iterdir()
|
||||
) == ["owner"]
|
||||
@@ -0,0 +1,76 @@
|
||||
"""PNG identity includes timing, even when visible atlas pixels are identical."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from models import Catalog, ImportFailureError
|
||||
from tests.conftest import api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_transparent_animations_with_different_timing_keep_distinct_ids(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Distinguish frame counts even when transparent atlas pixels match."""
|
||||
assets = {
|
||||
f"empty{count}.tgs": gzip.compress(
|
||||
encoded(
|
||||
{
|
||||
"v": "5.5.2",
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 20,
|
||||
"ip": 0,
|
||||
"op": count,
|
||||
"layers": [],
|
||||
}
|
||||
)
|
||||
)
|
||||
for count in (9, 10)
|
||||
}
|
||||
with api_server(routes_for(assets)) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
catalog = Catalog.model_validate_json(
|
||||
(tmp_path / "cache" / "catalog.json").read_bytes()
|
||||
)
|
||||
stickers = catalog.packs[0].stickers
|
||||
assert [s.frames for s in stickers] == [9, 10]
|
||||
assert stickers[0].id != stickers[1].id
|
||||
pixels: list[bytes] = []
|
||||
for sticker in stickers:
|
||||
with Image.open(tmp_path / "cache" / "assets" / (sticker.id + ".png")) as image:
|
||||
assert image.size == (1024, 256)
|
||||
assert image.info["wowmine_frames"] == str(sticker.frames)
|
||||
pixels.append(image.tobytes())
|
||||
assert pixels[0] == pixels[1]
|
||||
|
||||
|
||||
def test_catalog_rejects_conflicting_frames_for_shared_asset_id() -> None:
|
||||
"""Reject an asset ID associated with incompatible animation timing."""
|
||||
with pytest.raises(ImportFailureError, match="conflicting frame counts"):
|
||||
_ = Catalog.model_validate_json(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [
|
||||
{
|
||||
"id": f"Pack{count}",
|
||||
"title": "Title",
|
||||
"stickers": [
|
||||
{"id": "a" * 64, "emoji": "", "frames": count},
|
||||
],
|
||||
}
|
||||
for count in (9, 10)
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,242 @@
|
||||
"""CLI conversion, catalog compatibility and hostile input rejection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, assert_never
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
from pydantic import JsonValue, TypeAdapter
|
||||
|
||||
from models import Catalog
|
||||
from tests.conftest import ROOT, TOKEN, Reply, api_server, encoded, routes_for
|
||||
from tests.rejected_inputs import invalid_catalog, reject_wire
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from tests.rejected_inputs import Failure
|
||||
|
||||
|
||||
def run_cli(
|
||||
directory: Path, origin: str, pack: str = "https://t.me/addstickers/FixturePack"
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
"""Run the installed or source CLI against an isolated fixture origin."""
|
||||
token = directory / "token"
|
||||
_ = token.write_text(TOKEN)
|
||||
command = (
|
||||
[os.environ["IMPORTER_BINARY"]]
|
||||
if "IMPORTER_BINARY" in os.environ
|
||||
else [
|
||||
sys.executable,
|
||||
str(ROOT / "import_pack.py"),
|
||||
]
|
||||
)
|
||||
return subprocess.run(
|
||||
[
|
||||
*command,
|
||||
"--token-file",
|
||||
str(token),
|
||||
"--pack",
|
||||
pack,
|
||||
"--output",
|
||||
str(directory / "cache"),
|
||||
"--api-base",
|
||||
origin,
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=90,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def test_import_converts_all_formats_preserves_packs_and_deduplicates(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
) -> None:
|
||||
"""Preserve the wire catalog, alpha, animation and deduplication contracts."""
|
||||
assets = {**conversion_assets, "duplicate.webp": conversion_assets["static.webp"]}
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
retained: JsonValue = {"id": "KeepMe", "title": "Other pack", "stickers": []}
|
||||
replaced: JsonValue = {"id": "FixturePack", "title": "Old title", "stickers": []}
|
||||
_ = (cache / "catalog.json").write_bytes(
|
||||
encoded({"version": 1, "packs": [retained, replaced]})
|
||||
)
|
||||
with api_server(routes_for(assets)) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 0, result.stderr
|
||||
statuses = [
|
||||
TypeAdapter[JsonValue](JsonValue).validate_json(line)
|
||||
for line in result.stdout.splitlines()
|
||||
]
|
||||
assert statuses == [
|
||||
{"status": "fetching"},
|
||||
*[{"status": "converting", "completed": i, "total": 4} for i in range(4)],
|
||||
{"status": "complete", "pack": "FixturePack", "stickers": 3},
|
||||
]
|
||||
raw = (cache / "catalog.json").read_bytes()
|
||||
assert TOKEN.encode() not in raw
|
||||
catalog = TypeAdapter[JsonValue](JsonValue).validate_json(raw)
|
||||
assert isinstance(catalog, dict)
|
||||
packs = catalog["packs"]
|
||||
assert isinstance(packs, list)
|
||||
assert packs[0] == retained
|
||||
pack = packs[1]
|
||||
assert isinstance(pack, dict)
|
||||
assert set(catalog) == {"version", "packs"}
|
||||
assert set(pack) == {"id", "title", "stickers"}
|
||||
assert pack["title"] == "Fixture pack"
|
||||
parsed = Catalog.model_validate_json(raw).packs[1]
|
||||
assert [sticker.frames for sticker in parsed.stickers] == [1, 20, 60]
|
||||
entries = pack["stickers"]
|
||||
assert isinstance(entries, list)
|
||||
for entry, sticker in zip(entries, parsed.stickers, strict=True):
|
||||
assert isinstance(entry, dict)
|
||||
assert set(entry) == {"id", "emoji", "frames"}
|
||||
asset = cache / "assets" / (sticker.id + ".png")
|
||||
assert hashlib.sha256(asset.read_bytes()).hexdigest() == sticker.id
|
||||
with Image.open(asset) as image:
|
||||
count = sticker.frames
|
||||
assert image.size == (
|
||||
min(8, count) * 128,
|
||||
((count + min(8, count) - 1) // min(8, count)) * 128,
|
||||
)
|
||||
assert image.mode == "RGBA"
|
||||
pixel = image.getpixel((0, 0))
|
||||
assert isinstance(pixel, tuple)
|
||||
assert pixel[3] == 0
|
||||
assert image.getchannel("A").getextrema() == (0, 255)
|
||||
if count == 1:
|
||||
assert image.getpixel((40, 60)) == (255, 0, 0, 255)
|
||||
if count > 1:
|
||||
last = ((count - 1) % 8 * 128, (count - 1) // 8 * 128)
|
||||
assert (
|
||||
image.crop((0, 0, 128, 128)).tobytes()
|
||||
!= image.crop(
|
||||
(*last, last[0] + 128, last[1] + 128),
|
||||
).tobytes()
|
||||
)
|
||||
assert TOKEN not in result.stdout + result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure",
|
||||
[
|
||||
"traversal",
|
||||
"absolute",
|
||||
"encoded_path",
|
||||
"redirect_api",
|
||||
"redirect_file",
|
||||
"oversize_download",
|
||||
"bad_json",
|
||||
"api_error",
|
||||
"dimensions",
|
||||
"expansion",
|
||||
"external_tgs",
|
||||
"duplicate_packs",
|
||||
"bad_catalog",
|
||||
"credential_metadata",
|
||||
"late_conversion",
|
||||
"catalog_bytes",
|
||||
"pack_limit",
|
||||
"overall_limit",
|
||||
],
|
||||
)
|
||||
def test_rejected_import_retains_catalog_and_hides_credentials(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
failure: Failure,
|
||||
) -> None:
|
||||
"""Retain committed state and redact credentials on every rejection path."""
|
||||
assets = {"static.webp": conversion_assets["static.webp"]}
|
||||
routes = routes_for(assets)
|
||||
cache = tmp_path / "cache"
|
||||
cache.mkdir()
|
||||
original = encoded(
|
||||
{"version": 1, "packs": [{"id": "Old", "title": "Retained", "stickers": []}]}
|
||||
)
|
||||
match failure:
|
||||
case (
|
||||
"traversal"
|
||||
| "absolute"
|
||||
| "encoded_path"
|
||||
| "redirect_api"
|
||||
| "redirect_file"
|
||||
| "oversize_download"
|
||||
| "bad_json"
|
||||
| "api_error"
|
||||
):
|
||||
reject_wire(routes, failure)
|
||||
case "dimensions":
|
||||
with io.BytesIO() as buffer:
|
||||
Image.new("RGBA", (513, 1)).save(buffer, format="WEBP")
|
||||
routes = routes_for({"huge.webp": buffer.getvalue()})
|
||||
case "expansion":
|
||||
routes = routes_for({"bomb.tgs": gzip.compress(b" " * 2_097_153)})
|
||||
case "external_tgs":
|
||||
routes = routes_for(
|
||||
{
|
||||
"linked.tgs": gzip.compress(
|
||||
encoded(
|
||||
{
|
||||
"w": 512,
|
||||
"h": 512,
|
||||
"fr": 30,
|
||||
"ip": 0,
|
||||
"op": 30,
|
||||
"assets": [
|
||||
{
|
||||
"id": "external",
|
||||
"p": "file:///etc/passwd",
|
||||
"u": "",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
case (
|
||||
"duplicate_packs"
|
||||
| "bad_catalog"
|
||||
| "catalog_bytes"
|
||||
| "pack_limit"
|
||||
| "overall_limit"
|
||||
):
|
||||
original = invalid_catalog(failure)
|
||||
case "credential_metadata":
|
||||
value = TypeAdapter[JsonValue](JsonValue).validate_json(
|
||||
routes["getStickerSet"].body
|
||||
)
|
||||
assert isinstance(value, dict)
|
||||
remote = value["result"]
|
||||
assert isinstance(remote, dict)
|
||||
remote["title"] = TOKEN
|
||||
routes["getStickerSet"] = Reply(json.dumps(value).encode())
|
||||
case "late_conversion":
|
||||
routes = routes_for({**assets, "broken.tgs": b"not gzip"})
|
||||
case _:
|
||||
assert_never(failure)
|
||||
_ = (cache / "catalog.json").write_bytes(original)
|
||||
with api_server(routes) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 1
|
||||
assert (cache / "catalog.json").read_bytes() == original
|
||||
assert TOKEN not in result.stdout + result.stderr
|
||||
assert "Traceback" not in result.stderr
|
||||
assert TypeAdapter[JsonValue](JsonValue).validate_json(result.stderr) == {
|
||||
"status": "error",
|
||||
"code": "import_failed",
|
||||
}
|
||||
stage_root = cache / ".wowmine-stickers-importer-v1"
|
||||
if stage_root.exists():
|
||||
assert sorted(p.name for p in stage_root.iterdir()) == ["owner"]
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Client catalog compatibility and player-controlled input rejection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from pydantic import JsonValue, ValidationError
|
||||
|
||||
from models import Catalog, ImportFailureError
|
||||
from tests.conftest import TOKEN, Reply, api_server, encoded, routes_for
|
||||
from tests.test_import import run_cli
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pack",
|
||||
[
|
||||
"https://evil.test/addstickers/FixturePack",
|
||||
"https://t.me@evil.test/addstickers/FixturePack",
|
||||
"https://user@t.me/addstickers/FixturePack",
|
||||
"//t.me/addstickers/FixturePack",
|
||||
"https://t.me/addstickers/FixturePack?host=evil.test",
|
||||
"FixturePack/../secret",
|
||||
"FixturePack\n",
|
||||
],
|
||||
)
|
||||
def test_player_pack_input_cannot_select_fetch_origin(
|
||||
tmp_path: Path, pack: str
|
||||
) -> None:
|
||||
"""Reject player-controlled origins before making any fixture request."""
|
||||
received: list[str] = []
|
||||
with api_server({}, received) as origin:
|
||||
result = run_cli(tmp_path, origin, pack)
|
||||
assert result.returncode == 1
|
||||
assert received == []
|
||||
assert not (tmp_path / "cache" / "catalog.json").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", ["getStickerSet", "static.webp"])
|
||||
def test_redirect_never_sends_token_to_destination(
|
||||
tmp_path: Path,
|
||||
conversion_assets: dict[str, bytes],
|
||||
route: str,
|
||||
) -> None:
|
||||
"""Never forward credential-bearing API or file redirects."""
|
||||
received: list[str] = []
|
||||
with api_server({}, received) as destination:
|
||||
routes = routes_for({"static.webp": conversion_assets["static.webp"]})
|
||||
routes[route] = Reply(b"", 302, destination + "/" + TOKEN)
|
||||
with api_server(routes) as origin:
|
||||
result = run_cli(tmp_path, origin)
|
||||
assert result.returncode == 1
|
||||
assert received == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("frames", 0),
|
||||
("frames", 61),
|
||||
("id", "A" * 64),
|
||||
("emoji", "😀" * 33),
|
||||
],
|
||||
)
|
||||
def test_catalog_rejects_values_client_cannot_use(field: str, value: str | int) -> None:
|
||||
"""Reject sticker values outside the client's catalog contract."""
|
||||
sticker: JsonValue = {"id": "a" * 64, "emoji": "", "frames": 1, field: value}
|
||||
with pytest.raises((ValueError, UnicodeError, ImportFailureError)):
|
||||
_ = Catalog.model_validate_json(
|
||||
encoded(
|
||||
{
|
||||
"version": 1,
|
||||
"packs": [{"id": "Pack", "title": "Title", "stickers": [sticker]}],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [True, 0, 2, "1"])
|
||||
def test_catalog_version_requires_integer_one(*, version: bool | int | str) -> None:
|
||||
"""Reject booleans, other versions and string coercion for catalog version."""
|
||||
with pytest.raises(ValidationError):
|
||||
_ = Catalog.model_validate_json(encoded({"version": version, "packs": []}))
|
||||
@@ -0,0 +1,8 @@
|
||||
# Local types for verified python-lottie Cairo exporter API.
|
||||
from typing import BinaryIO
|
||||
|
||||
from lottie.objects import Animation
|
||||
|
||||
def export_png(
|
||||
animation: Animation, fp: BinaryIO, frame: float = 0, dpi: float = 96
|
||||
) -> None: ...
|
||||
@@ -0,0 +1,6 @@
|
||||
# Local types for verified python-lottie 0.7.2 vector loading API.
|
||||
from pydantic import JsonValue
|
||||
|
||||
class Animation:
|
||||
@classmethod
|
||||
def load(cls, lottiedict: dict[str, JsonValue]) -> Animation: ...
|
||||
Reference in New Issue
Block a user