provisioning.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "bufio"
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "net"
  23. "net/http"
  24. "strings"
  25. "time"
  26. "github.com/gorilla/websocket"
  27. log "maunium.net/go/maulogger/v2"
  28. "maunium.net/go/mautrix/id"
  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. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
  47. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
  48. }
  49. type responseWrap struct {
  50. http.ResponseWriter
  51. statusCode int
  52. }
  53. var _ http.Hijacker = (*responseWrap)(nil)
  54. func (rw *responseWrap) WriteHeader(statusCode int) {
  55. rw.ResponseWriter.WriteHeader(statusCode)
  56. rw.statusCode = statusCode
  57. }
  58. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  59. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  60. if !ok {
  61. return nil, nil, errors.New("response does not implement http.Hijacker")
  62. }
  63. return hijacker.Hijack()
  64. }
  65. func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
  66. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  67. auth := r.Header.Get("Authorization")
  68. if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
  69. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  70. for _, part := range authParts {
  71. part = strings.TrimSpace(part)
  72. if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
  73. auth = part[len("net.maunium.whatsapp.auth-"):]
  74. break
  75. }
  76. }
  77. } else if strings.HasPrefix(auth, "Bearer ") {
  78. auth = auth[len("Bearer "):]
  79. }
  80. if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
  81. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  82. "error": "Invalid auth token",
  83. "errcode": "M_FORBIDDEN",
  84. })
  85. return
  86. }
  87. userID := r.URL.Query().Get("user_id")
  88. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  89. start := time.Now()
  90. wWrap := &responseWrap{w, 200}
  91. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  92. duration := time.Now().Sub(start).Seconds()
  93. prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  94. })
  95. }
  96. type Error struct {
  97. Success bool `json:"success"`
  98. Error string `json:"error"`
  99. ErrCode string `json:"errcode"`
  100. }
  101. type Response struct {
  102. Success bool `json:"success"`
  103. Status string `json:"status"`
  104. }
  105. func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
  106. user := r.Context().Value("user").(*User)
  107. if user.Session == nil && user.Client == nil {
  108. jsonResponse(w, http.StatusNotFound, Error{
  109. Error: "Nothing to purge: no session information stored and no active connection.",
  110. ErrCode: "no session",
  111. })
  112. return
  113. }
  114. user.DeleteConnection()
  115. user.DeleteSession()
  116. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  117. }
  118. func (prov *ProvisioningAPI) DeleteConnection(w http.ResponseWriter, r *http.Request) {
  119. user := r.Context().Value("user").(*User)
  120. if user.Client == nil {
  121. jsonResponse(w, http.StatusNotFound, Error{
  122. Error: "You don't have a WhatsApp connection.",
  123. ErrCode: "not connected",
  124. })
  125. return
  126. }
  127. user.DeleteConnection()
  128. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp and connection deleted"})
  129. }
  130. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  131. user := r.Context().Value("user").(*User)
  132. if user.Client == nil {
  133. jsonResponse(w, http.StatusNotFound, Error{
  134. Error: "You don't have a WhatsApp connection.",
  135. ErrCode: "no connection",
  136. })
  137. return
  138. }
  139. user.DeleteConnection()
  140. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  141. }
  142. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  143. user := r.Context().Value("user").(*User)
  144. if user.Client == nil {
  145. if user.Session == nil {
  146. jsonResponse(w, http.StatusForbidden, Error{
  147. Error: "No existing connection and no session. Please log in first.",
  148. ErrCode: "no session",
  149. })
  150. } else {
  151. user.Connect(false)
  152. jsonResponse(w, http.StatusOK, Response{true, "Created connection to WhatsApp."})
  153. }
  154. return
  155. }
  156. // TODO reimplement
  157. //user.log.Debugln("Received /reconnect request, disconnecting")
  158. //wasConnected := true
  159. //err := user.Conn.Disconnect()
  160. //if err == whatsapp.ErrNotConnected {
  161. // wasConnected = false
  162. //} else if err != nil {
  163. // user.log.Warnln("Error while disconnecting:", err)
  164. //}
  165. //
  166. //user.log.Debugln("Restoring session for /reconnect")
  167. //err = user.Conn.Restore(true, r.Context())
  168. //user.log.Debugfln("Restore session for /reconnect responded with %v", err)
  169. //if err == whatsapp.ErrInvalidSession {
  170. // if user.Session != nil {
  171. // user.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  172. // user.Conn.SetSession(*user.Session)
  173. // err = user.Conn.Restore(true, r.Context())
  174. // } else {
  175. // jsonResponse(w, http.StatusForbidden, Error{
  176. // Error: "You're not logged in",
  177. // ErrCode: "not logged in",
  178. // })
  179. // return
  180. // }
  181. //}
  182. //if err == whatsapp.ErrLoginInProgress {
  183. // jsonResponse(w, http.StatusConflict, Error{
  184. // Error: "A login or reconnection is already in progress.",
  185. // ErrCode: "login in progress",
  186. // })
  187. // return
  188. //} else if err == whatsapp.ErrAlreadyLoggedIn {
  189. // jsonResponse(w, http.StatusConflict, Error{
  190. // Error: "You were already connected.",
  191. // ErrCode: err.Error(),
  192. // })
  193. // return
  194. //}
  195. //if err != nil {
  196. // user.log.Warnln("Error while reconnecting:", err)
  197. // jsonResponse(w, http.StatusInternalServerError, Error{
  198. // Error: fmt.Sprintf("Unknown error while reconnecting: %v", err),
  199. // ErrCode: err.Error(),
  200. // })
  201. // user.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  202. // err = user.Conn.Disconnect()
  203. // if err != nil {
  204. // user.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  205. // }
  206. // return
  207. //}
  208. //user.ConnectionErrors = 0
  209. //user.PostLogin()
  210. //
  211. //var msg string
  212. //if wasConnected {
  213. // msg = "Reconnected successfully."
  214. //} else {
  215. // msg = "Connected successfully."
  216. //}
  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. "conn": nil,
  226. }
  227. if user.JID.IsEmpty() {
  228. wa["jid"] = user.JID.String()
  229. }
  230. if user.Client != nil {
  231. wa["conn"] = map[string]interface{}{
  232. "is_connected": user.Client.IsConnected(),
  233. "is_logged_in": user.Client.IsLoggedIn,
  234. }
  235. }
  236. resp := map[string]interface{}{
  237. "mxid": user.MXID,
  238. "admin": user.Admin,
  239. "whitelisted": user.Whitelisted,
  240. "relaybot_whitelisted": user.RelaybotWhitelisted,
  241. "whatsapp": wa,
  242. }
  243. jsonResponse(w, http.StatusOK, resp)
  244. }
  245. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  246. w.Header().Add("Content-Type", "application/json")
  247. w.WriteHeader(status)
  248. _ = json.NewEncoder(w).Encode(response)
  249. }
  250. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  251. user := r.Context().Value("user").(*User)
  252. if user.Session == nil {
  253. jsonResponse(w, http.StatusNotFound, Error{
  254. Error: "You're not logged in",
  255. ErrCode: "not logged in",
  256. })
  257. return
  258. }
  259. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  260. if user.Client == nil {
  261. if !force {
  262. jsonResponse(w, http.StatusNotFound, Error{
  263. Error: "You're not connected",
  264. ErrCode: "not connected",
  265. })
  266. }
  267. } else {
  268. // TODO reimplement
  269. //err := user.Client.Logout()
  270. //if err != nil {
  271. // user.log.Warnln("Error while logging out:", err)
  272. // if !force {
  273. // jsonResponse(w, http.StatusInternalServerError, Error{
  274. // Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  275. // ErrCode: err.Error(),
  276. // })
  277. // return
  278. // }
  279. //}
  280. user.DeleteConnection()
  281. }
  282. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  283. user.removeFromJIDMap(StateLoggedOut)
  284. user.DeleteSession()
  285. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  286. }
  287. var upgrader = websocket.Upgrader{
  288. CheckOrigin: func(r *http.Request) bool {
  289. return true
  290. },
  291. Subprotocols: []string{"net.maunium.whatsapp.login"},
  292. }
  293. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  294. // TODO reimplement
  295. //userID := r.URL.Query().Get("user_id")
  296. //user := prov.bridge.GetUserByMXID(id.UserID(userID))
  297. //
  298. //c, err := upgrader.Upgrade(w, r, nil)
  299. //if err != nil {
  300. // prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  301. // return
  302. //}
  303. //defer c.Close()
  304. //if !user.Connect(true) {
  305. // user.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  306. // _ = c.WriteJSON(Error{
  307. // Error: "Failed to connect to WhatsApp",
  308. // ErrCode: "connection error",
  309. // })
  310. // return
  311. //}
  312. //
  313. //qrChan := make(chan string, 3)
  314. //go func() {
  315. // for code := range qrChan {
  316. // if code == "stop" {
  317. // return
  318. // }
  319. // _ = c.WriteJSON(map[string]interface{}{
  320. // "code": code,
  321. // })
  322. // }
  323. //}()
  324. //
  325. //go func() {
  326. // // Read everything so SetCloseHandler() works
  327. // for {
  328. // _, _, err = c.ReadMessage()
  329. // if err != nil {
  330. // break
  331. // }
  332. // }
  333. //}()
  334. //ctx, cancel := context.WithCancel(context.Background())
  335. //c.SetCloseHandler(func(code int, text string) error {
  336. // user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  337. // cancel()
  338. // return nil
  339. //})
  340. //
  341. //user.log.Debugln("Starting login via provisioning API")
  342. //session, jid, err := user.Conn.Login(qrChan, ctx)
  343. //qrChan <- "stop"
  344. //if err != nil {
  345. // var msg string
  346. // if errors.Is(err, whatsapp.ErrAlreadyLoggedIn) {
  347. // msg = "You're already logged in"
  348. // } else if errors.Is(err, whatsapp.ErrLoginInProgress) {
  349. // msg = "You have a login in progress already."
  350. // } else if errors.Is(err, whatsapp.ErrLoginTimedOut) {
  351. // msg = "QR code scan timed out. Please try again."
  352. // } else if errors.Is(err, whatsapp.ErrInvalidWebsocket) {
  353. // msg = "WhatsApp connection error. Please try again."
  354. // // TODO might need to make sure it reconnects?
  355. // } else if errors.Is(err, whatsapp.ErrMultiDeviceNotSupported) {
  356. // msg = "WhatsApp multi-device is not currently supported. Please disable it and try again."
  357. // } else {
  358. // msg = fmt.Sprintf("Unknown error while logging in: %v", err)
  359. // }
  360. // user.log.Warnln("Failed to log in:", err)
  361. // _ = c.WriteJSON(Error{
  362. // Error: msg,
  363. // ErrCode: err.Error(),
  364. // })
  365. // return
  366. //}
  367. //user.log.Debugln("Successful login as", jid, "via provisioning API")
  368. //user.ConnectionErrors = 0
  369. //user.JID = strings.Replace(jid, whatsapp.OldUserSuffix, whatsapp.NewUserSuffix, 1)
  370. //user.addToJIDMap()
  371. //user.SetSession(&session)
  372. //_ = c.WriteJSON(map[string]interface{}{
  373. // "success": true,
  374. // "jid": user.JID,
  375. //})
  376. //user.PostLogin()
  377. }