provisioning.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. }
  164. if user.Client != nil {
  165. wa["conn"] = map[string]interface{}{
  166. "is_connected": user.Client.IsConnected(),
  167. "is_logged_in": user.Client.IsLoggedIn,
  168. }
  169. }
  170. resp := map[string]interface{}{
  171. "mxid": user.MXID,
  172. "admin": user.Admin,
  173. "whitelisted": user.Whitelisted,
  174. "relay_whitelisted": user.RelayWhitelisted,
  175. "whatsapp": wa,
  176. }
  177. jsonResponse(w, http.StatusOK, resp)
  178. }
  179. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  180. w.Header().Add("Content-Type", "application/json")
  181. w.WriteHeader(status)
  182. _ = json.NewEncoder(w).Encode(response)
  183. }
  184. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  185. user := r.Context().Value("user").(*User)
  186. if user.Session == nil {
  187. jsonResponse(w, http.StatusNotFound, Error{
  188. Error: "You're not logged in",
  189. ErrCode: "not logged in",
  190. })
  191. return
  192. }
  193. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  194. if user.Client == nil {
  195. if !force {
  196. jsonResponse(w, http.StatusNotFound, Error{
  197. Error: "You're not connected",
  198. ErrCode: "not connected",
  199. })
  200. }
  201. } else {
  202. err := user.Client.Logout()
  203. if err != nil {
  204. user.log.Warnln("Error while logging out:", err)
  205. if !force {
  206. jsonResponse(w, http.StatusInternalServerError, Error{
  207. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  208. ErrCode: err.Error(),
  209. })
  210. return
  211. }
  212. } else {
  213. user.Session = nil
  214. }
  215. user.DeleteConnection()
  216. }
  217. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  218. user.removeFromJIDMap(StateLoggedOut)
  219. user.DeleteSession()
  220. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  221. }
  222. var upgrader = websocket.Upgrader{
  223. CheckOrigin: func(r *http.Request) bool {
  224. return true
  225. },
  226. Subprotocols: []string{"net.maunium.whatsapp.login"},
  227. }
  228. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  229. userID := r.URL.Query().Get("user_id")
  230. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  231. c, err := upgrader.Upgrade(w, r, nil)
  232. if err != nil {
  233. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  234. return
  235. }
  236. defer func() {
  237. err := c.Close()
  238. if err != nil {
  239. user.log.Debugln("Error closing websocket:", err)
  240. }
  241. }()
  242. go func() {
  243. // Read everything so SetCloseHandler() works
  244. for {
  245. _, _, err = c.ReadMessage()
  246. if err != nil {
  247. break
  248. }
  249. }
  250. }()
  251. ctx, cancel := context.WithCancel(context.Background())
  252. c.SetCloseHandler(func(code int, text string) error {
  253. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  254. cancel()
  255. return nil
  256. })
  257. qrChan, err := user.Login(ctx)
  258. if err != nil {
  259. user.log.Errorf("Failed to log in from provisioning API:", err)
  260. if errors.Is(err, ErrAlreadyLoggedIn) {
  261. go user.Connect()
  262. _ = c.WriteJSON(Error{
  263. Error: "You're already logged into WhatsApp",
  264. ErrCode: "already logged in",
  265. })
  266. } else {
  267. _ = c.WriteJSON(Error{
  268. Error: "Failed to connect to WhatsApp",
  269. ErrCode: "connection error",
  270. })
  271. }
  272. }
  273. user.log.Debugln("Started login via provisioning API")
  274. for {
  275. select {
  276. case evt := <-qrChan:
  277. switch evt {
  278. case whatsmeow.QRChannelSuccess:
  279. jid := user.Client.Store.ID
  280. user.log.Debugln("Successful login as", jid, "via provisioning API")
  281. _ = c.WriteJSON(map[string]interface{}{
  282. "success": true,
  283. "jid": jid,
  284. "phone": fmt.Sprintf("+%s", jid.User),
  285. })
  286. case whatsmeow.QRChannelTimeout:
  287. user.log.Debugln("Login via provisioning API timed out")
  288. _ = c.WriteJSON(Error{
  289. Error: "QR code scan timed out. Please try again.",
  290. ErrCode: "login timed out",
  291. })
  292. case whatsmeow.QRChannelErrUnexpectedEvent:
  293. user.log.Debugln("Login via provisioning API failed due to unexpected event")
  294. _ = c.WriteJSON(Error{
  295. Error: "Got unexpected event while waiting for QRs, perhaps you're already logged in?",
  296. ErrCode: "unexpected event",
  297. })
  298. case whatsmeow.QRChannelScannedWithoutMultidevice:
  299. _ = c.WriteJSON(Error{
  300. Error: "Please enable the WhatsApp multidevice beta and scan the QR code again.",
  301. ErrCode: "multidevice not enabled",
  302. })
  303. continue
  304. default:
  305. _ = c.WriteJSON(map[string]interface{}{
  306. "code": string(evt),
  307. })
  308. continue
  309. }
  310. return
  311. case <-ctx.Done():
  312. return
  313. }
  314. }
  315. }