provisioning.go 12 KB

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