29bec0c974d13a90d147ee849c3261e5c2f430b0
[oweals/peertube.git] / server / middlewares / activitypub.ts
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 { database as db } from '../initializers'
6 import { ACTIVITY_PUB } from '../initializers/constants'
7 import { fetchRemoteAccountAndCreateServer } from '../lib/activitypub/account'
8
9 async function checkSignature (req: Request, res: Response, next: NextFunction) {
10   const signatureObject: ActivityPubSignature = req.body.signature
11
12   logger.debug('Checking signature of account %s...', signatureObject.creator)
13
14   let account = await db.Account.loadByUrl(signatureObject.creator)
15
16   // We don't have this account in our database, fetch it on remote
17   if (!account) {
18     const accountResult = await fetchRemoteAccountAndCreateServer(signatureObject.creator)
19
20     if (!accountResult) {
21       return res.sendStatus(403)
22     }
23
24     // Save our new account in database
25     account = accountResult.account
26     await account.save()
27   }
28
29   const verified = await isSignatureVerified(account, req.body)
30   if (verified === false) return res.sendStatus(403)
31
32   res.locals.signature = {
33     account
34   }
35
36   return next()
37 }
38
39 function executeIfActivityPub (fun: RequestHandler | RequestHandler[]) {
40   return (req: Request, res: Response, next: NextFunction) => {
41     if (req.header('Accept') !== ACTIVITY_PUB.ACCEPT_HEADER) {
42       return next()
43     }
44
45     if (Array.isArray(fun) === true) {
46       return eachSeries(fun as RequestHandler[], (f, cb) => {
47         f(req, res, cb)
48       }, next)
49     }
50
51     return (fun as RequestHandler)(req, res, next)
52   }
53 }
54
55 // ---------------------------------------------------------------------------
56
57 export {
58   checkSignature,
59   executeIfActivityPub
60 }