Debian Codegraph @

server/server_matrix.go

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