provisioning.go 23 KB

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