provisioning.go 10 KB

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