provisioning.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. package bridge
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "net"
  9. "net/http"
  10. "strings"
  11. "time"
  12. "github.com/gorilla/mux"
  13. "github.com/gorilla/websocket"
  14. log "maunium.net/go/maulogger/v2"
  15. "maunium.net/go/mautrix/id"
  16. "go.mau.fi/mautrix-discord/remoteauth"
  17. )
  18. const (
  19. SecWebSocketProtocol = "com.gitlab.beeper.discord"
  20. )
  21. type ProvisioningAPI struct {
  22. bridge *Bridge
  23. log log.Logger
  24. }
  25. func newProvisioningAPI(bridge *Bridge) *ProvisioningAPI {
  26. p := &ProvisioningAPI{
  27. bridge: bridge,
  28. log: bridge.log.Sub("Provisioning"),
  29. }
  30. prefix := bridge.Config.Appservice.Provisioning.Prefix
  31. p.log.Debugln("Enabling provisioning API at", prefix)
  32. r := bridge.as.Router.PathPrefix(prefix).Subrouter()
  33. r.Use(p.authMiddleware)
  34. r.HandleFunc("/disconnect", p.disconnect).Methods(http.MethodPost)
  35. r.HandleFunc("/ping", p.ping).Methods(http.MethodGet)
  36. r.HandleFunc("/login", p.login).Methods(http.MethodGet)
  37. r.HandleFunc("/logout", p.logout).Methods(http.MethodPost)
  38. r.HandleFunc("/reconnect", p.reconnect).Methods(http.MethodPost)
  39. // Setup the guild endpoints
  40. r.HandleFunc("/guilds", p.guildsList).Methods(http.MethodGet)
  41. r.HandleFunc("/guilds/{guildID}/bridge", p.guildsBridge).Methods(http.MethodPost)
  42. r.HandleFunc("/guilds/{guildID}/unbridge", p.guildsUnbridge).Methods(http.MethodPost)
  43. r.HandleFunc("/guilds/{guildID}/joinentire", p.guildsJoinEntire).Methods(http.MethodPost)
  44. return p
  45. }
  46. func jsonResponse(w http.ResponseWriter, status int, response interface{}) {
  47. w.Header().Add("Content-Type", "application/json")
  48. w.WriteHeader(status)
  49. json.NewEncoder(w).Encode(response)
  50. }
  51. // Response structs
  52. type Response struct {
  53. Success bool `json:"success"`
  54. Status string `json:"status"`
  55. }
  56. type Error struct {
  57. Success bool `json:"success"`
  58. Error string `json:"error"`
  59. ErrCode string `json:"errcode"`
  60. }
  61. // Wrapped http.ResponseWriter to capture the status code
  62. type responseWrap struct {
  63. http.ResponseWriter
  64. statusCode int
  65. }
  66. var _ http.Hijacker = (*responseWrap)(nil)
  67. func (rw *responseWrap) WriteHeader(statusCode int) {
  68. rw.ResponseWriter.WriteHeader(statusCode)
  69. rw.statusCode = statusCode
  70. }
  71. func (rw *responseWrap) Hijack() (net.Conn, *bufio.ReadWriter, error) {
  72. hijacker, ok := rw.ResponseWriter.(http.Hijacker)
  73. if !ok {
  74. return nil, nil, errors.New("response does not implement http.Hijacker")
  75. }
  76. return hijacker.Hijack()
  77. }
  78. // Middleware
  79. func (p *ProvisioningAPI) authMiddleware(h http.Handler) http.Handler {
  80. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  81. auth := r.Header.Get("Authorization")
  82. // Special case the login endpoint to use the discord qrcode auth
  83. if auth == "" && strings.HasSuffix(r.URL.Path, "/login") {
  84. authParts := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
  85. for _, part := range authParts {
  86. part = strings.TrimSpace(part)
  87. if strings.HasPrefix(part, SecWebSocketProtocol+"-") {
  88. auth = part[len(SecWebSocketProtocol+"-"):]
  89. break
  90. }
  91. }
  92. } else if strings.HasPrefix(auth, "Bearer ") {
  93. auth = auth[len("Bearer "):]
  94. }
  95. if auth != p.bridge.Config.Appservice.Provisioning.SharedSecret {
  96. jsonResponse(w, http.StatusForbidden, map[string]interface{}{
  97. "error": "Invalid auth token",
  98. "errcode": "M_FORBIDDEN",
  99. })
  100. return
  101. }
  102. userID := r.URL.Query().Get("user_id")
  103. user := p.bridge.GetUserByMXID(id.UserID(userID))
  104. start := time.Now()
  105. wWrap := &responseWrap{w, 200}
  106. h.ServeHTTP(wWrap, r.WithContext(context.WithValue(r.Context(), "user", user)))
  107. duration := time.Now().Sub(start).Seconds()
  108. p.log.Infofln("%s %s from %s took %.2f seconds and returned status %d", r.Method, r.URL.Path, user.MXID, duration, wWrap.statusCode)
  109. })
  110. }
  111. // websocket upgrader
  112. var upgrader = websocket.Upgrader{
  113. CheckOrigin: func(r *http.Request) bool {
  114. return true
  115. },
  116. Subprotocols: []string{SecWebSocketProtocol},
  117. }
  118. // Handlers
  119. func (p *ProvisioningAPI) disconnect(w http.ResponseWriter, r *http.Request) {
  120. user := r.Context().Value("user").(*User)
  121. if !user.Connected() {
  122. jsonResponse(w, http.StatusConflict, Error{
  123. Error: "You're not connected to discord",
  124. ErrCode: "not connected",
  125. })
  126. return
  127. }
  128. if err := user.Disconnect(); err != nil {
  129. jsonResponse(w, http.StatusInternalServerError, Error{
  130. Error: "Failed to disconnect from discord",
  131. ErrCode: "failed to disconnect",
  132. })
  133. } else {
  134. jsonResponse(w, http.StatusOK, Response{
  135. Success: true,
  136. Status: "Disconnected from Discord",
  137. })
  138. }
  139. }
  140. func (p *ProvisioningAPI) ping(w http.ResponseWriter, r *http.Request) {
  141. user := r.Context().Value("user").(*User)
  142. discord := map[string]interface{}{
  143. "logged_in": user.LoggedIn(),
  144. "connected": user.Connected(),
  145. "conn": nil,
  146. }
  147. user.Lock()
  148. if user.ID != "" {
  149. discord["id"] = user.ID
  150. }
  151. if user.Session != nil {
  152. user.Session.Lock()
  153. discord["conn"] = map[string]interface{}{
  154. "last_heartbeat_ack": user.Session.LastHeartbeatAck,
  155. "last_heartbeat_sent": user.Session.LastHeartbeatSent,
  156. }
  157. user.Session.Unlock()
  158. }
  159. resp := map[string]interface{}{
  160. "discord": discord,
  161. "management_room": user.ManagementRoom,
  162. "mxid": user.MXID,
  163. }
  164. user.Unlock()
  165. jsonResponse(w, http.StatusOK, resp)
  166. }
  167. func (p *ProvisioningAPI) logout(w http.ResponseWriter, r *http.Request) {
  168. user := r.Context().Value("user").(*User)
  169. force := strings.ToLower(r.URL.Query().Get("force")) != "false"
  170. if !user.LoggedIn() {
  171. jsonResponse(w, http.StatusNotFound, Error{
  172. Error: "You're not logged in",
  173. ErrCode: "not logged in",
  174. })
  175. return
  176. }
  177. if user.Session == nil {
  178. if force {
  179. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  180. } else {
  181. jsonResponse(w, http.StatusNotFound, Error{
  182. Error: "You're not logged in",
  183. ErrCode: "not logged in",
  184. })
  185. }
  186. return
  187. }
  188. err := user.Logout()
  189. if err != nil {
  190. user.log.Warnln("Error while logging out:", err)
  191. if !force {
  192. jsonResponse(w, http.StatusInternalServerError, Error{
  193. Error: fmt.Sprintf("Unknown error while logging out: %v", err),
  194. ErrCode: err.Error(),
  195. })
  196. return
  197. }
  198. }
  199. jsonResponse(w, http.StatusOK, Response{true, "Logged out successfully."})
  200. }
  201. func (p *ProvisioningAPI) login(w http.ResponseWriter, r *http.Request) {
  202. userID := r.URL.Query().Get("user_id")
  203. user := p.bridge.GetUserByMXID(id.UserID(userID))
  204. c, err := upgrader.Upgrade(w, r, nil)
  205. if err != nil {
  206. p.log.Errorln("Failed to upgrade connection to websocket:", err)
  207. return
  208. }
  209. defer func() {
  210. err := c.Close()
  211. if err != nil {
  212. user.log.Debugln("Error closing websocket:", err)
  213. }
  214. }()
  215. go func() {
  216. // Read everything so SetCloseHandler() works
  217. for {
  218. _, _, err := c.ReadMessage()
  219. if err != nil {
  220. break
  221. }
  222. }
  223. }()
  224. ctx, cancel := context.WithCancel(context.Background())
  225. c.SetCloseHandler(func(code int, text string) error {
  226. user.log.Debugfln("Login websocket closed (%d), cancelling login", code)
  227. cancel()
  228. return nil
  229. })
  230. if user.LoggedIn() {
  231. c.WriteJSON(Error{
  232. Error: "You're already logged into Discord",
  233. ErrCode: "already logged in",
  234. })
  235. return
  236. }
  237. client, err := remoteauth.New()
  238. if err != nil {
  239. user.log.Errorf("Failed to log in from provisioning API:", err)
  240. c.WriteJSON(Error{
  241. Error: "Failed to connect to Discord",
  242. ErrCode: "connection error",
  243. })
  244. }
  245. qrChan := make(chan string)
  246. doneChan := make(chan struct{})
  247. user.log.Debugln("Started login via provisioning API")
  248. err = client.Dial(ctx, qrChan, doneChan)
  249. if err != nil {
  250. close(qrChan)
  251. close(doneChan)
  252. }
  253. for {
  254. select {
  255. case qrCode, ok := <-qrChan:
  256. if !ok {
  257. continue
  258. }
  259. c.WriteJSON(map[string]interface{}{
  260. "code": qrCode,
  261. "timeout": 120, // TODO: move this to the library or something
  262. })
  263. case <-doneChan:
  264. discordUser, err := client.Result()
  265. if err != nil {
  266. c.WriteJSON(Error{
  267. Error: "Failed to connect to Discord",
  268. ErrCode: "connection error",
  269. })
  270. p.log.Errorfln("failed to login via qrcode:", err)
  271. return
  272. }
  273. user.ID = discordUser.UserID
  274. user.Update()
  275. if err := user.Login(discordUser.Token); err != nil {
  276. c.WriteJSON(Error{
  277. Error: "Failed to connect to Discord",
  278. ErrCode: "connection error",
  279. })
  280. p.log.Errorfln("failed to login via qrcode:", err)
  281. return
  282. }
  283. c.WriteJSON(map[string]interface{}{
  284. "success": true,
  285. "id": user.ID,
  286. })
  287. return
  288. case <-ctx.Done():
  289. return
  290. }
  291. }
  292. }
  293. func (p *ProvisioningAPI) reconnect(w http.ResponseWriter, r *http.Request) {
  294. user := r.Context().Value("user").(*User)
  295. if user.Connected() {
  296. jsonResponse(w, http.StatusConflict, Error{
  297. Error: "You're already connected to discord",
  298. ErrCode: "already connected",
  299. })
  300. return
  301. }
  302. if err := user.Connect(); err != nil {
  303. jsonResponse(w, http.StatusInternalServerError, Error{
  304. Error: "Failed to connect to discord",
  305. ErrCode: "failed to connect",
  306. })
  307. } else {
  308. jsonResponse(w, http.StatusOK, Response{
  309. Success: true,
  310. Status: "Connected to Discord",
  311. })
  312. }
  313. }
  314. func (p *ProvisioningAPI) guildsList(w http.ResponseWriter, r *http.Request) {
  315. user := r.Context().Value("user").(*User)
  316. user.guildsLock.Lock()
  317. defer user.guildsLock.Unlock()
  318. data := make([]map[string]interface{}, len(user.guilds))
  319. idx := 0
  320. for _, guild := range user.guilds {
  321. data[idx] = map[string]interface{}{
  322. "name": guild.GuildName,
  323. "id": guild.GuildID,
  324. "bridged": guild.Bridge,
  325. }
  326. idx++
  327. }
  328. jsonResponse(w, http.StatusOK, data)
  329. }
  330. func (p *ProvisioningAPI) guildsBridge(w http.ResponseWriter, r *http.Request) {
  331. user := r.Context().Value("user").(*User)
  332. guildID, _ := mux.Vars(r)["guildID"]
  333. if err := user.bridgeGuild(guildID, false); err != nil {
  334. jsonResponse(w, http.StatusNotFound, Error{
  335. Error: err.Error(),
  336. ErrCode: "M_NOT_FOUND",
  337. })
  338. } else {
  339. w.WriteHeader(http.StatusCreated)
  340. }
  341. }
  342. func (p *ProvisioningAPI) guildsUnbridge(w http.ResponseWriter, r *http.Request) {
  343. user := r.Context().Value("user").(*User)
  344. guildID, _ := mux.Vars(r)["guildID"]
  345. if err := user.unbridgeGuild(guildID); err != nil {
  346. jsonResponse(w, http.StatusNotFound, Error{
  347. Error: err.Error(),
  348. ErrCode: "M_NOT_FOUND",
  349. })
  350. return
  351. }
  352. w.WriteHeader(http.StatusNoContent)
  353. }
  354. func (p *ProvisioningAPI) guildsJoinEntire(w http.ResponseWriter, r *http.Request) {
  355. user := r.Context().Value("user").(*User)
  356. guildID, _ := mux.Vars(r)["guildID"]
  357. if err := user.bridgeGuild(guildID, true); err != nil {
  358. jsonResponse(w, http.StatusNotFound, Error{
  359. Error: err.Error(),
  360. ErrCode: "M_NOT_FOUND",
  361. })
  362. } else {
  363. w.WriteHeader(http.StatusCreated)
  364. }
  365. }