diff --git a/src/scrobbler/federation/protocol/hostmeta.py b/src/scrobbler/federation/protocol/hostmeta.py new file mode 100644 index 0000000..b35e372 --- /dev/null +++ b/src/scrobbler/federation/protocol/hostmeta.py @@ -0,0 +1,15 @@ +"""/.well-known/host-meta (RFC 6415): points older clients at WebFinger.""" + +from xml.sax.saxutils import quoteattr + +CONTENT_TYPE = "application/xrd+xml" + + +def xrd(base_url: str) -> str: + template = quoteattr(f"{base_url}/.well-known/webfinger?resource={{uri}}") + return ( + '\n' + '\n' + f' \n' + "\n" + ) diff --git a/src/scrobbler/federation/protocol/media.py b/src/scrobbler/federation/protocol/media.py new file mode 100644 index 0000000..eecbbb0 --- /dev/null +++ b/src/scrobbler/federation/protocol/media.py @@ -0,0 +1,37 @@ +"""ActivityPub media types and content negotiation.""" + +ACTIVITY_JSON = "application/activity+json" +AS_PROFILE = "https://www.w3.org/ns/activitystreams" +LD_JSON = f'application/ld+json; profile="{AS_PROFILE}"' +JRD_JSON = "application/jrd+json" + + +def _media_ranges(header: str): + for part in (header or "").split(","): + pieces = [p.strip() for p in part.split(";")] + media = pieces[0].lower() + params = {} + for piece in pieces[1:]: + name, _, value = piece.partition("=") + params[name.strip().lower()] = value.strip().strip('"') + try: + quality = float(params.get("q", "1")) + except ValueError: + quality = 0.0 + yield media, params, quality + + +def is_activitypub(media: str, params: dict) -> bool: + if media == ACTIVITY_JSON: + return True + # ld+json counts when it names the ActivityStreams profile (or no profile at all) + return media == "application/ld+json" and params.get("profile", AS_PROFILE) == AS_PROFILE + + +def wants_activitypub(accept: str | None) -> bool: + """True if an Accept header asks for ActivityPub JSON (rather than HTML).""" + return any(q > 0 and is_activitypub(m, p) for m, p, q in _media_ranges(accept or "")) + + +def is_activitypub_content_type(content_type: str | None) -> bool: + return any(is_activitypub(m, p) for m, p, _ in _media_ranges(content_type or "")) diff --git a/src/scrobbler/federation/protocol/nodeinfo.py b/src/scrobbler/federation/protocol/nodeinfo.py new file mode 100644 index 0000000..7735bd1 --- /dev/null +++ b/src/scrobbler/federation/protocol/nodeinfo.py @@ -0,0 +1,19 @@ +"""NodeInfo 2.1 (https://nodeinfo.diaspora.software/): what software a server runs.""" + +SCHEMA_21 = "http://nodeinfo.diaspora.software/ns/schema/2.1" + + +def discovery(base_url: str) -> dict: + return {"links": [{"rel": SCHEMA_21, "href": f"{base_url}/nodeinfo/2.1"}]} + + +def document(*, version: str, users_total: int, open_registrations: bool) -> dict: + return { + "version": "2.1", + "software": {"name": "scrobbler", "version": version}, + "protocols": ["activitypub"], + "services": {"inbound": [], "outbound": []}, + "openRegistrations": open_registrations, + "usage": {"users": {"total": users_total}, "localPosts": 0}, + "metadata": {}, + } diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py new file mode 100644 index 0000000..d9ce6d1 --- /dev/null +++ b/src/scrobbler/federation/protocol/vocab.py @@ -0,0 +1,147 @@ +"""ActivityStreams / ActivityPub document builders (plain dicts, ready for JSON).""" + +import html +from dataclasses import dataclass + +AS_CONTEXT = "https://www.w3.org/ns/activitystreams" +SECURITY_CONTEXT = "https://w3id.org/security/v1" +PUBLIC = "https://www.w3.org/ns/activitystreams#Public" + +# The extension terms Mastodon and friends understand on actors. +ACTOR_CONTEXT = [ + AS_CONTEXT, + SECURITY_CONTEXT, + { + "manuallyApprovesFollowers": "as:manuallyApprovesFollowers", + "toot": "http://joinmastodon.org/ns#", + "discoverable": "toot:discoverable", + "indexable": "toot:indexable", + "schema": "http://schema.org#", + "PropertyValue": "schema:PropertyValue", + "value": "schema:value", + }, +] + + +@dataclass(frozen=True) +class ActorUrls: + id: str + inbox: str + outbox: str + followers: str + following: str + shared_inbox: str + key_id: str + profile_page: str + + +def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls: + actor = f"{base_url}/users/{username}" + return ActorUrls( + id=actor, + inbox=f"{actor}/inbox", + outbox=f"{actor}/outbox", + followers=f"{actor}/followers", + following=f"{actor}/following", + shared_inbox=f"{base_url}/inbox", + key_id=f"{actor}#main-key", + profile_page=profile_page, + ) + + +def text_to_html(text: str | None) -> str: + """Plain text (e.g. a bio) as the small HTML subset Mastodon keeps.""" + if not text or not text.strip(): + return "" + paragraphs = [p for p in text.strip().replace("\r\n", "\n").split("\n\n") if p.strip()] + return "".join( + "

" + "
".join(html.escape(line) for line in p.split("\n")) + "

" + for p in paragraphs + ) + + +def public_key(urls: ActorUrls, public_key_pem: str) -> dict: + return {"id": urls.key_id, "owner": urls.id, "publicKeyPem": public_key_pem} + + +def person( + urls: ActorUrls, + *, + username: str, + name: str, + summary: str | None, + public_key_pem: str, + manually_approves_followers: bool, + discoverable: bool, + indexable: bool, + published: str | None = None, + fields: list[tuple[str, str]] = (), +) -> dict: + """A user's actor document. `fields` are (name, plain-text value) profile fields.""" + doc = { + "@context": ACTOR_CONTEXT, + "id": urls.id, + "type": "Person", + "preferredUsername": username, + "name": name, + "summary": text_to_html(summary), + "url": urls.profile_page, + "inbox": urls.inbox, + "outbox": urls.outbox, + "followers": urls.followers, + "following": urls.following, + "endpoints": {"sharedInbox": urls.shared_inbox}, + "publicKey": public_key(urls, public_key_pem), + "manuallyApprovesFollowers": manually_approves_followers, + "discoverable": discoverable, + "indexable": indexable, + "attachment": [ + {"type": "PropertyValue", "name": field, "value": html.escape(value)} + for field, value in fields + ], + } + if published: + doc["published"] = published + return doc + + +def application( + *, + actor_id: str, + username: str, + inbox: str, + outbox: str, + shared_inbox: str, + key_id: str, + public_key_pem: str, + url: str, +) -> dict: + """The instance actor: signs fetches on the server's behalf.""" + return { + "@context": ACTOR_CONTEXT, + "id": actor_id, + "type": "Application", + "preferredUsername": username, + "name": username, + "url": url, + "inbox": inbox, + "outbox": outbox, + "endpoints": {"sharedInbox": shared_inbox}, + "publicKey": {"id": key_id, "owner": actor_id, "publicKeyPem": public_key_pem}, + "manuallyApprovesFollowers": True, + "discoverable": False, + "indexable": False, + } + + +def ordered_collection(collection_id: str, total: int, items: list | None = None) -> dict: + """A collection. With items=None only the count is published (e.g. followers).""" + doc = { + "@context": AS_CONTEXT, + "id": collection_id, + "type": "OrderedCollection", + "totalItems": total, + } + if items is not None: + doc["orderedItems"] = items + return doc diff --git a/src/scrobbler/federation/protocol/webfinger.py b/src/scrobbler/federation/protocol/webfinger.py new file mode 100644 index 0000000..cf4a09b --- /dev/null +++ b/src/scrobbler/federation/protocol/webfinger.py @@ -0,0 +1,44 @@ +"""WebFinger (RFC 7033): resolving acct:user@domain to an actor.""" + +import re + +from scrobbler.federation.protocol.media import ACTIVITY_JSON + +_USERNAME = re.compile(r"^[A-Za-z0-9_.-]{1,64}$") + + +class ResourceError(ValueError): + """The resource isn't something this server answers for (400, not 404).""" + + +def parse_resource(resource: str | None, *, domain: str, base_url: str) -> str: + """The username in `acct:user@domain` (optionally with a leading @), or in an actor URL + `/users/`. Raises ResourceError for anything else.""" + value = (resource or "").strip() + if value.lower().startswith(f"{base_url.lower()}/users/"): + username = value[len(base_url) + len("/users/") :] + else: + if value.lower().startswith("acct:"): + value = value[5:] + value = value.lstrip("@") + username, at, host = value.rpartition("@") + if not at or host.lower() != domain.lower(): + raise ResourceError("resource must be acct:user@" + domain) + if not _USERNAME.match(username): + raise ResourceError("invalid username") + return username + + +def jrd(*, username: str, domain: str, actor_id: str, profile_page: str) -> dict: + return { + "subject": f"acct:{username}@{domain}", + "aliases": [actor_id, profile_page], + "links": [ + {"rel": "self", "type": ACTIVITY_JSON, "href": actor_id}, + { + "rel": "http://webfinger.net/rel/profile-page", + "type": "text/html", + "href": profile_page, + }, + ], + } diff --git a/tests/test_federation_protocol.py b/tests/test_federation_protocol.py new file mode 100644 index 0000000..35fc76c --- /dev/null +++ b/tests/test_federation_protocol.py @@ -0,0 +1,130 @@ +import xml.etree.ElementTree as ET + +import pytest + +from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger + +BASE = "https://scrobble.test" + + +@pytest.mark.parametrize( + ("accept", "expected"), + [ + ("application/activity+json", True), + ('application/ld+json; profile="https://www.w3.org/ns/activitystreams"', True), + ("application/ld+json", True), + ('application/ld+json; profile="https://example.com/other"', False), + ("text/html,application/xhtml+xml,*/*;q=0.8", False), + ("application/activity+json;q=0", False), + ("text/html, application/activity+json;q=0.5", True), + ("", False), + (None, False), + ], +) +def test_accept_negotiation(accept, expected): + assert media.wants_activitypub(accept) is expected + + +@pytest.mark.parametrize( + ("resource", "username"), + [ + ("acct:alice@scrobble.test", "alice"), + ("acct:Alice@SCROBBLE.TEST", "Alice"), + ("alice@scrobble.test", "alice"), + ("@alice@scrobble.test", "alice"), + (" acct:alice@scrobble.test ", "alice"), + ("https://scrobble.test/users/alice", "alice"), + ], +) +def test_webfinger_resources(resource, username): + assert webfinger.parse_resource(resource, domain="scrobble.test", base_url=BASE) == username + + +@pytest.mark.parametrize( + "resource", + [ + "acct:alice@elsewhere.example", + "acct:alice", + "", + None, + "acct:al ice@scrobble.test", + "https://elsewhere.example/users/alice", + "https://scrobble.test/users/alice/../../admin", + ], +) +def test_webfinger_rejects_other_resources(resource): + with pytest.raises(webfinger.ResourceError): + webfinger.parse_resource(resource, domain="scrobble.test", base_url=BASE) + + +def test_jrd_shape(): + doc = webfinger.jrd( + username="alice", + domain="scrobble.test", + actor_id=f"{BASE}/users/alice", + profile_page=f"{BASE}/profile.html?u=alice", + ) + assert doc["subject"] == "acct:alice@scrobble.test" + [self_link] = [link for link in doc["links"] if link["rel"] == "self"] + assert self_link == { + "rel": "self", + "type": "application/activity+json", + "href": f"{BASE}/users/alice", + } + + +def test_person_document(): + urls = vocab.actor_urls(BASE, "alice", f"{BASE}/profile.html?u=alice") + doc = vocab.person( + urls, + username="alice", + name="Alice", + summary="Listens a lot.\n\n", + public_key_pem="PEM", + manually_approves_followers=True, + discoverable=False, + indexable=False, + fields=[("Scrobbles", "1,234 & counting")], + ) + assert doc["id"] == f"{BASE}/users/alice" + assert doc["type"] == "Person" + assert doc["inbox"] == f"{BASE}/users/alice/inbox" + assert doc["endpoints"] == {"sharedInbox": f"{BASE}/inbox"} + assert doc["publicKey"] == { + "id": f"{BASE}/users/alice#main-key", + "owner": doc["id"], + "publicKeyPem": "PEM", + } + assert doc["summary"] == "

Listens a lot.

<script>x</script>

" + assert doc["attachment"] == [ + {"type": "PropertyValue", "name": "Scrobbles", "value": "1,234 & counting"} + ] + assert (doc["manuallyApprovesFollowers"], doc["discoverable"], doc["indexable"]) == ( + True, + False, + False, + ) + assert vocab.AS_CONTEXT in doc["@context"] and vocab.SECURITY_CONTEXT in doc["@context"] + + +def test_collections(): + assert vocab.ordered_collection("x", 3) == { + "@context": vocab.AS_CONTEXT, + "id": "x", + "type": "OrderedCollection", + "totalItems": 3, + } + assert vocab.ordered_collection("x", 0, items=[])["orderedItems"] == [] + + +def test_nodeinfo(): + assert nodeinfo.discovery(BASE)["links"][0]["href"] == f"{BASE}/nodeinfo/2.1" + doc = nodeinfo.document(version="0.2.0", users_total=3, open_registrations=True) + assert doc["software"] == {"name": "scrobbler", "version": "0.2.0"} + assert doc["protocols"] == ["activitypub"] + assert doc["usage"]["users"]["total"] == 3 + + +def test_host_meta_points_at_webfinger(): + link = ET.fromstring(hostmeta.xrd(BASE)).find("{http://docs.oasis-open.org/ns/xri/xrd-1.0}Link") + assert link.get("template") == f"{BASE}/.well-known/webfinger?resource={{uri}}"