provisioning.go 12 KB

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