8 import simplejson as json
10 from Crypto.PublicKey import RSA
11 from .database import DATABASE
14 # generate actor keys if not present
15 if "actorKeys" not in DATABASE:
16 logging.info("No actor keys present, generating 4096-bit RSA keypair.")
18 privkey = RSA.generate(4096)
19 pubkey = privkey.publickey()
21 DATABASE["actorKeys"] = {
22 "publicKey": pubkey.exportKey('PEM'),
23 "privateKey": privkey.exportKey('PEM')
27 PRIVKEY = RSA.importKey(DATABASE["actorKeys"]["privateKey"])
28 PUBKEY = PRIVKEY.publickey()
31 from . import app, CONFIG
32 from .remote_actor import fetch_actor
35 AP_CONFIG = CONFIG.get('ap', {'host': 'localhost','blocked_instances':[]})
38 async def actor(request):
40 "@context": "https://www.w3.org/ns/activitystreams",
42 "sharedInbox": "https://{}/inbox".format(request.host)
44 "followers": "https://{}/followers".format(request.host),
45 "following": "https://{}/following".format(request.host),
46 "inbox": "https://{}/inbox".format(request.host),
47 "sharedInbox": "https://{}/inbox".format(request.host),
48 "name": "ActivityRelay",
49 "type": "Application",
50 "id": "https://{}/actor".format(request.host),
52 "id": "https://{}/actor#main-key".format(request.host),
53 "owner": "https://{}/actor".format(request.host),
54 "publicKeyPem": DATABASE["actorKeys"]["publicKey"]
56 "summary": "ActivityRelay bot",
57 "preferredUsername": "relay",
58 "url": "https://{}/actor".format(request.host)
60 return aiohttp.web.json_response(data)
63 app.router.add_get('/actor', actor)
66 from .http_signatures import sign_headers
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)
75 url = urllib.parse.urlsplit(inbox)
78 data = json.dumps(message)
80 '(request-target)': 'post {}'.format(url.path),
81 'Content-Length': str(len(data)),
82 'Content-Type': 'application/activity+json',
83 'User-Agent': 'ActivityRelay'
85 headers['signature'] = sign_headers(headers, PRIVKEY, our_key_id)
87 logging.debug('%r >> %r', inbox, message)
89 async with aiohttp.ClientSession() as session:
90 async with session.post(inbox, data=data, headers=headers) as resp:
91 resp_payload = await resp.text()
92 logging.debug('%r >> resp %r', inbox, resp_payload)
95 async def follow_remote_actor(actor_uri):
96 logging.info('following: %r', actor_uri)
98 actor = await fetch_actor(actor_uri)
101 "@context": "https://www.w3.org/ns/activitystreams",
104 "object": actor['id'],
105 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
106 "actor": "https://{}/actor".format(AP_CONFIG['host'])
108 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
111 async def unfollow_remote_actor(actor_uri):
112 logging.info('unfollowing: %r', actor_uri)
114 actor = await fetch_actor(actor_uri)
117 "@context": "https://www.w3.org/ns/activitystreams",
123 "actor": actor['id'],
124 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4())
126 "id": "https://{}/activities/{}".format(AP_CONFIG['host'], uuid.uuid4()),
127 "actor": "https://{}/actor".format(AP_CONFIG['host'])
129 await push_message_to_actor(actor, message, "https://{}/actor#main-key".format(AP_CONFIG['host']))
132 tag_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
133 def strip_html(data):
134 no_tags = tag_re.sub('', data)
135 return cgi.escape(no_tags)
138 def distill_inboxes(actor):
141 inbox = get_actor_inbox(actor)
142 targets = [target for target in DATABASE.get('relay-list', []) if target != inbox]
144 assert inbox not in targets
149 def distill_object_id(activity):
150 logging.debug('>> determining object ID for %r', activity['object'])
151 obj = activity['object']
153 if isinstance(obj, str):
159 async def handle_relay(actor, data, request):
160 object_id = distill_object_id(data)
162 # don't relay mastodon announces -- causes LRP fake direction issues
163 if data['type'] == 'Announce' and len(data.get('cc', [])) > 0:
167 "@context": "https://www.w3.org/ns/activitystreams",
169 "to": ["https://{}/actor/followers".format(request.host)],
170 "actor": "https://{}/actor".format(request.host),
172 "id": "https://{}/activities/{}".format(request.host, uuid.uuid4())
175 logging.debug('>> relay: %r', message)
177 inboxes = distill_inboxes(actor)
179 futures = [push_message_to_actor({'inbox': inbox}, message, 'https://{}/actor#main-key'.format(request.host)) for inbox in inboxes]
180 asyncio.ensure_future(asyncio.gather(*futures))
183 async def handle_follow(actor, data, request):
186 following = DATABASE.get('relay-list', [])
187 inbox = get_actor_inbox(actor)
189 if urllib.parse.urlsplit(inbox).hostname in AP_CONFIG['blocked_instances']:
192 if inbox not in following:
194 DATABASE['relay-list'] = following
197 "@context": "https://www.w3.org/ns/activitystreams",
200 "actor": "https://{}/actor".format(request.host),
202 # this is wrong per litepub, but mastodon < 2.4 is not compliant with that profile.
206 "object": "https://{}/actor".format(request.host),
210 "id": "https://{}/activities/{}".format(request.host, uuid.uuid4()),
213 asyncio.ensure_future(push_message_to_actor(actor, message, 'https://{}/actor#main-key'.format(request.host)))
215 if data['object'].endswith('/actor'):
216 asyncio.ensure_future(follow_remote_actor(actor['id']))
219 async def handle_undo(actor, data, request):
222 child = data['object']
223 if child['type'] == 'Follow':
224 following = DATABASE.get('relay-list', [])
226 inbox = get_actor_inbox(actor)
228 if inbox in following:
229 following.remove(inbox)
230 DATABASE['relay-list'] = following
232 if child['object'].endswith('/actor'):
233 await unfollow_remote_actor(actor['id'])
237 'Announce': handle_relay,
238 'Create': handle_relay,
239 'Follow': handle_follow,
244 async def inbox(request):
245 data = await request.json()
247 if 'actor' not in data or not request['validated']:
248 raise aiohttp.web.HTTPUnauthorized(body='access denied', content_type='text/plain')
250 actor = await fetch_actor(data["actor"])
251 actor_uri = 'https://{}/actor'.format(request.host)
253 logging.debug(">> payload %r", data)
255 processor = processors.get(data['type'], None)
257 await processor(actor, data, request)
259 return aiohttp.web.Response(body=b'{}', content_type='application/activity+json')
262 app.router.add_post('/inbox', inbox)