2018-01-25 09:05:18 -05:00
|
|
|
import { buildSignedActivity } from '../../../../helpers/activitypub'
|
|
|
|
import { getServerActor } from '../../../../helpers/utils'
|
|
|
|
import { ActorModel } from '../../../../models/activitypub/actor'
|
2018-10-10 02:51:58 -04:00
|
|
|
import { sha256 } from '../../../../helpers/core-utils'
|
2018-10-19 05:41:19 -04:00
|
|
|
import { HTTP_SIGNATURE } from '../../../../initializers'
|
2018-01-25 09:05:18 -05:00
|
|
|
|
2018-10-10 02:51:58 -04:00
|
|
|
type Payload = { body: any, signatureActorId?: number }
|
|
|
|
|
|
|
|
async function computeBody (payload: Payload) {
|
2018-01-25 09:05:18 -05:00
|
|
|
let body = payload.body
|
|
|
|
|
|
|
|
if (payload.signatureActorId) {
|
|
|
|
const actorSignature = await ActorModel.load(payload.signatureActorId)
|
|
|
|
if (!actorSignature) throw new Error('Unknown signature actor id.')
|
|
|
|
body = await buildSignedActivity(actorSignature, payload.body)
|
|
|
|
}
|
|
|
|
|
|
|
|
return body
|
|
|
|
}
|
|
|
|
|
2018-10-10 02:51:58 -04:00
|
|
|
async function buildSignedRequestOptions (payload: Payload) {
|
2018-07-25 16:01:25 -04:00
|
|
|
let actor: ActorModel | null
|
2018-01-25 09:05:18 -05:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
|
|
|
|
const keyId = actor.getWebfingerUrl()
|
|
|
|
return {
|
2018-10-19 05:41:19 -04:00
|
|
|
algorithm: HTTP_SIGNATURE.ALGORITHM,
|
|
|
|
authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME,
|
2018-01-25 09:05:18 -05:00
|
|
|
keyId,
|
2018-10-10 02:51:58 -04:00
|
|
|
key: actor.privateKey,
|
2018-10-19 05:41:19 -04:00
|
|
|
headers: HTTP_SIGNATURE.HEADERS_TO_SIGN
|
2018-10-10 02:51:58 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-23 05:38:48 -04:00
|
|
|
function buildGlobalHeaders (body: any) {
|
2018-10-10 02:51:58 -04:00
|
|
|
return {
|
2018-10-23 05:38:48 -04:00
|
|
|
'Digest': buildDigest(body)
|
2018-01-25 09:05:18 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-23 05:38:48 -04:00
|
|
|
function buildDigest (body: any) {
|
|
|
|
const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
|
|
|
|
|
|
|
|
return 'SHA-256=' + sha256(rawBody, 'base64')
|
|
|
|
}
|
|
|
|
|
2018-01-25 09:05:18 -05:00
|
|
|
export {
|
2018-10-23 05:38:48 -04:00
|
|
|
buildDigest,
|
2018-10-10 02:51:58 -04:00
|
|
|
buildGlobalHeaders,
|
2018-01-25 09:05:18 -05:00
|
|
|
computeBody,
|
|
|
|
buildSignedRequestOptions
|
|
|
|
}
|