server_matrix.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. // errMatrix represents an error when handing Matrix gateway messages
  70. type errMatrix struct {
  71. pushKey string
  72. err error
  73. }
  74. func (e errMatrix) Error() string {
  75. if e.err != nil {
  76. return fmt.Sprintf("message with push key %s rejected: %s", e.pushKey, e.err.Error())
  77. }
  78. return fmt.Sprintf("message with push key %s rejected", e.pushKey)
  79. }
  80. const (
  81. // matrixPushKeyHeader is a header that's used internally to pass the Matrix push key (from the matrixRequest)
  82. // along with the request. The push key is only used if an error occurs down the line.
  83. matrixPushKeyHeader = "X-Matrix-Pushkey"
  84. )
  85. // newRequestFromMatrixJSON reads the request body as a Matrix JSON message, parses the "pushkey", and creates a new
  86. // HTTP request that looks like a normal ntfy request from it.
  87. //
  88. // It basically converts a Matrix push gatewqy request:
  89. //
  90. // POST /_matrix/push/v1/notify HTTP/1.1
  91. // { "notification": { "devices": [ { "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1", ... } ] } }
  92. //
  93. // to a ntfy request, looking like this:
  94. //
  95. // POST /upDAHJKFFDFD?up=1 HTTP/1.1
  96. // { "notification": { "devices": [ { "pushkey": "https://ntfy.sh/upDAHJKFFDFD?up=1", ... } ] } }
  97. func newRequestFromMatrixJSON(r *http.Request, baseURL string, messageLimit int) (*http.Request, error) {
  98. if baseURL == "" {
  99. return nil, errHTTPInternalErrorMissingBaseURL
  100. }
  101. body, err := util.Peek(r.Body, messageLimit)
  102. if err != nil {
  103. return nil, err
  104. }
  105. defer r.Body.Close()
  106. if body.LimitReached {
  107. return nil, errHTTPEntityTooLargeMatrixRequest
  108. }
  109. var m matrixRequest
  110. if err := json.Unmarshal(body.PeekedBytes, &m); err != nil {
  111. return nil, errHTTPBadRequestMatrixMessageInvalid
  112. } else if m.Notification == nil || len(m.Notification.Devices) == 0 || m.Notification.Devices[0].PushKey == "" {
  113. return nil, errHTTPBadRequestMatrixMessageInvalid
  114. }
  115. pushKey := m.Notification.Devices[0].PushKey // We ignore other devices for now, see discussion in #316
  116. if !strings.HasPrefix(pushKey, baseURL+"/") {
  117. return nil, &errMatrix{pushKey: pushKey, err: wrapErrHTTP(errHTTPBadRequestMatrixPushkeyBaseURLMismatch, "received push key: %s, configured base URL: %s", pushKey, baseURL)}
  118. }
  119. newRequest, err := http.NewRequest(http.MethodPost, pushKey, io.NopCloser(bytes.NewReader(body.PeekedBytes)))
  120. if err != nil {
  121. return nil, &errMatrix{pushKey: pushKey, err: err}
  122. }
  123. newRequest.RemoteAddr = r.RemoteAddr // Not strictly necessary, since visitor was already extracted
  124. if r.Header.Get("X-Forwarded-For") != "" {
  125. newRequest.Header.Set("X-Forwarded-For", r.Header.Get("X-Forwarded-For"))
  126. }
  127. newRequest.Header.Set(matrixPushKeyHeader, pushKey)
  128. return newRequest, nil
  129. }
  130. // writeMatrixDiscoveryResponse writes the UnifiedPush Matrix Gateway Discovery response to the given http.ResponseWriter,
  131. // as per the spec (https://unifiedpush.org/developers/gateway/).
  132. func writeMatrixDiscoveryResponse(w http.ResponseWriter) error {
  133. w.Header().Set("Content-Type", "application/json")
  134. _, err := io.WriteString(w, `{"unifiedpush":{"gateway":"matrix"}}`+"\n")
  135. return err
  136. }
  137. // writeMatrixError logs and writes the errMatrix to the given http.ResponseWriter as a matrixResponse
  138. func writeMatrixError(w http.ResponseWriter, r *http.Request, v *visitor, err *errMatrix) error {
  139. logvr(v, r).Tag(tagMatrix).Err(err).Debug("Matrix gateway error")
  140. return writeMatrixResponse(w, err.pushKey)
  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. }