provisioning.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. }
  121. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  122. user := r.Context().Value("user").(*User)
  123. if user.Client == nil {
  124. jsonResponse(w, http.StatusNotFound, Error{
  125. Error: "You don't have a WhatsApp connection.",
  126. ErrCode: "no connection",
  127. })
  128. return
  129. }
  130. user.DeleteConnection()
  131. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  132. }
  133. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  134. user := r.Context().Value("user").(*User)
  135. if user.Client == nil {
  136. if user.Session == nil {
  137. jsonResponse(w, http.StatusForbidden, Error{
  138. Error: "No existing connection and no session. Please log in first.",
  139. ErrCode: "no session",
  140. })
  141. } else {
  142. user.Connect()
  143. jsonResponse(w, http.StatusAccepted, Response{true, "Created connection to WhatsApp."})
  144. }
  145. } else {
  146. user.DeleteConnection()
  147. user.Connect()
  148. jsonResponse(w, http.StatusAccepted, Response{true, "Restarted connection to WhatsApp"})
  149. }
  150. }
  151. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  152. user := r.Context().Value("user").(*User)
  153. wa := map[string]interface{}{
  154. "has_session": user.Session != nil,
  155. "management_room": user.ManagementRoom,
  156. "conn": nil,
  157. }
  158. if user.JID.IsEmpty() {
  159. wa["jid"] = user.JID.String()
  160. }
  161. if user.Client != nil {
  162. wa["conn"] = map[string]interface{}{
  163. "is_connected": user.Client.IsConnected(),
  164. "is_logged_in": user.Client.IsLoggedIn,
  165. }
  166. }
  167. resp := map[string]interface{}{
  168. "mxid": user.MXID,
  169. "admin": user.Admin,
  170. "whitelisted": user.Whitelisted,
  171. "relaybot_whitelisted": user.RelaybotWhitelisted,
  172. "whatsapp": wa,
  173. }
  174. jsonResponse(w, http.StatusOK, resp)
  175. }
  176. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  177. w.Header().Add("Content-Type", "application/json")
  178. w.WriteHeader(status)
  179. _ = json.NewEncoder(w).Encode(response)
  180. }
  181. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  182. user := r.Context().Value("user").(*User)
  183. if user.Session == nil {
  184. jsonResponse(w, http.StatusNotFound, Error{
  185. Error: "You're not logged in",
  186. ErrCode: "not logged in",
  187. })
  188. return
  189. }
  190. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  191. if user.Client == nil {
  192. if !force {
  193. jsonResponse(w, http.StatusNotFound, Error{
  194. Error: "You're not connected",
  195. ErrCode: "not connected",
  196. })
  197. }
  198. } else {
  199. err := user.Client.Logout()
  200. if err != nil {
  201. user.log.Warnln("Error while logging out:", err)
  202. if !force {
  203. jsonResponse(w, http.StatusInternalServerError, Error{
  204. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  205. ErrCode: err.Error(),
  206. })
  207. return
  208. }
  209. }
  210. user.DeleteConnection()
  211. }
  212. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  213. user.removeFromJIDMap(StateLoggedOut)
  214. user.DeleteSession()
  215. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  216. }
  217. var upgrader = websocket.Upgrader{
  218. CheckOrigin: func(r *http.Request) bool {
  219. return true
  220. },
  221. Subprotocols: []string{"net.maunium.whatsapp.login"},
  222. }
  223. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  224. userID := r.URL.Query().Get("user_id")
  225. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  226. c, err := upgrader.Upgrade(w, r, nil)
  227. if err != nil {
  228. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  229. return
  230. }
  231. defer func() {
  232. err := c.Close()
  233. if err != nil {
  234. user.log.Debugln("Error closing websocket:", err)
  235. }
  236. }()
  237. go func() {
  238. // Read everything so SetCloseHandler() works
  239. for {
  240. _, _, err = c.ReadMessage()
  241. if err != nil {
  242. break
  243. }
  244. }
  245. }()
  246. ctx, cancel := context.WithCancel(context.Background())
  247. c.SetCloseHandler(func(code int, text string) error {
  248. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  249. cancel()
  250. return nil
  251. })
  252. qrChan, err := user.Login(ctx)
  253. if err != nil {
  254. user.log.Errorf("Failed to log in from provisioning API:", err)
  255. if errors.Is(err, ErrAlreadyLoggedIn) {
  256. go user.Connect()
  257. _ = c.WriteJSON(Error{
  258. Error: "You're already logged into WhatsApp",
  259. ErrCode: "already logged in",
  260. })
  261. } else {
  262. _ = c.WriteJSON(Error{
  263. Error: "Failed to connect to WhatsApp",
  264. ErrCode: "connection error",
  265. })
  266. }
  267. }
  268. user.log.Debugln("Started login via provisioning API")
  269. for {
  270. select {
  271. case evt := <-qrChan:
  272. switch evt {
  273. case whatsmeow.QRChannelSuccess:
  274. jid := user.Client.Store.ID
  275. user.log.Debugln("Successful login as", jid, "via provisioning API")
  276. _ = c.WriteJSON(map[string]interface{}{
  277. "success": true,
  278. "jid": jid,
  279. "phone": fmt.Sprintf("+%s", jid.User),
  280. })
  281. case whatsmeow.QRChannelTimeout:
  282. user.log.Debugln("Login via provisioning API timed out")
  283. _ = c.WriteJSON(Error{
  284. Error: "QR code scan timed out. Please try again.",
  285. ErrCode: "login timed out",
  286. })
  287. default:
  288. _ = c.WriteJSON(map[string]interface{}{
  289. "code": string(evt),
  290. })
  291. continue
  292. }
  293. return
  294. case <-ctx.Done():
  295. return
  296. }
  297. }
  298. }