7 import simplejson as json
9 from urllib.parse import urlsplit
10 from Crypto.PublicKey import RSA
11 from .database import DATABASE
12 from .http_debug import http_debug
14 from cachetools import LFUCache
17 # generate actor keys if not present
18 if "actorKeys" not in DATABASE:
19 logging.info("No actor keys present, generating 4096-bit RSA keypair.")
21 privkey = RSA.generate(4096)
22 pubkey = privkey.publickey()
24 DATABASE["actorKeys"] = {
25 "publicKey": pubkey.exportKey('PEM').decode('utf-8'),
26 "privateKey": privkey.exportKey('PEM').decode('utf-8')
30 PRIVKEY = RSA.importKey(DATABASE["actorKeys"]["privateKey"])
31 PUBKEY = PRIVKEY.publickey()
33 sem = asyncio.Semaphore(500)
35 from . import app, CONFIG
36 from .remote_actor import fetch_actor
39 AP_CONFIG = CONFIG['ap']
40 CACHE_SIZE = CONFIG.get('cache-size', 16384)
43 CACHE = LFUCache(CACHE_SIZE)
46 async def actor(request):
48 "@context": "https://www.w3.org/ns/activitystreams",
50 "sharedInbox": "https://{}/inbox".format(request.host)
52 "followers": "https://{}/followers".format(request.host),
53 "following": "https://{}/following".format(request.host),
54 "inbox": "https://{}/inbox".format(request.host),
55 "name": "ActivityRelay",
56 "type": "Application",
57 "id": "https://{}/actor".format(request.host),
59 "id": "https://{}/actor#main-key".format(request.host),
60 "owner": "https://{}/actor".format(request.host),
61 "publicKeyPem": DATABASE["actorKeys"]["publicKey"]
63 "summary": "ActivityRelay bot",
64 "preferredUsername": "relay",
65 "url": "https://{}/actor".format(request.host)
67 return aiohttp.web.json_response(data)
70 app.router.add_get('/actor', actor)
73 from .http_signatures import sign_headers
76 get_actor_inbox = lambda actor: actor.get('endpoints', {}).get('sharedInbox', actor['inbox'])
79 async def push_message_to_actor(actor, message, our_key_id):
80 inbox = get_actor_inbox(actor)
84 data = json.dumps(message)
86 '(request-target)': 'post {}'.format(url.path),
87 'Content-Length': str(len(data)),
88 'Content-Type': 'application/activity+json',
89 'User-Agent': 'ActivityRelay'
91 headers['signature'] = sign_headers(headers, PRIVKEY, our_key_id)
92 headers.pop('(request-target)')
94 logging.debug('%r >> %r', inbox, message)
99 async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
100 async with session.post(inbox, data=data, headers=headers) as resp:
101 if resp.status == 202:
103 resp_payload = await resp.text()
104 logging.debug('%r >> resp %r', inbox, resp_payload)
105 except Exception as e:
106 logging.info('Caught %r while pushing to %r.', e, inbox)
109 async def follow_remote_actor(actor_uri):
110 actor = await fetch_actor(actor_uri)
113 logging.info('failed to fetch actor at: %r', actor_uri)
116 if AP_CONFIG['whitelist_enabled'] is True and urlsplit(actor_uri).hostname not in AP_CONFIG['whitelist']:
117 logging.info('refusing to follow non-whitelisted actor: %r', actor_uri)
120 logging.info('following: %r', actor_uri)
123 "@context": "https://www.w3.org/ns/activitystreams",
126 "object": actor['id'],
127 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
128 "actor": "https://{}/actor".format(AP_CONFIG['host'])
130 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
133 async def unfollow_remote_actor(actor_uri):
134 actor = await fetch_actor(actor_uri)
136 logging.info('failed to fetch actor at: %r', actor_uri)
139 logging.info('unfollowing: %r', actor_uri)
142 "@context": "https://www.w3.org/ns/activitystreams",
148 "actor": actor['id'],
149 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4())
151 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
152 "actor": "https://{}/actor".format(AP_CONFIG['host'])
154 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
157 tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
158 def strip_html(data):
159 no_tags = tag_re.sub('', data)
160 return cgi.escape(no_tags)
163 def distill_inboxes(actor, object_id):
166 origin_hostname = urlsplit(object_id).hostname
168 inbox = get_actor_inbox(actor)
169 targets = [target for target in DATABASE.get('relay-list', []) if target != inbox]
170 targets = [target for target in targets if urlsplit(target).hostname != origin_hostname]
171 hostnames = [urlsplit(target).hostname for target in targets]
173 assert inbox not in targets
174 assert origin_hostname not in hostnames
179 def distill_object_id(activity):
180 logging.debug('>> determining object ID for %r', activity['object'])
181 obj = activity['object']
183 if isinstance(obj, str):
189 async def handle_relay(actor, data, request):
192 object_id = distill_object_id(data)
194 if object_id in CACHE:
195 logging.debug('>> already relayed %r as %r', object_id, CACHE[object_id])
198 activity_id = "https://{}/activities/{}".format(request.host, uuid.uuid4())
201 "@context": "https://www.w3.org/ns/activitystreams",
203 "to": ["https://{}/followers".format(request.host)],
204 "actor": "https://{}/actor".format(request.host),
209 logging.debug('>> relay: %r', message)
211 inboxes = distill_inboxes(actor, object_id)
213 futures = [push_message_to_actor({'inbox': inbox}, message, 'https://{}/actor#main-key'.format(request.host)) for inbox in inboxes]
214 asyncio.ensure_future(asyncio.gather(*futures))
216 CACHE[object_id] = activity_id
219 async def handle_forward(actor, data, request):
220 object_id = distill_object_id(data)
222 logging.debug('>> Relay %r', data)
224 inboxes = distill_inboxes(actor, object_id)
227 push_message_to_actor(
230 'https://{}/actor#main-key'.format(request.host))
231 for inbox in inboxes]
232 asyncio.ensure_future(asyncio.gather(*futures))
235 async def handle_follow(actor, data, request):
238 following = DATABASE.get('relay-list', [])
239 inbox = get_actor_inbox(actor)
241 if urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
244 if inbox not in following:
246 DATABASE['relay-list'] = following
248 asyncio.ensure_future(follow_remote_actor(actor['id']))
251 "@context": "https://www.w3.org/ns/activitystreams",
254 "actor": "https://{}/actor".format(request.host),
256 # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
260 "object": "https://{}/actor".format(request.host),
264 "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
267 asyncio.ensure_future(push_message_to_actor(actor, message, 'https://{}/actor#main-key'.format(request.host)))
270 async def handle_undo(actor, data, request):
273 child = data['object']
274 if child['type'] == 'Follow':
275 following = DATABASE.get('relay-list', [])
277 inbox = get_actor_inbox(actor)
279 if inbox in following:
280 following.remove(inbox)
281 DATABASE['relay-list'] = following
283 await unfollow_remote_actor(actor['id'])
287 'Announce': handle_relay,
288 'Create': handle_relay,
289 'Delete': handle_forward,
290 'Follow': handle_follow,
292 'Update': handle_forward,
296 async def inbox(request):
297 data = await request.json()
298 instance = urlsplit(data['actor']).hostname
300 if 'actor' not in data or not request['validated']:
301 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
303 elif data['type'] != 'Follow' and 'https://{}/inbox'.format(instance) not in DATABASE['relay-list']:
304 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
306 elif AP_CONFIG['whitelist_enabled'] is True and instance not in AP_CONFIG['whitelist']:
307 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
309 actor = await fetch_actor(data["actor"])
310 actor_uri = 'https://{}/actor'.format(request.host)
312 logging.debug(">> payload %r", data)
314 processor = processors.get(data['type'], None)
316 await processor(actor, data, request)
318 return aiohttp.web.Response(body=b'{}', content_type='application/activity+json')
320 app.router.add_post('/inbox', inbox)