# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """What an uploaded file actually is, decided from its bytes. The filename a phone sends is not evidence: it is attacker-chosen, it is discarded on the way in (the stored name is a content hash), and ".jpg" on a file that is not a JPEG would be stored, served, and then refused by ``pack_load`` on the *next* start -- taking the bot down for a photo that looked fine when it arrived. So the suffix is derived here instead, from the magic bytes, and anything not on the allowlist never reaches the album. The ISO base-media formats (mp4, mov, m4v, heic, heif, avif) share one container and are told apart by the brand in the ``ftyp`` box rather than by extension, which is the only thing that distinguishes an iPhone photo from an iPhone video at the byte level. SVG is the one member with no magic number at all -- it is XML -- so it is matched on a leading prefix instead, and it is the one format where that is the whole test. """ from __future__ import annotations from dataclasses import dataclass from typing import Final # How much of a file the sniffer ever looks at. The longest test is the # ISO-BMFF brand, which ends at byte 12; the SVG prefix scan wants a little # room for leading whitespace and a byte-order mark. HEADER_BYTES: Final = 64 # A byte-order mark, which a phone's XML writer may emit ahead of " MediaKind | None: """Identify one upload, or None when it is not a format we accept. Args: payload: The file exactly as it arrived. Returns: The matching kind, or None for anything off the allowlist. """ header = payload[:HEADER_BYTES] for signature, kind in _SIGNATURES: if header.startswith(signature): return kind if _is_riff_webp(header): return WEBP brand = _iso_brand(header) if brand is not None: return _BRANDS.get(brand, MP4) return SVG if _is_svg(header) else None def _is_riff_webp(header: bytes) -> bool: """True for a RIFF container whose form type is WEBP. Both halves are checked: RIFF also carries wav and avi, and a bare "RIFF" test would file either of them as a picture. """ return header.startswith(b"RIFF") and header[8:12] == b"WEBP" def _iso_brand(header: bytes) -> bytes | None: """The lowercased ISO base-media brand, or None if this is not one. The box length at bytes 0..4 is deliberately not validated. It varies between writers and is not what identifies the format; "ftyp" at byte 4 is, and every file in this family has it. """ if header[4:8] != b"ftyp": return None return header[8:12].lower() def _is_svg(header: bytes) -> bool: """True for something that opens like an SVG document. A prefix test rather than a parse: this decides *which* allowlist entry a file belongs to, not whether it is well-formed, and a document that opens with "