Repository navigation
Expand file tree
/
Copy pathwebpush.go
More file actions
328 lines (300 loc) · 9.64 KB
/
Copy pathwebpush.go
File metadata and controls
328 lines (300 loc) · 9.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package main
// Web Push (RFC 8030 / 8291 / 8292) sender for the soju.im/webpush
// IRCv3 extension.
//
// obbyircd owns the IRC-protocol half: the soju.im/webpush capability,
// the WEBPUSH REGISTER/UNREGISTER commands, the per-account subscription
// store, and the decision of *when* a push should fire. It does NOT do
// the encryption itself -- obbyircd's outbound HTTP path is strlen-based
// and would truncate the aes128gcm ciphertext at its first NUL byte.
//
// So obbyircd POSTs a small JSON blob (the subscription + the plaintext
// IRC line) to this backend, which owns the VAPID keypair and does the
// RFC 8291 encryption + delivery via webpush-go. The VAPID public key
// is exposed at /push/vapid-key so obbyircd can advertise it in the
// VAPID= ISUPPORT token at startup.
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"path/filepath"
"regexp"
"syscall"
"time"
webpush "github.com/SherClockHolmes/webpush-go"
)
var (
vapidPrivateKey string
vapidPublicKey string
vapidSubject string
)
type vapidKeyfile struct {
Private string `json:"private"`
Public string `json:"public"`
}
// vapidKeyPath returns where the VAPID keypair is persisted. Defaults
// to data/vapid.json, the directory the stack mounts as a volume, so the
// key survives a redeploy; override with VAPID_KEY_FILE.
func vapidKeyPath() string {
if p := os.Getenv("VAPID_KEY_FILE"); p != "" {
return p
}
return filepath.Join("data", "vapid.json")
}
// InitWebPush loads the VAPID keypair from disk, generating and
// persisting a fresh one on first run. The keypair must be stable
// across restarts: the public half is baked into every client's push
// subscription, so regenerating it would silently invalidate every
// existing subscription.
func InitWebPush() error {
path := vapidKeyPath()
k, err := readVAPIDKeyfile(path)
if errors.Is(err, fs.ErrNotExist) && os.Getenv("VAPID_KEY_FILE") == "" {
k, err = adoptLegacyVAPIDKeyfile(path)
}
switch {
case err == nil:
vapidPrivateKey, vapidPublicKey = k.Private, k.Public
case errors.Is(err, fs.ErrNotExist):
priv, pub, err := webpush.GenerateVAPIDKeys()
if err != nil {
return err
}
vapidPrivateKey, vapidPublicKey = priv, pub
if err := writeVAPIDKeyfile(path, vapidKeyfile{Private: priv, Public: pub}); err != nil {
return fmt.Errorf("persist VAPID keyfile %s: %w", path, err)
}
log.Printf("webpush: generated new VAPID keypair -> %s", path)
default:
return err
}
// VAPID 'sub' claim: a mailto: or https URL identifying the sender,
// shown to push services for abuse contact.
vapidSubject = os.Getenv("VAPID_SUBJECT")
if vapidSubject == "" {
vapidSubject = "mailto:admin@obby.t3ks.com"
}
log.Printf("webpush: ready (VAPID public key %s…)", truncForLog(vapidPublicKey, 12))
return nil
}
func readVAPIDKeyfile(path string) (vapidKeyfile, error) {
var k vapidKeyfile
data, err := os.ReadFile(path)
if err != nil {
return k, err
}
if err := json.Unmarshal(data, &k); err != nil {
return k, fmt.Errorf("unreadable VAPID keyfile %s, fix or remove it: %w", path, err)
}
if k.Private == "" || k.Public == "" {
return k, fmt.Errorf("VAPID keyfile %s is missing a key, fix or remove it", path)
}
return k, nil
}
// Earlier releases kept the key in the working directory, so we move it into data/ to keep existing subscriptions valid.
func adoptLegacyVAPIDKeyfile(path string) (vapidKeyfile, error) {
k, err := readVAPIDKeyfile("vapid.json")
if err != nil {
return k, err
}
if err := writeVAPIDKeyfile(path, k); err != nil {
return k, fmt.Errorf("move legacy VAPID keyfile to %s: %w", path, err)
}
log.Printf("webpush: moved legacy VAPID keypair vapid.json -> %s", path)
return k, nil
}
// We write through a synced rename so a crash leaves a whole keyfile or none, since InitWebPush refuses to start on a truncated one.
func writeVAPIDKeyfile(path string, k vapidKeyfile) error {
b, err := json.MarshalIndent(k, "", " ")
if err != nil {
return err
}
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
f, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(b); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
if err := os.Rename(f.Name(), path); err != nil {
return err
}
d, err := os.Open(dir)
if err != nil {
return err
}
if err := d.Sync(); err != nil {
d.Close()
return err
}
return d.Close()
}
func truncForLog(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n]
}
// handleVapidKey serves the VAPID public key. The public key is, by
// design, non-secret -- clients embed it in their PushManager
// subscription and obbyircd advertises it in ISUPPORT -- so this needs
// no auth.
func handleVapidKey(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"publicKey": vapidPublicKey})
}
// pushSendRequest is the JSON obbyircd POSTs to /push/send.
type pushSendRequest struct {
Endpoint string `json:"endpoint"`
P256dh string `json:"p256dh"`
Auth string `json:"auth"`
Payload string `json:"payload"`
TTL int `json:"ttl"`
// The push service keeps only the newest undelivered push per topic (RFC 8030 section 5.4).
Topic string `json:"topic"`
}
var pushTopicPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,32}$`)
// handlePushSend encrypts `payload` for the given subscription and
// delivers it to the push service. Guarded by ServerAuthMiddleware
// (X-ObsidianIRC-Key) -- only obbyircd should reach this.
//
// The push service's HTTP status is relayed back in the response so
// obbyircd can prune dead subscriptions when it sees 404/410 (RFC 8030
// "subscription expired or no longer valid").
func handlePushSend(w http.ResponseWriter, r *http.Request) {
var req pushSendRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid JSON body", http.StatusBadRequest)
return
}
if req.Endpoint == "" || req.P256dh == "" || req.Auth == "" {
http.Error(w, "missing subscription fields", http.StatusBadRequest)
return
}
if !isPushEndpointURL(req.Endpoint) {
replyEndpointGone(w, "endpoint must be an https URL")
return
}
if req.Topic != "" && !pushTopicPattern.MatchString(req.Topic) {
http.Error(w, "topic must be 1-32 URL-safe base64 characters", http.StatusBadRequest)
return
}
sub := &webpush.Subscription{
Endpoint: req.Endpoint,
Keys: webpush.Keys{
P256dh: req.P256dh,
Auth: req.Auth,
},
}
ttl := req.TTL
if ttl <= 0 {
ttl = 86400 // 1 day; push services hold the message this long if the device is offline
}
resp, err := webpush.SendNotification([]byte(req.Payload), sub, &webpush.Options{
Subscriber: vapidSubject,
VAPIDPublicKey: vapidPublicKey,
VAPIDPrivateKey: vapidPrivateKey,
TTL: ttl,
Topic: req.Topic,
// We ask for high urgency because push services hold back normal pushes while a phone dozes.
Urgency: webpush.UrgencyHigh,
HTTPClient: pushHTTPClient,
})
if err != nil {
log.Printf("webpush: send error to %s: %v", truncForLog(req.Endpoint, 48), err)
if errors.Is(err, errInternalAddress) {
replyEndpointGone(w, "endpoint resolves to an internal address")
return
}
http.Error(w, "send failed", http.StatusBadGateway)
return
}
defer resp.Body.Close()
log.Printf("webpush: delivered to %s -> push service status %d",
truncForLog(req.Endpoint, 48), resp.StatusCode)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]int{"status": resp.StatusCode})
}
// Any logged-in IRC user can register an endpoint, so we POST only to public
// HTTPS hosts and check the address we actually dial.
var pushHTTPClient = &http.Client{
Timeout: 15 * time.Second,
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
Control: refuseInternalAddress,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
},
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
var errInternalAddress = errors.New("address resolves to an internal network")
func refuseInternalAddress(_, address string, _ syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
ip, err := netip.ParseAddr(host)
if err != nil || !isPublicIP(ip.Unmap()) {
return errInternalAddress
}
return nil
}
var nonPublicPrefixes = []netip.Prefix{
netip.MustParsePrefix("100.64.0.0/10"),
netip.MustParsePrefix("240.0.0.0/4"),
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("64:ff9b::/96"),
netip.MustParsePrefix("64:ff9b:1::/48"),
netip.MustParsePrefix("2002::/16"),
}
func isPublicIP(ip netip.Addr) bool {
if !ip.IsGlobalUnicast() || ip.IsPrivate() {
return false
}
for _, prefix := range nonPublicPrefixes {
if prefix.Contains(ip) {
return false
}
}
return true
}
func isPushEndpointURL(raw string) bool {
u, err := url.Parse(raw)
return err == nil && u.Scheme == "https" && u.Hostname() != "" && u.User == nil
}
// We report a refused endpoint as a 410 inside a 200, since obbyircd reads
// only the body of a 200 and drops the subscription on a 410.
func replyEndpointGone(w http.ResponseWriter, reason string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]any{"status": http.StatusGone, "error": reason})
}