1 import { NextFunction, Request, Response } from 'express'
2 import { ActivityPubSignature } from '../../shared'
3 import { logger } from '../helpers/logger'
4 import { isHTTPSignatureVerified, isJsonLDSignatureVerified, parseHTTPSignature } from '../helpers/peertube-crypto'
5 import { ACCEPT_HEADERS, ACTIVITY_PUB, HTTP_SIGNATURE } from '../initializers/constants'
6 import { getOrCreateActorAndServerAndModel } from '../lib/activitypub'
7 import { loadActorUrlOrGetFromWebfinger } from '../helpers/webfinger'
9 async function checkSignature (req: Request, res: Response, next: NextFunction) {
11 const httpSignatureChecked = await checkHttpSignature(req, res)
12 if (httpSignatureChecked !== true) return
14 const actor = res.locals.signature.actor
17 const bodyActor = req.body.actor
18 const bodyActorId = bodyActor && bodyActor.id ? bodyActor.id : bodyActor
19 if (bodyActorId && bodyActorId !== actor.url) {
20 const jsonLDSignatureChecked = await checkJsonLDSignature(req, res)
21 if (jsonLDSignatureChecked !== true) return
26 logger.error('Error in ActivityPub signature checker.', err)
27 return res.sendStatus(403)
31 function executeIfActivityPub (req: Request, res: Response, next: NextFunction) {
32 const accepted = req.accepts(ACCEPT_HEADERS)
33 if (accepted === false || ACTIVITY_PUB.POTENTIAL_ACCEPT_HEADERS.indexOf(accepted) === -1) {
38 logger.debug('ActivityPub request for %s.', req.url)
43 // ---------------------------------------------------------------------------
51 // ---------------------------------------------------------------------------
53 async function checkHttpSignature (req: Request, res: Response) {
54 // FIXME: mastodon does not include the Signature scheme
55 const sig = req.headers[HTTP_SIGNATURE.HEADER_NAME] as string
56 if (sig && sig.startsWith('Signature ') === false) req.headers[HTTP_SIGNATURE.HEADER_NAME] = 'Signature ' + sig
58 const parsed = parseHTTPSignature(req)
60 const keyId = parsed.keyId
66 logger.debug('Checking HTTP signature of actor %s...', keyId)
68 let [ actorUrl ] = keyId.split('#')
69 if (actorUrl.startsWith('acct:')) {
70 actorUrl = await loadActorUrlOrGetFromWebfinger(actorUrl.replace(/^acct:/, ''))
73 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
75 const verified = isHTTPSignatureVerified(parsed, actor)
76 if (verified !== true) {
77 logger.warn('Signature from %s is invalid', actorUrl, { parsed })
83 res.locals.signature = { actor }
88 async function checkJsonLDSignature (req: Request, res: Response) {
89 const signatureObject: ActivityPubSignature = req.body.signature
91 if (!signatureObject || !signatureObject.creator) {
96 const [ creator ] = signatureObject.creator.split('#')
98 logger.debug('Checking JsonLD signature of actor %s...', creator)
100 const actor = await getOrCreateActorAndServerAndModel(creator)
101 const verified = await isJsonLDSignatureVerified(actor, req.body)
103 if (verified !== true) {
108 res.locals.signature = { actor }