PeerTube/server/lib/activitypub/send/http.ts

69 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-03-23 16:14:33 +01:00
import { buildDigest, signJsonLDObject } from '@server/helpers/peertube-crypto'
import { ACTIVITY_PUB, HTTP_SIGNATURE } from '@server/initializers/constants'
import { ActorModel } from '@server/models/actor/actor'
2021-05-11 11:15:29 +02:00
import { getServerActor } from '@server/models/application/application'
2022-03-23 16:14:33 +01:00
import { MActor } from '@server/types/models'
2021-05-11 11:15:29 +02:00
import { ContextType } from '@shared/models/activitypub/context'
2022-03-23 16:14:33 +01:00
import { activityPubContextify } from '../context'
2022-03-23 16:14:33 +01:00
type Payload <T> = { body: T, contextType: ContextType, signatureActorId?: number }
2018-10-10 08:51:58 +02:00
2021-03-08 14:24:11 +01:00
async function computeBody <T> (
payload: Payload<T>
): Promise<T | T & { type: 'RsaSignature2017', creator: string, created: string }> {
let body = payload.body
if (payload.signatureActorId) {
const actorSignature = await ActorModel.load(payload.signatureActorId)
if (!actorSignature) throw new Error('Unknown signature actor id.')
2021-03-08 14:24:11 +01:00
2022-03-23 16:14:33 +01:00
body = await signAndContextify(actorSignature, payload.body, payload.contextType)
}
return body
}
2021-03-08 14:24:11 +01:00
async function buildSignedRequestOptions (payload: Payload<any>) {
2019-08-15 11:53:26 +02:00
let actor: MActor | null
if (payload.signatureActorId) {
actor = await ActorModel.load(payload.signatureActorId)
if (!actor) throw new Error('Unknown signature actor id.')
} else {
// We need to sign the request, so use the server
actor = await getServerActor()
}
2019-04-25 15:19:53 +02:00
const keyId = actor.url
return {
algorithm: HTTP_SIGNATURE.ALGORITHM,
authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME,
keyId,
2018-10-10 08:51:58 +02:00
key: actor.privateKey,
headers: HTTP_SIGNATURE.HEADERS_TO_SIGN
2018-10-10 08:51:58 +02:00
}
}
function buildGlobalHeaders (body: any) {
2018-10-10 08:51:58 +02:00
return {
2021-03-10 11:17:20 +01:00
'digest': buildDigest(body),
'content-type': 'application/activity+json',
'accept': ACTIVITY_PUB.ACCEPT_HEADER
}
}
2022-03-23 16:14:33 +01:00
function signAndContextify <T> (byActor: MActor, data: T, contextType: ContextType | null) {
const activity = contextType
? activityPubContextify(data, contextType)
: data
return signJsonLDObject(byActor, activity)
}
export {
2018-10-10 08:51:58 +02:00
buildGlobalHeaders,
computeBody,
2022-03-23 16:14:33 +01:00
buildSignedRequestOptions,
signAndContextify
}