]>
Commit | Line | Data |
---|---|---|
a219c910 C |
1 | import { buildDigest, signJsonLDObject } from '@server/helpers/peertube-crypto' |
2 | import { ACTIVITY_PUB, HTTP_SIGNATURE } from '@server/initializers/constants' | |
3 | import { ActorModel } from '@server/models/actor/actor' | |
7d9ba5c0 | 4 | import { getServerActor } from '@server/models/application/application' |
a219c910 | 5 | import { MActor } from '@server/types/models' |
7d9ba5c0 | 6 | import { ContextType } from '@shared/models/activitypub/context' |
a219c910 | 7 | import { activityPubContextify } from '../context' |
94a5ff8a | 8 | |
a219c910 | 9 | type Payload <T> = { body: T, contextType: ContextType, signatureActorId?: number } |
729bb184 | 10 | |
db4b15f2 C |
11 | async function computeBody <T> ( |
12 | payload: Payload<T> | |
13 | ): Promise<T | T & { type: 'RsaSignature2017', creator: string, created: string }> { | |
94a5ff8a C |
14 | let body = payload.body |
15 | ||
16 | if (payload.signatureActorId) { | |
17 | const actorSignature = await ActorModel.load(payload.signatureActorId) | |
18 | if (!actorSignature) throw new Error('Unknown signature actor id.') | |
db4b15f2 | 19 | |
a219c910 | 20 | body = await signAndContextify(actorSignature, payload.body, payload.contextType) |
94a5ff8a C |
21 | } |
22 | ||
23 | return body | |
24 | } | |
25 | ||
db4b15f2 | 26 | async function buildSignedRequestOptions (payload: Payload<any>) { |
453e83ea C |
27 | let actor: MActor | null |
28 | ||
94a5ff8a C |
29 | if (payload.signatureActorId) { |
30 | actor = await ActorModel.load(payload.signatureActorId) | |
31 | if (!actor) throw new Error('Unknown signature actor id.') | |
32 | } else { | |
33 | // We need to sign the request, so use the server | |
34 | actor = await getServerActor() | |
35 | } | |
36 | ||
c28bcdd1 | 37 | const keyId = actor.url |
94a5ff8a | 38 | return { |
41f2ebae C |
39 | algorithm: HTTP_SIGNATURE.ALGORITHM, |
40 | authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME, | |
94a5ff8a | 41 | keyId, |
729bb184 | 42 | key: actor.privateKey, |
41f2ebae | 43 | headers: HTTP_SIGNATURE.HEADERS_TO_SIGN |
729bb184 C |
44 | } |
45 | } | |
46 | ||
df66d815 | 47 | function buildGlobalHeaders (body: any) { |
729bb184 | 48 | return { |
e7053b1d C |
49 | 'digest': buildDigest(body), |
50 | 'content-type': 'application/activity+json', | |
51 | 'accept': ACTIVITY_PUB.ACCEPT_HEADER | |
94a5ff8a C |
52 | } |
53 | } | |
54 | ||
a219c910 C |
55 | function signAndContextify <T> (byActor: MActor, data: T, contextType: ContextType | null) { |
56 | const activity = contextType | |
57 | ? activityPubContextify(data, contextType) | |
58 | : data | |
59 | ||
60 | return signJsonLDObject(byActor, activity) | |
61 | } | |
62 | ||
94a5ff8a | 63 | export { |
729bb184 | 64 | buildGlobalHeaders, |
94a5ff8a | 65 | computeBody, |
a219c910 C |
66 | buildSignedRequestOptions, |
67 | signAndContextify | |
94a5ff8a | 68 | } |