provisioning.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. "strconv"
  26. "strings"
  27. "time"
  28. "github.com/gorilla/mux"
  29. "github.com/gorilla/websocket"
  30. "go.mau.fi/whatsmeow/appstate"
  31. waBinary "go.mau.fi/whatsmeow/binary"
  32. "go.mau.fi/whatsmeow/types"
  33. "go.mau.fi/whatsmeow"
  34. log "maunium.net/go/maulogger/v2"
  35. "maunium.net/go/mautrix/bridge/status"
  36. "maunium.net/go/mautrix/id"
  37. )
  38. type ProvisioningAPI struct {
  39. bridge *WABridge
  40. log log.Logger
  41. }
  42. func (prov *ProvisioningAPI) Init() {
  43. prov.log = prov.bridge.Log.Sub("Provisioning")
  44. prov.log.Debugln("Enabling provisioning API at", prov.bridge.Config.Bridge.Provisioning.Prefix)
  45. r := prov.bridge.AS.Router.PathPrefix(prov.bridge.Config.Bridge.Provisioning.Prefix).Subrouter()
  46. r.Use(prov.AuthMiddleware)
  47. r.HandleFunc("/v1/ping", prov.Ping).Methods(http.MethodGet)
  48. r.HandleFunc("/v1/login", prov.Login).Methods(http.MethodGet)
  49. r.HandleFunc("/v1/logout", prov.Logout).Methods(http.MethodPost)
  50. r.HandleFunc("/v1/delete_session", prov.DeleteSession).Methods(http.MethodPost)
  51. r.HandleFunc("/v1/disconnect", prov.Disconnect).Methods(http.MethodPost)
  52. r.HandleFunc("/v1/reconnect", prov.Reconnect).Methods(http.MethodPost)
  53. r.HandleFunc("/v1/debug/appstate/{name}", prov.SyncAppState).Methods(http.MethodPost)
  54. r.HandleFunc("/v1/debug/retry", prov.SendRetryReceipt).Methods(http.MethodPost)
  55. r.HandleFunc("/v1/contacts", prov.ListContacts).Methods(http.MethodGet)
  56. r.HandleFunc("/v1/groups", prov.ListGroups).Methods(http.MethodGet)
  57. r.HandleFunc("/v1/resolve_identifier/{number}", prov.ResolveIdentifier).Methods(http.MethodGet)
  58. r.HandleFunc("/v1/bulk_resolve_identifier", prov.BulkResolveIdentifier).Methods(http.MethodPost)
  59. r.HandleFunc("/v1/pm/{number}", prov.StartPM).Methods(http.MethodPost)
  60. r.HandleFunc("/v1/open/{groupID}", prov.OpenGroup).Methods(http.MethodPost)
  61. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.asmux/ping", prov.BridgeStatePing).Methods(http.MethodPost)
  62. prov.bridge.AS.Router.HandleFunc("/_matrix/app/com.beeper.bridge_state", prov.BridgeStatePing).Methods(http.MethodPost)
  63. // Deprecated, just use /disconnect
  64. r.HandleFunc("/v1/delete_connection", prov.Disconnect).Methods(http.MethodPost)
  65. }
  66. type responseWrap struct {
  67. http.ResponseWriter
  68. statusCode int
  69. }
  70. var _ http.Hijacker = (*responseWrap)(nil)
  71. func (rw *responseWrap) WriteHeader(statusCode int) {
  72. rw.ResponseWriter.WriteHeader(statusCode)
  73. rw.statusCode = statusCode
  74. }
  75. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  76. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  77. if !ok {
  78. return nil, nil, errors.New("response does not implement http.Hijacker")
  79. }
  80. return hijacker.Hijack()
  81. }
  82. func (prov *ProvisioningAPI) AuthMiddleware(h http.Handler) http.Handler {
  83. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  84. auth := r.Header.Get("Authorization")
  85. if len(auth) == 0 && strings.HasSuffix(r.URL.Path, "/login") {
  86. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  87. for _, part := range authParts {
  88. part = strings.TrimSpace(part)
  89. if strings.HasPrefix(part, "net.maunium.whatsapp.auth-") {
  90. auth = part[len("net.maunium.whatsapp.auth-"):]
  91. break
  92. }
  93. }
  94. } else if strings.HasPrefix(auth, "Bearer ") {
  95. auth = auth[len("Bearer "):]
  96. }
  97. if auth != prov.bridge.Config.Bridge.Provisioning.SharedSecret {
  98. prov.log.Infof("Authentication token does not match shared secret")
  99. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  100. "error": "Authentication token does not match shared secret",
  101. "errcode": "M_FORBIDDEN",
  102. })
  103. return
  104. }
  105. userID := r.URL.Query().Get("user_id")
  106. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  107. start := time.Now()
  108. wWrap := &responseWrap{w, 200}
  109. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  110. duration := time.Now().Sub(start).Seconds()
  111. prov.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  112. })
  113. }
  114. type Error struct {
  115. Success bool `json:"success"`
  116. Error string `json:"error"`
  117. ErrCode string `json:"errcode"`
  118. }
  119. type Response struct {
  120. Success bool `json:"success"`
  121. Status string `json:"status"`
  122. }
  123. func (prov *ProvisioningAPI) DeleteSession(w http.ResponseWriter, r *http.Request) {
  124. user := r.Context().Value("user").(*User)
  125. if user.Session == nil && user.Client == nil {
  126. jsonResponse(w, http.StatusNotFound, Error{
  127. Error: "Nothing to purge: no session information stored and no active connection.",
  128. ErrCode: "no session",
  129. })
  130. return
  131. }
  132. user.DeleteConnection()
  133. user.DeleteSession()
  134. jsonResponse(w, http.StatusOK, Response{true, "Session information purged"})
  135. user.removeFromJIDMap(status.BridgeState{StateEvent: status.StateLoggedOut})
  136. }
  137. func (prov *ProvisioningAPI) Disconnect(w http.ResponseWriter, r *http.Request) {
  138. user := r.Context().Value("user").(*User)
  139. if user.Client == nil {
  140. jsonResponse(w, http.StatusNotFound, Error{
  141. Error: "You don't have a WhatsApp connection.",
  142. ErrCode: "no connection",
  143. })
  144. return
  145. }
  146. user.DeleteConnection()
  147. jsonResponse(w, http.StatusOK, Response{true, "Disconnected from WhatsApp"})
  148. user.BridgeState.Send(status.BridgeState{StateEvent: status.StateBadCredentials, Error: WANotConnected})
  149. }
  150. func (prov *ProvisioningAPI) Reconnect(w http.ResponseWriter, r *http.Request) {
  151. user := r.Context().Value("user").(*User)
  152. if user.Client == nil {
  153. if user.Session == nil {
  154. jsonResponse(w, http.StatusForbidden, Error{
  155. Error: "No existing connection and no session. Please log in first.",
  156. ErrCode: "no session",
  157. })
  158. } else {
  159. user.Connect()
  160. jsonResponse(w, http.StatusAccepted, Response{true, "Created connection to WhatsApp."})
  161. }
  162. } else {
  163. user.DeleteConnection()
  164. user.BridgeState.Send(status.BridgeState{StateEvent: status.StateTransientDisconnect, Error: WANotConnected})
  165. user.Connect()
  166. jsonResponse(w, http.StatusAccepted, Response{true, "Restarted connection to WhatsApp"})
  167. }
  168. }
  169. type debugRetryReceiptContent struct {
  170. ID types.MessageID `json:"id"`
  171. From types.JID `json:"from"`
  172. Recipient types.JID `json:"recipient"`
  173. Participant types.JID `json:"participant"`
  174. Timestamp int64 `json:"timestamp"`
  175. Count int `json:"count"`
  176. ForceIncludeIdentity bool `json:"force_include_identity"`
  177. }
  178. func (prov *ProvisioningAPI) SendRetryReceipt(w http.ResponseWriter, r *http.Request) {
  179. var req debugRetryReceiptContent
  180. user := r.Context().Value("user").(*User)
  181. if user == nil || user.Client == nil {
  182. jsonResponse(w, http.StatusNotFound, Error{
  183. Error: "User is not connected to WhatsApp",
  184. ErrCode: "no session",
  185. })
  186. return
  187. } else if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  188. jsonResponse(w, http.StatusBadRequest, Error{
  189. Error: "Failed to parse request JSON",
  190. ErrCode: "bad json",
  191. })
  192. } else {
  193. node := &waBinary.Node{
  194. Attrs: waBinary.Attrs{
  195. "id": string(req.ID),
  196. "from": req.From,
  197. "t": strconv.FormatInt(req.Timestamp, 10),
  198. },
  199. }
  200. if !req.Recipient.IsEmpty() {
  201. node.Attrs["recipient"] = req.Recipient
  202. }
  203. if !req.Participant.IsEmpty() {
  204. node.Attrs["participant"] = req.Participant
  205. }
  206. if req.Count > 0 {
  207. node.Content = []waBinary.Node{{
  208. Tag: "enc",
  209. Attrs: waBinary.Attrs{"count": strconv.Itoa(req.Count)},
  210. }}
  211. }
  212. user.Client.DangerousInternals().SendRetryReceipt(node, req.ForceIncludeIdentity)
  213. }
  214. }
  215. func (prov *ProvisioningAPI) SyncAppState(w http.ResponseWriter, r *http.Request) {
  216. user := r.Context().Value("user").(*User)
  217. if user == nil || user.Client == nil {
  218. jsonResponse(w, http.StatusNotFound, Error{
  219. Error: "User is not connected to WhatsApp",
  220. ErrCode: "no session",
  221. })
  222. return
  223. }
  224. vars := mux.Vars(r)
  225. nameStr := vars["name"]
  226. if len(nameStr) == 0 {
  227. jsonResponse(w, http.StatusBadRequest, Error{
  228. Error: "The `name` parameter is required",
  229. ErrCode: "missing-name-param",
  230. })
  231. return
  232. }
  233. var name appstate.WAPatchName
  234. for _, existingName := range appstate.AllPatchNames {
  235. if nameStr == string(existingName) {
  236. name = existingName
  237. }
  238. }
  239. if len(name) == 0 {
  240. jsonResponse(w, http.StatusBadRequest, Error{
  241. Error: fmt.Sprintf("'%s' is not a valid app state patch name", nameStr),
  242. ErrCode: "invalid-name-param",
  243. })
  244. return
  245. }
  246. fullStr := r.URL.Query().Get("full")
  247. fullSync := len(fullStr) > 0 && (fullStr == "1" || strings.ToLower(fullStr)[0] == 't')
  248. err := user.Client.FetchAppState(name, fullSync, false)
  249. if err != nil {
  250. jsonResponse(w, http.StatusInternalServerError, Error{false, err.Error(), "sync-fail"})
  251. } else {
  252. jsonResponse(w, http.StatusOK, Response{true, fmt.Sprintf("Synced app state %s", name)})
  253. }
  254. }
  255. func (prov *ProvisioningAPI) ListContacts(w http.ResponseWriter, r *http.Request) {
  256. if user := r.Context().Value("user").(*User); user.Session == nil {
  257. jsonResponse(w, http.StatusBadRequest, Error{
  258. Error: "User is not logged into WhatsApp",
  259. ErrCode: "no session",
  260. })
  261. } else if contacts, err := user.Session.Contacts.GetAllContacts(); err != nil {
  262. prov.log.Errorfln("Failed to fetch %s's contacts: %v", user.MXID, err)
  263. jsonResponse(w, http.StatusInternalServerError, Error{
  264. Error: "Internal server error while fetching contact list",
  265. ErrCode: "failed to get contacts",
  266. })
  267. } else {
  268. augmentedContacts := map[types.JID]interface{}{}
  269. for jid, contact := range contacts {
  270. var avatarUrl id.ContentURI
  271. if puppet := prov.bridge.GetPuppetByJID(jid); puppet != nil {
  272. avatarUrl = puppet.AvatarURL
  273. }
  274. augmentedContacts[jid] = map[string]interface{}{
  275. "Found": contact.Found,
  276. "FirstName": contact.FirstName,
  277. "FullName": contact.FullName,
  278. "PushName": contact.PushName,
  279. "BusinessName": contact.BusinessName,
  280. "AvatarURL": avatarUrl,
  281. }
  282. }
  283. jsonResponse(w, http.StatusOK, augmentedContacts)
  284. }
  285. }
  286. func (prov *ProvisioningAPI) ListGroups(w http.ResponseWriter, r *http.Request) {
  287. if user := r.Context().Value("user").(*User); user.Session == nil {
  288. jsonResponse(w, http.StatusBadRequest, Error{
  289. Error: "User is not logged into WhatsApp",
  290. ErrCode: "no session",
  291. })
  292. } else if groups, err := user.getCachedGroupList(); err != nil {
  293. prov.log.Errorfln("Failed to fetch %s's groups: %v", user.MXID, err)
  294. jsonResponse(w, http.StatusInternalServerError, Error{
  295. Error: "Internal server error while fetching group list",
  296. ErrCode: "failed to get groups",
  297. })
  298. } else {
  299. jsonResponse(w, http.StatusOK, groups)
  300. }
  301. }
  302. type OtherUserInfo struct {
  303. MXID id.UserID `json:"mxid"`
  304. JID types.JID `json:"jid"`
  305. Name string `json:"displayname"`
  306. Avatar id.ContentURI `json:"avatar_url"`
  307. }
  308. type PortalInfo struct {
  309. RoomID id.RoomID `json:"room_id"`
  310. OtherUser *OtherUserInfo `json:"other_user,omitempty"`
  311. GroupInfo *types.GroupInfo `json:"group_info,omitempty"`
  312. JustCreated bool `json:"just_created"`
  313. }
  314. func looksEmaily(str string) bool {
  315. for _, char := range str {
  316. // Characters that are usually in emails, but shouldn't be in phone numbers
  317. if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || char == '@' {
  318. return true
  319. }
  320. }
  321. return false
  322. }
  323. func (prov *ProvisioningAPI) resolveIdentifier(w http.ResponseWriter, r *http.Request) (types.JID, *User) {
  324. number, _ := mux.Vars(r)["number"]
  325. if strings.HasSuffix(number, "@"+types.DefaultUserServer) {
  326. jid, _ := types.ParseJID(number)
  327. number = "+" + jid.User
  328. }
  329. if looksEmaily(number) {
  330. jsonResponse(w, http.StatusBadRequest, Error{
  331. Error: "WhatsApp only supports phone numbers as user identifiers",
  332. ErrCode: "number looks like email",
  333. })
  334. } else if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
  335. jsonResponse(w, http.StatusBadRequest, Error{
  336. Error: "User is not logged into WhatsApp",
  337. ErrCode: "no session",
  338. })
  339. } else if resp, err := user.Client.IsOnWhatsApp([]string{number}); err != nil {
  340. jsonResponse(w, http.StatusInternalServerError, Error{
  341. Error: fmt.Sprintf("Failed to check if number is on WhatsApp: %v", err),
  342. ErrCode: "error checking number",
  343. })
  344. } else if len(resp) == 0 {
  345. jsonResponse(w, http.StatusInternalServerError, Error{
  346. Error: "Didn't get a response to checking if the number is on WhatsApp",
  347. ErrCode: "error checking number",
  348. })
  349. } else if !resp[0].IsIn {
  350. jsonResponse(w, http.StatusNotFound, Error{
  351. Error: fmt.Sprintf("The server said +%s is not on WhatsApp", resp[0].JID.User),
  352. ErrCode: "not on whatsapp",
  353. })
  354. } else {
  355. return resp[0].JID, user
  356. }
  357. return types.EmptyJID, nil
  358. }
  359. func (prov *ProvisioningAPI) StartPM(w http.ResponseWriter, r *http.Request) {
  360. jid, user := prov.resolveIdentifier(w, r)
  361. if jid.IsEmpty() || user == nil {
  362. // resolveIdentifier already responded with an error
  363. return
  364. }
  365. portal, puppet, justCreated, err := user.StartPM(jid, "provisioning API PM")
  366. if err != nil {
  367. jsonResponse(w, http.StatusInternalServerError, Error{
  368. Error: fmt.Sprintf("Failed to create portal: %v", err),
  369. })
  370. }
  371. status := http.StatusOK
  372. if justCreated {
  373. status = http.StatusCreated
  374. }
  375. jsonResponse(w, status, PortalInfo{
  376. RoomID: portal.MXID,
  377. OtherUser: &OtherUserInfo{
  378. JID: puppet.JID,
  379. MXID: puppet.MXID,
  380. Name: puppet.Displayname,
  381. Avatar: puppet.AvatarURL,
  382. },
  383. JustCreated: justCreated,
  384. })
  385. }
  386. func (prov *ProvisioningAPI) ResolveIdentifier(w http.ResponseWriter, r *http.Request) {
  387. jid, user := prov.resolveIdentifier(w, r)
  388. if jid.IsEmpty() || user == nil {
  389. // resolveIdentifier already responded with an error
  390. return
  391. }
  392. portal := user.GetPortalByJID(jid)
  393. puppet := user.bridge.GetPuppetByJID(jid)
  394. jsonResponse(w, http.StatusOK, PortalInfo{
  395. RoomID: portal.MXID,
  396. OtherUser: &OtherUserInfo{
  397. JID: puppet.JID,
  398. MXID: puppet.MXID,
  399. Name: puppet.Displayname,
  400. Avatar: puppet.AvatarURL,
  401. },
  402. })
  403. }
  404. type ReqBulkResolveIdentifier struct {
  405. Numbers []string `json:"numbers"`
  406. }
  407. func (prov *ProvisioningAPI) BulkResolveIdentifier(w http.ResponseWriter, r *http.Request) {
  408. var req ReqBulkResolveIdentifier
  409. var resp []types.IsOnWhatsAppResponse
  410. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  411. jsonResponse(w, http.StatusBadRequest, Error{
  412. Error: "Failed to parse request JSON",
  413. ErrCode: "bad json",
  414. })
  415. } else if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
  416. jsonResponse(w, http.StatusBadRequest, Error{
  417. Error: "User is not logged into WhatsApp",
  418. ErrCode: "no session",
  419. })
  420. } else if resp, err = user.Client.IsOnWhatsApp(req.Numbers); err != nil {
  421. jsonResponse(w, http.StatusInternalServerError, Error{
  422. Error: fmt.Sprintf("Failed to check if number is on WhatsApp: %v", err),
  423. ErrCode: "error checking number",
  424. })
  425. } else {
  426. jsonResponse(w, http.StatusOK, resp)
  427. }
  428. }
  429. func (prov *ProvisioningAPI) OpenGroup(w http.ResponseWriter, r *http.Request) {
  430. groupID, _ := mux.Vars(r)["groupID"]
  431. if user := r.Context().Value("user").(*User); !user.IsLoggedIn() {
  432. jsonResponse(w, http.StatusBadRequest, Error{
  433. Error: "User is not logged into WhatsApp",
  434. ErrCode: "no session",
  435. })
  436. } else if jid, err := types.ParseJID(groupID); err != nil || jid.Server != types.GroupServer || (!strings.ContainsRune(jid.User, '-') && len(jid.User) < 15) {
  437. jsonResponse(w, http.StatusBadRequest, Error{
  438. Error: "Invalid group ID",
  439. ErrCode: "invalid group id",
  440. })
  441. } else if info, err := user.Client.GetGroupInfo(jid); err != nil {
  442. // TODO return better responses for different errors (like ErrGroupNotFound and ErrNotInGroup)
  443. jsonResponse(w, http.StatusInternalServerError, Error{
  444. Error: fmt.Sprintf("Failed to get group info: %v", err),
  445. ErrCode: "error getting group info",
  446. })
  447. } else {
  448. prov.log.Debugln("Importing", jid, "for", user.MXID)
  449. portal := user.GetPortalByJID(info.JID)
  450. status := http.StatusOK
  451. if len(portal.MXID) == 0 {
  452. err = portal.CreateMatrixRoom(user, info, true, true)
  453. if err != nil {
  454. jsonResponse(w, http.StatusInternalServerError, Error{
  455. Error: fmt.Sprintf("Failed to create portal: %v", err),
  456. })
  457. return
  458. }
  459. status = http.StatusCreated
  460. }
  461. jsonResponse(w, status, PortalInfo{
  462. RoomID: portal.MXID,
  463. GroupInfo: info,
  464. JustCreated: status == http.StatusCreated,
  465. })
  466. }
  467. }
  468. func (prov *ProvisioningAPI) Ping(w http.ResponseWriter, r *http.Request) {
  469. user := r.Context().Value("user").(*User)
  470. wa := map[string]interface{}{
  471. "has_session": user.Session != nil,
  472. "management_room": user.ManagementRoom,
  473. "conn": nil,
  474. }
  475. if !user.JID.IsEmpty() {
  476. wa["jid"] = user.JID.String()
  477. wa["phone"] = "+" + user.JID.User
  478. wa["device"] = user.JID.Device
  479. if user.Session != nil {
  480. wa["platform"] = user.Session.Platform
  481. }
  482. }
  483. if user.Client != nil {
  484. wa["conn"] = map[string]interface{}{
  485. "is_connected": user.Client.IsConnected(),
  486. "is_logged_in": user.Client.IsLoggedIn(),
  487. }
  488. }
  489. resp := map[string]interface{}{
  490. "mxid": user.MXID,
  491. "admin": user.Admin,
  492. "whitelisted": user.Whitelisted,
  493. "relay_whitelisted": user.RelayWhitelisted,
  494. "whatsapp": wa,
  495. }
  496. jsonResponse(w, http.StatusOK, resp)
  497. }
  498. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  499. w.Header().Add("Content-Type", "application/json")
  500. w.WriteHeader(status)
  501. _ = json.NewEncoder(w).Encode(response)
  502. }
  503. func (prov *ProvisioningAPI) Logout(w http.ResponseWriter, r *http.Request) {
  504. user := r.Context().Value("user").(*User)
  505. if user.Session == nil {
  506. jsonResponse(w, http.StatusOK, Error{
  507. Error: "You're not logged in",
  508. ErrCode: "not logged in",
  509. })
  510. return
  511. }
  512. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  513. if user.Client == nil {
  514. if !force {
  515. jsonResponse(w, http.StatusNotFound, Error{
  516. Error: "You're not connected",
  517. ErrCode: "not connected",
  518. })
  519. }
  520. } else {
  521. err := user.Client.Logout()
  522. if err != nil {
  523. user.log.Warnln("Error while logging out:", err)
  524. if !force {
  525. jsonResponse(w, http.StatusInternalServerError, Error{
  526. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  527. ErrCode: err.Error(),
  528. })
  529. return
  530. }
  531. } else {
  532. user.Session = nil
  533. }
  534. user.DeleteConnection()
  535. }
  536. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  537. user.removeFromJIDMap(status.BridgeState{StateEvent: status.StateLoggedOut})
  538. user.DeleteSession()
  539. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  540. }
  541. var upgrader = websocket.Upgrader{
  542. CheckOrigin: func(r *http.Request) bool {
  543. return true
  544. },
  545. Subprotocols: []string{"net.maunium.whatsapp.login"},
  546. }
  547. func (prov *ProvisioningAPI) Login(w http.ResponseWriter, r *http.Request) {
  548. userID := r.URL.Query().Get("user_id")
  549. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  550. c, err := upgrader.Upgrade(w, r, nil)
  551. if err != nil {
  552. prov.log.Errorln("Failed to upgrade connection to websocket:", err)
  553. return
  554. }
  555. defer func() {
  556. err := c.Close()
  557. if err != nil {
  558. user.log.Debugln("Error closing websocket:", err)
  559. }
  560. }()
  561. go func() {
  562. // Read everything so SetCloseHandler() works
  563. for {
  564. _, _, err = c.ReadMessage()
  565. if err != nil {
  566. break
  567. }
  568. }
  569. }()
  570. ctx, cancel := context.WithCancel(context.Background())
  571. c.SetCloseHandler(func(code int, text string) error {
  572. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  573. cancel()
  574. return nil
  575. })
  576. if userTimezone := r.URL.Query().Get("tz"); userTimezone != "" {
  577. user.log.Debug("Setting timezone to %s", userTimezone)
  578. user.Timezone = userTimezone
  579. user.Update()
  580. } else {
  581. user.log.Debug("No timezone provided in request")
  582. }
  583. qrChan, err := user.Login(ctx)
  584. if err != nil {
  585. user.log.Errorln("Failed to log in from provisioning API:", err)
  586. if errors.Is(err, ErrAlreadyLoggedIn) {
  587. go user.Connect()
  588. _ = c.WriteJSON(Error{
  589. Error: "You're already logged into WhatsApp",
  590. ErrCode: "already logged in",
  591. })
  592. } else {
  593. _ = c.WriteJSON(Error{
  594. Error: "Failed to connect to WhatsApp",
  595. ErrCode: "connection error",
  596. })
  597. }
  598. }
  599. user.log.Debugln("Started login via provisioning API")
  600. Segment.Track(user.MXID, "$login_start")
  601. for {
  602. select {
  603. case evt := <-qrChan:
  604. switch evt.Event {
  605. case whatsmeow.QRChannelSuccess.Event:
  606. jid := user.Client.Store.ID
  607. user.log.Debugln("Successful login as", jid, "via provisioning API")
  608. Segment.Track(user.MXID, "$login_success")
  609. _ = c.WriteJSON(map[string]interface{}{
  610. "success": true,
  611. "jid": jid,
  612. "phone": fmt.Sprintf("+%s", jid.User),
  613. "platform": user.Client.Store.Platform,
  614. })
  615. case whatsmeow.QRChannelTimeout.Event:
  616. user.log.Debugln("Login via provisioning API timed out")
  617. errCode := "login timed out"
  618. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  619. _ = c.WriteJSON(Error{
  620. Error: "QR code scan timed out. Please try again.",
  621. ErrCode: errCode,
  622. })
  623. case whatsmeow.QRChannelErrUnexpectedEvent.Event:
  624. user.log.Debugln("Login via provisioning API failed due to unexpected event")
  625. errCode := "unexpected event"
  626. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  627. _ = c.WriteJSON(Error{
  628. Error: "Got unexpected event while waiting for QRs, perhaps you're already logged in?",
  629. ErrCode: errCode,
  630. })
  631. case whatsmeow.QRChannelClientOutdated.Event:
  632. user.log.Debugln("Login via provisioning API failed due to outdated client")
  633. errCode := "bridge outdated"
  634. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  635. _ = c.WriteJSON(Error{
  636. Error: "Got client outdated error while waiting for QRs. The bridge must be updated to continue.",
  637. ErrCode: errCode,
  638. })
  639. case whatsmeow.QRChannelScannedWithoutMultidevice.Event:
  640. errCode := "multidevice not enabled"
  641. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  642. _ = c.WriteJSON(Error{
  643. Error: "Please enable the WhatsApp multidevice beta and scan the QR code again.",
  644. ErrCode: errCode,
  645. })
  646. continue
  647. case "error":
  648. errCode := "fatal error"
  649. Segment.Track(user.MXID, "$login_failure", map[string]interface{}{"error": errCode})
  650. _ = c.WriteJSON(Error{
  651. Error: "Fatal error while logging in",
  652. ErrCode: errCode,
  653. })
  654. case "code":
  655. Segment.Track(user.MXID, "$qrcode_retrieved")
  656. _ = c.WriteJSON(map[string]interface{}{
  657. "code": evt.Code,
  658. "timeout": int(evt.Timeout.Seconds()),
  659. })
  660. continue
  661. }
  662. return
  663. case <-ctx.Done():
  664. return
  665. }
  666. }
  667. }