provisioning.go 9.8 KB

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