provisioning.go 17 KB

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