provisioning.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2022 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/mux"
  28. "github.com/gorilla/websocket"
  29. "go.mau.fi/whatsmeow/appstate"
  30. "go.mau.fi/whatsmeow/types"
  31. "go.mau.fi/whatsmeow"
  32. log "maunium.net/go/maulogger/v2"
  33. "maunium.net/go/mautrix/id"
  34. )
  35. type ProvisioningAPI struct {
  36. bridge *Bridge
  37. log log.Logger
  38. }
  39. func (prov *ProvisioningAPI) Init() {
  40. prov.log = prov.bridge.Log.Sub("Provisioning")
  41. prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.AppService.Provisioning.Prefix)
  42. r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.AppService.Provisioning.Prefix).Subrouter()
  43. r.Use(prov.AuthMiddleware)
  44. r.HandleFunc("/ping", prov.Ping).Methods(http.MethodGet)
  45. r.HandleFunc("/login", prov.Login).Methods(http.MethodGet)
  46. r.HandleFunc("/logout", prov.Logout).Methods(http.MethodPost)
  47. r.HandleFunc("/delete_session", prov.DeleteSession).Methods(http.MethodPost)
  48. r.HandleFunc("/disconnect", prov.Disconnect).Methods(http.MethodPost)
  49. r.HandleFunc("/reconnect", prov.Reconnect).Methods(http.MethodPost)
  50. r.HandleFunc("/sync/appstate/{name}", prov.SyncAppState).Methods(http.MethodPost)
  51. r.HandleFunc("/contacts", prov.ListContacts).Methods(http.MethodGet)
  52. r.HandleFunc("/pm/{number}", prov.StartPM).Methods(http.MethodPost)
  53. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
  54. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
  55. // Deprecated, just use /disconnect
  56. r.HandleFunc("/delete_connection", prov.Disconnect).Methods(http.MethodPost)
  57. }
  58. type responseWrap struct {
  59. http.ResponseWriter
  60. statusCode int
  61. }
  62. var _ http.Hijacker = (*responseWrap)(nil)
  63. func (rw *responseWrap) WriteHeader(statusCode int) {
  64. rw.ResponseWriter.WriteHeader(statusCode)
  65. rw.statusCode = statusCode
  66. }
  67. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  68. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  69. if !ok {
  70. return nil, nil, errors.New("response does not implement http.Hijacker")
  71. }
  72. return hijacker.Hijack()
  73. }
  74. func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
  75. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  76. auth := r.Header.Get("Authorization")
  77. if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
  78. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  79. for _, part := range authParts {
  80. part = strings.TrimSpace(part)
  81. if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
  82. auth = part[len("net.maunium.whatsapp.auth-"):]
  83. break
  84. }
  85. }
  86. } else if strings.HasPrefix(auth, "Bearer ") {
  87. auth = auth[len("Bearer "):]
  88. }
  89. if auth != prov.bridge.Config.AppService.Provisioning.SharedSecret {
  90. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  91. "error": "Invalid auth token",
  92. "errcode": "M_FORBIDDEN",
  93. })
  94. return
  95. }
  96. userID := r.URL.Query().Get("user_id")
  97. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  98. start := time.Now()
  99. wWrap := &responseWrap{w, 200}
  100. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  101. duration := time.Now().Sub(start).Seconds()
  102. prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  103. })
  104. }
  105. type Error struct {
  106. Success bool `json:"success"`
  107. Error string `json:"error"`
  108. ErrCode string `json:"errcode"`
  109. }
  110. type Response struct {
  111. Success bool `json:"success"`
  112. Status string `json:"status"`
  113. }
  114. func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
  115. user := r.Context().Value("user").(*User)
  116. if user.Session == nil && user.Client == nil {
  117. jsonResponse(w, http.StatusNotFound, Error{
  118. Error: "Nothing to purge: no session information stored and no active connection.",
  119. ErrCode: "no session",
  120. })
  121. return
  122. }
  123. user.DeleteConnection()
  124. user.DeleteSession()
  125. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  126. user.removeFromJIDMap(StateLoggedOut)
  127. }
  128. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  129. user := r.Context().Value("user").(*User)
  130. if user.Client == nil {
  131. jsonResponse(w, http.StatusNotFound, Error{
  132. Error: "You don't have a WhatsApp connection.",
  133. ErrCode: "no connection",
  134. })
  135. return
  136. }
  137. user.DeleteConnection()
  138. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  139. user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  140. }
  141. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  142. user := r.Context().Value("user").(*User)
  143. if user.Client == nil {
  144. if user.Session == nil {
  145. jsonResponse(w, http.StatusForbidden, Error{
  146. Error: "No existing connection and no session. Please log in first.",
  147. ErrCode: "no session",
  148. })
  149. } else {
  150. user.Connect()
  151. jsonResponse(w, http.StatusAccepted, Response{true, "Created connection to WhatsApp."})
  152. }
  153. } else {
  154. user.DeleteConnection()
  155. user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect, Error: WANotConnected})
  156. user.Connect()
  157. jsonResponse(w, http.StatusAccepted, Response{true, "Restarted connection to WhatsApp"})
  158. }
  159. }
  160. func (prov *ProvisioningAPI) SyncAppState(w http.ResponseWriter, r *http.Request) {
  161. user := r.Context().Value("user").(*User)
  162. if user == nil || user.Client == nil {
  163. jsonResponse(w, http.StatusNotFound, Error{
  164. Error: "User is not connected to WhatsApp",
  165. ErrCode: "no session",
  166. })
  167. return
  168. }
  169. vars := mux.Vars(r)
  170. nameStr := vars["name"]
  171. if len(nameStr) == 0 {
  172. jsonResponse(w, http.StatusBadRequest, Error{
  173. Error: "The `name` parameter is required",
  174. ErrCode: "missing-name-param",
  175. })
  176. return
  177. }
  178. var name appstate.WAPatchName
  179. for _, existingName := range appstate.AllPatchNames {
  180. if nameStr == string(existingName) {
  181. name = existingName
  182. }
  183. }
  184. if len(name) == 0 {
  185. jsonResponse(w, http.StatusBadRequest, Error{
  186. Error: fmt.Sprintf("'%s' is not a valid app state patch name", nameStr),
  187. ErrCode: "invalid-name-param",
  188. })
  189. return
  190. }
  191. fullStr := r.URL.Query().Get("full")
  192. fullSync := len(fullStr) > 0 && (fullStr == "1" || strings.ToLower(fullStr)[0] == 't')
  193. err := user.Client.FetchAppState(name, fullSync, false)
  194. if err != nil {
  195. jsonResponse(w, http.StatusInternalServerError, Error{false, err.Error(), "sync-fail"})
  196. } else {
  197. jsonResponse(w, http.StatusOK, Response{true, fmt.Sprintf("Synced app state %s", name)})
  198. }
  199. }
  200. func (prov *ProvisioningAPI) ListContacts(w http.ResponseWriter, r *http.Request) {
  201. if user := r.Context().Value("user").(*User); user.Session == nil {
  202. jsonResponse(w, http.StatusBadRequest, Error{
  203. Error: "User is not logged into WhatsApp",
  204. ErrCode: "no session",
  205. })
  206. } else if contacts, err := user.Session.Contacts.GetAllContacts(); err != nil {
  207. prov.log.Errorfln("Failed to fetch %s's contacts: %v", user.MXID, err)
  208. jsonResponse(w, http.StatusInternalServerError, Error{
  209. Error: "Internal server error while fetching contact list",
  210. ErrCode: "failed to get contacts",
  211. })
  212. } else {
  213. jsonResponse(w, http.StatusOK, contacts)
  214. }
  215. }
  216. type OtherUserInfo struct {
  217. MXID id.UserID `json:"mxid"`
  218. JID types.JID `json:"jid"`
  219. Name string `json:"displayname"`
  220. Avatar id.ContentURI `json:"avatar_url"`
  221. }
  222. type PortalInfo struct {
  223. RoomID id.RoomID `json:"room_id"`
  224. OtherUser OtherUserInfo `json:"other_user"`
  225. JustCreated bool `json:"just_created"`
  226. }
  227. func (prov *ProvisioningAPI) StartPM(w http.ResponseWriter, r *http.Request) {
  228. number, _ := mux.Vars(r)["number"]
  229. if strings.HasSuffix(number, "@"+types.DefaultUserServer) {
  230. jid, _ := types.ParseJID(number)
  231. number = "+" + jid.User
  232. }
  233. if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
  234. jsonResponse(w, http.StatusBadRequest, Error{
  235. Error: "User is not logged into WhatsApp",
  236. ErrCode: "no session",
  237. })
  238. } else if resp, err := user.Client.IsOnWhatsApp([]string{number}); err != nil {
  239. jsonResponse(w, http.StatusInternalServerError, Error{
  240. Error: fmt.Sprintf("Failed to check if number is on WhatsApp: %v", err),
  241. ErrCode: "error checking number",
  242. })
  243. } else if len(resp) == 0 {
  244. jsonResponse(w, http.StatusInternalServerError, Error{
  245. Error: "Didn't get a response to checking if the number is on WhatsApp",
  246. ErrCode: "error checking number",
  247. })
  248. } else if !resp[0].IsIn {
  249. jsonResponse(w, http.StatusNotFound, Error{
  250. Error: fmt.Sprintf("The server said +%s is not on WhatsApp", resp[0].JID.User),
  251. ErrCode: "not on whatsapp",
  252. })
  253. } else if portal, puppet, justCreated, err := user.StartPM(resp[0].JID, "provisioning API PM"); err != nil {
  254. jsonResponse(w, http.StatusInternalServerError, Error{
  255. Error: fmt.Sprintf("Failed to create portal: %v", err),
  256. })
  257. } else {
  258. status := http.StatusOK
  259. if justCreated {
  260. status = http.StatusCreated
  261. }
  262. jsonResponse(w, status, PortalInfo{
  263. RoomID: portal.MXID,
  264. OtherUser: OtherUserInfo{
  265. JID: puppet.JID,
  266. MXID: puppet.MXID,
  267. Name: puppet.Displayname,
  268. Avatar: puppet.AvatarURL,
  269. },
  270. JustCreated: justCreated,
  271. })
  272. }
  273. }
  274. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  275. user := r.Context().Value("user").(*User)
  276. wa := map[string]interface{}{
  277. "has_session": user.Session != nil,
  278. "management_room": user.ManagementRoom,
  279. "conn": nil,
  280. }
  281. if !user.JID.IsEmpty() {
  282. wa["jid"] = user.JID.String()
  283. wa["phone"] = "+" + user.JID.User
  284. wa["device"] = user.JID.Device
  285. }
  286. if user.Client != nil {
  287. wa["conn"] = map[string]interface{}{
  288. "is_connected": user.Client.IsConnected(),
  289. "is_logged_in": user.Client.IsLoggedIn(),
  290. }
  291. }
  292. resp := map[string]interface{}{
  293. "mxid": user.MXID,
  294. "admin": user.Admin,
  295. "whitelisted": user.Whitelisted,
  296. "relay_whitelisted": user.RelayWhitelisted,
  297. "whatsapp": wa,
  298. }
  299. jsonResponse(w, http.StatusOK, resp)
  300. }
  301. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  302. w.Header().Add("Content-Type", "application/json")
  303. w.WriteHeader(status)
  304. _ = json.NewEncoder(w).Encode(response)
  305. }
  306. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  307. user := r.Context().Value("user").(*User)
  308. if user.Session == nil {
  309. jsonResponse(w, http.StatusNotFound, Error{
  310. Error: "You're not logged in",
  311. ErrCode: "not logged in",
  312. })
  313. return
  314. }
  315. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  316. if user.Client == nil {
  317. if !force {
  318. jsonResponse(w, http.StatusNotFound, Error{
  319. Error: "You're not connected",
  320. ErrCode: "not connected",
  321. })
  322. }
  323. } else {
  324. err := user.Client.Logout()
  325. if err != nil {
  326. user.log.Warnln("Error while logging out:", err)
  327. if !force {
  328. jsonResponse(w, http.StatusInternalServerError, Error{
  329. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  330. ErrCode: err.Error(),
  331. })
  332. return
  333. }
  334. } else {
  335. user.Session = nil
  336. }
  337. user.DeleteConnection()
  338. }
  339. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  340. user.removeFromJIDMap(StateLoggedOut)
  341. user.DeleteSession()
  342. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  343. }
  344. var upgrader = websocket.Upgrader{
  345. CheckOrigin: func(r *http.Request) bool {
  346. return true
  347. },
  348. Subprotocols: []string{"net.maunium.whatsapp.login"},
  349. }
  350. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  351. userID := r.URL.Query().Get("user_id")
  352. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  353. c, err := upgrader.Upgrade(w, r, nil)
  354. if err != nil {
  355. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  356. return
  357. }
  358. defer func() {
  359. err := c.Close()
  360. if err != nil {
  361. user.log.Debugln("Error closing websocket:", err)
  362. }
  363. }()
  364. go func() {
  365. // Read everything so SetCloseHandler() works
  366. for {
  367. _, _, err = c.ReadMessage()
  368. if err != nil {
  369. break
  370. }
  371. }
  372. }()
  373. ctx, cancel := context.WithCancel(context.Background())
  374. c.SetCloseHandler(func(code int, text string) error {
  375. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  376. cancel()
  377. return nil
  378. })
  379. qrChan, err := user.Login(ctx)
  380. if err != nil {
  381. user.log.Errorf("Failed to log in from provisioning API:", err)
  382. if errors.Is(err, ErrAlreadyLoggedIn) {
  383. go user.Connect()
  384. _ = c.WriteJSON(Error{
  385. Error: "You're already logged into WhatsApp",
  386. ErrCode: "already logged in",
  387. })
  388. } else {
  389. _ = c.WriteJSON(Error{
  390. Error: "Failed to connect to WhatsApp",
  391. ErrCode: "connection error",
  392. })
  393. }
  394. }
  395. user.log.Debugln("Started login via provisioning API")
  396. for {
  397. select {
  398. case evt := <-qrChan:
  399. switch evt.Event {
  400. case whatsmeow.QRChannelSuccess.Event:
  401. jid := user.Client.Store.ID
  402. user.log.Debugln("Successful login as", jid, "via provisioning API")
  403. _ = c.WriteJSON(map[string]interface{}{
  404. "success": true,
  405. "jid": jid,
  406. "phone": fmt.Sprintf("+%s", jid.User),
  407. })
  408. case whatsmeow.QRChannelTimeout.Event:
  409. user.log.Debugln("Login via provisioning API timed out")
  410. _ = c.WriteJSON(Error{
  411. Error: "QR code scan timed out. Please try again.",
  412. ErrCode: "login timed out",
  413. })
  414. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  415. user.log.Debugln("Login via provisioning API failed due to unexpected event")
  416. _ = c.WriteJSON(Error{
  417. Error: "Got unexpected event while waiting for QRs, perhaps you're already logged in?",
  418. ErrCode: "unexpected event",
  419. })
  420. case whatsmeow.QRChannelClientOutdated.Event:
  421. user.log.Debugln("Login via provisioning API failed due to outdated client")
  422. _ = c.WriteJSON(Error{
  423. Error: "Got client outdated error while waiting for QRs. The bridge must be updated to continue.",
  424. ErrCode: "bridge outdated",
  425. })
  426. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  427. _ = c.WriteJSON(Error{
  428. Error: "Please enable the WhatsApp multidevice beta and scan the QR code again.",
  429. ErrCode: "multidevice not enabled",
  430. })
  431. continue
  432. case "error":
  433. _ = c.WriteJSON(Error{
  434. Error: "Fatal error while logging in",
  435. ErrCode: "fatal error",
  436. })
  437. case "code":
  438. _ = c.WriteJSON(map[string]interface{}{
  439. "code": evt.Code,
  440. "timeout": int(evt.Timeout.Seconds()),
  441. })
  442. continue
  443. }
  444. return
  445. case <-ctx.Done():
  446. return
  447. }
  448. }
  449. }