]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/lib/job-queue/handlers/utils/activitypub-http-utils.ts
Begin auth plugin support
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / utils / activitypub-http-utils.ts
... / ...
CommitLineData
1import { buildSignedActivity, ContextType } from '../../../../helpers/activitypub'
2import { getServerActor } from '../../../../helpers/utils'
3import { ActorModel } from '../../../../models/activitypub/actor'
4import { sha256 } from '../../../../helpers/core-utils'
5import { ACTIVITY_PUB, HTTP_SIGNATURE } from '../../../../initializers/constants'
6import { MActor } from '../../../../typings/models'
7
8type Payload = { body: any, contextType?: ContextType, signatureActorId?: number }
9
10async 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, payload.contextType)
17 }
18
19 return body
20}
21
22async 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
43function buildGlobalHeaders (body: any) {
44 return {
45 'Digest': buildDigest(body),
46 'Content-Type': 'application/activity+json',
47 'Accept': ACTIVITY_PUB.ACCEPT_HEADER
48 }
49}
50
51function buildDigest (body: any) {
52 const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
53
54 return 'SHA-256=' + sha256(rawBody, 'base64')
55}
56
57export {
58 buildDigest,
59 buildGlobalHeaders,
60 computeBody,
61 buildSignedRequestOptions
62}