~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
60 lines · 2.2 KB Raw History
#!/usr/bin/env -S uv run --script
"""Check deployment-specific preview metadata and the cached PNG endpoint."""
import hashlib
import html.parser
import http.client
import struct
import sys
from urllib.parse import urlsplit


class Metadata(html.parser.HTMLParser):
    def __init__(self):
        super().__init__()
        self.values = {}

    def handle_starttag(self, tag, attrs):
        if tag == "meta":
            attrs = dict(attrs)
            self.values[attrs.get("property", attrs.get("name"))] = attrs.get("content")


def check(base, public_url=None):
    url = urlsplit(base)
    public_url = public_url or base
    public_host = urlsplit(public_url).netloc

    def request(path, method="GET", headers=None):
        conn = http.client.HTTPConnection(url.hostname, url.port, timeout=10)
        try:
            conn.request(method, path, headers=headers or {})
            response = conn.getresponse()
            body = response.read()
            assert response.status == 200, (path, response.status)
            return {name.lower(): value for name, value in response.getheaders()}, body
        finally:
            conn.close()

    _, page = request("/")
    metadata = Metadata()
    metadata.feed(page.decode())
    values = metadata.values
    assert values["og:title"] == public_host, values
    assert values["twitter:title"] == public_host, values
    assert values["og:image"] == public_url + "/og-image?v=3", values
    assert values["twitter:image"] == values["og:image"], values
    headers, png = request("/og-image?v=3")
    assert headers["content-type"] == "image/png", headers
    assert png[:8] == b"\x89PNG\r\n\x1a\n"
    assert struct.unpack(">II", png[16:24]) == (1200, 630)
    assert "public" in headers["cache-control"], headers
    head, empty = request("/og-image?v=3", "HEAD")
    assert not empty
    assert int(head["content-length"]) == len(png), head
    _, repeated = request("/og-image?v=3", headers={"Host": "wrong-deployment.example"})
    assert hashlib.sha256(repeated).digest() == hashlib.sha256(png).digest()
    print("preview: configured hostname metadata, PNG, HEAD and cached Host-independent bytes passed")


if __name__ == "__main__":
    check(sys.argv[1].rstrip("/"), sys.argv[2].rstrip("/") if len(sys.argv) > 2 else None)