provisioning.go 11 KB

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