provisioning.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 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/websocket"
  28. "github.com/Rhymen/go-whatsapp"
  29. log "maunium.net/go/maulogger/v2"
  30. "maunium.net/go/mautrix/id"
  31. )
  32. type ProvisioningAPI struct {
  33. bridge *Bridge
  34. log log.Logger
  35. }
  36. func (prov *ProvisioningAPI) Init() {
  37. prov.log = prov.bridge.Log.Sub("Provisioning")
  38. prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
  39. r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
  40. r.Use(prov.AuthMiddleware)
  41. r.HandleFunc("/ping", prov.Ping).Methods(http.MethodGet)
  42. r.HandleFunc("/login", prov.Login).Methods(http.MethodGet)
  43. r.HandleFunc("/logout", prov.Logout).Methods(http.MethodPost)
  44. r.HandleFunc("/delete_session", prov.DeleteSession).Methods(http.MethodPost)
  45. r.HandleFunc("/delete_connection", prov.DeleteConnection).Methods(http.MethodPost)
  46. r.HandleFunc("/disconnect", prov.Disconnect).Methods(http.MethodPost)
  47. r.HandleFunc("/reconnect", prov.Reconnect).Methods(http.MethodPost)
  48. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
  49. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
  50. }
  51. type responseWrap struct {
  52. http.ResponseWriter
  53. statusCode int
  54. }
  55. var _ http.Hijacker = (*responseWrap)(nil)
  56. func (rw *responseWrap) WriteHeader(statusCode int) {
  57. rw.ResponseWriter.WriteHeader(statusCode)
  58. rw.statusCode = statusCode
  59. }
  60. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  61. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  62. if !ok {
  63. return nil, nil, errors.New("response does not implement http.Hijacker")
  64. }
  65. return hijacker.Hijack()
  66. }
  67. func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
  68. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  69. auth := r.Header.Get("Authorization")
  70. if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
  71. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  72. for _, part := range authParts {
  73. part = strings.TrimSpace(part)
  74. if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
  75. auth = part[len("net.maunium.whatsapp.auth-"):]
  76. break
  77. }
  78. }
  79. } else if strings.HasPrefix(auth, "Bearer ") {
  80. auth = auth[len("Bearer "):]
  81. }
  82. if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
  83. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  84. "error": "Invalid auth token",
  85. "errcode": "M_FORBIDDEN",
  86. })
  87. return
  88. }
  89. userID := r.URL.Query().Get("user_id")
  90. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  91. start := time.Now()
  92. wWrap := &responseWrap{w, 200}
  93. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  94. duration := time.Now().Sub(start).Seconds()
  95. prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  96. })
  97. }
  98. type Error struct {
  99. Success bool `json:"success"`
  100. Error string `json:"error"`
  101. ErrCode string `json:"errcode"`
  102. }
  103. type Response struct {
  104. Success bool `json:"success"`
  105. Status string `json:"status"`
  106. }
  107. func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
  108. user := r.Context().Value("user").(*User)
  109. if user.Session == nil && user.Conn == nil {
  110. jsonResponse(w, http.StatusNotFound, Error{
  111. Error: "Nothing to purge: no session information stored and no active connection.",
  112. ErrCode: "no session",
  113. })
  114. return
  115. }
  116. user.DeleteConnection()
  117. user.SetSession(nil)
  118. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  119. }
  120. func (prov *ProvisioningAPI) DeleteConnection(w http.ResponseWriter, r *http.Request) {
  121. user := r.Context().Value("user").(*User)
  122. if user.Conn == nil {
  123. jsonResponse(w, http.StatusNotFound, Error{
  124. Error: "You don't have a WhatsApp connection.",
  125. ErrCode: "not connected",
  126. })
  127. return
  128. }
  129. user.DeleteConnection()
  130. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp and connection deleted"})
  131. }
  132. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  133. user := r.Context().Value("user").(*User)
  134. if user.Conn == nil {
  135. jsonResponse(w, http.StatusNotFound, Error{
  136. Error: "You don't have a WhatsApp connection.",
  137. ErrCode: "no connection",
  138. })
  139. return
  140. }
  141. err := user.Conn.Disconnect()
  142. if err == whatsapp.ErrNotConnected {
  143. jsonResponse(w, http.StatusNotFound, Error{
  144. Error: "You were not connected",
  145. ErrCode: "not connected",
  146. })
  147. return
  148. } else if err != nil {
  149. user.log.Warnln("Error while disconnecting:", err)
  150. jsonResponse(w, http.StatusInternalServerError, Error{
  151. Error: fmt.Sprintf("Unknown error while disconnecting: %v", err),
  152. ErrCode: err.Error(),
  153. })
  154. return
  155. }
  156. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  157. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  158. }
  159. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  160. user := r.Context().Value("user").(*User)
  161. if user.Conn == nil {
  162. if user.Session == nil {
  163. jsonResponse(w, http.StatusForbidden, Error{
  164. Error: "No existing connection and no session. Please log in first.",
  165. ErrCode: "no session",
  166. })
  167. } else {
  168. user.Connect(false)
  169. jsonResponse(w, http.StatusOK, Response{true, "Created connection to WhatsApp."})
  170. }
  171. return
  172. }
  173. user.log.Debugln("Received /reconnect request, disconnecting")
  174. wasConnected := true
  175. err := user.Conn.Disconnect()
  176. if err == whatsapp.ErrNotConnected {
  177. wasConnected = false
  178. } else if err != nil {
  179. user.log.Warnln("Error while disconnecting:", err)
  180. }
  181. user.log.Debugln("Restoring session for /reconnect")
  182. err = user.Conn.Restore(true, r.Context())
  183. user.log.Debugfln("Restore session for /reconnect responded with %v", err)
  184. if err == whatsapp.ErrInvalidSession {
  185. if user.Session != nil {
  186. user.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  187. user.Conn.SetSession(*user.Session)
  188. err = user.Conn.Restore(true, r.Context())
  189. } else {
  190. jsonResponse(w, http.StatusForbidden, Error{
  191. Error: "You're not logged in",
  192. ErrCode: "not logged in",
  193. })
  194. return
  195. }
  196. }
  197. if err == whatsapp.ErrLoginInProgress {
  198. jsonResponse(w, http.StatusConflict, Error{
  199. Error: "A login or reconnection is already in progress.",
  200. ErrCode: "login in progress",
  201. })
  202. return
  203. } else if err == whatsapp.ErrAlreadyLoggedIn {
  204. jsonResponse(w, http.StatusConflict, Error{
  205. Error: "You were already connected.",
  206. ErrCode: err.Error(),
  207. })
  208. return
  209. }
  210. if err != nil {
  211. user.log.Warnln("Error while reconnecting:", err)
  212. jsonResponse(w, http.StatusInternalServerError, Error{
  213. Error: fmt.Sprintf("Unknown error while reconnecting: %v", err),
  214. ErrCode: err.Error(),
  215. })
  216. user.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  217. err = user.Conn.Disconnect()
  218. if err != nil {
  219. user.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  220. }
  221. return
  222. }
  223. user.ConnectionErrors = 0
  224. user.PostLogin()
  225. var msg string
  226. if wasConnected {
  227. msg = "Reconnected successfully."
  228. } else {
  229. msg = "Connected successfully."
  230. }
  231. jsonResponse(w, http.StatusOK, Response{true, msg})
  232. }
  233. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  234. user := r.Context().Value("user").(*User)
  235. wa := map[string]interface{}{
  236. "has_session": user.Session != nil,
  237. "management_room": user.ManagementRoom,
  238. "jid": user.JID,
  239. "conn": nil,
  240. "ping": nil,
  241. }
  242. if user.Conn != nil {
  243. wa["conn"] = map[string]interface{}{
  244. "is_connected": user.Conn.IsConnected(),
  245. "is_logged_in": user.Conn.IsLoggedIn(),
  246. "is_login_in_progress": user.Conn.IsLoginInProgress(),
  247. }
  248. user.log.Debugln("Pinging WhatsApp mobile due to /ping API request")
  249. err := user.Conn.AdminTest()
  250. var errStr string
  251. if err == whatsapp.ErrPingFalse {
  252. user.log.Debugln("Forwarding ping false error from provisioning API to HandleError")
  253. go user.HandleError(err)
  254. }
  255. if err != nil {
  256. errStr = err.Error()
  257. }
  258. wa["ping"] = map[string]interface{}{
  259. "ok": err == nil,
  260. "err": errStr,
  261. }
  262. user.log.Debugfln("Admin test response for /ping: %v (conn: %t, login: %t, in progress: %t)",
  263. err, user.Conn.IsConnected(), user.Conn.IsLoggedIn(), user.Conn.IsLoginInProgress())
  264. }
  265. resp := map[string]interface{}{
  266. "mxid": user.MXID,
  267. "admin": user.Admin,
  268. "whitelisted": user.Whitelisted,
  269. "relaybot_whitelisted": user.RelaybotWhitelisted,
  270. "whatsapp": wa,
  271. }
  272. jsonResponse(w, http.StatusOK, resp)
  273. }
  274. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  275. w.Header().Add("Content-Type", "application/json")
  276. w.WriteHeader(status)
  277. _ = json.NewEncoder(w).Encode(response)
  278. }
  279. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  280. user := r.Context().Value("user").(*User)
  281. if user.Session == nil {
  282. jsonResponse(w, http.StatusNotFound, Error{
  283. Error: "You're not logged in",
  284. ErrCode: "not logged in",
  285. })
  286. return
  287. }
  288. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  289. if user.Conn == nil {
  290. if !force {
  291. jsonResponse(w, http.StatusNotFound, Error{
  292. Error: "You're not connected",
  293. ErrCode: "not connected",
  294. })
  295. }
  296. } else {
  297. err := user.Conn.Logout()
  298. if err != nil {
  299. user.log.Warnln("Error while logging out:", err)
  300. if !force {
  301. jsonResponse(w, http.StatusInternalServerError, Error{
  302. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  303. ErrCode: err.Error(),
  304. })
  305. return
  306. }
  307. }
  308. user.DeleteConnection()
  309. }
  310. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  311. user.removeFromJIDMap(StateLoggedOut)
  312. // TODO this causes a foreign key violation, which should be fixed
  313. //ce.User.JID = ""
  314. user.SetSession(nil)
  315. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  316. }
  317. var upgrader = websocket.Upgrader{
  318. CheckOrigin: func(r *http.Request) bool {
  319. return true
  320. },
  321. Subprotocols: []string{"net.maunium.whatsapp.login"},
  322. }
  323. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  324. userID := r.URL.Query().Get("user_id")
  325. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  326. c, err := upgrader.Upgrade(w, r, nil)
  327. if err != nil {
  328. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  329. return
  330. }
  331. defer c.Close()
  332. if !user.Connect(true) {
  333. user.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  334. _ = c.WriteJSON(Error{
  335. Error: "Failed to connect to WhatsApp",
  336. ErrCode: "connection error",
  337. })
  338. return
  339. }
  340. qrChan := make(chan string, 3)
  341. go func() {
  342. for code := range qrChan {
  343. if code == "stop" {
  344. return
  345. }
  346. _ = c.WriteJSON(map[string]interface{}{
  347. "code": code,
  348. })
  349. }
  350. }()
  351. go func() {
  352. // Read everything so SetCloseHandler() works
  353. for {
  354. _, _, err = c.ReadMessage()
  355. if err != nil {
  356. break
  357. }
  358. }
  359. }()
  360. ctx, cancel := context.WithCancel(context.Background())
  361. c.SetCloseHandler(func(code int, text string) error {
  362. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  363. cancel()
  364. return nil
  365. })
  366. user.log.Debugln("Starting login via provisioning API")
  367. session, jid, err := user.Conn.Login(qrChan, ctx)
  368. qrChan <- "stop"
  369. if err != nil {
  370. var msg string
  371. if errors.Is(err, whatsapp.ErrAlreadyLoggedIn) {
  372. msg = "You're already logged in"
  373. } else if errors.Is(err, whatsapp.ErrLoginInProgress) {
  374. msg = "You have a login in progress already."
  375. } else if errors.Is(err, whatsapp.ErrLoginTimedOut) {
  376. msg = "QR code scan timed out. Please try again."
  377. } else if errors.Is(err, whatsapp.ErrInvalidWebsocket) {
  378. msg = "WhatsApp connection error. Please try again."
  379. // TODO might need to make sure it reconnects?
  380. } else {
  381. msg = fmt.Sprintf("Unknown error while logging in: %v", err)
  382. }
  383. user.log.Warnln("Failed to log in:", err)
  384. _ = c.WriteJSON(Error{
  385. Error: msg,
  386. ErrCode: err.Error(),
  387. })
  388. return
  389. }
  390. user.log.Debugln("Successful login as", jid, "via provisioning API")
  391. user.ConnectionErrors = 0
  392. user.JID = strings.Replace(jid, whatsapp.OldUserSuffix, whatsapp.NewUserSuffix, 1)
  393. user.addToJIDMap()
  394. user.SetSession(&session)
  395. _ = c.WriteJSON(map[string]interface{}{
  396. "success": true,
  397. "jid": user.JID,
  398. })
  399. user.PostLogin()
  400. }