provisioning.go 11 KB

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