forked from unmojang/drasl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
335 lines (298 loc) · 11.2 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package main
import (
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"golang.org/x/time/rate"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"log"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strings"
"sync"
)
const DEBUG = false
var bodyDump = middleware.BodyDump(func(c echo.Context, reqBody, resBody []byte) {
fmt.Printf("%s\n", reqBody)
fmt.Printf("%s\n", resBody)
})
type App struct {
FrontEndURL string
AuthURL string
AccountURL string
ServicesURL string
SessionURL string
AuthlibInjectorURL string
DB *gorm.DB
Config *Config
AnonymousLoginUsernameRegex *regexp.Regexp
Constants *ConstantsType
PlayerCertificateKeys []SerializedKey
ProfilePropertyKeys []SerializedKey
Key *rsa.PrivateKey
KeyB3Sum512 []byte
SkinMutex *sync.Mutex
}
func handleError(err error, c echo.Context) {
if err != nil {
c.Logger().Error(err)
}
if httpError, ok := err.(*echo.HTTPError); ok {
if httpError.Code == http.StatusNotFound {
if s, ok := httpError.Message.(string); ok {
e := c.String(httpError.Code, s)
Check(e)
return
}
}
}
e := c.String(http.StatusInternalServerError, "Internal server error")
Check(e)
}
func makeRateLimiter(app *App) echo.MiddlewareFunc {
requestsPerSecond := rate.Limit(app.Config.RateLimit.RequestsPerSecond)
return middleware.RateLimiterWithConfig(middleware.RateLimiterConfig{
Skipper: func(c echo.Context) bool {
switch c.Path() {
case "/",
"/drasl/challenge-skin",
"/drasl/profile",
"/drasl/registration",
"/drasl/public*",
"/drasl/texture/cape*",
"/drasl/texture/skin*":
return true
default:
return false
}
},
Store: middleware.NewRateLimiterMemoryStore(requestsPerSecond),
DenyHandler: func(c echo.Context, identifier string, err error) error {
path := c.Path()
split := strings.Split(path, "/")
if path == "/" || (len(split) >= 2 && split[1] == "drasl") {
setErrorMessage(&c, "Too many requests. Try again later.")
return c.Redirect(http.StatusSeeOther, getReturnURL(&c, app.FrontEndURL))
} else {
return &echo.HTTPError{
Code: http.StatusTooManyRequests,
Message: "Too many requests. Try again later.",
Internal: err,
}
}
},
})
}
func GetServer(app *App) *echo.Echo {
e := echo.New()
e.HideBanner = true
e.HidePort = app.Config.HideListenAddress
e.HTTPErrorHandler = handleError
if app.Config.LogRequests {
e.Use(middleware.Logger())
}
if DEBUG {
e.Use(bodyDump)
}
if !app.Config.RateLimit.Disable {
e.Use(makeRateLimiter(app))
}
// Front
t := NewTemplate(app)
e.Renderer = t
e.GET("/", FrontRoot(app))
e.GET("/drasl/challenge-skin", FrontChallengeSkin(app))
e.GET("/drasl/profile", FrontProfile(app))
e.GET("/drasl/registration", FrontRegistration(app))
e.POST("/drasl/delete-account", FrontDeleteAccount(app))
e.POST("/drasl/login", FrontLogin(app))
e.POST("/drasl/logout", FrontLogout(app))
e.POST("/drasl/register", FrontRegister(app))
e.POST("/drasl/update", FrontUpdate(app))
e.Static("/drasl/public", path.Join(app.Config.DataDirectory, "public"))
e.Static("/drasl/texture/cape", path.Join(app.Config.StateDirectory, "cape"))
e.Static("/drasl/texture/skin", path.Join(app.Config.StateDirectory, "skin"))
e.GET("/authlib-injector", AuthlibInjectorRoot(app))
e.GET("/authlib-injector/", AuthlibInjectorRoot(app))
// Auth
authAuthenticate := AuthAuthenticate(app)
authInvalidate := AuthInvalidate(app)
authRefresh := AuthRefresh(app)
authSignout := AuthSignout(app)
authValidate := AuthValidate(app)
e.POST("/authenticate", authAuthenticate)
e.POST("/invalidate", authInvalidate)
e.POST("/refresh", authRefresh)
e.POST("/signout", authSignout)
e.POST("/validate", authValidate)
e.GET("/auth", AuthGetServerInfo(app))
e.POST("/auth/authenticate", authAuthenticate)
e.POST("/auth/invalidate", authInvalidate)
e.POST("/auth/refresh", authRefresh)
e.POST("/auth/signout", authSignout)
e.POST("/auth/validate", authValidate)
// authlib-injector
e.POST("/authlib-injector/authserver/authenticate", authAuthenticate)
e.POST("/authlib-injector/authserver/invalidate", authInvalidate)
e.POST("/authlib-injector/authserver/refresh", authRefresh)
e.POST("/authlib-injector/authserver/signout", authSignout)
e.POST("/authlib-injector/authserver/validate", authValidate)
// Account
accountVerifySecurityLocation := AccountVerifySecurityLocation(app)
accountPlayerNameToID := AccountPlayerNameToID(app)
accountPlayerNamesToIDs := AccountPlayerNamesToIDs(app)
e.GET("/user/security/location", accountVerifySecurityLocation)
e.GET("/users/profiles/minecraft/:playerName", accountPlayerNameToID)
e.POST("/profiles/minecraft", accountPlayerNamesToIDs)
e.GET("/account/user/security/location", accountVerifySecurityLocation)
e.GET("/account/users/profiles/minecraft/:playerName", accountPlayerNameToID)
e.POST("/account/profiles/minecraft", accountPlayerNamesToIDs)
// Session
sessionHasJoined := SessionHasJoined(app)
sessionJoin := SessionJoin(app)
sessionProfile := SessionProfile(app)
e.GET("/session/minecraft/hasJoined", sessionHasJoined)
e.POST("/session/minecraft/join", sessionJoin)
e.GET("/session/minecraft/profile/:id", sessionProfile)
e.GET("/session/session/minecraft/hasJoined", sessionHasJoined)
e.POST("/session/session/minecraft/join", sessionJoin)
e.GET("/session/session/minecraft/profile/:id", sessionProfile)
// authlib-injector
e.GET("/authlib-injector/sessionserver/session/minecraft/hasJoined", sessionHasJoined)
e.POST("/authlib-injector/sessionserver/session/minecraft/join", sessionJoin)
e.GET("/authlib-injector/sessionserver/session/minecraft/profile/:id", sessionProfile)
// Services
servicesPlayerAttributes := ServicesPlayerAttributes(app)
servicesPlayerCertificates := ServicesPlayerCertificates(app)
servicesUUIDToNameHistory := ServicesUUIDToNameHistory(app)
servicesDeleteCape := ServicesDeleteCape(app)
servicesDeleteSkin := ServicesDeleteSkin(app)
servicesProfileInformation := ServicesProfileInformation(app)
servicesNameAvailability := ServicesNameAvailability(app)
servicesNameChange := ServicesNameChange(app)
servicesBlocklist := ServicesBlocklist(app)
servicesMSAMigration := ServicesMSAMigration(app)
servicesUploadSkin := ServicesUploadSkin(app)
servicesChangeName := ServicesChangeName(app)
servicesPublicKeys := ServicesPublicKeys(app)
e.GET("/player/attributes", servicesPlayerAttributes)
e.POST("/player/certificates", servicesPlayerCertificates)
e.GET("/user/profiles/:uuid/names", servicesUUIDToNameHistory)
e.DELETE("/minecraft/profile/capes/active", servicesDeleteCape)
e.DELETE("/minecraft/profile/skins/active", servicesDeleteSkin)
e.GET("/minecraft/profile", servicesProfileInformation)
e.GET("/minecraft/profile/name/:playerName/available", servicesNameAvailability)
e.GET("/minecraft/profile/namechange", servicesNameChange)
e.GET("/privacy/blocklist", servicesBlocklist)
e.GET("/rollout/v1/msamigration", servicesMSAMigration)
e.POST("/minecraft/profile/skins", servicesUploadSkin)
e.PUT("/minecraft/profile/name/:playerName", servicesChangeName)
e.GET("/publickeys", servicesPublicKeys)
e.GET("/services/player/attributes", servicesPlayerAttributes)
e.POST("/services/player/certificates", servicesPlayerCertificates)
e.GET("/services/user/profiles/:uuid/names", servicesUUIDToNameHistory)
e.DELETE("/services/minecraft/profile/capes/active", servicesDeleteCape)
e.DELETE("/services/minecraft/profile/skins/active", servicesDeleteSkin)
e.GET("/services/minecraft/profile", servicesProfileInformation)
e.GET("/services/minecraft/profile/name/:playerName/available", servicesNameAvailability)
e.GET("/services/minecraft/profile/namechange", servicesNameChange)
e.GET("/services/privacy/blocklist", servicesBlocklist)
e.GET("/services/rollout/v1/msamigration", servicesMSAMigration)
e.POST("/services/minecraft/profile/skins", servicesUploadSkin)
e.PUT("/services/minecraft/profile/name/:playerName", servicesChangeName)
e.GET("/services/publickeys", servicesPublicKeys)
return e
}
func setup(config *Config) *App {
key := ReadOrCreateKey(config)
keyB3Sum512 := KeyB3Sum512(key)
db_path := path.Join(config.StateDirectory, "drasl.db")
db, err := gorm.Open(sqlite.Open(db_path), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
Check(err)
err = db.AutoMigrate(&User{})
Check(err)
err = db.AutoMigrate(&TokenPair{})
Check(err)
var anonymousLoginUsernameRegex *regexp.Regexp
if config.AnonymousLogin.Allow {
anonymousLoginUsernameRegex, err = regexp.Compile(config.AnonymousLogin.UsernameRegex)
Check(err)
}
playerCertificateKeys := make([]SerializedKey, 0, 1)
profilePropertyKeys := make([]SerializedKey, 0, 1)
publicKeyDer, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
Check(err)
serializedKey := SerializedKey{PublicKey: base64.StdEncoding.EncodeToString(publicKeyDer)}
profilePropertyKeys = append(profilePropertyKeys, serializedKey)
playerCertificateKeys = append(playerCertificateKeys, serializedKey)
for _, fallbackAPIServer := range config.FallbackAPIServers {
reqURL, err := url.JoinPath(fallbackAPIServer.ServicesURL, "publickeys")
if err != nil {
log.Println(err)
continue
}
res, err := http.Get(reqURL)
if err != nil {
log.Println(err)
continue
}
defer res.Body.Close()
if res.StatusCode == http.StatusOK {
var publicKeysRes PublicKeysResponse
err = json.NewDecoder(res.Body).Decode(&publicKeysRes)
if err != nil {
log.Println(err)
continue
}
profilePropertyKeys = append(profilePropertyKeys, publicKeysRes.ProfilePropertyKeys...)
playerCertificateKeys = append(playerCertificateKeys, publicKeysRes.PlayerCertificateKeys...)
break
}
}
return &App{
Config: config,
AnonymousLoginUsernameRegex: anonymousLoginUsernameRegex,
Constants: Constants,
DB: db,
Key: key,
KeyB3Sum512: keyB3Sum512,
FrontEndURL: config.BaseURL,
PlayerCertificateKeys: playerCertificateKeys,
ProfilePropertyKeys: profilePropertyKeys,
AccountURL: Unwrap(url.JoinPath(config.BaseURL, "account")),
AuthURL: Unwrap(url.JoinPath(config.BaseURL, "auth")),
ServicesURL: Unwrap(url.JoinPath(config.BaseURL, "services")),
SessionURL: Unwrap(url.JoinPath(config.BaseURL, "session")),
AuthlibInjectorURL: Unwrap(url.JoinPath(config.BaseURL, "authlib-injector")),
}
}
func runServer(e *echo.Echo, listenAddress string) {
e.Logger.Fatal(e.Start(listenAddress))
}
func main() {
defaultConfigPath := path.Join(Constants.ConfigDirectory, "config.toml")
configPath := flag.String("config", defaultConfigPath, "Path to config file")
help := flag.Bool("help", false, "Show help message")
flag.Parse()
if *help {
fmt.Println("Usage: drasl [options]")
fmt.Println("Options:")
flag.PrintDefaults()
os.Exit(0)
}
config := ReadOrCreateConfig(*configPath)
app := setup(config)
runServer(GetServer(app), app.Config.ListenAddress)
}