server_matrix.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "heckel.io/ntfy/util"
  7. "io"
  8. "net/http"
  9. "strings"
  10. )
  11. // Matrix Push Gateway / UnifiedPush / ntfy integration:
  12. //
  13. // ntfy implements a Matrix Push Gateway (as defined in https://spec.matrix.org/v1.2/push-gateway-api/),
  14. // in combination with UnifiedPush as the Provider Push Protocol (as defined in https://unifiedpush.org/developers/gateway/).
  15. //
  16. // In the picture below, ntfy is the Push Gateway (mostly in this file), as well as the Push Provider (ntfy's
  17. // main functionality). UnifiedPush is the Provider Push Protocol, as implemented by the ntfy server and the
  18. // ntfy Android app.
  19. //
  20. // +--------------------+ +-------------------+
  21. // Matrix HTTP | | | |
  22. // Notification Protocol | App Developer | | Device Vendor |
  23. // | | | |
  24. // +-------------------+ | +----------------+ | | +---------------+ |
  25. // | | | | | | | | | |
  26. // | Matrix homeserver +-----> Push Gateway +------> Push Provider | |
  27. // | | | | | | | | | |
  28. // +-^-----------------+ | +----------------+ | | +----+----------+ |
  29. // | | | | | |
  30. // Matrix | | | | | |
  31. // Client/Server API + | | | | |
  32. // | | +--------------------+ +-------------------+
  33. // | +--+-+ |
  34. // | | <-------------------------------------------+
  35. // +---+ |
  36. // | | Provider Push Protocol
  37. // +----+
  38. //
  39. // Mobile Device or Client
  40. //
  41. // matrixRequest represents a Matrix message, as it is sent to a Push Gateway (as per
  42. // this spec: https://spec.matrix.org/v1.2/push-gateway-api/).
  43. //
  44. // From the message, we only require the "pushkey", as it represents our target topic URL.
  45. // A message may look like this (excerpt):
  46. //
  47. // {
  48. // "notification": {
  49. // "devices": [
  50. // {
  51. // "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1",
  52. // ...
  53. // }
  54. // ]
  55. // }
  56. // }
  57. type matrixRequest struct {
  58. Notification *struct {
  59. Devices []*struct {
  60. PushKey string `json:"pushkey"`
  61. } `json:"devices"`
  62. } `json:"notification"`
  63. }
  64. // matrixResponse represents the response to a Matrix push gateway message, as defined
  65. // in the spec (https://spec.matrix.org/v1.2/push-gateway-api/).
  66. type matrixResponse struct {
  67. Rejected []string `json:"rejected"`
  68. }
  69. // errMatrixPushkeyRejected represents an error when handing Matrix gateway messages
  70. //
  71. // If the push key is set, the app server will remove it and will never send messages using the same
  72. // push key again, until the user repairs it.
  73. type errMatrixPushkeyRejected struct {
  74. rejectedPushKey string
  75. configuredBaseURL string
  76. }
  77. func (e errMatrixPushkeyRejected) Error() string {
  78. return fmt.Sprintf("push key must be prefixed with base URL, received push key: %s, configured base URL: %s", e.rejectedPushKey, e.configuredBaseURL)
  79. }
  80. // newRequestFromMatrixJSON reads the request body as a Matrix JSON message, parses the "pushkey", and creates a new
  81. // HTTP request that looks like a normal ntfy request from it.
  82. //
  83. // It basically converts a Matrix push gatewqy request:
  84. //
  85. // POST /_matrix/push/v1/notify HTTP/1.1
  86. // { "notification": { "devices": [ { "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1", ... } ] } }
  87. //
  88. // to a ntfy request, looking like this:
  89. //
  90. // POST /upDAHJKFFDFD?up=1 HTTP/1.1
  91. // { "notification": { "devices": [ { "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1", ... } ] } }
  92. func newRequestFromMatrixJSON(r *http.Request, baseURL string, messageLimit int) (*http.Request, error) {
  93. if baseURL == "" {
  94. return nil, errHTTPInternalErrorMissingBaseURL
  95. }
  96. body, err := util.Peek(r.Body, messageLimit)
  97. if err != nil {
  98. return nil, err
  99. }
  100. defer r.Body.Close()
  101. if body.LimitReached {
  102. return nil, errHTTPEntityTooLargeMatrixRequest
  103. }
  104. var m matrixRequest
  105. if err := json.Unmarshal(body.PeekedBytes, &m); err != nil {
  106. return nil, errHTTPBadRequestMatrixMessageInvalid
  107. } else if m.Notification == nil || len(m.Notification.Devices) == 0 || m.Notification.Devices[0].PushKey == "" {
  108. return nil, errHTTPBadRequestMatrixMessageInvalid
  109. }
  110. pushKey := m.Notification.Devices[0].PushKey // We ignore other devices for now, see discussion in #316
  111. if !strings.HasPrefix(pushKey, baseURL+"/") {
  112. return nil, &errMatrixPushkeyRejected{rejectedPushKey: pushKey, configuredBaseURL: baseURL}
  113. }
  114. newRequest, err := http.NewRequest(http.MethodPost, pushKey, io.NopCloser(bytes.NewReader(body.PeekedBytes)))
  115. if err != nil {
  116. return nil, err
  117. }
  118. newRequest.RemoteAddr = r.RemoteAddr // Not strictly necessary, since visitor was already extracted
  119. if r.Header.Get("X-Forwarded-For") != "" {
  120. newRequest.Header.Set("X-Forwarded-For", r.Header.Get("X-Forwarded-For"))
  121. }
  122. return newRequest, nil
  123. }
  124. // writeMatrixDiscoveryResponse writes the UnifiedPush Matrix Gateway Discovery response to the given http.ResponseWriter,
  125. // as per the spec (https://unifiedpush.org/developers/gateway/).
  126. func writeMatrixDiscoveryResponse(w http.ResponseWriter) error {
  127. w.Header().Set("Content-Type", "application/json")
  128. _, err := io.WriteString(w, `{"unifiedpush":{"gateway":"matrix"}}`+"\n")
  129. return err
  130. }
  131. // writeMatrixSuccess writes a successful matrixResponse (no rejected push key) to the given http.ResponseWriter
  132. func writeMatrixSuccess(w http.ResponseWriter) error {
  133. return writeMatrixResponse(w, "")
  134. }
  135. // writeMatrixResponse writes a matrixResponse to the given http.ResponseWriter, as defined in
  136. // the spec (https://spec.matrix.org/v1.2/push-gateway-api/)
  137. func writeMatrixResponse(w http.ResponseWriter, rejectedPushKey string) error {
  138. rejected := make([]string, 0)
  139. if rejectedPushKey != "" {
  140. rejected = append(rejected, rejectedPushKey)
  141. }
  142. response := &matrixResponse{
  143. Rejected: rejected,
  144. }
  145. w.Header().Set("Content-Type", "application/json")
  146. if err := json.NewEncoder(w).Encode(response); err != nil {
  147. return err
  148. }
  149. return nil
  150. }