provisioning.go 23 KB

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