provisioning.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. "fmt"
  23. "net"
  24. "net/http"
  25. "strings"
  26. "time"
  27. "github.com/gorilla/websocket"
  28. "go.mau.fi/whatsmeow"
  29. log "maunium.net/go/maulogger/v2"
  30. "maunium.net/go/mautrix/id"
  31. )
  32. type ProvisioningAPI struct {
  33. bridge *Bridge
  34. log log.Logger
  35. }
  36. func (prov *ProvisioningAPI) Init() {
  37. prov.log = prov.bridge.Log.Sub("Provisioning")
  38. prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
  39. r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
  40. r.Use(prov.AuthMiddleware)
  41. r.HandleFunc("/ping", prov.Ping).Methods(http.MethodGet)
  42. r.HandleFunc("/login", prov.Login).Methods(http.MethodGet)
  43. r.HandleFunc("/logout", prov.Logout).Methods(http.MethodPost)
  44. r.HandleFunc("/delete_session", prov.DeleteSession).Methods(http.MethodPost)
  45. r.HandleFunc("/disconnect", prov.Disconnect).Methods(http.MethodPost)
  46. r.HandleFunc("/reconnect", prov.Reconnect).Methods(http.MethodPost)
  47. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
  48. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
  49. // Deprecated, just use /disconnect
  50. r.HandleFunc("/delete_connection", prov.Disconnect).Methods(http.MethodPost)
  51. }
  52. type responseWrap struct {
  53. http.ResponseWriter
  54. statusCode int
  55. }
  56. var _ http.Hijacker = (*responseWrap)(nil)
  57. func (rw *responseWrap) WriteHeader(statusCode int) {
  58. rw.ResponseWriter.WriteHeader(statusCode)
  59. rw.statusCode = statusCode
  60. }
  61. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  62. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  63. if !ok {
  64. return nil, nil, errors.New("response does not implement http.Hijacker")
  65. }
  66. return hijacker.Hijack()
  67. }
  68. func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
  69. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  70. auth := r.Header.Get("Authorization")
  71. if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
  72. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  73. for _, part := range authParts {
  74. part = strings.TrimSpace(part)
  75. if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
  76. auth = part[len("net.maunium.whatsapp.auth-"):]
  77. break
  78. }
  79. }
  80. } else if strings.HasPrefix(auth, "Bearer ") {
  81. auth = auth[len("Bearer "):]
  82. }
  83. if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
  84. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  85. "error": "Invalid auth token",
  86. "errcode": "M_FORBIDDEN",
  87. })
  88. return
  89. }
  90. userID := r.URL.Query().Get("user_id")
  91. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  92. start := time.Now()
  93. wWrap := &responseWrap{w, 200}
  94. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  95. duration := time.Now().Sub(start).Seconds()
  96. prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  97. })
  98. }
  99. type Error struct {
  100. Success bool `json:"success"`
  101. Error string `json:"error"`
  102. ErrCode string `json:"errcode"`
  103. }
  104. type Response struct {
  105. Success bool `json:"success"`
  106. Status string `json:"status"`
  107. }
  108. func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
  109. user := r.Context().Value("user").(*User)
  110. if user.Session == nil && user.Client == nil {
  111. jsonResponse(w, http.StatusNotFound, Error{
  112. Error: "Nothing to purge: no session information stored and no active connection.",
  113. ErrCode: "no session",
  114. })
  115. return
  116. }
  117. user.DeleteConnection()
  118. user.DeleteSession()
  119. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  120. user.removeFromJIDMap(StateLoggedOut)
  121. }
  122. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  123. user := r.Context().Value("user").(*User)
  124. if user.Client == nil {
  125. jsonResponse(w, http.StatusNotFound, Error{
  126. Error: "You don't have a WhatsApp connection.",
  127. ErrCode: "no connection",
  128. })
  129. return
  130. }
  131. user.DeleteConnection()
  132. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  133. user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  134. }
  135. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  136. user := r.Context().Value("user").(*User)
  137. if user.Client == nil {
  138. if user.Session == nil {
  139. jsonResponse(w, http.StatusForbidden, Error{
  140. Error: "No existing connection and no session. Please log in first.",
  141. ErrCode: "no session",
  142. })
  143. } else {
  144. user.Connect()
  145. jsonResponse(w, http.StatusAccepted, Response{true, "Created connection to WhatsApp."})
  146. }
  147. } else {
  148. user.DeleteConnection()
  149. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  150. user.Connect()
  151. jsonResponse(w, http.StatusAccepted, Response{true, "Restarted connection to WhatsApp"})
  152. }
  153. }
  154. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  155. user := r.Context().Value("user").(*User)
  156. wa := map[string]interface{}{
  157. "has_session": user.Session != nil,
  158. "management_room": user.ManagementRoom,
  159. "conn": nil,
  160. }
  161. if !user.JID.IsEmpty() {
  162. wa["jid"] = user.JID.String()
  163. wa["phone"] = "+" + user.JID.User
  164. wa["device"] = user.JID.Device
  165. }
  166. if user.Client != nil {
  167. wa["conn"] = map[string]interface{}{
  168. "is_connected": user.Client.IsConnected(),
  169. "is_logged_in": user.Client.IsLoggedIn,
  170. }
  171. }
  172. resp := map[string]interface{}{
  173. "mxid": user.MXID,
  174. "admin": user.Admin,
  175. "whitelisted": user.Whitelisted,
  176. "relay_whitelisted": user.RelayWhitelisted,
  177. "whatsapp": wa,
  178. }
  179. jsonResponse(w, http.StatusOK, resp)
  180. }
  181. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  182. w.Header().Add("Content-Type", "application/json")
  183. w.WriteHeader(status)
  184. _ = json.NewEncoder(w).Encode(response)
  185. }
  186. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  187. user := r.Context().Value("user").(*User)
  188. if user.Session == nil {
  189. jsonResponse(w, http.StatusNotFound, Error{
  190. Error: "You're not logged in",
  191. ErrCode: "not logged in",
  192. })
  193. return
  194. }
  195. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  196. if user.Client == nil {
  197. if !force {
  198. jsonResponse(w, http.StatusNotFound, Error{
  199. Error: "You're not connected",
  200. ErrCode: "not connected",
  201. })
  202. }
  203. } else {
  204. err := user.Client.Logout()
  205. if err != nil {
  206. user.log.Warnln("Error while logging out:", err)
  207. if !force {
  208. jsonResponse(w, http.StatusInternalServerError, Error{
  209. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  210. ErrCode: err.Error(),
  211. })
  212. return
  213. }
  214. } else {
  215. user.Session = nil
  216. }
  217. user.DeleteConnection()
  218. }
  219. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  220. user.removeFromJIDMap(StateLoggedOut)
  221. user.DeleteSession()
  222. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  223. }
  224. var upgrader = websocket.Upgrader{
  225. CheckOrigin: func(r *http.Request) bool {
  226. return true
  227. },
  228. Subprotocols: []string{"net.maunium.whatsapp.login"},
  229. }
  230. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  231. userID := r.URL.Query().Get("user_id")
  232. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  233. c, err := upgrader.Upgrade(w, r, nil)
  234. if err != nil {
  235. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  236. return
  237. }
  238. defer func() {
  239. err := c.Close()
  240. if err != nil {
  241. user.log.Debugln("Error closing websocket:", err)
  242. }
  243. }()
  244. go func() {
  245. // Read everything so SetCloseHandler() works
  246. for {
  247. _, _, err = c.ReadMessage()
  248. if err != nil {
  249. break
  250. }
  251. }
  252. }()
  253. ctx, cancel := context.WithCancel(context.Background())
  254. c.SetCloseHandler(func(code int, text string) error {
  255. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  256. cancel()
  257. return nil
  258. })
  259. qrChan, err := user.Login(ctx)
  260. if err != nil {
  261. user.log.Errorf("Failed to log in from provisioning API:", err)
  262. if errors.Is(err, ErrAlreadyLoggedIn) {
  263. go user.Connect()
  264. _ = c.WriteJSON(Error{
  265. Error: "You're already logged into WhatsApp",
  266. ErrCode: "already logged in",
  267. })
  268. } else {
  269. _ = c.WriteJSON(Error{
  270. Error: "Failed to connect to WhatsApp",
  271. ErrCode: "connection error",
  272. })
  273. }
  274. }
  275. user.log.Debugln("Started login via provisioning API")
  276. for {
  277. select {
  278. case evt := <-qrChan:
  279. switch evt {
  280. case whatsmeow.QRChannelSuccess:
  281. jid := user.Client.Store.ID
  282. user.log.Debugln("Successful login as", jid, "via provisioning API")
  283. _ = c.WriteJSON(map[string]interface{}{
  284. "success": true,
  285. "jid": jid,
  286. "phone": fmt.Sprintf("+%s", jid.User),
  287. })
  288. case whatsmeow.QRChannelTimeout:
  289. user.log.Debugln("Login via provisioning API timed out")
  290. _ = c.WriteJSON(Error{
  291. Error: "QR code scan timed out. Please try again.",
  292. ErrCode: "login timed out",
  293. })
  294. case whatsmeow.QRChannelErrUnexpectedEvent:
  295. user.log.Debugln("Login via provisioning API failed due to unexpected event")
  296. _ = c.WriteJSON(Error{
  297. Error: "Got unexpected event while waiting for QRs, perhaps you're already logged in?",
  298. ErrCode: "unexpected event",
  299. })
  300. case whatsmeow.QRChannelScannedWithoutMultidevice:
  301. _ = c.WriteJSON(Error{
  302. Error: "Please enable the WhatsApp multidevice beta and scan the QR code again.",
  303. ErrCode: "multidevice not enabled",
  304. })
  305. continue
  306. default:
  307. _ = c.WriteJSON(map[string]interface{}{
  308. "code": string(evt),
  309. })
  310. continue
  311. }
  312. return
  313. case <-ctx.Done():
  314. return
  315. }
  316. }
  317. }