provisioning.go 12 KB

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