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'
7 type Payload = { body: any, signatureActorId?: number }
9 async function computeBody (payload: Payload) {
10 let body = payload.body
12 if (payload.signatureActorId) {
13 const actorSignature = await ActorModel.load(payload.signatureActorId)
14 if (!actorSignature) throw new Error('Unknown signature actor id.')
15 body = await buildSignedActivity(actorSignature, payload.body)
21 async function buildSignedRequestOptions (payload: Payload) {
22 let actor: ActorModel | null
23 if (payload.signatureActorId) {
24 actor = await ActorModel.load(payload.signatureActorId)
25 if (!actor) throw new Error('Unknown signature actor id.')
27 // We need to sign the request, so use the server
28 actor = await getServerActor()
31 const keyId = actor.url
33 algorithm: HTTP_SIGNATURE.ALGORITHM,
34 authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME,
36 key: actor.privateKey,
37 headers: HTTP_SIGNATURE.HEADERS_TO_SIGN
41 function buildGlobalHeaders (body: any) {
43 'Digest': buildDigest(body)
47 function buildDigest (body: any) {
48 const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
50 return 'SHA-256=' + sha256(rawBody, 'base64')
57 buildSignedRequestOptions