Move to eslint
[oweals/peertube.git] / server / lib / job-queue / handlers / utils / activitypub-http-utils.ts
1 import { buildSignedActivity } from '../../../../helpers/activitypub'
2 import { getServerActor } from '../../../../helpers/utils'
3 import { ActorModel } from '../../../../models/activitypub/actor'
4 import { sha256 } from '../../../../helpers/core-utils'
5 import { HTTP_SIGNATURE } from '../../../../initializers/constants'
6 import { MActor } from '../../../../typings/models'
7
8 type Payload = { body: any, signatureActorId?: number }
9
10 async function computeBody (payload: Payload) {
11   let body = payload.body
12
13   if (payload.signatureActorId) {
14     const actorSignature = await ActorModel.load(payload.signatureActorId)
15     if (!actorSignature) throw new Error('Unknown signature actor id.')
16     body = await buildSignedActivity(actorSignature, payload.body)
17   }
18
19   return body
20 }
21
22 async function buildSignedRequestOptions (payload: Payload) {
23   let actor: MActor | null
24
25   if (payload.signatureActorId) {
26     actor = await ActorModel.load(payload.signatureActorId)
27     if (!actor) throw new Error('Unknown signature actor id.')
28   } else {
29     // We need to sign the request, so use the server
30     actor = await getServerActor()
31   }
32
33   const keyId = actor.url
34   return {
35     algorithm: HTTP_SIGNATURE.ALGORITHM,
36     authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME,
37     keyId,
38     key: actor.privateKey,
39     headers: HTTP_SIGNATURE.HEADERS_TO_SIGN
40   }
41 }
42
43 function buildGlobalHeaders (body: any) {
44   return {
45     Digest: buildDigest(body)
46   }
47 }
48
49 function buildDigest (body: any) {
50   const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
51
52   return 'SHA-256=' + sha256(rawBody, 'base64')
53 }
54
55 export {
56   buildDigest,
57   buildGlobalHeaders,
58   computeBody,
59   buildSignedRequestOptions
60 }