provisioning.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. }
  86. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  87. }
  88. func (prov *ProvisioningAPI) DeleteConnection(w http.ResponseWriter, r *http.Request) {
  89. user := r.Context().Value("user").(*User)
  90. if user.Conn == nil {
  91. jsonResponse(w, http.StatusNotFound, Error{
  92. Error: "You don't have a WhatsApp connection.",
  93. ErrCode: "not connected",
  94. })
  95. return
  96. }
  97. sess, err := user.Conn.Disconnect()
  98. if err == nil && len(sess.Wid) > 0 {
  99. user.SetSession(&sess)
  100. }
  101. user.Conn.RemoveHandlers()
  102. user.Conn = nil
  103. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  104. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp and connection deleted"})
  105. }
  106. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  107. user := r.Context().Value("user").(*User)
  108. if user.Conn == nil {
  109. jsonResponse(w, http.StatusNotFound, Error{
  110. Error: "You don't have a WhatsApp connection.",
  111. ErrCode: "no connection",
  112. })
  113. return
  114. }
  115. sess, err := user.Conn.Disconnect()
  116. if err == whatsapp.ErrNotConnected {
  117. jsonResponse(w, http.StatusNotFound, Error{
  118. Error: "You were not connected",
  119. ErrCode: "not connected",
  120. })
  121. return
  122. } else if err != nil {
  123. user.log.Warnln("Error while disconnecting:", err)
  124. jsonResponse(w, http.StatusInternalServerError, Error{
  125. Error: fmt.Sprintf("Unknown error while disconnecting: %v", err),
  126. ErrCode: err.Error(),
  127. })
  128. return
  129. } else if len(sess.Wid) > 0 {
  130. user.SetSession(&sess)
  131. }
  132. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  133. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  134. }
  135. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  136. user := r.Context().Value("user").(*User)
  137. if user.Conn == nil {
  138. if user.Session == nil {
  139. jsonResponse(w, http.StatusForbidden, Error{
  140. Error: "No existing connection and no session. Please log in first.",
  141. ErrCode: "no session",
  142. })
  143. } else {
  144. user.Connect(false)
  145. jsonResponse(w, http.StatusOK, Response{true, "Created connection to WhatsApp."})
  146. }
  147. return
  148. }
  149. wasConnected := true
  150. sess, err := user.Conn.Disconnect()
  151. if err == whatsapp.ErrNotConnected {
  152. wasConnected = false
  153. } else if err != nil {
  154. user.log.Warnln("Error while disconnecting:", err)
  155. } else if len(sess.Wid) > 0 {
  156. user.SetSession(&sess)
  157. }
  158. err = user.Conn.Restore()
  159. if err == whatsapp.ErrInvalidSession {
  160. if user.Session != nil {
  161. user.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  162. var sess whatsapp.Session
  163. sess, err = user.Conn.RestoreWithSession(*user.Session)
  164. if err == nil {
  165. user.SetSession(&sess)
  166. }
  167. } else {
  168. jsonResponse(w, http.StatusForbidden, Error{
  169. Error: "You're not logged in",
  170. ErrCode: "not logged in",
  171. })
  172. return
  173. }
  174. } else if err == whatsapp.ErrLoginInProgress {
  175. jsonResponse(w, http.StatusConflict, Error{
  176. Error: "A login or reconnection is already in progress.",
  177. ErrCode: "login in progress",
  178. })
  179. return
  180. } else if err == whatsapp.ErrAlreadyLoggedIn {
  181. jsonResponse(w, http.StatusConflict, Error{
  182. Error: "You were already connected.",
  183. ErrCode: err.Error(),
  184. })
  185. return
  186. }
  187. if err != nil {
  188. user.log.Warnln("Error while reconnecting:", err)
  189. if err.Error() == "restore session connection timed out" {
  190. jsonResponse(w, http.StatusForbidden, Error{
  191. Error: "Reconnection timed out. Is WhatsApp on your phone reachable?",
  192. ErrCode: err.Error(),
  193. })
  194. } else {
  195. jsonResponse(w, http.StatusForbidden, Error{
  196. Error: fmt.Sprintf("Unknown error while reconnecting: %v", err),
  197. ErrCode: err.Error(),
  198. })
  199. }
  200. user.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  201. sess, err := user.Conn.Disconnect()
  202. if err != nil {
  203. user.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  204. } else if len(sess.Wid) > 0 {
  205. user.SetSession(&sess)
  206. }
  207. return
  208. }
  209. user.ConnectionErrors = 0
  210. user.PostLogin()
  211. var msg string
  212. if wasConnected {
  213. msg = "Reconnected successfully."
  214. } else {
  215. msg = "Connected successfully."
  216. }
  217. jsonResponse(w, http.StatusOK, Response{true, msg})
  218. }
  219. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  220. user := r.Context().Value("user").(*User)
  221. wa := map[string]interface{}{
  222. "has_session": user.Session != nil,
  223. "management_room": user.ManagementRoom,
  224. "jid": user.JID,
  225. "conn": nil,
  226. "ping": nil,
  227. }
  228. if user.Conn != nil {
  229. wa["conn"] = map[string]interface{}{
  230. "is_connected": user.Conn.IsConnected(),
  231. "is_logged_in": user.Conn.IsLoggedIn(),
  232. "is_login_in_progress": user.Conn.IsLoginInProgress(),
  233. }
  234. err := user.Conn.AdminTest()
  235. wa["ping"] = map[string]interface{}{
  236. "ok": err == nil,
  237. "err": err,
  238. }
  239. }
  240. resp := map[string]interface{}{
  241. "mxid": user.MXID,
  242. "admin": user.Admin,
  243. "whitelisted": user.Whitelisted,
  244. "relaybot_whitelisted": user.RelaybotWhitelisted,
  245. "whatsapp": wa,
  246. }
  247. jsonResponse(w, http.StatusOK, resp)
  248. }
  249. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  250. w.Header().Add("Content-Type", "application/json")
  251. w.WriteHeader(status)
  252. _ = json.NewEncoder(w).Encode(response)
  253. }
  254. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  255. user := r.Context().Value("user").(*User)
  256. if user.Session == nil {
  257. jsonResponse(w, http.StatusNotFound, Error{
  258. Error: "You're not logged in",
  259. ErrCode: "not logged in",
  260. })
  261. return
  262. }
  263. err := user.Conn.Logout()
  264. if err != nil {
  265. user.log.Warnln("Error while logging out:", err)
  266. jsonResponse(w, http.StatusInternalServerError, Error{
  267. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  268. ErrCode: err.Error(),
  269. })
  270. return
  271. }
  272. _, err = user.Conn.Disconnect()
  273. if err != nil {
  274. user.log.Warnln("Error while disconnecting after logout:", err)
  275. }
  276. user.Conn.RemoveHandlers()
  277. user.Conn = nil
  278. user.removeFromJIDMap()
  279. // TODO this causes a foreign key violation, which should be fixed
  280. //ce.User.JID = ""
  281. user.SetSession(nil)
  282. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  283. }
  284. var upgrader = websocket.Upgrader{}
  285. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  286. userID := r.URL.Query().Get("user_id")
  287. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  288. c, err := upgrader.Upgrade(w, r, nil)
  289. if err != nil {
  290. prov.log.Errorfln("Failed to upgrade connection to websocket:", err)
  291. return
  292. }
  293. defer c.Close()
  294. if !user.Connect(true) {
  295. user.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  296. _ = c.WriteJSON(Error{
  297. Error: "Failed to connect to WhatsApp",
  298. ErrCode: "connection error",
  299. })
  300. return
  301. }
  302. qrChan := make(chan string, 3)
  303. go func() {
  304. for code := range qrChan {
  305. if code == "stop" {
  306. return
  307. }
  308. _ = c.WriteJSON(map[string]interface{}{
  309. "code": code,
  310. })
  311. }
  312. }()
  313. session, err := user.Conn.LoginWithRetry(qrChan, user.bridge.Config.Bridge.LoginQRRegenCount)
  314. qrChan <- "stop"
  315. if err != nil {
  316. var msg string
  317. if err == whatsapp.ErrAlreadyLoggedIn {
  318. msg = "You're already logged in"
  319. } else if err == whatsapp.ErrLoginInProgress {
  320. msg = "You have a login in progress already."
  321. } else if err == whatsapp.ErrLoginTimedOut {
  322. msg = "QR code scan timed out. Please try again."
  323. } else {
  324. user.log.Warnln("Failed to log in:", err)
  325. msg = fmt.Sprintf("Unknown error while logging in: %v", err)
  326. }
  327. _ = c.WriteJSON(Error{
  328. Error: msg,
  329. ErrCode: err.Error(),
  330. })
  331. return
  332. }
  333. user.ConnectionErrors = 0
  334. user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1)
  335. user.addToJIDMap()
  336. user.SetSession(&session)
  337. _ = c.WriteJSON(map[string]interface{}{
  338. "success": true,
  339. "jid": user.JID,
  340. })
  341. user.PostLogin()
  342. }