"""fleetmesh-protocol-activitypub: ActivityPub & ActivityStreams 2.0 package.
Conforms to ProtocolPackage (fleetmesh_core.wire.interfaces.ProtocolPackage).
Mounts WebFinger (RFC 7033), Actor profiles, S2S Inbox federation,
Outbox feeds, and Blossom unified media onto ProtocolHostRouter.
"""
from __future__ import annotations
import json
import urllib.parse
from typing import Any, Mapping, Optional
from fleetmesh_core.wire.interfaces import (
ProtocolHealth,
ProtocolHostRouter,
ProtocolIdentityAdapter,
)
from fleetmesh_node.protocols.activitypub.actor import Actor, WebFingerService, ed25519_pubkey_to_pem
from fleetmesh_node.protocols.activitypub.federation import FederationService, StrainScoreKeeper
from fleetmesh_node.protocols.activitypub.media import ActivityPubMediaManager
from fleetmesh_node.protocols.activitypub.store import ActivityPubStore
from fleetmesh_node.protocols.base import BaseProtocolPackage, Ed25519IdentityAdapter
__all__ = [
'ActivityPubIdentityAdapter',
'ActivityPubProtocolPackage',
]
[docs]class ActivityPubIdentityAdapter(Ed25519IdentityAdapter):
"""Translates between Fleetmesh Ed25519 identities and ActivityPub Actor URIs."""
[docs] def __init__(self, actor: Actor, private_key: Any = None):
super().__init__(private_key=private_key)
self.actor = actor
[docs] def resolve_id(self, uri: str) -> Optional[str]:
if uri in (self.actor.acct_uri, self.actor.actor_url):
return self.actor.actor_url
return None
[docs] def verify_assertion(self, payload: bytes, signature: bytes, pubkey: str) -> bool:
try:
raw_pub = bytes.fromhex(pubkey) if len(pubkey) == 64 else pubkey.encode('utf-8')
except ValueError:
return False
return self._verify_ed25519_bytes(payload, signature, raw_pub)
[docs]class ActivityPubProtocolPackage(BaseProtocolPackage):
"""The ActivityPub & ActivityStreams 2.0 suite for Fleetmesh."""
name: str = 'activitypub'
version: str = '1.0.0'
standards: tuple[str, ...] = (
'activitypub',
'activitystreams-2.0',
'RFC-7033',
'RFC-9421',
'rfc7033-webfinger',
'draft-cavage-http-signatures',
'rfc9421',
)
[docs] def __init__(
self,
domain: str = "node.fleetmesh.local",
username: str = "node",
actor: Optional[Actor] = None,
store: Optional[ActivityPubStore] = None,
private_key: Optional[Any] = None,
blob_store: Optional[Any] = None,
strain_ledger: Optional[Any] = None,
keystore: Optional[Any] = None,
allow_local_federation: bool = False,
):
self.domain = domain
self.username = username
self.keystore = keystore
self.private_key = private_key
self.blob_store = blob_store
# Storage
self.store = store or ActivityPubStore(":memory:")
# Actor Document
pub_pem = ""
if private_key is not None:
try:
pub_bytes = private_key.public_key().public_bytes_raw()
pub_pem = ed25519_pubkey_to_pem(pub_bytes)
except Exception:
pass
self.actor = actor or Actor(
domain=domain,
username=username,
public_key_pem=pub_pem,
)
# WebFinger Service
self.webfinger = WebFingerService(self.actor)
# Media Manager
self.media = ActivityPubMediaManager(
base_url=f"{self.actor.scheme}://{self.actor.domain}",
blob_store=blob_store,
)
# Federation Service
self.federation = FederationService(
store=self.store,
local_actor=self.actor,
private_key=private_key,
strain_score_keeper=StrainScoreKeeper(strain_ledger=strain_ledger),
allow_local_federation=allow_local_federation,
)
self.config: Mapping[str, Any] = {}
self._enabled: bool = True
self._host: Optional[ProtocolHostRouter] = None
[docs] def identity_adapter(self, keystore: Any) -> Optional[ProtocolIdentityAdapter]:
return ActivityPubIdentityAdapter(actor=self.actor, private_key=self.private_key)
[docs] def mount_ingress(self, host: ProtocolHostRouter) -> None:
if not self._enabled:
return
self._host = host
from fleetmesh_node.transport import ws
# 1. WebFinger RFC 7033
def _handle_webfinger(conn: Any, req: Any) -> bool:
uri = getattr(req, 'path', '')
parsed = urllib.parse.urlparse(uri)
qparams = urllib.parse.parse_qs(parsed.query)
status, headers, body = self.webfinger.handle_webfinger_request(qparams)
ws.http_response(
conn,
"200 OK" if status == 200 else f"{status} Error",
body,
headers.get('Content-Type', 'application/jrd+json'),
)
return True
host.mount_route('/.well-known/webfinger', _handle_webfinger, methods=('GET',), owner=self.name)
# 2. Shared Inbox & Personal Inbox POST
def _handle_inbox_post(conn: Any, req: Any) -> bool:
method = getattr(req, 'method', 'POST')
path = getattr(req, 'path', '')
raw_headers = getattr(req, 'headers', {}) or {}
headers = {
(k.decode('latin-1') if isinstance(k, bytes) else str(k)): (
v.decode('latin-1') if isinstance(v, bytes) else str(v)
)
for k, v in raw_headers.items()
}
body = getattr(req, 'body', None)
if body is None:
body = ws.read_body(conn, req)
status, resp_headers, resp_body = self.federation.handle_inbox(method, path, headers, body)
ws.http_response(
conn,
f"{status} OK" if status in (200, 202) else f"{status} Error",
resp_body,
resp_headers.get('Content-Type', 'application/json'),
)
return True
host.mount_route('/inbox', _handle_inbox_post, methods=('POST',), owner=self.name)
host.mount_route(f"/users/{self.actor.username}/inbox", _handle_inbox_post, methods=('POST',), owner=self.name)
# 3. User Actor Profile, Outbox, Followers, Following
def _handle_user_routes(conn: Any, req: Any) -> bool:
path = getattr(req, 'path', '').split('?')[0].rstrip('/')
user_prefix = f"/users/{self.actor.username}"
if path == user_prefix:
# Actor JSON-LD
body = json.dumps(self.actor.to_jsonld(), indent=2).encode('utf-8')
ws.http_response(conn, "200 OK", body, "application/activity+json")
return True
if path == f"{user_prefix}/outbox":
# Outbox OrderedCollection
acts = self.store.list_outbox(self.actor.actor_url)
coll = self.store.as_ordered_collection(acts, len(acts), f"{self.actor.actor_url}/outbox")
body = json.dumps(coll, indent=2).encode('utf-8')
ws.http_response(conn, "200 OK", body, "application/activity+json")
return True
if path == f"{user_prefix}/followers":
followers = self.store.get_followers(self.actor.actor_url)
coll = self.store.as_ordered_collection(followers, len(followers), f"{self.actor.actor_url}/followers")
body = json.dumps(coll, indent=2).encode('utf-8')
ws.http_response(conn, "200 OK", body, "application/activity+json")
return True
if path == f"{user_prefix}/following":
following = self.store.get_following(self.actor.actor_url)
coll = self.store.as_ordered_collection(following, len(following), f"{self.actor.actor_url}/following")
body = json.dumps(coll, indent=2).encode('utf-8')
ws.http_response(conn, "200 OK", body, "application/activity+json")
return True
ws.http_response(conn, "404 Not Found", b'{"error": "not found"}', "application/json")
return True
host.mount_route(f"/users/{self.actor.username}", _handle_user_routes, methods=('GET',), owner=self.name)
# 4. Media Attachments
def _handle_media(conn: Any, req: Any) -> bool:
path = getattr(req, 'path', '')
status, headers, body = self.media.handle_media_request(path)
ws.http_response(
conn,
"200 OK" if status == 200 else f"{status} Error",
body,
headers.get('Content-Type', 'application/octet-stream'),
)
return True
host.mount_route('/media', _handle_media, methods=('GET',), owner=self.name)
[docs] def transport_rung(self, context: Any) -> Optional[Any]:
return None
[docs] def compartments(self) -> tuple[type[Any], ...]:
return ()
[docs] def start(self) -> None:
pass
[docs] def stop(self) -> None:
self.store.close()
[docs] def health(self) -> ProtocolHealth:
if not self._enabled:
return ProtocolHealth(
healthy=True,
status="disabled",
connections_active=0,
messages_in=0,
messages_out=0,
errors=(),
)
return ProtocolHealth(
healthy=True,
status="serving",
connections_active=self.store.count_followers(self.actor.actor_url),
messages_in=self.store.count_inbox(),
messages_out=self.store.count_outbox(),
errors=(),
)
[docs] def descriptor_capabilities(self) -> tuple[tuple[str, str], ...]:
if not self._enabled:
return ()
return (
('c', 'activitypub'),
('c', 'activitystreams-2.0'),
('c', 'webfinger'),
)