forked from mautrix/whatsapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provisioning.go
399 lines (366 loc) · 11.9 KB
/
provisioning.go
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
// Copyright (C) 2021 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"go.mau.fi/whatsmeow/appstate"
"go.mau.fi/whatsmeow"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix/id"
)
type ProvisioningAPI struct {
bridge *Bridge
log log.Logger
}
func (prov *ProvisioningAPI) Init() {
prov.log = prov.bridge.Log.Sub("Provisioning")
prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
r.Use(prov.AuthMiddleware)
r.HandleFunc("/ping", prov.Ping).Methods(http.MethodGet)
r.HandleFunc("/login", prov.Login).Methods(http.MethodGet)
r.HandleFunc("/logout", prov.Logout).Methods(http.MethodPost)
r.HandleFunc("/delete_session", prov.DeleteSession).Methods(http.MethodPost)
r.HandleFunc("/disconnect", prov.Disconnect).Methods(http.MethodPost)
r.HandleFunc("/reconnect", prov.Reconnect).Methods(http.MethodPost)
r.HandleFunc("/sync/appstate/{name}", prov.SyncAppState).Methods(http.MethodPost)
prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
// Deprecated, just use /disconnect
r.HandleFunc("/delete_connection", prov.Disconnect).Methods(http.MethodPost)
}
type responseWrap struct {
http.ResponseWriter
statusCode int
}
var _ http.Hijacker = (*responseWrap)(nil)
func (rw *responseWrap) WriteHeader(statusCode int) {
rw.ResponseWriter.WriteHeader(statusCode)
rw.statusCode = statusCode
}
func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := rw.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("response does not implement http.Hijacker")
}
return hijacker.Hijack()
}
func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
for _, part := range authParts {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
auth = part[len("net.maunium.whatsapp.auth-"):]
break
}
}
} else if strings.HasPrefix(auth, "Bearer ") {
auth = auth[len("Bearer "):]
}
if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
jsonResponse(w, http.StatusForbidden, map[string]interface{}{
"error": "Invalid auth token",
"errcode": "M_FORBIDDEN",
})
return
}
userID := r.URL.Query().Get("user_id")
user := prov.bridge.GetUserByMXID(id.UserID(userID))
start := time.Now()
wWrap := &responseWrap{w, 200}
h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
duration := time.Now().Sub(start).Seconds()
prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
})
}
type Error struct {
Success bool `json:"success"`
Error string `json:"error"`
ErrCode string `json:"errcode"`
}
type Response struct {
Success bool `json:"success"`
Status string `json:"status"`
}
func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
if user.Session == nil && user.Client == nil {
jsonResponse(w, http.StatusNotFound, Error{
Error: "Nothing to purge: no session information stored and no active connection.",
ErrCode: "no session",
})
return
}
user.DeleteConnection()
user.DeleteSession()
jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
user.removeFromJIDMap(StateLoggedOut)
}
func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
if user.Client == nil {
jsonResponse(w, http.StatusNotFound, Error{
Error: "You don't have a WhatsApp connection.",
ErrCode: "no connection",
})
return
}
user.DeleteConnection()
jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
}
func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
if user.Client == nil {
if user.Session == nil {
jsonResponse(w, http.StatusForbidden, Error{
Error: "No existing connection and no session. Please log in first.",
ErrCode: "no session",
})
} else {
user.Connect()
jsonResponse(w, http.StatusAccepted, Response{true, "Created connection to WhatsApp."})
}
} else {
user.DeleteConnection()
user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
user.Connect()
jsonResponse(w, http.StatusAccepted, Response{true, "Restarted connection to WhatsApp"})
}
}
func (prov *ProvisioningAPI) SyncAppState(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
if user == nil || user.Client == nil {
jsonResponse(w, http.StatusNotFound, Error{
Error: "User is not connected to WhatsApp",
ErrCode: "no session",
})
return
}
vars := mux.Vars(r)
nameStr := vars["name"]
if len(nameStr) == 0 {
jsonResponse(w, http.StatusBadRequest, Error{
Error: "The `name` parameter is required",
ErrCode: "missing-name-param",
})
return
}
var name appstate.WAPatchName
for _, existingName := range appstate.AllPatchNames {
if nameStr == string(existingName) {
name = existingName
}
}
if len(name) == 0 {
jsonResponse(w, http.StatusBadRequest, Error{
Error: fmt.Sprintf("'%s' is not a valid app state patch name", nameStr),
ErrCode: "invalid-name-param",
})
return
}
fullStr := r.URL.Query().Get("full")
fullSync := len(fullStr) > 0 && (fullStr == "1" || strings.ToLower(fullStr)[0] == 't')
err := user.Client.FetchAppState(name, fullSync, false)
if err != nil {
jsonResponse(w, http.StatusInternalServerError, Error{false, err.Error(), "sync-fail"})
} else {
jsonResponse(w, http.StatusOK, Response{true, fmt.Sprintf("Synced app state %s", name)})
}
}
func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
wa := map[string]interface{}{
"has_session": user.Session != nil,
"management_room": user.ManagementRoom,
"conn": nil,
}
if !user.JID.IsEmpty() {
wa["jid"] = user.JID.String()
wa["phone"] = "+" + user.JID.User
wa["device"] = user.JID.Device
}
if user.Client != nil {
wa["conn"] = map[string]interface{}{
"is_connected": user.Client.IsConnected(),
"is_logged_in": user.Client.IsLoggedIn(),
}
}
resp := map[string]interface{}{
"mxid": user.MXID,
"admin": user.Admin,
"whitelisted": user.Whitelisted,
"relay_whitelisted": user.RelayWhitelisted,
"whatsapp": wa,
}
jsonResponse(w, http.StatusOK, resp)
}
func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(response)
}
func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
if user.Session == nil {
jsonResponse(w, http.StatusNotFound, Error{
Error: "You're not logged in",
ErrCode: "not logged in",
})
return
}
force := strings.ToLower(r.URL.Query().Get("force")) != "false"
if user.Client == nil {
if !force {
jsonResponse(w, http.StatusNotFound, Error{
Error: "You're not connected",
ErrCode: "not connected",
})
}
} else {
err := user.Client.Logout()
if err != nil {
user.log.Warnln("Error while logging out:", err)
if !force {
jsonResponse(w, http.StatusInternalServerError, Error{
Error: fmt.Sprintf("Unknown error while logging out: %v", err),
ErrCode: err.Error(),
})
return
}
} else {
user.Session = nil
}
user.DeleteConnection()
}
user.bridge.Metrics.TrackConnectionState(user.JID, false)
user.removeFromJIDMap(StateLoggedOut)
user.DeleteSession()
jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
Subprotocols: []string{"net.maunium.whatsapp.login"},
}
func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
userID := r.URL.Query().Get("user_id")
user := prov.bridge.GetUserByMXID(id.UserID(userID))
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
prov.log.Errorln("Failed to upgrade connection to websocket:", err)
return
}
defer func() {
err := c.Close()
if err != nil {
user.log.Debugln("Error closing websocket:", err)
}
}()
go func() {
// Read everything so SetCloseHandler() works
for {
_, _, err = c.ReadMessage()
if err != nil {
break
}
}
}()
ctx, cancel := context.WithCancel(context.Background())
c.SetCloseHandler(func(code int, text string) error {
user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
cancel()
return nil
})
qrChan, err := user.Login(ctx)
if err != nil {
user.log.Errorf("Failed to log in from provisioning API:", err)
if errors.Is(err, ErrAlreadyLoggedIn) {
go user.Connect()
_ = c.WriteJSON(Error{
Error: "You're already logged into WhatsApp",
ErrCode: "already logged in",
})
} else {
_ = c.WriteJSON(Error{
Error: "Failed to connect to WhatsApp",
ErrCode: "connection error",
})
}
}
user.log.Debugln("Started login via provisioning API")
for {
select {
case evt := <-qrChan:
switch evt.Event {
case whatsmeow.QRChannelSuccess.Event:
jid := user.Client.Store.ID
user.log.Debugln("Successful login as", jid, "via provisioning API")
_ = c.WriteJSON(map[string]interface{}{
"success": true,
"jid": jid,
"phone": fmt.Sprintf("+%s", jid.User),
})
case whatsmeow.QRChannelTimeout.Event:
user.log.Debugln("Login via provisioning API timed out")
_ = c.WriteJSON(Error{
Error: "QR code scan timed out. Please try again.",
ErrCode: "login timed out",
})
case whatsmeow.QRChannelErrUnexpectedEvent.Event:
user.log.Debugln("Login via provisioning API failed due to unexpected event")
_ = c.WriteJSON(Error{
Error: "Got unexpected event while waiting for QRs, perhaps you're already logged in?",
ErrCode: "unexpected event",
})
case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
_ = c.WriteJSON(Error{
Error: "Please enable the WhatsApp multidevice beta and scan the QR code again.",
ErrCode: "multidevice not enabled",
})
continue
case "error":
_ = c.WriteJSON(Error{
Error: "Fatal error while logging in",
ErrCode: "fatal error",
})
case "code":
_ = c.WriteJSON(map[string]interface{}{
"code": evt.Code,
"timeout": int(evt.Timeout.Seconds()),
})
continue
}
return
case <-ctx.Done():
return
}
}
}