"""ActivityPub Actor and WebFinger (RFC 7033) service.
Standard library only. Manages:
- WebFinger discovery (/.well-known/webfinger?resource=acct:user@domain).
- Actor JSON-LD document generation with W3C Security Vocabulary.
- Ed25519 and RSA SubjectPublicKeyInfo PEM encoding.
"""
from __future__ import annotations
import base64
import json
from typing import Any, Mapping, Optional
from fleetmesh_core.conformance.errors import FleetmeshError
__all__ = [
'ActorError',
'ed25519_pubkey_to_pem',
'parse_acct_uri',
'Actor',
'WebFingerService',
]
# Standard Ed25519 SubjectPublicKeyInfo prefix (RFC 8410)
_ED25519_SPKI_PREFIX = bytes([
0x30, 0x2a, # SEQUENCE (42 bytes)
0x30, 0x05, # SEQUENCE (5 bytes)
0x06, 0x03, 0x2b, 0x65, 0x70, # OID 1.3.101.112 (id-Ed25519)
0x03, 0x21, 0x00, # BIT STRING (33 bytes, 0 unused bits)
])
[docs]class ActorError(FleetmeshError):
"""Base error for ActivityPub actor operations."""
[docs]def ed25519_pubkey_to_pem(raw_bytes: bytes) -> str:
"""Format 32-byte Ed25519 raw public key as standard SubjectPublicKeyInfo PEM."""
if len(raw_bytes) != 32:
raise ActorError(f"invalid Ed25519 public key length: {len(raw_bytes)}")
der = _ED25519_SPKI_PREFIX + raw_bytes
b64 = base64.b64encode(der).decode('ascii')
# 64-character line wrapped
lines = [b64[i:i + 64] for i in range(0, len(b64), 64)]
body = '\n'.join(lines)
return f"-----BEGIN PUBLIC KEY-----\n{body}\n-----END PUBLIC KEY-----\n"
[docs]def parse_acct_uri(uri: str) -> tuple[str, str]:
"""Parse an acct: URI into (username, domain).
Example: 'acct:node@example.com' -> ('node', 'example.com')
"""
s = uri.strip()
if s.startswith('acct:'):
s = s[5:]
parts = s.split('@')
if len(parts) != 2 or not parts[0] or not parts[1]:
raise ActorError(f"invalid acct URI: {uri}")
return parts[0].lower(), parts[1].lower()
[docs]class Actor:
"""An ActivityPub Actor profile."""
[docs] def __init__(
self,
domain: str,
username: str = "node",
name: str = "Fleetmesh Edge Node",
summary: str = "Autonomous Fleetmesh edge node",
public_key_pem: str = "",
actor_type: str = "Service",
icon_url: Optional[str] = None,
use_https: bool = True,
):
self.domain = domain.lower().strip()
self.username = username.lower().strip()
self.name = name
self.summary = summary
self.public_key_pem = public_key_pem
self.actor_type = actor_type
self.icon_url = icon_url
self.scheme = "https" if use_https else "http"
@property
def acct_uri(self) -> str:
return f"acct:{self.username}@{self.domain}"
@property
def id(self) -> str:
return self.actor_url
@property
def actor_url(self) -> str:
return f"{self.scheme}://{self.domain}/users/{self.username}"
@property
def inbox_url(self) -> str:
return f"{self.actor_url}/inbox"
@property
def outbox_url(self) -> str:
return f"{self.actor_url}/outbox"
@property
def followers_url(self) -> str:
return f"{self.actor_url}/followers"
@property
def following_url(self) -> str:
return f"{self.actor_url}/following"
@property
def shared_inbox_url(self) -> str:
return f"{self.scheme}://{self.domain}/inbox"
@property
def public_key_id(self) -> str:
return f"{self.actor_url}#main-key"
[docs] def to_jsonld(self) -> Mapping[str, Any]:
"""Produce W3C ActivityStreams 2.0 / ActivityPub Actor JSON-LD document."""
doc = {
'@context': [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/v1',
],
'id': self.actor_url,
'type': self.actor_type,
'following': self.following_url,
'followers': self.followers_url,
'inbox': self.inbox_url,
'outbox': self.outbox_url,
'preferredUsername': self.username,
'name': self.name,
'summary': self.summary,
'url': self.actor_url,
'endpoints': {
'sharedInbox': self.shared_inbox_url,
},
'publicKey': {
'id': self.public_key_id,
'owner': self.actor_url,
'publicKeyPem': self.public_key_pem,
},
}
if self.icon_url:
doc['icon'] = {
'type': 'Image',
'mediaType': 'image/png',
'url': self.icon_url,
}
return doc
[docs]class WebFingerService:
"""Answers RFC 7033 WebFinger and Actor JSON-LD requests."""
[docs] def __init__(self, actor: Any):
if isinstance(actor, Mapping):
self.actors = dict(actor)
self.actor = next(iter(actor.values())) if actor else None
else:
self.actor = actor
self.actors = {actor.username: actor} if actor else {}
[docs] def handle_webfinger_request(
self,
params: dict[str, list[str]],
) -> tuple[int, dict[str, str], bytes]:
"""Dispatch GET /.well-known/webfinger."""
resource_list = params.get('resource', [])
if not resource_list:
body = json.dumps({'error': 'invalid_request', 'message': 'missing resource parameter'}).encode()
return 400, {'Content-Type': 'application/json'}, body
resource = resource_list[0].strip()
if self.actor is None:
body = json.dumps({'error': 'not_found', 'message': f"resource {resource} not found"}).encode()
return 404, {'Content-Type': 'application/json'}, body
actor = self.actor
# Check if requested resource matches this actor
matches = False
if resource == actor.acct_uri:
matches = True
elif resource == actor.actor_url:
matches = True
elif resource.startswith('acct:'):
try:
u, d = parse_acct_uri(resource)
if u == actor.username and d == actor.domain:
matches = True
except Exception:
pass
if not matches:
body = json.dumps({'error': 'not_found', 'message': f"resource {resource} not found"}).encode()
return 404, {'Content-Type': 'application/json'}, body
jrd = {
'subject': actor.acct_uri,
'aliases': [
actor.actor_url,
],
'links': [
{
'rel': 'self',
'type': 'application/activity+json',
'href': actor.actor_url,
},
{
'rel': 'http://webfinger.example.org/rel/profile-page',
'type': 'text/html',
'href': actor.actor_url,
},
],
}
return 200, {'Content-Type': 'application/jrd+json; charset=utf-8'}, json.dumps(jrd).encode()
[docs] def handle_actor_request(self) -> tuple[int, dict[str, str], bytes]:
"""Dispatch GET /users/<username>."""
if self.actor is None:
return 404, {'Content-Type': 'application/json'}, b'{"error": "not_found"}'
doc = self.actor.to_jsonld()
return 200, {'Content-Type': 'application/activity+json; charset=utf-8'}, json.dumps(doc).encode()
handle_webfinger = handle_webfinger_request