7 import simplejson as json
11 from urllib.parse import urlsplit
12 from Crypto.PublicKey import RSA
13 from cachetools import LFUCache
15 from . import app, CONFIG
16 from .database import DATABASE
17 from .http_debug import http_debug
18 from .remote_actor import fetch_actor
19 from .http_signatures import sign_headers, generate_body_digest
22 # generate actor keys if not present
23 if "actorKeys" not in DATABASE:
24 logging.info("No actor keys present, generating 4096-bit RSA keypair.")
26 privkey = RSA.generate(4096)
27 pubkey = privkey.publickey()
29 DATABASE["actorKeys"] = {
30 "publicKey": pubkey.exportKey('PEM').decode('utf-8'),
31 "privateKey": privkey.exportKey('PEM').decode('utf-8')
35 PRIVKEY = RSA.importKey(DATABASE["actorKeys"]["privateKey"])
36 PUBKEY = PRIVKEY.publickey()
37 AP_CONFIG = CONFIG['ap']
38 CACHE_SIZE = CONFIG.get('cache-size', 16384)
39 CACHE = LFUCache(CACHE_SIZE)
41 sem = asyncio.Semaphore(500)
44 async def actor(request):
46 "@context": "https://www.w3.org/ns/activitystreams",
48 "sharedInbox": "https://{}/inbox".format(request.host)
50 "followers": "https://{}/followers".format(request.host),
51 "following": "https://{}/following".format(request.host),
52 "inbox": "https://{}/inbox".format(request.host),
53 "name": "ActivityRelay",
54 "type": "Application",
55 "id": "https://{}/actor".format(request.host),
57 "id": "https://{}/actor#main-key".format(request.host),
58 "owner": "https://{}/actor".format(request.host),
59 "publicKeyPem": DATABASE["actorKeys"]["publicKey"]
61 "summary": "ActivityRelay bot",
62 "preferredUsername": "relay",
63 "url": "https://{}/actor".format(request.host)
65 return aiohttp.web.json_response(data, content_type='application/activity+json')
68 app.router.add_get('/actor', actor)
69 get_actor_inbox = lambda actor: actor.get('endpoints', {}).get('sharedInbox', actor['inbox'])
72 async def push_message_to_actor(actor, message, our_key_id):
73 inbox = get_actor_inbox(actor)
77 data = json.dumps(message)
79 '(request-target)': 'post {}'.format(url.path),
80 'Content-Length': str(len(data)),
81 'Content-Type': 'application/activity+json',
82 'User-Agent': 'ActivityRelay',
84 'Digest': 'SHA-256={}'.format(generate_body_digest(data)),
85 'Date': datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
87 headers['signature'] = sign_headers(headers, PRIVKEY, our_key_id)
88 headers.pop('(request-target)')
91 logging.debug('%r >> %r', inbox, message)
96 async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
97 async with session.post(inbox, data=data, headers=headers) as resp:
98 if resp.status == 202:
100 resp_payload = await resp.text()
101 logging.debug('%r >> resp %r', inbox, resp_payload)
102 except Exception as e:
103 logging.info('Caught %r while pushing to %r.', e, inbox)
106 async def fetch_nodeinfo(domain):
107 nodeinfo_data = await fetch_actor(f'https://{domain}/nodeinfo/2.0.json')
108 software = nodeinfo_data.get('software')
109 return software.get('name') if software else None
112 async def follow_remote_actor(actor_uri):
113 actor = await fetch_actor(actor_uri)
116 logging.info('failed to fetch actor at: %r', actor_uri)
119 if AP_CONFIG['whitelist_enabled'] is True and urlsplit(actor_uri).hostname not in AP_CONFIG['whitelist']:
120 logging.info('refusing to follow non-whitelisted actor: %r', actor_uri)
123 logging.info('following: %r', actor_uri)
126 "@context": "https://www.w3.org/ns/activitystreams",
129 "object": actor['id'],
130 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
131 "actor": "https://{}/actor".format(AP_CONFIG['host'])
133 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
136 async def unfollow_remote_actor(actor_uri):
137 actor = await fetch_actor(actor_uri)
139 logging.info('failed to fetch actor at: %r', actor_uri)
142 logging.info('unfollowing: %r', actor_uri)
145 "@context": "https://www.w3.org/ns/activitystreams",
151 "actor": actor['id'],
152 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4())
154 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
155 "actor": "https://{}/actor".format(AP_CONFIG['host'])
157 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
160 tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
161 def strip_html(data):
162 no_tags = tag_re.sub('', data)
163 return cgi.escape(no_tags)
166 def distill_inboxes(actor, object_id):
169 origin_hostname = urlsplit(object_id).hostname
171 inbox = get_actor_inbox(actor)
172 targets = [target for target in DATABASE.get('relay-list', []) if target != inbox]
173 targets = [target for target in targets if urlsplit(target).hostname != origin_hostname]
174 hostnames = [urlsplit(target).hostname for target in targets]
176 assert inbox not in targets
177 assert origin_hostname not in hostnames
182 def distill_object_id(activity):
183 logging.debug('>> determining object ID for %r', activity['object'])
184 obj = activity['object']
186 if isinstance(obj, str):
192 async def handle_relay(actor, data, request):
195 object_id = distill_object_id(data)
197 if object_id in CACHE:
198 logging.debug('>> already relayed %r as %r', object_id, CACHE[object_id])
201 activity_id = "https://{}/activities/{}".format(request.host, uuid.uuid4())
204 "@context": "https://www.w3.org/ns/activitystreams",
206 "to": ["https://{}/followers".format(request.host)],
207 "actor": "https://{}/actor".format(request.host),
212 logging.debug('>> relay: %r', message)
214 inboxes = distill_inboxes(actor, object_id)
216 futures = [push_message_to_actor({'inbox': inbox}, message, 'https://{}/actor#main-key'.format(request.host)) for inbox in inboxes]
217 asyncio.ensure_future(asyncio.gather(*futures))
219 CACHE[object_id] = activity_id
222 async def handle_forward(actor, data, request):
223 object_id = distill_object_id(data)
225 logging.debug('>> Relay %r', data)
227 inboxes = distill_inboxes(actor, object_id)
230 push_message_to_actor(
233 'https://{}/actor#main-key'.format(request.host))
234 for inbox in inboxes]
235 asyncio.ensure_future(asyncio.gather(*futures))
238 async def handle_follow(actor, data, request):
241 following = DATABASE.get('relay-list', [])
242 inbox = get_actor_inbox(actor)
245 if urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
248 if inbox not in following:
250 DATABASE['relay-list'] = following
252 asyncio.ensure_future(follow_remote_actor(actor['id']))
255 "@context": "https://www.w3.org/ns/activitystreams",
258 "actor": "https://{}/actor".format(request.host),
260 # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
264 "object": "https://{}/actor".format(request.host),
268 "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
271 asyncio.ensure_future(push_message_to_actor(actor, message, 'https://{}/actor#main-key'.format(request.host)))
274 async def handle_undo(actor, data, request):
277 child = data['object']
278 if child['type'] == 'Follow':
279 following = DATABASE.get('relay-list', [])
281 inbox = get_actor_inbox(actor)
283 if inbox in following:
284 following.remove(inbox)
285 DATABASE['relay-list'] = following
287 await unfollow_remote_actor(actor['id'])
291 'Announce': handle_relay,
292 'Create': handle_relay,
293 'Delete': handle_forward,
294 'Follow': handle_follow,
296 'Update': handle_forward,
300 async def inbox(request):
301 data = await request.json()
302 instance = urlsplit(data['actor']).hostname
304 if AP_CONFIG['block_relays']:
305 software = await fetch_nodeinfo(instance)
307 if software and 'relay' in software.lower():
308 raise aiohttp.web.HTTPUnauthorized(body='relays have been blocked', content_type='text/plain')
310 if 'actor' not in data or not request['validated']:
311 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
313 elif data['type'] != 'Follow' and 'https://{}/inbox'.format(instance) not in DATABASE['relay-list']:
314 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
316 elif AP_CONFIG['whitelist_enabled'] is True and instance not in AP_CONFIG['whitelist']:
317 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
319 actor = await fetch_actor(data["actor"])
320 actor_uri = 'https://{}/actor'.format(request.host)
322 logging.debug(">> payload %r", data)
324 processor = processors.get(data['type'], None)
326 await processor(actor, data, request)
328 return aiohttp.web.Response(body=b'{}', content_type='application/activity+json')
330 app.router.add_post('/inbox', inbox)