[refactor] remove username field and let instance_name be the only AP Actor

This commit is contained in:
les
2019-12-04 00:50:15 +01:00
parent e84d7f3bd1
commit 3116e776a0
23 changed files with 159 additions and 201 deletions

View File

@@ -10,26 +10,23 @@ module.exports = {
const body = req.body
if (typeof body.object !== 'string') { return }
const username = body.object.replace(`${config.baseurl}/federation/u/`, '')
const user = await User.findOne({ where: { username }, include: { model: FedUsers, as: 'followers' } })
if (!user) { return res.status(404).send('User not found') }
if (username !== req.settings.instance_name) { return res.status(404).send('User not found') }
// check for duplicate
if (!user.followers.includes(body.actor)) {
await user.addFollowers([req.fedi_user.ap_id])
// await user.update({ followers: [...user.followers, body.actor] })
debug('%s followed by %s (%d)', username, body.actor, user.followers.length + 1)
} else {
debug('duplicate %s followed by %s', username, body.actor)
}
// if (!user.followers.includes(body.actor)) {
// await user.addFollowers([req.fedi_user.id])
// await user.update({ followers: [...user.followers, body.actor] })
await req.fedi_user.update({ follower: true })
debug('Followed by %s', body.actor)
const guid = crypto.randomBytes(16).toString('hex')
const message = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': `${config.baseurl}/federation/${guid}`,
'type': 'Accept',
'actor': `${config.baseurl}/federation/u/${user.username}`,
'actor': `${config.baseurl}/federation/u/${username}`,
'object': body
}
Helpers.signAndSend(message, user, req.fedi_user.object.inbox)
Helpers.signAndSend(message, req.fedi_user.object.inbox)
res.sendStatus(200)
},
@@ -37,16 +34,14 @@ module.exports = {
async unfollow (req, res) {
const body = req.body
const username = body.object.object.replace(`${config.baseurl}/federation/u/`, '')
const user = await User.findOne({ where: { username }, include: { model: FedUsers, as: 'followers' } })
if (!user) { return res.status(404).send('User not found') }
if (username !== req.settings.instance_name) { return res.status(404).send('User not found') }
if (body.actor !== body.object.actor || body.actor !== req.fedi_user.ap_id) {
debug('Unfollow an user created by a different actor !?!?')
return res.status(400).send('Bad things')
}
if (req.fedi_user) { await user.removeFollowers(req.fedi_user.ap_id) }
debug('%s unfollowed by %s', username, body.actor)
await req.fedi_user.update({ follower: false })
debug('Unfollowed by %s', body.actor)
res.sendStatus(200)
}
}

View File

@@ -4,7 +4,7 @@ const crypto = require('crypto')
const config = require('config')
const httpSignature = require('http-signature')
const debug = require('debug')('federation:helpers')
const { user: User, fed_users: FedUsers, instances: Instances } = require('../api/models')
const { APUser, Instance } = require('../api/models')
const url = require('url')
const settingsController = require('../api/controller/settings')
@@ -24,10 +24,10 @@ const Helpers = {
next()
},
async signAndSend (message, user, inbox) {
async signAndSend (message, inbox) {
// get the URI of the actor object and append 'inbox' to it
const inboxUrl = new url.URL(inbox)
const privkey = user.rsa.privateKey
const privkey = settingsController.secretSettings.privateKey
const signer = crypto.createSign('sha256')
const d = new Date()
const stringToSign = `(request-target): post ${inboxUrl.pathname}\nhost: ${inboxUrl.hostname}\ndate: ${d.toUTCString()}`
@@ -35,7 +35,7 @@ const Helpers = {
signer.end()
const signature = signer.sign(privkey)
const signature_b64 = signature.toString('base64')
const header = `keyId="${config.baseurl}/federation/u/${user.username}",headers="(request-target) host date",signature="${signature_b64}"`
const header = `keyId="${config.baseurl}/federation/u/${settingsController.settings.instance_name}",headers="(request-target) host date",signature="${signature_b64}"`
const ret = await fetch(inbox, {
headers: {
'Host': inboxUrl.hostname,
@@ -49,82 +49,38 @@ const Helpers = {
debug('sign %s => %s', ret.status, await ret.text())
},
async sendEvent (event, user, type = 'Create') {
async sendEvent (event, type = 'Create') {
if (!settingsController.settings.enable_federation) {
debug('event not send, federation disabled')
return
}
// event is sent by user that published it and by the admin instance
// collect followers from admin and user
const instanceAdmin = await User.findOne({ where: { email: config.admin_email }, include: { model: FedUsers, as: 'followers' } })
if (!instanceAdmin || !instanceAdmin.username) {
debug('Instance admin not found (there is no user with email => %s)', config.admin_email)
return
}
const followers = await APUser.findAll({ where: { follow: true } })
const recipients = {}
instanceAdmin.followers.forEach(follower => {
followers.forEach(follower => {
const sharedInbox = follower.object.endpoints.sharedInbox
if (!recipients[sharedInbox]) { recipients[sharedInbox] = [] }
recipients[sharedInbox].push(follower.ap_id)
})
for (const sharedInbox in recipients) {
debug('Notify %s with event %s (from admin %s) cc => %d', sharedInbox, event.title, instanceAdmin.username, recipients[sharedInbox].length)
debug('Notify %s with event %s cc => %d', sharedInbox, event.title , recipients[sharedInbox].length)
const body = {
id: `${config.baseurl}/federation/m/${event.id}#create`,
type,
to: ['https://www.w3.org/ns/activitystreams#Public'],
cc: [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, ...recipients[sharedInbox]],
cc: [`${config.baseurl}/federation/u/${settingsController.settings.instance_name}/followers`, ...recipients[sharedInbox]],
// cc: recipients[sharedInbox],
actor: `${config.baseurl}/federation/u/${instanceAdmin.username}`,
// object: event.toAP(instanceAdmin.username, [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, ...recipients[sharedInbox]])
object: event.toAP(instanceAdmin.username, recipients[sharedInbox])
actor: `${config.baseurl}/federation/u/${settingsController.settings.instance_name}`,
// object: event.toNoteAP(instanceAdmin.username, [`${config.baseurl}/federation/u/${instanceAdmin.username}/followers`, ...recipients[sharedInbox]])
object: event.toNoteAP(settingsController.settings.instance_name, recipients[sharedInbox])
}
body['@context'] = [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/v1',
{ Hashtag: 'as:Hashtag' } ]
Helpers.signAndSend(body, instanceAdmin, sharedInbox)
Helpers.signAndSend(body, sharedInbox)
}
// TODO
// in case the event is published by the Admin itself do not add user
// if (instanceAdmin.id === user.id) {
// debug('Event published by instance Admin')
// return
// }
// if (!user.settings.enable_federation || !user.username) {
// debug('Federation disabled for user %d (%s)', user.id, user.username)
// return
// }
// 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] = [] }
// recipients[sharedInbox].push(follower.ap_id)
// })
// for (const sharedInbox in recipients) {
// debug('Notify %s with event %s (from user %s) cc => %d', sharedInbox, event.title, user.username, recipients[sharedInbox].length)
// const body = {
// id: `${config.baseurl}/federation/m/${event.id}#create`,
// type: 'Create',
// to: ['https://www.w3.org/ns/activitystreams#Public'],
// cc: [`${config.baseurl}/federation/u/${user.username}/followers`, ...recipients[sharedInbox]],
// // cc: recipients[sharedInbox],
// actor: `${config.baseurl}/federation/u/${user.username}`,
// // object: event.toAP(user.username, [`${config.baseurl}/federation/u/${user.username}/followers`, ...recipients[sharedInbox]])
// object: event.toAP(user.username, recipients[sharedInbox])
// }
// body['@context'] = 'https://www.w3.org/ns/activitystreams'
// Helpers.signAndSend(body, user, sharedInbox)
// }
},
async getActor (URL, instance, force = false) {
@@ -132,7 +88,7 @@ const Helpers = {
// try with cache first
if (!force) {
fedi_user = await FedUsers.findByPk(URL, { include: Instances })
fedi_user = await APUser.findByPk(URL, { include: Instance })
if (fedi_user) {
if (!fedi_user.instances) {
fedi_user.setInstance(instance)
@@ -151,7 +107,7 @@ const Helpers = {
})
if (fedi_user) {
fedi_user = await FedUsers.create({ ap_id: URL, object: fedi_user })
fedi_user = await APUser.create({ ap_id: URL, object: fedi_user })
}
return fedi_user
},
@@ -163,7 +119,7 @@ const Helpers = {
debug('getInstance %s', domain)
let instance
if (!force) {
instance = await Instances.findByPk(domain)
instance = await Instance.findByPk(domain)
if (instance) { return instance }
}
@@ -174,7 +130,7 @@ const Helpers = {
stats: instance.stats,
thumbnail: instance.thumbnail
}
return Instances.create({ name: instance.title, domain, data, blocked: false })
return Instance.create({ name: instance.title, domain, data, blocked: false })
})
.catch(e => {
debug(e)

View File

@@ -33,7 +33,7 @@ router.get('/m/:event_id', async (req, res) => {
const event = await Event.findByPk(req.params.event_id, { include: [ User, Tag, Place ] })
if (!event) { return res.status(404).send('Not found') }
return res.json(event.toAP(event.user.username))
return res.json(event.toNoteAP(event.user.username))
})
// get any message coming from federation

View File

@@ -23,8 +23,8 @@ module.exports = {
id: `${config.baseurl}/federation/u/${name}`,
type: 'Person',
summary: config.description,
name: user.display_name || user.username,
preferredUsername: user.username,
name,
preferredUsername: name,
inbox: `${config.baseurl}/federation/u/${name}/inbox`,
// outbox: `${config.baseurl}/federation/u/${name}/outbox`,
// followers: `${config.baseurl}/federation/u/${name}/followers`,
@@ -42,19 +42,23 @@ module.exports = {
publicKey: {
id: `${config.baseurl}/federation/u/${name}#main-key`,
owner: `${config.baseurl}/federation/u/${name}`,
publicKeyPem: get(user, 'rsa.publicKey', '')
publicKeyPem: req.settings.publicKey
}
}
res.type('application/activity+json; charset=utf-8')
res.json(ret)
},
async followers (req, res) {
async followers(req, res) {
// TODO
const name = req.params.name
const page = req.query.page
debug('Retrieve %s followers', name)
if (!name) { return res.status(400).send('Bad request.') }
const user = await User.findOne({ where: { username: name }, include: [{ model: FedUsers, as: 'followers' }] })
if (!user) { return res.status(404).send(`No record found for ${name}`) }
if (name !== req.settings.instance_name) {
return res.status(404).send(`No record found for ${name}`)
}
const followers = await APUser.findAll({ where: { follower: true } })
res.type('application/activity+json; charset=utf-8')
@@ -64,19 +68,19 @@ module.exports = {
'@context': 'https://www.w3.org/ns/activitystreams',
id: `${config.baseurl}/federation/u/${name}/followers`,
type: 'OrderedCollection',
totalItems: user.followers.length,
totalItems: followers.length,
first: `${config.baseurl}/federation/u/${name}/followers?page=true`,
last: `${config.baseurl}/federation/u/${name}/followers?page=true`,
orderedItems: user.followers.map(f => f.ap_id)
orderedItems: followers.map(f => f.ap_id)
})
}
return res.json({
'@context': 'https://www.w3.org/ns/activitystreams',
id: `${config.baseurl}/federation/u/${name}/followers?page=${page}`,
type: 'OrderedCollectionPage',
totalItems: user.followers.length,
totalItems: followers.length,
partOf: `${config.baseurl}/federation/u/${name}/followers`,
orderedItems: user.followers.map(f => f.ap_id)
orderedItems: followers.map(f => f.ap_id)
})
},
@@ -115,7 +119,7 @@ module.exports = {
totalItems: user.events.length,
partOf: `${config.baseurl}/federation/u/${name}/outbox`,
orderedItems: user.events.map(e => ({
...e.toAP(user.username), actor: `${config.baseurl}/federation/u/${user.username}`}))
...e.toNoteAP(user.username), actor: `${config.baseurl}/federation/u/${user.username}` }))
// user.events.map(e => ({
// id: `${config.baseurl}/federation/m/${e.id}#create`,
// type: 'Create',
@@ -123,7 +127,7 @@ module.exports = {
// cc: [`${config.baseurl}/federation/u/${user.username}/followers`],
// published: e.createdAt,
// actor: `${config.baseurl}/federation/u/${user.username}`,
// object: e.toAP(user.username)
// object: e.toNoteAP(user.username)
// }))
})
}

View File

@@ -15,23 +15,20 @@ router.use((req, res, next) => {
res.status(404).send('Federation disabled')
})
router.get('/webfinger', async (req, res) => {
router.get('/webfinger', (req, res) => {
if (!req.query || !req.query.resource || !req.query.resource.includes('acct:')) {
debug('Bad webfinger request => %s', req.query && req.query.resource)
return res.status(400).send('Bad request. Please make sure "acct:USER@DOMAIN" is what you are sending as the "resource" query parameter.')
}
const resource = req.query.resource
const domain = url.parse(req.settings.baseurl).host
const domain = (new url.URL(req.settings.baseurl)).host
const [, name, req_domain] = resource.match(/acct:(.*)@(.*)/)
if (domain !== req_domain) {
debug('Bad webfinger request, requested domain "%s" instead of "%s"', req_domain, domain)
return res.status(400).send('Bad request. Please make sure "acct:USER@DOMAIN" is what you are sending as the "resource" query parameter.')
}
const user = await User.findOne({ where: { username: name } })
if (!user) {
if (name !== req.settings.instance_name) {
debug('User not found: %s', name)
return res.status(404).send(`No record found for ${name}`)
}