PeerTube/server/middlewares/activitypub.ts

60 lines
1.7 KiB
TypeScript
Raw Normal View History

2017-11-14 10:31:26 -06:00
import { NextFunction, Request, Response, RequestHandler } 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-11-15 04:00:25 -06:00
import { fetchRemoteAccountAndCreateServer } from '../helpers/activitypub'
2017-11-14 10:31:26 -06:00
import { database as db, ACTIVITY_PUB_ACCEPT_HEADER } from '../initializers'
import { each, eachSeries, waterfall } from 'async'
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)
let account = await db.Account.loadByUrl(signatureObject.creator)
// We don't have this account in our database, fetch it on remote
if (!account) {
2017-11-15 04:00:25 -06:00
const accountResult = await fetchRemoteAccountAndCreateServer(signatureObject.creator)
2017-11-09 10:51:58 -06:00
2017-11-14 10:31:26 -06:00
if (!accountResult) {
2017-11-09 10:51:58 -06:00
return res.sendStatus(403)
}
// Save our new account in database
2017-11-14 10:31:26 -06:00
account = accountResult.account
2017-11-09 10:51:58 -06:00
await account.save()
}
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-14 10:31:26 -06:00
if (req.header('Accept') !== ACTIVITY_PUB_ACCEPT_HEADER) {
2017-11-09 10:51:58 -06:00
return next()
}
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
}