1 import { eachSeries } from 'async'
2 import { NextFunction, Request, RequestHandler, Response } from 'express'
3 import { ActivityPubSignature } from '../../shared'
4 import { isSignatureVerified, logger } from '../helpers'
5 import { ACCEPT_HEADERS, ACTIVITY_PUB } from '../initializers'
6 import { fetchRemoteAccount, saveAccountAndServerIfNotExist } from '../lib/activitypub'
7 import { AccountModel } from '../models/account/account'
9 async function checkSignature (req: Request, res: Response, next: NextFunction) {
10 const signatureObject: ActivityPubSignature = req.body.signature
12 logger.debug('Checking signature of account %s...', signatureObject.creator)
14 let account = await AccountModel.loadByUrl(signatureObject.creator)
16 // We don't have this account in our database, fetch it on remote
18 account = await fetchRemoteAccount(signatureObject.creator)
21 return res.sendStatus(403)
24 // Save our new account and its server in database
25 await saveAccountAndServerIfNotExist(account)
28 const verified = await isSignatureVerified(account, req.body)
29 if (verified === false) return res.sendStatus(403)
31 res.locals.signature = {
38 function executeIfActivityPub (fun: RequestHandler | RequestHandler[]) {
39 return (req: Request, res: Response, next: NextFunction) => {
40 const accepted = req.accepts(ACCEPT_HEADERS)
41 if (accepted === false || ACTIVITY_PUB.POTENTIAL_ACCEPT_HEADERS.indexOf(accepted) === -1) {
45 logger.debug('ActivityPub request for %s.', req.url)
47 if (Array.isArray(fun) === true) {
48 return eachSeries(fun as RequestHandler[], (f, cb) => {
53 return (fun as RequestHandler)(req, res, next)
57 // ---------------------------------------------------------------------------