provisioning.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bufio"
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "net"
  24. "net/http"
  25. "strings"
  26. "time"
  27. "github.com/gorilla/mux"
  28. "github.com/gorilla/websocket"
  29. "go.mau.fi/whatsmeow/appstate"
  30. "go.mau.fi/whatsmeow"
  31. log "maunium.net/go/maulogger/v2"
  32. "maunium.net/go/mautrix/id"
  33. )
  34. type ProvisioningAPI struct {
  35. bridge *Bridge
  36. log log.Logger
  37. }
  38. func (prov *ProvisioningAPI) Init() {
  39. prov.log = prov.bridge.Log.Sub("Provisioning")
  40. prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
  41. r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
  42. r.Use(prov.AuthMiddleware)
  43. r.HandleFunc("/ping", prov.Ping).Methods(http.MethodGet)
  44. r.HandleFunc("/login", prov.Login).Methods(http.MethodGet)
  45. r.HandleFunc("/logout", prov.Logout).Methods(http.MethodPost)
  46. r.HandleFunc("/delete_session", prov.DeleteSession).Methods(http.MethodPost)
  47. r.HandleFunc("/disconnect", prov.Disconnect).Methods(http.MethodPost)
  48. r.HandleFunc("/reconnect", prov.Reconnect).Methods(http.MethodPost)
  49. r.HandleFunc("/sync/appstate/{name}", prov.SyncAppState).Methods(http.MethodPost)
  50. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
  51. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
  52. // Deprecated, just use /disconnect
  53. r.HandleFunc("/delete_connection", prov.Disconnect).Methods(http.MethodPost)
  54. }
  55. type responseWrap struct {
  56. http.ResponseWriter
  57. statusCode int
  58. }
  59. var _ http.Hijacker = (*responseWrap)(nil)
  60. func (rw *responseWrap) WriteHeader(statusCode int) {
  61. rw.ResponseWriter.WriteHeader(statusCode)
  62. rw.statusCode = statusCode
  63. }
  64. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  65. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  66. if !ok {
  67. return nil, nil, errors.New("response does not implement http.Hijacker")
  68. }
  69. return hijacker.Hijack()
  70. }
  71. func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
  72. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  73. auth := r.Header.Get("Authorization")
  74. if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
  75. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  76. for _, part := range authParts {
  77. part = strings.TrimSpace(part)
  78. if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
  79. auth = part[len("net.maunium.whatsapp.auth-"):]
  80. break
  81. }
  82. }
  83. } else if strings.HasPrefix(auth, "Bearer ") {
  84. auth = auth[len("Bearer "):]
  85. }
  86. if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
  87. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  88. "error": "Invalid auth token",
  89. "errcode": "M_FORBIDDEN",
  90. })
  91. return
  92. }
  93. userID := r.URL.Query().Get("user_id")
  94. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  95. start := time.Now()
  96. wWrap := &responseWrap{w, 200}
  97. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  98. duration := time.Now().Sub(start).Seconds()
  99. prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  100. })
  101. }
  102. type Error struct {
  103. Success bool `json:"success"`
  104. Error string `json:"error"`
  105. ErrCode string `json:"errcode"`
  106. }
  107. type Response struct {
  108. Success bool `json:"success"`
  109. Status string `json:"status"`
  110. }
  111. func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
  112. user := r.Context().Value("user").(*User)
  113. if user.Session == nil && user.Client == nil {
  114. jsonResponse(w, http.StatusNotFound, Error{
  115. Error: "Nothing to purge: no session information stored and no active connection.",
  116. ErrCode: "no session",
  117. })
  118. return
  119. }
  120. user.DeleteConnection()
  121. user.DeleteSession()
  122. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  123. user.removeFromJIDMap(StateLoggedOut)
  124. }
  125. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  126. user := r.Context().Value("user").(*User)
  127. if user.Client == nil {
  128. jsonResponse(w, http.StatusNotFound, Error{
  129. Error: "You don't have a WhatsApp connection.",
  130. ErrCode: "no connection",
  131. })
  132. return
  133. }
  134. user.DeleteConnection()
  135. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  136. user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  137. }
  138. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  139. user := r.Context().Value("user").(*User)
  140. if user.Client == nil {
  141. if user.Session == nil {
  142. jsonResponse(w, http.StatusForbidden, Error{
  143. Error: "No existing connection and no session. Please log in first.",
  144. ErrCode: "no session",
  145. })
  146. } else {
  147. user.Connect()
  148. jsonResponse(w, http.StatusAccepted, Response{true, "Created connection to WhatsApp."})
  149. }
  150. } else {
  151. user.DeleteConnection()
  152. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  153. user.Connect()
  154. jsonResponse(w, http.StatusAccepted, Response{true, "Restarted connection to WhatsApp"})
  155. }
  156. }
  157. func (prov *ProvisioningAPI) SyncAppState(w http.ResponseWriter, r *http.Request) {
  158. user := r.Context().Value("user").(*User)
  159. if user == nil || user.Client == nil {
  160. jsonResponse(w, http.StatusNotFound, Error{
  161. Error: "User is not connected to WhatsApp",
  162. ErrCode: "no session",
  163. })
  164. return
  165. }
  166. vars := mux.Vars(r)
  167. nameStr := vars["name"]
  168. if len(nameStr) == 0 {
  169. jsonResponse(w, http.StatusBadRequest, Error{
  170. Error: "The `name` parameter is required",
  171. ErrCode: "missing-name-param",
  172. })
  173. return
  174. }
  175. var name appstate.WAPatchName
  176. for _, existingName := range appstate.AllPatchNames {
  177. if nameStr == string(existingName) {
  178. name = existingName
  179. }
  180. }
  181. if len(name) == 0 {
  182. jsonResponse(w, http.StatusBadRequest, Error{
  183. Error: fmt.Sprintf("'%s' is not a valid app state patch name", nameStr),
  184. ErrCode: "invalid-name-param",
  185. })
  186. return
  187. }
  188. fullStr := r.URL.Query().Get("full")
  189. fullSync := len(fullStr) > 0 && (fullStr == "1" || strings.ToLower(fullStr)[0] == 't')
  190. err := user.Client.FetchAppState(name, fullSync, false)
  191. if err != nil {
  192. jsonResponse(w, http.StatusInternalServerError, Error{false, err.Error(), "sync-fail"})
  193. } else {
  194. jsonResponse(w, http.StatusOK, Response{true, fmt.Sprintf("Synced app state %s", name)})
  195. }
  196. }
  197. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  198. user := r.Context().Value("user").(*User)
  199. wa := map[string]interface{}{
  200. "has_session": user.Session != nil,
  201. "management_room": user.ManagementRoom,
  202. "conn": nil,
  203. }
  204. if !user.JID.IsEmpty() {
  205. wa["jid"] = user.JID.String()
  206. wa["phone"] = "+" + user.JID.User
  207. wa["device"] = user.JID.Device
  208. }
  209. if user.Client != nil {
  210. wa["conn"] = map[string]interface{}{
  211. "is_connected": user.Client.IsConnected(),
  212. "is_logged_in": user.Client.IsLoggedIn(),
  213. }
  214. }
  215. resp := map[string]interface{}{
  216. "mxid": user.MXID,
  217. "admin": user.Admin,
  218. "whitelisted": user.Whitelisted,
  219. "relay_whitelisted": user.RelayWhitelisted,
  220. "whatsapp": wa,
  221. }
  222. jsonResponse(w, http.StatusOK, resp)
  223. }
  224. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  225. w.Header().Add("Content-Type", "application/json")
  226. w.WriteHeader(status)
  227. _ = json.NewEncoder(w).Encode(response)
  228. }
  229. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  230. user := r.Context().Value("user").(*User)
  231. if user.Session == nil {
  232. jsonResponse(w, http.StatusNotFound, Error{
  233. Error: "You're not logged in",
  234. ErrCode: "not logged in",
  235. })
  236. return
  237. }
  238. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  239. if user.Client == nil {
  240. if !force {
  241. jsonResponse(w, http.StatusNotFound, Error{
  242. Error: "You're not connected",
  243. ErrCode: "not connected",
  244. })
  245. }
  246. } else {
  247. err := user.Client.Logout()
  248. if err != nil {
  249. user.log.Warnln("Error while logging out:", err)
  250. if !force {
  251. jsonResponse(w, http.StatusInternalServerError, Error{
  252. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  253. ErrCode: err.Error(),
  254. })
  255. return
  256. }
  257. } else {
  258. user.Session = nil
  259. }
  260. user.DeleteConnection()
  261. }
  262. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  263. user.removeFromJIDMap(StateLoggedOut)
  264. user.DeleteSession()
  265. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  266. }
  267. var upgrader = websocket.Upgrader{
  268. CheckOrigin: func(r *http.Request) bool {
  269. return true
  270. },
  271. Subprotocols: []string{"net.maunium.whatsapp.login"},
  272. }
  273. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  274. userID := r.URL.Query().Get("user_id")
  275. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  276. c, err := upgrader.Upgrade(w, r, nil)
  277. if err != nil {
  278. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  279. return
  280. }
  281. defer func() {
  282. err := c.Close()
  283. if err != nil {
  284. user.log.Debugln("Error closing websocket:", err)
  285. }
  286. }()
  287. go func() {
  288. // Read everything so SetCloseHandler() works
  289. for {
  290. _, _, err = c.ReadMessage()
  291. if err != nil {
  292. break
  293. }
  294. }
  295. }()
  296. ctx, cancel := context.WithCancel(context.Background())
  297. c.SetCloseHandler(func(code int, text string) error {
  298. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  299. cancel()
  300. return nil
  301. })
  302. qrChan, err := user.Login(ctx)
  303. if err != nil {
  304. user.log.Errorf("Failed to log in from provisioning API:", err)
  305. if errors.Is(err, ErrAlreadyLoggedIn) {
  306. go user.Connect()
  307. _ = c.WriteJSON(Error{
  308. Error: "You're already logged into WhatsApp",
  309. ErrCode: "already logged in",
  310. })
  311. } else {
  312. _ = c.WriteJSON(Error{
  313. Error: "Failed to connect to WhatsApp",
  314. ErrCode: "connection error",
  315. })
  316. }
  317. }
  318. user.log.Debugln("Started login via provisioning API")
  319. for {
  320. select {
  321. case evt := <-qrChan:
  322. switch evt.Event {
  323. case whatsmeow.QRChannelSuccess.Event:
  324. jid := user.Client.Store.ID
  325. user.log.Debugln("Successful login as", jid, "via provisioning API")
  326. _ = c.WriteJSON(map[string]interface{}{
  327. "success": true,
  328. "jid": jid,
  329. "phone": fmt.Sprintf("+%s", jid.User),
  330. })
  331. case whatsmeow.QRChannelTimeout.Event:
  332. user.log.Debugln("Login via provisioning API timed out")
  333. _ = c.WriteJSON(Error{
  334. Error: "QR code scan timed out. Please try again.",
  335. ErrCode: "login timed out",
  336. })
  337. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  338. user.log.Debugln("Login via provisioning API failed due to unexpected event")
  339. _ = c.WriteJSON(Error{
  340. Error: "Got unexpected event while waiting for QRs, perhaps you're already logged in?",
  341. ErrCode: "unexpected event",
  342. })
  343. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  344. _ = c.WriteJSON(Error{
  345. Error: "Please enable the WhatsApp multidevice beta and scan the QR code again.",
  346. ErrCode: "multidevice not enabled",
  347. })
  348. continue
  349. case "error":
  350. _ = c.WriteJSON(Error{
  351. Error: "Fatal error while logging in",
  352. ErrCode: "fatal error",
  353. })
  354. case "code":
  355. _ = c.WriteJSON(map[string]interface{}{
  356. "code": evt.Code,
  357. "timeout": int(evt.Timeout.Seconds()),
  358. })
  359. continue
  360. }
  361. return
  362. case <-ctx.Done():
  363. return
  364. }
  365. }
  366. }