paste-bin/paste_bin/validate.py
Jarian 985e070757 port: FastAPI rewrite built by the arch-llm spec pipeline
Spec-first port of the Flask app (still on main):
- schema.arch: signed arch-llm spec (single source of truth)
- paste_bin/: generated FastAPI backend, verified 51/51 frozen owner
  tests, 92.5% coverage (build r3, 2026-11-18)
- ui/: SPA + emitted OpenAPI contract (openapi.json + generated
  client.js); the app calls only window.PasteBinAPI
- 7 old bugs fixed (file raw 500, silent expiry, AVI-as-webp,
  stripped content, limiter leak, trusted mimetype, stale tmp)
- 62/62 live probe green; /health + JSON index added; JSON API

Full report on the wiki: 'FastAPI port (arch-llm pipeline)'.
2026-11-18 23:00:23 +00:00

104 lines
2.8 KiB
Python

from __future__ import annotations
import re
import uuid
from datetime import datetime, timedelta, timezone
ALLOWED_IMAGE_EXTENSIONS = {"png", "jpg", "jpeg", "gif", "bmp", "webp", "tiff"}
ALLOWED_TEXT_EXTENSIONS = {
"txt", "py", "js", "ts", "c", "cpp", "h", "java", "rb", "go", "rs", "md",
"json", "xml", "yaml", "yml", "html", "css", "sh", "log", "csv", "sql",
"ini", "cfg", "toml", "lua", "php", "swift", "kt", "scala", "r", "pl",
"hs", "zig", "nix",
}
MAX_UPLOAD_BYTES = 20 * 1024 * 1024
_PASTE_ID_RE = re.compile(r"^[a-f0-9]{16}$")
def generate_paste_id() -> str:
return uuid.uuid4().hex[:16]
def is_valid_paste_id(paste_id: str) -> bool:
return bool(_PASTE_ID_RE.match(paste_id))
def sanitize_filename(filename: str) -> str:
name = filename
if "/" in name:
name = name.rsplit("/", 1)[-1]
if "\\" in name:
name = name.rsplit("\\", 1)[-1]
cleaned = []
for ch in name:
if ch.isascii() and (ch.isalpha() or ch.isdigit() or ch in "._-"):
cleaned.append(ch)
else:
cleaned.append("_")
return "".join(cleaned).lstrip(".")[:255]
def parse_expiry(expiry: str) -> str | None:
now = datetime.now(timezone.utc)
if expiry == "1h":
result = now + timedelta(hours=1)
elif expiry == "1d":
result = now + timedelta(days=1)
elif expiry == "1w":
result = now + timedelta(weeks=1)
elif expiry == "1m":
result = now + timedelta(days=30)
elif expiry == "forever":
return None
else:
raise ValueError(f"Unknown expiry: {expiry}")
return result.isoformat().replace("+00:00", "Z")
def check_image_magic(data: bytes, ext: str) -> bool:
if ext == "png":
return data.startswith(b"\x89PNG\r\n\x1a\n")
if ext == "jpg":
return data.startswith(b"\xff\xd8\xff")
if ext == "gif":
return data.startswith(b"GIF87a") or data.startswith(b"GIF89a")
if ext == "bmp":
return data.startswith(b"BM")
if ext == "webp":
return data[:4] == b"RIFF" and data[8:12] == b"WEBP"
if ext == "tiff":
return True
return False
def derive_mimetype(ext: str) -> str:
if ext == "png":
return "image/png"
if ext in {"jpg", "jpeg"}:
return "image/jpeg"
if ext == "gif":
return "image/gif"
if ext == "bmp":
return "image/bmp"
if ext == "webp":
return "image/webp"
if ext == "tiff":
return "image/tiff"
return "application/octet-stream"
def is_image_ext(filename: str) -> bool:
if "." not in filename:
return False
return filename.rsplit(".", 1)[1].lower() in ALLOWED_IMAGE_EXTENSIONS
def is_text_ext(filename: str) -> bool:
if "." not in filename:
return False
return filename.rsplit(".", 1)[1].lower() in ALLOWED_TEXT_EXTENSIONS