Federation protocol building blocks (phase 1, step 2)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 12s
CI / test (push) Successful in 57s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s

Pure, framework-free code in federation/protocol:
- media: ActivityPub content types and Accept negotiation
- vocab: actor URLs, Person and Application actors (Mastodon's extension
  terms), public keys, collections, plain text to safe HTML
- webfinger: acct:/actor-URL resource parsing (other domains and bad
  usernames rejected) and JRD documents
- nodeinfo: discovery and NodeInfo 2.1; hostmeta: XRD pointing at
  WebFinger

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 20:20:24 +01:00
1 parent 98c65547f3
commit e890568c54
6 files changed
+392

No files matched your search

@@ -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 (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">\n'
f' <Link rel="lrdd" type="application/jrd+json" template={template}/>\n'
"</XRD>\n"
)
@@ -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 ""))
@@ -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": {},
}
+147
View File
@@ -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(
"<p>" + "<br>".join(html.escape(line) for line in p.split("\n")) + "</p>"
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
@@ -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
`<base_url>/users/<user>`. 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,
},
],
}