gancio-upstream/server/federation/helpers.js

185 lines
7.2 KiB
JavaScript
Raw Normal View History

2019-08-02 17:29:55 +02:00
const fetch = require('node-fetch')
2019-08-10 15:00:08 +02:00
// const request = require('request')
2019-07-31 02:01:21 +02:00
const crypto = require('crypto')
2019-07-30 18:57:45 +02:00
const config = require('config')
2019-08-02 17:29:55 +02:00
const httpSignature = require('http-signature')
2019-09-11 21:20:44 +02:00
const debug = require('debug')('federation:helpers')
2019-09-12 14:59:51 +02:00
const { user: User, fed_users: FedUsers } = require('../api/models')
2019-09-11 12:00:13 +02:00
const url = require('url')
2019-09-25 14:38:16 +02:00
const settingsController = require('../api/controller/settings')
2019-07-30 18:32:26 +02:00
const Helpers = {
// ignore unimplemented ping url from fediverse
2019-10-28 17:33:20 +01:00
spamFilter (req, res, next) {
const urlToIgnore = [
'/api/v1/instance',
'/api/meta',
2019-09-18 12:55:33 +02:00
'/api/statusnet/version.json',
'/api/gnusocial/version.json',
'/api/statusnet/config.json',
2019-10-28 17:33:20 +01:00
'/poco'
]
2019-10-28 17:33:20 +01:00
if (urlToIgnore.includes(req.path)) { return res.status(404).send('Not Found') }
next()
},
2019-09-26 15:22:02 +02:00
async signAndSend (message, user, inbox) {
2019-07-30 18:32:26 +02:00
// get the URI of the actor object and append 'inbox' to it
2019-09-26 15:22:02 +02:00
const inboxUrl = url.parse(inbox)
// const toPath = toOrigin.path + '/inbox'
2019-07-30 18:32:26 +02:00
// get the private key
const privkey = user.rsa.privateKey
const signer = crypto.createSign('sha256')
2019-07-31 01:43:08 +02:00
const d = new Date()
2019-09-26 15:22:02 +02:00
const stringToSign = `(request-target): post ${inboxUrl.path}\nhost: ${inboxUrl.hostname}\ndate: ${d.toUTCString()}`
debug('Sign and send', user.username, inbox)
2019-07-30 18:32:26 +02:00
signer.update(stringToSign)
signer.end()
const signature = signer.sign(privkey)
const signature_b64 = signature.toString('base64')
2019-07-31 01:43:08 +02:00
const header = `keyId="${config.baseurl}/federation/u/${user.username}",headers="(request-target) host date",signature="${signature_b64}"`
2019-09-26 15:22:02 +02:00
const ret = await fetch(inbox, {
2019-07-30 18:32:26 +02:00
headers: {
2019-09-26 15:22:02 +02:00
'Host': inboxUrl.hostname,
2019-07-30 18:32:26 +02:00
'Date': d.toUTCString(),
2019-08-01 15:18:45 +02:00
'Signature': header,
2019-08-10 15:00:08 +02:00
'Content-Type': 'application/activity+json; charset=utf-8',
'Accept': 'application/activity+json, application/json; chartset=utf-8'
2019-07-30 18:32:26 +02:00
},
method: 'POST',
2019-08-10 15:00:08 +02:00
body: JSON.stringify(message) })
2019-09-11 21:20:44 +02:00
debug('sign %s => %s', ret.status, await ret.text())
2019-07-31 01:43:08 +02:00
},
2019-09-11 12:00:13 +02:00
2019-10-28 17:33:20 +01:00
async sendEvent (event, user, type = 'Create') {
2019-09-25 14:38:16 +02:00
if (!settingsController.settings.enable_federation) {
2019-09-18 12:55:33 +02:00
debug('event not send, federation disabled')
return
}
2019-09-11 12:00:13 +02:00
// event is sent by user that published it and by the admin instance
2019-09-12 14:59:51 +02:00
// collect followers from admin and user
2019-10-28 17:33:20 +01:00
const instanceAdmin = await User.findOne({ where: { email: config.admin_email }, include: { model: FedUsers, as: 'followers' } })
2019-09-11 19:12:24 +02:00
if (!instanceAdmin || !instanceAdmin.username) {
2019-09-24 11:46:11 +02:00
debug('Instance admin not found (there is no user with email => %s)', config.admin_email)
2019-09-11 13:12:05 +02:00
return
}
2019-09-11 12:00:13 +02:00
let recipients = {}
instanceAdmin.followers.forEach(follower => {
2019-09-18 12:55:33 +02:00
const sharedInbox = follower.object.endpoints.sharedInbox
2019-10-28 17:33:20 +01:00
if (!recipients[sharedInbox]) { recipients[sharedInbox] = [] }
2019-09-18 12:55:33 +02:00
recipients[sharedInbox].push(follower.ap_id)
})
2019-10-28 17:33:20 +01:00
for (const sharedInbox in recipients) {
2019-09-18 12:55:33 +02:00
debug('Notify %s with event %s (from admin %s) cc => %d', sharedInbox, event.title, instanceAdmin.username, recipients[sharedInbox].length)
2019-09-11 13:12:05 +02:00
const body = {
2019-09-11 21:20:44 +02:00
id: `${config.baseurl}/federation/m/${event.id}#create`,
type,
2019-09-11 21:20:44 +02:00
to: ['https://www.w3.org/ns/activitystreams#Public'],
2019-09-26 00:24:05 +02:00
cc: [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, ...recipients[sharedInbox]],
2019-10-28 17:33:20 +01:00
// cc: recipients[sharedInbox],
2019-09-11 13:12:05 +02:00
actor: `${config.baseurl}/federation/u/${instanceAdmin.username}`,
2019-09-18 12:55:33 +02:00
// object: event.toAP(instanceAdmin.username, [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, ...recipients[sharedInbox]])
object: event.toAP(instanceAdmin.username, recipients[sharedInbox])
2019-09-11 13:12:05 +02:00
}
2019-09-26 22:46:04 +02:00
body['@context'] = [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/v1',
{ Hashtag: 'as:Hashtag' } ]
Helpers.signAndSend(body, instanceAdmin, sharedInbox)
2019-09-11 12:00:13 +02:00
}
2019-09-11 19:12:24 +02:00
2019-09-26 22:46:04 +02:00
return
// TODO
// in case the event is published by the Admin itself do not add user
2019-09-11 13:12:05 +02:00
if (instanceAdmin.id === user.id) {
2019-09-11 21:20:44 +02:00
debug('Event published by instance Admin')
return
}
2019-09-11 21:20:44 +02:00
if (!user.settings.enable_federation || !user.username) {
debug('Federation disabled for user %d (%s)', user.id, user.username)
2019-09-11 13:12:05 +02:00
return
}
2019-09-18 12:55:33 +02:00
debug('Sending to user followers => ', user.username)
user = await User.findByPk( user.id, { include: { model: FedUsers, as: 'followers' }})
debug('Sending to user followers => ', user.followers.length)
recipients = {}
user.followers.forEach(follower => {
const sharedInbox = follower.object.endpoints.sharedInbox
if (!recipients[sharedInbox]) recipients[sharedInbox] = []
2019-09-18 12:55:33 +02:00
recipients[sharedInbox].push(follower.ap_id)
})
for(const sharedInbox in recipients) {
2019-09-18 12:55:33 +02:00
debug('Notify %s with event %s (from user %s) cc => %d', sharedInbox, event.title, user.username, recipients[sharedInbox].length)
2019-09-11 13:12:05 +02:00
const body = {
2019-09-11 19:12:24 +02:00
id: `${config.baseurl}/federation/m/${event.id}#create`,
2019-09-11 13:12:05 +02:00
type: 'Create',
2019-09-11 19:12:24 +02:00
to: ['https://www.w3.org/ns/activitystreams#Public'],
2019-09-26 00:24:05 +02:00
cc: [`${config.baseurl}/federation/u/${user.username}/followers`, ...recipients[sharedInbox]],
//cc: recipients[sharedInbox],
2019-09-11 13:12:05 +02:00
actor: `${config.baseurl}/federation/u/${user.username}`,
2019-09-18 12:55:33 +02:00
// object: event.toAP(user.username, [`${config.baseurl}/federation/u/${user.username}/followers`, ...recipients[sharedInbox]])
object: event.toAP(user.username, recipients[sharedInbox])
2019-09-11 13:12:05 +02:00
}
2019-07-31 02:08:46 +02:00
body['@context'] = 'https://www.w3.org/ns/activitystreams'
Helpers.signAndSend(body, user, sharedInbox)
2019-09-11 12:00:13 +02:00
}
2019-08-02 13:43:28 +02:00
},
2019-09-11 19:12:24 +02:00
async getActor (url, force = false) {
2019-09-12 14:59:51 +02:00
let fedi_user
2019-08-09 01:58:11 +02:00
// try with cache first
2019-09-12 14:59:51 +02:00
if (!force) fedi_user = await FedUsers.findByPk(url)
if (fedi_user) return fedi_user.object
fedi_user = await fetch(url, { headers: { 'Accept': 'application/jrd+json, application/json' } })
2019-08-09 00:19:57 +02:00
.then(res => {
if (!res.ok) {
debug('[ERR] Actor %s => %s', url, res.statusText)
return false
}
return res.json()
})
2019-09-12 14:59:51 +02:00
if (fedi_user) {
await FedUsers.create({ap_id: url, object: fedi_user})
}
return fedi_user
2019-08-02 13:43:28 +02:00
},
2019-08-02 17:29:55 +02:00
// ref: https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
2019-09-11 19:12:24 +02:00
async verifySignature (req, res, next) {
2019-08-03 00:48:48 +02:00
let user = await Helpers.getActor(req.body.actor)
2019-09-11 19:12:24 +02:00
if (!user) { return res.status(401).send('Actor not found') }
2019-09-12 14:59:51 +02:00
2019-08-02 17:29:55 +02:00
// little hack -> https://github.com/joyent/node-http-signature/pull/83
req.headers.authorization = 'Signature ' + req.headers.signature
2019-09-12 14:59:51 +02:00
req.fedi_user = user
2019-09-11 19:12:24 +02:00
// another little hack :/
// https://github.com/joyent/node-http-signature/issues/87
req.url = '/federation' + req.url
2019-08-02 17:29:55 +02:00
const parsed = httpSignature.parseRequest(req)
2019-09-11 19:12:24 +02:00
if (httpSignature.verifySignature(parsed, user.publicKey.publicKeyPem)) { return next() }
2019-09-12 14:59:51 +02:00
2019-08-02 17:29:55 +02:00
// signature not valid, try without cache
2019-08-03 00:48:48 +02:00
user = await Helpers.getActor(req.body.actor, true)
2019-09-11 19:12:24 +02:00
if (!user) { return res.status(401).send('Actor not found') }
if (httpSignature.verifySignature(parsed, user.publicKey.publicKeyPem)) { return next() }
2019-09-12 14:59:51 +02:00
2019-08-02 17:29:55 +02:00
// still not valid
2019-09-11 12:00:13 +02:00
debug('Invalid signature from user %s', req.body.actor)
res.send('Request signature could not be verified', 401)
2019-09-12 14:59:51 +02:00
2019-07-30 18:32:26 +02:00
}
}
2019-07-30 18:57:45 +02:00
module.exports = Helpers