provisioning.go 8.5 KB

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