message.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package hub
  2. import (
  3. "github.com/mudler/edgevpn/pkg/utils"
  4. "github.com/pkg/errors"
  5. )
  6. // Message gets converted to/from JSON and sent in the body of pubsub messages.
  7. type Message struct {
  8. Message string
  9. SenderID string
  10. Annotations map[string]string
  11. }
  12. type MessageOption func(cfg *Message) error
  13. // Apply applies the given options to the config, returning the first error
  14. // encountered (if any).
  15. func (m *Message) Apply(opts ...MessageOption) error {
  16. for _, opt := range opts {
  17. if opt == nil {
  18. continue
  19. }
  20. if err := opt(m); err != nil {
  21. return err
  22. }
  23. }
  24. return nil
  25. }
  26. func NewMessage(s string) *Message {
  27. return &Message{Message: s}
  28. }
  29. func (m *Message) Seal(key string) error {
  30. enckey := [32]byte{}
  31. copy(enckey[:], key)
  32. enc, err := utils.AESEncrypt(m.Message, &enckey)
  33. if err != nil {
  34. return errors.Wrap(err, "while sealing message")
  35. }
  36. m.Message = enc
  37. return nil
  38. }
  39. func (m *Message) Unseal(key string) error {
  40. enckey := [32]byte{}
  41. copy(enckey[:], key)
  42. dec, err := utils.AESDecrypt(m.Message, &enckey)
  43. if err != nil {
  44. return errors.Wrapf(err, "while unsealing message from peer: %s", m.SenderID)
  45. }
  46. m.Message = dec
  47. return nil
  48. }
  49. func (m *Message) Copy() *Message {
  50. copy := *m
  51. return &copy
  52. }
  53. func (m *Message) WithMessage(s string) *Message {
  54. copy := m.Copy()
  55. copy.Message = s
  56. return copy
  57. }