8 import simplejson as json
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'),
26 "privateKey": privkey.exportKey('PEM')
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':[]})
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 "sharedInbox": "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)
82 url = urllib.parse.urlsplit(inbox)
85 data = json.dumps(message)
87 '(request-target)': 'post {}'.format(url.path),
88 'Content-Length': str(len(data)),
89 'Content-Type': 'application/activity+json',
90 'User-Agent': 'ActivityRelay'
92 headers['signature'] = sign_headers(headers, PRIVKEY, our_key_id)
93 headers.pop('(request-target)')
95 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 resp_payload = await resp.text()
100 logging.debug('%r >> resp %r', inbox, resp_payload)
103 async def follow_remote_actor(actor_uri):
104 logging.info('following: %r', actor_uri)
106 actor = await fetch_actor(actor_uri)
109 "@context": "https://www.w3.org/ns/activitystreams",
112 "object": actor['id'],
113 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
114 "actor": "https://{}/actor".format(AP_CONFIG['host'])
116 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
119 async def unfollow_remote_actor(actor_uri):
120 logging.info('unfollowing: %r', actor_uri)
122 actor = await fetch_actor(actor_uri)
125 "@context": "https://www.w3.org/ns/activitystreams",
131 "actor": actor['id'],
132 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4())
134 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
135 "actor": "https://{}/actor".format(AP_CONFIG['host'])
137 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
140 tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
141 def strip_html(data):
142 no_tags = tag_re.sub('', data)
143 return cgi.escape(no_tags)
146 def distill_inboxes(actor):
149 inbox = get_actor_inbox(actor)
150 targets = [target for target in DATABASE.get('relay-list', []) if target != inbox]
152 assert inbox not in targets
157 def distill_object_id(activity):
158 logging.debug('>> determining object ID for %r', activity['object'])
159 obj = activity['object']
161 if isinstance(obj, str):
167 async def handle_relay(actor, data, request):
168 object_id = distill_object_id(data)
170 # don't relay mastodon announces -- causes LRP fake direction issues
171 if data['type'] == 'Announce' and len(data.get('cc', [])) > 0:
175 "@context": "https://www.w3.org/ns/activitystreams",
177 "to": ["https://{}/actor/followers".format(request.host)],
178 "actor": "https://{}/actor".format(request.host),
180 "id": "https://{}/activities/{}".format(request.host, uuid.uuid4())
183 logging.debug('>> relay: %r', message)
185 inboxes = distill_inboxes(actor)
187 futures = [push_message_to_actor({'inbox': inbox}, message, 'https://{}/actor#main-key'.format(request.host)) for inbox in inboxes]
188 asyncio.ensure_future(asyncio.gather(*futures))
191 async def handle_follow(actor, data, request):
194 following = DATABASE.get('relay-list', [])
195 inbox = get_actor_inbox(actor)
197 if urllib.parse.urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
200 if inbox not in following:
202 DATABASE['relay-list'] = following
205 "@context": "https://www.w3.org/ns/activitystreams",
208 "actor": "https://{}/actor".format(request.host),
210 # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
214 "object": "https://{}/actor".format(request.host),
218 "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
221 asyncio.ensure_future(push_message_to_actor(actor, message, 'https://{}/actor#main-key'.format(request.host)))
223 if data['object'].endswith('/actor'):
224 asyncio.ensure_future(follow_remote_actor(actor['id']))
227 async def handle_undo(actor, data, request):
230 child = data['object']
231 if child['type'] == 'Follow':
232 following = DATABASE.get('relay-list', [])
234 inbox = get_actor_inbox(actor)
236 if inbox in following:
237 following.remove(inbox)
238 DATABASE['relay-list'] = following
240 if child['object'].endswith('/actor'):
241 await unfollow_remote_actor(actor['id'])
245 'Announce': handle_relay,
246 'Create': handle_relay,
247 'Follow': handle_follow,
252 async def inbox(request):
253 data = await request.json()
255 if 'actor' not in data or not request['validated']:
256 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
258 actor = await fetch_actor(data["actor"])
259 actor_uri = 'https://{}/actor'.format(request.host)
261 logging.debug(">> payload %r", data)
263 processor = processors.get(data['type'], None)
265 await processor(actor, data, request)
267 return aiohttp.web.Response(body=b'{}', content_type='application/activity+json')
270 app.router.add_post('/inbox', inbox)