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 { fetchRemoteAccountAndCreateServer } from '../helpers/activitypub'
6 import { database as db } from '../initializers'
7 import { ACTIVITY_PUB } from '../initializers/constants'
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 db.Account.loadByUrl(signatureObject.creator)
16 // We don't have this account in our database, fetch it on remote
18 const accountResult = await fetchRemoteAccountAndCreateServer(signatureObject.creator)
21 return res.sendStatus(403)
24 // Save our new account in database
25 account = accountResult.account
29 const verified = await isSignatureVerified(account, req.body)
30 if (verified === false) return res.sendStatus(403)
32 res.locals.signature = {
39 function executeIfActivityPub (fun: RequestHandler | RequestHandler[]) {
40 return (req: Request, res: Response, next: NextFunction) => {
41 if (req.header('Accept') !== ACTIVITY_PUB.ACCEPT_HEADER) {
45 if (Array.isArray(fun) === true) {
46 return eachSeries(fun as RequestHandler[], (f, cb) => {
51 return (fun as RequestHandler)(req, res, next)
55 // ---------------------------------------------------------------------------