]>
Commit | Line | Data |
---|---|---|
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 { fetchRemoteAccount, saveAccountAndServerIfNotExist } 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 | account = await fetchRemoteAccount(signatureObject.creator) | |
19 | ||
20 | if (!account) { | |
21 | return res.sendStatus(403) | |
22 | } | |
23 | ||
24 | // Save our new account and its server in database | |
25 | await saveAccountAndServerIfNotExist(account) | |
26 | } | |
27 | ||
28 | const verified = await isSignatureVerified(account, req.body) | |
29 | if (verified === false) return res.sendStatus(403) | |
30 | ||
31 | res.locals.signature = { | |
32 | account | |
33 | } | |
34 | ||
35 | return next() | |
36 | } | |
37 | ||
38 | function executeIfActivityPub (fun: RequestHandler | RequestHandler[]) { | |
39 | return (req: Request, res: Response, next: NextFunction) => { | |
40 | if (req.accepts(ACTIVITY_PUB.POTENTIAL_ACCEPT_HEADERS) === false) { | |
41 | return next() | |
42 | } | |
43 | ||
44 | logger.debug('ActivityPub request for %s.', req.url) | |
45 | ||
46 | if (Array.isArray(fun) === true) { | |
47 | return eachSeries(fun as RequestHandler[], (f, cb) => { | |
48 | f(req, res, cb) | |
49 | }, next) | |
50 | } | |
51 | ||
52 | return (fun as RequestHandler)(req, res, next) | |
53 | } | |
54 | } | |
55 | ||
56 | // --------------------------------------------------------------------------- | |
57 | ||
58 | export { | |
59 | checkSignature, | |
60 | executeIfActivityPub | |
61 | } |