server_matrix.go 6.9 KB

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