activitypub-http-utils.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { buildSignedActivity } from '../../../../helpers/activitypub'
  2. import { getServerActor } from '../../../../helpers/utils'
  3. import { ActorModel } from '../../../../models/activitypub/actor'
  4. import { sha256 } from '../../../../helpers/core-utils'
  5. import { HTTP_SIGNATURE } from '../../../../initializers/constants'
  6. type Payload = { body: any, signatureActorId?: number }
  7. async function computeBody (payload: Payload) {
  8. let body = payload.body
  9. if (payload.signatureActorId) {
  10. const actorSignature = await ActorModel.load(payload.signatureActorId)
  11. if (!actorSignature) throw new Error('Unknown signature actor id.')
  12. body = await buildSignedActivity(actorSignature, payload.body)
  13. }
  14. return body
  15. }
  16. async function buildSignedRequestOptions (payload: Payload) {
  17. let actor: ActorModel | null
  18. if (payload.signatureActorId) {
  19. actor = await ActorModel.load(payload.signatureActorId)
  20. if (!actor) throw new Error('Unknown signature actor id.')
  21. } else {
  22. // We need to sign the request, so use the server
  23. actor = await getServerActor()
  24. }
  25. const keyId = actor.url
  26. return {
  27. algorithm: HTTP_SIGNATURE.ALGORITHM,
  28. authorizationHeaderName: HTTP_SIGNATURE.HEADER_NAME,
  29. keyId,
  30. key: actor.privateKey,
  31. headers: HTTP_SIGNATURE.HEADERS_TO_SIGN
  32. }
  33. }
  34. function buildGlobalHeaders (body: any) {
  35. return {
  36. 'Digest': buildDigest(body)
  37. }
  38. }
  39. function buildDigest (body: any) {
  40. const rawBody = typeof body === 'string' ? body : JSON.stringify(body)
  41. return 'SHA-256=' + sha256(rawBody, 'base64')
  42. }
  43. export {
  44. buildDigest,
  45. buildGlobalHeaders,
  46. computeBody,
  47. buildSignedRequestOptions
  48. }