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)
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 follow_remote_actor(actor_uri):
107 actor = await fetch_actor(actor_uri)
110 logging.info('failed to fetch actor at: %r', actor_uri)
113 if AP_CONFIG['whitelist_enabled'] is True and urlsplit(actor_uri).hostname not in AP_CONFIG['whitelist']:
114 logging.info('refusing to follow non-whitelisted actor: %r', actor_uri)
117 logging.info('following: %r', actor_uri)
120 "@context": "https://www.w3.org/ns/activitystreams",
123 "object": actor['id'],
124 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
125 "actor": "https://{}/actor".format(AP_CONFIG['host'])
127 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
130 async def unfollow_remote_actor(actor_uri):
131 actor = await fetch_actor(actor_uri)
133 logging.info('failed to fetch actor at: %r', actor_uri)
136 logging.info('unfollowing: %r', actor_uri)
139 "@context": "https://www.w3.org/ns/activitystreams",
145 "actor": actor['id'],
146 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4())
148 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
149 "actor": "https://{}/actor".format(AP_CONFIG['host'])
151 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
154 tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
155 def strip_html(data):
156 no_tags = tag_re.sub('', data)
157 return cgi.escape(no_tags)
160 def distill_inboxes(actor, object_id):
163 origin_hostname = urlsplit(object_id).hostname
165 inbox = get_actor_inbox(actor)
166 targets = [target for target in DATABASE.get('relay-list', []) if target != inbox]
167 targets = [target for target in targets if urlsplit(target).hostname != origin_hostname]
168 hostnames = [urlsplit(target).hostname for target in targets]
170 assert inbox not in targets
171 assert origin_hostname not in hostnames
176 def distill_object_id(activity):
177 logging.debug('>> determining object ID for %r', activity['object'])
178 obj = activity['object']
180 if isinstance(obj, str):
186 async def handle_relay(actor, data, request):
189 object_id = distill_object_id(data)
191 if object_id in CACHE:
192 logging.debug('>> already relayed %r as %r', object_id, CACHE[object_id])
195 activity_id = "https://{}/activities/{}".format(request.host, uuid.uuid4())
198 "@context": "https://www.w3.org/ns/activitystreams",
200 "to": ["https://{}/followers".format(request.host)],
201 "actor": "https://{}/actor".format(request.host),
206 logging.debug('>> relay: %r', message)
208 inboxes = distill_inboxes(actor, object_id)
210 futures = [push_message_to_actor({'inbox': inbox}, message, 'https://{}/actor#main-key'.format(request.host)) for inbox in inboxes]
211 asyncio.ensure_future(asyncio.gather(*futures))
213 CACHE[object_id] = activity_id
216 async def handle_forward(actor, data, request):
217 object_id = distill_object_id(data)
219 logging.debug('>> Relay %r', data)
221 inboxes = distill_inboxes(actor, object_id)
224 push_message_to_actor(
227 'https://{}/actor#main-key'.format(request.host))
228 for inbox in inboxes]
229 asyncio.ensure_future(asyncio.gather(*futures))
232 async def handle_follow(actor, data, request):
235 following = DATABASE.get('relay-list', [])
236 inbox = get_actor_inbox(actor)
238 if urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
241 if inbox not in following:
243 DATABASE['relay-list'] = following
245 asyncio.ensure_future(follow_remote_actor(actor['id']))
248 "@context": "https://www.w3.org/ns/activitystreams",
251 "actor": "https://{}/actor".format(request.host),
253 # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
257 "object": "https://{}/actor".format(request.host),
261 "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
264 asyncio.ensure_future(push_message_to_actor(actor, message, 'https://{}/actor#main-key'.format(request.host)))
267 async def handle_undo(actor, data, request):
270 child = data['object']
271 if child['type'] == 'Follow':
272 following = DATABASE.get('relay-list', [])
274 inbox = get_actor_inbox(actor)
276 if inbox in following:
277 following.remove(inbox)
278 DATABASE['relay-list'] = following
280 await unfollow_remote_actor(actor['id'])
284 'Announce': handle_relay,
285 'Create': handle_relay,
286 'Delete': handle_forward,
287 'Follow': handle_follow,
289 'Update': handle_forward,
293 async def inbox(request):
294 data = await request.json()
295 instance = urlsplit(data['actor']).hostname
297 if 'actor' not in data or not request['validated']:
298 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
300 elif data['type'] != 'Follow' and 'https://{}/inbox'.format(instance) not in DATABASE['relay-list']:
301 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
303 elif AP_CONFIG['whitelist_enabled'] is True and instance not in AP_CONFIG['whitelist']:
304 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
306 actor = await fetch_actor(data["actor"])
307 actor_uri = 'https://{}/actor'.format(request.host)
309 logging.debug(">> payload %r", data)
311 processor = processors.get(data['type'], None)
313 await processor(actor, data, request)
315 return aiohttp.web.Response(body=b'{}', content_type='application/activity+json')
317 app.router.add_post('/inbox', inbox)