provisioning.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. 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. "jid": user.JID,
  223. "conn": nil,
  224. "ping": nil,
  225. }
  226. if user.Conn != nil {
  227. wa["conn"] = map[string]interface{}{
  228. "is_connected": user.Conn.IsConnected(),
  229. "is_logged_in": user.Conn.IsLoggedIn(),
  230. "is_login_in_progress": user.Conn.IsLoginInProgress(),
  231. }
  232. ok, err := user.Conn.AdminTest()
  233. wa["ping"] = map[string]interface{}{
  234. "ok": ok,
  235. "err": err,
  236. }
  237. }
  238. resp := map[string]interface{}{
  239. "mxid": user.MXID,
  240. "admin": user.Admin,
  241. "whitelisted": user.Whitelisted,
  242. "relaybot_whitelisted": user.RelaybotWhitelisted,
  243. "whatsapp": wa,
  244. }
  245. jsonResponse(w, http.StatusOK, resp)
  246. }
  247. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  248. w.Header().Add("Content-Type", "application/json")
  249. w.WriteHeader(status)
  250. _ = json.NewEncoder(w).Encode(response)
  251. }
  252. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  253. user := r.Context().Value("user").(*User)
  254. if user.Session == nil {
  255. jsonResponse(w, http.StatusNotFound, Error{
  256. Error: "You're not logged in",
  257. ErrCode: "not logged in",
  258. })
  259. return
  260. }
  261. err := user.Conn.Logout()
  262. if err != nil {
  263. user.log.Warnln("Error while logging out:", err)
  264. jsonResponse(w, http.StatusInternalServerError, Error{
  265. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  266. ErrCode: err.Error(),
  267. })
  268. return
  269. }
  270. _, err = user.Conn.Disconnect()
  271. if err != nil {
  272. user.log.Warnln("Error while disconnecting after logout:", err)
  273. }
  274. user.Conn.RemoveHandlers()
  275. user.Conn = nil
  276. user.removeFromJIDMap()
  277. // TODO this causes a foreign key violation, which should be fixed
  278. //ce.User.JID = ""
  279. user.SetSession(nil)
  280. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  281. }
  282. var upgrader = websocket.Upgrader{}
  283. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  284. userID := r.URL.Query().Get("user_id")
  285. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  286. c, err := upgrader.Upgrade(w, r, nil)
  287. if err != nil {
  288. prov.log.Errorfln("Failed to upgrade connection to websocket:", err)
  289. return
  290. }
  291. defer c.Close()
  292. if !user.Connect(true) {
  293. user.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  294. _ = c.WriteJSON(Error{
  295. Error: "Failed to connect to WhatsApp",
  296. ErrCode: "connection error",
  297. })
  298. return
  299. }
  300. qrChan := make(chan string, 3)
  301. go func() {
  302. for code := range qrChan {
  303. if code == "stop" {
  304. return
  305. }
  306. _ = c.WriteJSON(map[string]interface{}{
  307. "code": code,
  308. })
  309. }
  310. }()
  311. session, err := user.Conn.LoginWithRetry(qrChan, user.bridge.Config.Bridge.LoginQRRegenCount)
  312. qrChan <- "stop"
  313. if err != nil {
  314. var msg string
  315. if err == whatsapp.ErrAlreadyLoggedIn {
  316. msg = "You're already logged in"
  317. } else if err == whatsapp.ErrLoginInProgress {
  318. msg = "You have a login in progress already."
  319. } else if err == whatsapp.ErrLoginTimedOut {
  320. msg = "QR code scan timed out. Please try again."
  321. } else {
  322. user.log.Warnln("Failed to log in:", err)
  323. msg = fmt.Sprintf("Unknown error while logging in: %v", err)
  324. }
  325. _ = c.WriteJSON(Error{
  326. Error: msg,
  327. ErrCode: err.Error(),
  328. })
  329. return
  330. }
  331. user.ConnectionErrors = 0
  332. user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1)
  333. user.addToJIDMap()
  334. user.SetSession(&session)
  335. _ = c.WriteJSON(map[string]interface{}{
  336. "success": true,
  337. "jid": user.JID,
  338. })
  339. user.PostLogin()
  340. }