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()
34 from . import app, CONFIG
35 from .remote_actor import fetch_actor
38 AP_CONFIG = CONFIG.get('ap', {'host': 'localhost','blocked_instances':[], 'whitelist_enabled': False, 'whitelist': []})
39 CACHE_SIZE = CONFIG.get('cache-size', 16384)
42 CACHE = LFUCache(CACHE_SIZE)
45 async def actor(request):
47 "@context": "https://www.w3.org/ns/activitystreams",
49 "sharedInbox": "https://{}/inbox".format(request.host)
51 "followers": "https://{}/followers".format(request.host),
52 "following": "https://{}/following".format(request.host),
53 "inbox": "https://{}/inbox".format(request.host),
54 "name": "ActivityRelay",
55 "type": "Application",
56 "id": "https://{}/actor".format(request.host),
58 "id": "https://{}/actor#main-key".format(request.host),
59 "owner": "https://{}/actor".format(request.host),
60 "publicKeyPem": DATABASE["actorKeys"]["publicKey"]
62 "summary": "ActivityRelay bot",
63 "preferredUsername": "relay",
64 "url": "https://{}/actor".format(request.host)
66 return aiohttp.web.json_response(data)
69 app.router.add_get('/actor', actor)
72 from .http_signatures import sign_headers
75 get_actor_inbox = lambda actor: actor.get('endpoints', {}).get('sharedInbox', actor['inbox'])
78 async def push_message_to_actor(actor, message, our_key_id):
79 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)
97 async with aiohttp.ClientSession(trace_configs=[http_debug()]) as session:
98 async with session.post(inbox, data=data, headers=headers) as resp:
99 if resp.status == 202:
101 resp_payload = await resp.text()
102 logging.debug('%r >> resp %r', inbox, resp_payload)
103 except Exception as e:
104 logging.info('Caught %r while pushing to %r.', e, inbox)
107 async def follow_remote_actor(actor_uri):
108 actor = await fetch_actor(actor_uri)
111 logging.info('failed to fetch actor at: %r', actor_uri)
114 if AP_CONFIG['whitelist_enabled'] is True and urlsplit(actor_uri).hostname not in AP_CONFIG['whitelist']:
115 logging.info('refusing to follow non-whitelisted actor: %r', actor_uri)
118 logging.info('following: %r', actor_uri)
121 "@context": "https://www.w3.org/ns/activitystreams",
124 "object": actor['id'],
125 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
126 "actor": "https://{}/actor".format(AP_CONFIG['host'])
128 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
131 async def unfollow_remote_actor(actor_uri):
132 actor = await fetch_actor(actor_uri)
134 logging.info('failed to fetch actor at: %r', actor_uri)
137 logging.info('unfollowing: %r', actor_uri)
140 "@context": "https://www.w3.org/ns/activitystreams",
146 "actor": actor['id'],
147 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4())
149 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
150 "actor": "https://{}/actor".format(AP_CONFIG['host'])
152 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
155 tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
156 def strip_html(data):
157 no_tags = tag_re.sub('', data)
158 return cgi.escape(no_tags)
161 def distill_inboxes(actor, object_id):
164 origin_hostname = urlsplit(object_id).hostname
166 inbox = get_actor_inbox(actor)
167 targets = [target for target in DATABASE.get('relay-list', []) if target != inbox]
168 targets = [target for target in targets if urlsplit(target).hostname != origin_hostname]
169 hostnames = [urlsplit(target).hostname for target in targets]
171 assert inbox not in targets
172 assert origin_hostname not in hostnames
177 def distill_object_id(activity):
178 logging.debug('>> determining object ID for %r', activity['object'])
179 obj = activity['object']
181 if isinstance(obj, str):
187 async def handle_relay(actor, data, request):
190 object_id = distill_object_id(data)
192 if object_id in CACHE:
193 logging.debug('>> already relayed %r as %r', object_id, CACHE[object_id])
196 activity_id = "https://{}/activities/{}".format(request.host, uuid.uuid4())
199 "@context": "https://www.w3.org/ns/activitystreams",
201 "to": ["https://{}/followers".format(request.host)],
202 "actor": "https://{}/actor".format(request.host),
207 logging.debug('>> relay: %r', message)
209 inboxes = distill_inboxes(actor, object_id)
211 futures = [push_message_to_actor({'inbox': inbox}, message, 'https://{}/actor#main-key'.format(request.host)) for inbox in inboxes]
212 asyncio.ensure_future(asyncio.gather(*futures))
214 CACHE[object_id] = activity_id
217 async def handle_forward(actor, data, request):
218 object_id = distill_object_id(data)
220 logging.debug('>> Relay %r', data)
222 inboxes = distill_inboxes(actor, object_id)
225 push_message_to_actor(
228 'https://{}/actor#main-key'.format(request.host))
229 for inbox in inboxes]
230 asyncio.ensure_future(asyncio.gather(*futures))
233 async def handle_follow(actor, data, request):
236 following = DATABASE.get('relay-list', [])
237 inbox = get_actor_inbox(actor)
239 if urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
242 if inbox not in following:
244 DATABASE['relay-list'] = following
246 if data['object'].endswith('/actor'):
247 asyncio.ensure_future(follow_remote_actor(actor['id']))
250 "@context": "https://www.w3.org/ns/activitystreams",
253 "actor": "https://{}/actor".format(request.host),
255 # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
259 "object": "https://{}/actor".format(request.host),
263 "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
266 asyncio.ensure_future(push_message_to_actor(actor, message, 'https://{}/actor#main-key'.format(request.host)))
269 async def handle_undo(actor, data, request):
272 child = data['object']
273 if child['type'] == 'Follow':
274 following = DATABASE.get('relay-list', [])
276 inbox = get_actor_inbox(actor)
278 if inbox in following:
279 following.remove(inbox)
280 DATABASE['relay-list'] = following
282 if child['object'].endswith('/actor'):
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')
321 app.router.add_post('/inbox', inbox)