]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
598edb8a 1import { buildSignedActivity, ContextType } from '../../../../helpers/activitypub'
94a5ff8a
C
2import { getServerActor } from '../../../../helpers/utils'
3import { ActorModel } from '../../../../models/activitypub/actor'
729bb184 4import { sha256 } from '../../../../helpers/core-utils'
84ebcf34 5import { ACTIVITY_PUB, HTTP_SIGNATURE } from '../../../../initializers/constants'
453e83ea 6import { MActor } from '../../../../typings/models'
94a5ff8a 7
598edb8a 8type Payload = { body: any, contextType?: ContextType, signatureActorId?: number }
729bb184
C
9
10async function computeBody (payload: Payload) {
94a5ff8a
C
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.')
598edb8a 16 body = await buildSignedActivity(actorSignature, payload.body, payload.contextType)
94a5ff8a
C
17 }
18
19 return body
20}
21
729bb184 22async function buildSignedRequestOptions (payload: Payload) {
453e83ea
C
23 let actor: MActor | null
24
94a5ff8a
C
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
c28bcdd1 33 const keyId = actor.url
94a5ff8a 34 return {
41f2ebae
C
35 algorithm: HTTP_SIGNATURE.ALGORITHM,
36 authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME,
94a5ff8a 37 keyId,
729bb184 38 key: actor.privateKey,
41f2ebae 39 headers: HTTP_SIGNATURE.HEADERS_TO_SIGN
729bb184
C
40 }
41}
42
df66d815 43function buildGlobalHeaders (body: any) {
729bb184 44 return {
84ebcf34
C
45 'Digest': buildDigest(body),
46 'Content-Type': 'application/activity+json',
47 'Accept': ACTIVITY_PUB.ACCEPT_HEADER
94a5ff8a
C
48 }
49}
50
df66d815
C
51function buildDigest (body: any) {
52 const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
53
54 return 'SHA-256=' + sha256(rawBody, 'base64')
55}
56
94a5ff8a 57export {
df66d815 58 buildDigest,
729bb184 59 buildGlobalHeaders,
94a5ff8a
C
60 computeBody,
61 buildSignedRequestOptions
62}