2017-11-17 08:20:42 -06:00
|
|
|
import { eachSeries } from 'async'
|
|
|
|
import { NextFunction, Request, RequestHandler, Response } from 'express'
|
2017-11-09 10:51:58 -06:00
|
|
|
import { ActivityPubSignature } from '../../shared'
|
2017-11-14 10:31:26 -06:00
|
|
|
import { isSignatureVerified, logger } from '../helpers'
|
2017-12-12 10:53:50 -06:00
|
|
|
import { ACCEPT_HEADERS, ACTIVITY_PUB } from '../initializers'
|
|
|
|
import { fetchRemoteAccount, saveAccountAndServerIfNotExist } from '../lib/activitypub'
|
|
|
|
import { AccountModel } from '../models/account/account'
|
2017-11-09 10:51:58 -06:00
|
|
|
|
|
|
|
async function checkSignature (req: Request, res: Response, next: NextFunction) {
|
|
|
|
const signatureObject: ActivityPubSignature = req.body.signature
|
|
|
|
|
|
|
|
logger.debug('Checking signature of account %s...', signatureObject.creator)
|
|
|
|
|
2017-12-12 10:53:50 -06:00
|
|
|
let account = await AccountModel.loadByUrl(signatureObject.creator)
|
2017-11-09 10:51:58 -06:00
|
|
|
|
|
|
|
// We don't have this account in our database, fetch it on remote
|
|
|
|
if (!account) {
|
2017-11-21 06:43:29 -06:00
|
|
|
account = await fetchRemoteAccount(signatureObject.creator)
|
2017-11-09 10:51:58 -06:00
|
|
|
|
2017-11-21 06:43:29 -06:00
|
|
|
if (!account) {
|
2017-11-09 10:51:58 -06:00
|
|
|
return res.sendStatus(403)
|
|
|
|
}
|
|
|
|
|
2017-11-21 06:43:29 -06:00
|
|
|
// Save our new account and its server in database
|
|
|
|
await saveAccountAndServerIfNotExist(account)
|
2017-11-09 10:51:58 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
const verified = await isSignatureVerified(account, req.body)
|
|
|
|
if (verified === false) return res.sendStatus(403)
|
|
|
|
|
2017-11-14 10:31:26 -06:00
|
|
|
res.locals.signature = {
|
|
|
|
account
|
|
|
|
}
|
2017-11-09 10:51:58 -06:00
|
|
|
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
2017-11-14 10:31:26 -06:00
|
|
|
function executeIfActivityPub (fun: RequestHandler | RequestHandler[]) {
|
2017-11-09 10:51:58 -06:00
|
|
|
return (req: Request, res: Response, next: NextFunction) => {
|
2017-11-30 06:37:11 -06:00
|
|
|
const accepted = req.accepts(ACCEPT_HEADERS)
|
|
|
|
if (accepted === false || ACTIVITY_PUB.POTENTIAL_ACCEPT_HEADERS.indexOf(accepted) === -1) {
|
2017-11-09 10:51:58 -06:00
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
2017-11-29 04:34:44 -06:00
|
|
|
logger.debug('ActivityPub request for %s.', req.url)
|
|
|
|
|
2017-11-09 10:51:58 -06:00
|
|
|
if (Array.isArray(fun) === true) {
|
2017-11-14 10:31:26 -06:00
|
|
|
return eachSeries(fun as RequestHandler[], (f, cb) => {
|
|
|
|
f(req, res, cb)
|
|
|
|
}, next)
|
2017-11-09 10:51:58 -06:00
|
|
|
}
|
|
|
|
|
2017-11-14 10:31:26 -06:00
|
|
|
return (fun as RequestHandler)(req, res, next)
|
2017-11-09 10:51:58 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
|
|
|
checkSignature,
|
|
|
|
executeIfActivityPub
|
|
|
|
}
|