This commit is contained in:
les
2019-09-11 19:12:24 +02:00
parent 93baf01a55
commit 2fe956d117
65 changed files with 762 additions and 721 deletions

View File

@@ -5,13 +5,13 @@ const debug = require('debug')('fediverse:comment')
module.exports = {
async create (req, res) {
const body = req.body
//search for related event
// search for related event
const inReplyTo = body.object.inReplyTo
const match = inReplyTo.match('.*\/federation\/m\/(.*)')
console.error('inReplyTo', inReplyTo)
console.error('match', match)
if (!match || match.length<2) {
debug("Comment not found %s", inReplyTo)
if (!match || match.length < 2) {
debug('Comment not found %s', inReplyTo)
return res.status(404).send('Event not found!')
}
let event = await Event.findByPk(Number(match[1]))
@@ -20,7 +20,7 @@ module.exports = {
if (!event) {
// in reply to another comment...
const comment = await Comment.findOne({ where: { activitypub_id: inReplyTo }, include: [Event] })
if (!comment) return res.status(404).send('Not found')
if (!comment) { return res.status(404).send('Not found') }
event = comment.event
}
debug('comment from %s to "%s"', req.body.actor, event.title)
@@ -35,7 +35,7 @@ module.exports = {
},
async remove (req, res) {
const comment = await Comment.findOne({where: { activitypub_id: req.body.object.id }})
const comment = await Comment.findOne({ where: { activitypub_id: req.body.object.id } })
if (!comment) {
debug('Comment %s not found', req.body.object.id)
return res.status(404).send('Not found')

View File

@@ -5,21 +5,21 @@ const debug = require('debug')('fediverse:ego')
module.exports = {
async boost (req, res) {
const match = req.body.object.match(`${config.baseurl}/federation/m/(.*)`)
if (!match || match.length<2) return res.status(404).send('Event not found!')
if (!match || match.length < 2) { return res.status(404).send('Event not found!') }
debug('boost %s', match[1])
const event = await Event.findByPk(Number(match[1]))
if (!event) return res.status(404).send('Event not found!')
await event.update({ boost: [...event.boost, req.body.actor]})
if (!event) { return res.status(404).send('Event not found!') }
await event.update({ boost: [...event.boost, req.body.actor] })
res.sendStatus(201)
},
async bookmark (req, res) {
const match = req.body.object.match(`${config.baseurl}/federation/m/(.*)`)
if (!match || match.length<2) return res.status(404).send('Event not found!')
if (!match || match.length < 2) { return res.status(404).send('Event not found!') }
const event = await Event.findByPk(Number(match[1]))
debug('%s bookmark %s (%d)', req.body.actor, event.title, event.likes.length)
if (!event) return res.status(404).send('Event not found!')
await event.update({ likes: [...event.likes, req.body.actor]})
if (!event) { return res.status(404).send('Event not found!') }
await event.update({ likes: [...event.likes, req.body.actor] })
res.sendStatus(201)
},
@@ -27,11 +27,11 @@ module.exports = {
const body = req.body
const object = body.object
const match = object.object.match(`${config.baseurl}/federation/m/(.*)`)
if (!match || match.length<2) return res.status(404).send('Event not found!')
if (!match || match.length < 2) { return res.status(404).send('Event not found!') }
const event = await Event.findByPk(Number(match[1]))
debug('%s unbookmark %s (%d)', body.actor, event.title, event.likes.length)
if (!event) return res.status(404).send('Event not found!')
await event.update({ likes: [...event.likes.filter(actor => actor!==body.actor)]})
if (!event) { return res.status(404).send('Event not found!') }
await event.update({ likes: [...event.likes.filter(actor => actor !== body.actor)] })
res.sendStatus(201)
}
}
}

View File

@@ -8,25 +8,25 @@ module.exports = {
// follow request from fediverse
async follow (req, res) {
const body = req.body
if (typeof body.object !== 'string') return
if (typeof body.object !== 'string') { return }
const username = body.object.replace(`${config.baseurl}/federation/u/`, '')
const user = await User.findOne({ where: { username }})
if (!user) return res.status(404).send('User not found')
const user = await User.findOne({ where: { username } })
if (!user) { return res.status(404).send('User not found') }
// check for duplicate
if (user.followers.indexOf(body.actor) === -1) {
if (!user.followers.includes(body.actor)) {
await user.update({ followers: [...user.followers, body.actor] })
debug('%s followed by %s (%d)', username, body.actor, user.followers.length)
} else {
debug('duplicate %s followed by %s', username, body.actor)
}
const guid = crypto.randomBytes(16).toString('hex')
let message = {
const message = {
'@context': 'https://www.w3.org/ns/activitystreams',
'id': `${config.baseurl}/federation/${guid}`,
'type': 'Accept',
'actor': `${config.baseurl}/federation/u/${user.username}`,
'object': body,
'object': body
}
Helpers.signAndSend(message, user, body.actor)
res.sendStatus(200)
@@ -36,8 +36,8 @@ 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 }})
if (!user) return res.status(404).send('User not found')
const user = await User.findOne({ where: { username } })
if (!user) { return res.status(404).send('User not found') }
if (body.actor !== body.object.actor) {
debug('Unfollow an user created by a different actor !?!?')

View File

@@ -10,7 +10,7 @@ const url = require('url')
const actorCache = []
const Helpers = {
async signAndSend(message, user, to) {
async signAndSend (message, user, to) {
// get the URI of the actor object and append 'inbox' to it
const toInbox = to + '/inbox'
const toOrigin = url.parse(to)
@@ -36,19 +36,18 @@ const Helpers = {
},
method: 'POST',
body: JSON.stringify(message) })
},
async sendEvent(event, user) {
async sendEvent (event, user) {
// TODO: has to use sharedInbox!
// event is sent by user that published it and by the admin instance
const instanceAdmin = await User.findOne({where: { email: config.admin }})
if(!instanceAdmin || !instanceAdmin.username) {
const instanceAdmin = await User.findOne({ where: { email: config.admin } })
if (!instanceAdmin || !instanceAdmin.username) {
debug('Instance admin not found (there is no user with email => %s)', config.admin)
return
}
for(let follower of instanceAdmin.followers) {
for (const follower of instanceAdmin.followers) {
debug('Notify %s with event %s', follower, event.title)
const body = {
id: `${config.baseurl}/federation/m/c_${event.id}`,
@@ -60,21 +59,23 @@ const Helpers = {
body['@context'] = 'https://www.w3.org/ns/activitystreams'
Helpers.signAndSend(body, user, follower)
}
// in case the event is published by the Admin itself do not republish
if (instanceAdmin.id === user.id) {
debug('')
return
}
if (!user.settings.enable_federation || !user.username) return
for(let follower of user.followers) {
if (!user.settings.enable_federation || !user.username) { return }
for (const follower of user.followers) {
debug('Notify %s with event %s', follower, event.title)
const body = {
id: `${config.baseurl}/federation/m/c_${event.id}`,
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`],
published: event.createdAt,
actor: `${config.baseurl}/federation/u/${user.username}`,
url: `${config.baseurl}/federation/m/${event.id}`,
object: event.toAP(user.username, follower)
}
body['@context'] = 'https://www.w3.org/ns/activitystreams'
@@ -82,18 +83,18 @@ const Helpers = {
}
},
async getFederatedUser(address) {
async getFederatedUser (address) {
address = address.trim()
const [ username, host ] = address.split('@')
const url = `https://${host}/.well-known/webfinger?resource=acct:${username}@${host}`
return Helpers.getActor(url)
},
// TODO: cache
async getActor(url, force=false) {
async getActor (url, force = false) {
// try with cache first
if (!force && actorCache[url]) return actorCache[url]
const user = await fetch(url, { headers: {'Accept': 'application/jrd+json, application/json'} })
if (!force && actorCache[url]) { return actorCache[url] }
const user = await fetch(url, { headers: { 'Accept': 'application/jrd+json, application/json' } })
.then(res => {
if (!res.ok) {
debug('[ERR] Actor %s => %s', url, res.statusText)
@@ -106,23 +107,23 @@ const Helpers = {
},
// ref: https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
async verifySignature(req, res, next) {
async verifySignature (req, res, next) {
let user = await Helpers.getActor(req.body.actor)
if (!user) return res.status(401).send('Actor not found')
if (!user) { return res.status(401).send('Actor not found') }
// little hack -> https://github.com/joyent/node-http-signature/pull/83
req.headers.authorization = 'Signature ' + req.headers.signature
// another little hack :/
// another little hack :/
// https://github.com/joyent/node-http-signature/issues/87
req.url = '/federation' + req.url
const parsed = httpSignature.parseRequest(req)
if (httpSignature.verifySignature(parsed, user.publicKey.publicKeyPem)) return next()
if (httpSignature.verifySignature(parsed, user.publicKey.publicKeyPem)) { return next() }
// signature not valid, try without cache
user = await Helpers.getActor(req.body.actor, true)
if (!user) return res.status(401).send('Actor not found')
if (httpSignature.verifySignature(parsed, user.publicKey.publicKeyPem)) return next()
if (!user) { return res.status(401).send('Actor not found') }
if (httpSignature.verifySignature(parsed, user.publicKey.publicKeyPem)) { return next() }
// still not valid
debug('Invalid signature from user %s', req.body.actor)

View File

@@ -8,31 +8,30 @@ const { event: Event, user: User, tag: Tag, place: Place } = require('../api/mod
const Comments = require('./comments')
const Helpers = require('./helpers')
const Ego = require('./ego')
const debug = require('debug')('federation')
/**
* Federation is calling!
* ref: https://www.w3.org/TR/activitypub/#Overview
*/
router.use(cors())
router.use(express.json({type: ['application/json', 'application/activity+json', 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"']}))
router.use(express.json({ type: ['application/json', 'application/activity+json', 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"'] }))
router.get('/m/:event_id', async (req, res) => {
const event_id = req.params.event_id
// if (req.accepts('html')) return res.redirect(301, `/event/${event_id}`)
const event = await Event.findByPk(req.params.event_id, { include: [ User, Tag, Place ] })
if (!event) return res.status(404).send('Not found')
if (!event) { return res.status(404).send('Not found') }
return res.json(event.toAP(event.user.username))
})
// get any message coming from federation
// Federation is calling!
router.post('/u/:name/inbox', Helpers.verifySignature, async (req, res) => {
const b = req.body
switch(b.type) {
debug(b.type)
switch (b.type) {
case 'Follow':
Follows.follow(req, res)
break

View File

@@ -18,7 +18,7 @@ router.get('/', async (req, res) => {
},
protocols: ['activitypub'],
openRegistrations: settingsController.settings.allow_registration,
usage:{
usage: {
users: {
total: 10
}

View File

@@ -21,6 +21,16 @@ module.exports = {
inbox: `${config.baseurl}/federation/u/${name}/inbox`,
outbox: `${config.baseurl}/federation/u/${name}/outbox`,
followers: `${config.baseurl}/federation/u/${name}/followers`,
attachment: [{
type: 'PropertyValue',
name: 'Website',
value: `<a href='${config.baseurl}'>${config.baseurl}</a>`
}],
icon: {
type: 'Image',
mediaType: 'image/jpeg',
url: config.baseurl + '/favicon.ico'
},
publicKey: {
id: `${config.baseurl}/federation/u/${name}#main-key`,
owner: `${config.baseurl}/federation/u/${name}`,
@@ -32,62 +42,79 @@ module.exports = {
},
async followers (req, res) {
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 }})
if (!user) return res.status(404).send(`No record found for ${name}`)
const ret = {
'@context': [ 'https://www.w3.org/ns/activitystreams' ],
id: `${config.baseurl}/federation/u/${name}/followers`,
type: 'OrderedCollection',
totalItems: user.followers.length,
first: {
id: `${config.baseurl}/federation/u/${name}/followers?page=1`,
type: 'OrderedCollectionPage',
res.type('application/activity+json; charset=utf-8')
if (!page) {
debug('No pagination')
return res.json({
'@context': 'https://www.w3.org/ns/activitystreams',
id: `${config.baseurl}/federation/u/${name}/followers`,
type: 'OrderedCollection',
totalItems: user.followers.length,
partOf: `${config.baseurl}/federation/u/${name}/followers`,
orderedItems: user.followers,
}
first: `${config.baseurl}/federation/u/${name}/followers?page=true`,
last: `${config.baseurl}/federation/u/${name}/followers?page=true`,
})
}
res.json(ret)
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,
partOf: `${config.baseurl}/federation/u/${name}/followers` ,
orderedItems: user.followers
})
},
async outbox (req, res) {
const name = req.params.name
const page = req.query.page
if (!name) return res.status(400).send('Bad request.')
const user = await User.findOne({
include: [ { model: Event, include: [ Place, Tag ] } ],
where: { username: name }
})
if (!user) return res.status(404).send(`No record found for ${name}`)
if (!user) return res.status(404).send(`No record found for ${name}`)
debug('Inside outbox, should return all events from this user')
// https://www.w3.org/TR/activitypub/#outbox
res.type('application/activity+json; charset=utf-8')
if (!page) {
const ret = {
debug('Without pagination ')
return res.json({
'@context': 'https://www.w3.org/ns/activitystreams',
id: `${config.baseurl}/federation/u/${name}/outbox`,
type: 'OrderedCollection',
totalItems: user.events.length,
first: {
id: `${config.baseurl}/federation/u/${name}/outbox?page=true`,
type: 'OrderedCollectionPage',
totalItem: user.events.length,
partOf: `${config.baseurl}/federation/u/${name}/outbox`,
orderedItems: user.events.map(e => e.toAP(user.username))
}
}
res.type('application/activity+json; charset=utf-8')
return res.json(ret)
first: `${config.baseurl}/federation/u/${name}/outbox?page=true`,
last: `${config.baseurl}/federation/u/${name}/outbox?page=true`
})
}
const ret = {
debug('With pagination %s', page)
return res.json({
'@context': 'https://www.w3.org/ns/activitystreams',
id: `${config.baseurl}/federation/u/${name}/outbox?page=true`,
id: `${config.baseurl}/federation/u/${name}/outbox?page=${page}`,
type: 'OrderedCollectionPage',
partOf: `${config.baseurl}/federation/u/${name}/outbox`,
orderedItems: user.events.map(e => e.toAP(user.username))
}
res.type('application/activity+json; charset=utf-8')
res.json(ret)
totalItems: user.followers.length,
partOf: `${config.baseurl}/federation/u/${name}/outbox` ,
orderedItems: user.events.map(e => ({
id: `${config.baseurl}/federation/m/${e.id}#create`,
type: 'Create',
to: ['https://www.w3.org/ns/activitystreams#Public'],
cc: [`${config.baseurl}/federation/u/${user.username}/followers`],
published: e.createdAt,
actor: `${config.baseurl}/federation/u/${user.username}`,
object: e.toAP(user.username)
}))
})
}
}

View File

@@ -6,18 +6,30 @@ const settingsController = require('../api/controller/settings')
const config = require('config')
const version = require('../../package.json').version
const url = require('url')
const debug = require('debug')('webfinger')
router.use(cors())
router.get('/webfinger', async (req, res) => {
const resource = req.query.resource
if (!resource || !resource.includes('acct:')) {
debug('Bad webfinger request => %s', resource.query)
return res.status(400).send('Bad request. Please make sure "acct:USER@DOMAIN" is what you are sending as the "resource" query parameter.')
}
const name = resource.match(/acct:(.*)@/)[1]
const domain = url.parse(config.baseurl).host
const user = await User.findOne({where: { username: name } })
if (!user) return res.status(404).send(`No record found for ${name}`)
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) {
debug('User not found: %s', name)
return res.status(404).send(`No record found for ${name}`)
}
const ret = {
subject: `acct:${name}@${domain}`,
links: [
@@ -38,24 +50,24 @@ router.get('/nodeinfo/:nodeinfo_version', async (req, res) => {
nodeDescription: 'Gancio instance',
nodeName: config.title
},
openRegistrations : settingsController.settings.allow_registration,
protocols :['activitypub'],
services: { inbound: [], outbound :["atom1.0"]},
openRegistrations: settingsController.settings.allow_registration,
protocols: ['activitypub'],
services: { inbound: [], outbound: ['atom1.0'] },
software: {
name: 'gancio',
version
},
usage: {
usage: {
localComments: 0,
localPosts:0,
localPosts: 0,
users: {
total:3
total: 3
}
},
version: req.params.nodeinfo_version
}
if(req.params.nodeinfo_version === '2.1') {
if (req.params.nodeinfo_version === '2.1') {
ret.software.repository = 'https://git.lattuga.net/cisti/gancio'
}
res.json(ret)
@@ -72,7 +84,7 @@ router.get('/x-nodeinfo2', async (req, res) => {
},
protocols: ['activitypub'],
openRegistrations: settingsController.settings.allow_registration,
usage:{
usage: {
users: {
total: 10
}
@@ -83,18 +95,16 @@ router.get('/x-nodeinfo2', async (req, res) => {
res.json(ret)
})
router.get('/nodeinfo', async (req, res) => {
const ret = {
links: [
{ href: `${config.baseurl}/.well-known/nodeinfo/2.0`, rel: `http://nodeinfo.diaspora.software/ns/schema/2.0` },
{ href: `${config.baseurl}/.well-known/nodeinfo/2.1`, rel: `http://nodeinfo.diaspora.software/ns/schema/2.1` },
{ href: `${config.baseurl}/.well-known/nodeinfo/2.1`, rel: `http://nodeinfo.diaspora.software/ns/schema/2.1` }
]
}
res.json(ret)
})
router.use('/host-meta', (req, res) => {
res.type('application/xml')
res.send(`<?xml version="1.0" encoding="UTF-8"?>
@@ -104,12 +114,14 @@ router.use('/host-meta', (req, res) => {
})
// Handle 404
router.use(function(req, res) {
router.use((req, res) => {
debug('404 Page not found: %s', req.path)
res.status(404).send('404: Page not Found')
})
// Handle 500
router.use(function(error, req, res, next) {
router.use((error, req, res, next) => {
debug(error)
res.status(500).send('500: Internal Server Error')
})