-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
504 lines (425 loc) · 11.4 KB
/
auth.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package valorant
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
tls "github.com/refraction-networking/utls"
"github.com/valyala/fasthttp"
"net"
"net/url"
"strings"
)
func generateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}
func GenerateRandomStringURLSafe(n int) string {
b, _ := generateRandomBytes(n)
return base64.URLEncoding.EncodeToString(b)
}
var (
defaultHeaders = map[string]string{
"Content-Type": "application/json",
"Cache-Control": "no-cache",
"User-Agent": GenerateRandomStringURLSafe(111),
}
authHeaders = map[string]string{}
tlsConfig = &tls.Config{
CipherSuites: []uint16{tls.TLS_CHACHA20_POLY1305_SHA256},
MinVersion: tls.VersionTLS13,
}
)
type Auth struct {
Client *fasthttp.Client
CookieJar string
Region string
AccessToken string
IdToken string
ExpiresIn string
Token string
Version string
UserInfo userInfoResp
}
type handshakeBody struct {
ClientID string `json:"client_id"`
Nonce string `json:"nonce"`
RedirectURI string `json:"redirect_uri"`
ResponseType string `json:"response_type"`
Scope string `json:"scope"`
}
type handshakeRespBody struct {
Type string `json:"type"`
Country string `json:"country"`
}
type loginBody struct {
Type string `json:"type"`
Username string `json:"username"`
Password string `json:"password"`
}
type loginRespBody struct {
Type string `json:"type"`
Response struct {
Mode string `json:"mode"`
Parameters struct {
Uri string `json:"uri"`
} `json:"parameters"`
} `json:"response"`
Country string `json:"country"`
}
type userInfoResp struct {
Country string `json:"country"`
UserId string `json:"sub"`
EmailVerified bool `json:"email_verified"`
PlayerPlocale string `json:"player_plocale"`
CountryAt int `json:"country_at"`
Pw struct {
CngAt int `json:"cng_at"`
Reset bool `json:"reset"`
MustReset bool `json:"must_reset"`
} `json:"pw"`
PhoneNumberVerified bool `json:"phone_number_verified"`
AccountVerified bool `json:"account_verified"`
Ppid string `json:"ppid"`
PlayerLocale string `json:"player_locale"`
Acct struct {
Type int `json:"type"`
State string `json:"state"`
Adm bool `json:"adm"`
GameName string `json:"game_name"`
TagLine string `json:"tag_line"`
CreatedAt int `json:"created_at"`
} `json:"acct"`
Age int `json:"age"`
Jti string `json:"jti"`
Affinity struct {
Pp string `json:"pp"`
} `json:"affinity"`
}
type regionReq struct {
IdToken string `json:"id_token"`
}
type regionResp struct {
PasToken string `json:"token"`
Affinities struct {
Pbe string `json:"pbe"`
Live string `json:"live"`
} `json:"affinities"`
}
type clientVersionResp struct {
Status int `json:"status"`
Data struct {
ManifestId string `json:"manifest_id"`
Branch string `json:"branch"`
Version string `json:"version"`
BuildVersion string `json:"buildVersion"`
EngineVersion string `json:"engineVersion"`
RiotClientVersion string `json:"riotClientVersion"`
BuildData string `json:"buildData"`
} `json:"data"`
}
func dialTLS(addr string) (net.Conn, error) {
netConn, err := fasthttp.Dial(addr)
if err != nil {
return nil, err
}
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
config := tlsConfig.Clone()
config.ServerName = host
tlsConn := tls.UClient(netConn, config, tls.HelloGolang)
if err := tlsConn.Handshake(); err != nil {
return nil, err
}
return tlsConn, nil
}
func createClient() *fasthttp.Client {
client := &fasthttp.Client{
Dial: dialTLS,
}
return client
}
func (a *Auth) httpRequest(method, url string, body interface{}) (r []byte, ok bool) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod(method)
req.SetRequestURI(url)
for k, v := range authHeaders {
req.Header.Add(k, v)
}
req.Header.AddBytesV("Referer", req.URI().Host())
if body != nil {
bodyBytes, _ := json.Marshal(body)
req.SetBody(bodyBytes)
}
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := a.Client.Do(req, resp)
if err != nil {
return nil, false
}
r = resp.Body()
return r, true
}
func parseCookies(cookies []string, subs string) (string, error) {
for _, cookie := range cookies {
if strings.Contains(cookie, subs) {
return cookie, nil
}
}
return "", fmt.Errorf("could not find %s", subs)
}
func (a *Auth) getTokens(uri string) (ok bool) {
parsedUrl, err := url.Parse(uri)
if err != nil {
return false
}
query, err := url.ParseQuery(parsedUrl.Fragment)
if err != nil {
return false
}
access_token := query.Get("access_token")
id_token := query.Get("id_token")
expires_in := query.Get("expires_in")
a.AccessToken = access_token
a.IdToken = id_token
a.ExpiresIn = expires_in
return true
}
func (a *Auth) handshake() (cookie string, ok bool) {
body := handshakeBody{
ClientID: "play-valorant-web-prod",
Nonce: GenerateRandomStringURLSafe(16),
RedirectURI: "https://playvalorant.com/opt_in",
ResponseType: "token id_token",
Scope: "account openid",
}
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("POST")
req.SetRequestURI("https://auth.riotgames.com/api/v1/authorization")
for k, v := range authHeaders {
req.Header.Add(k, v)
}
req.Header.AddBytesV("Referer", req.URI().Host())
bodyBytes, _ := json.Marshal(body)
req.SetBody(bodyBytes)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := a.Client.Do(req, resp)
if err != nil {
return "", false
}
respBody := handshakeRespBody{}
if err := json.Unmarshal(resp.Body(), &respBody); err != nil {
return "", false
}
var cookies []string
resp.Header.VisitAll(func(key, value []byte) {
if string(key) == "Set-Cookie" {
cookies = append(cookies, string(value))
}
})
cookie, err = parseCookies(cookies, "asid")
if err != nil {
return "", false
}
return cookie, true
}
func (a *Auth) login(username, password string) (cookie string, ok bool) {
body := loginBody{
Type: "auth",
Username: username,
Password: password,
}
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("PUT")
req.SetRequestURI("https://auth.riotgames.com/api/v1/authorization")
for k, v := range authHeaders {
req.Header.Add(k, v)
}
req.Header.AddBytesV("Referer", req.URI().Host())
bodyBytes, _ := json.Marshal(body)
req.SetBody(bodyBytes)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := a.Client.Do(req, resp)
if err != nil {
return "", false
}
respBody := loginRespBody{}
if err := json.Unmarshal(resp.Body(), &respBody); err != nil {
return "", false
}
if respBody.Type == "error" {
return "", false
}
uri := respBody.Response.Parameters.Uri
if ok := a.getTokens(uri); !ok {
return "", false
}
var cookies []string
resp.Header.VisitAll(func(key, value []byte) {
if string(key) == "Set-Cookie" {
cookies = append(cookies, string(value))
}
})
cookie, err = parseCookies(cookies, "ssid")
if err != nil {
return "", false
}
return cookie, true
}
func (a *Auth) getEntitlements() (ok bool) {
body, ok := a.httpRequest("POST", "https://entitlements.auth.riotgames.com/api/token/v1", nil)
if !ok {
return false
}
bodyStruct := struct {
Token string `json:"entitlements_token"`
}{}
if err := json.Unmarshal(body, &bodyStruct); err != nil {
return false
}
a.Token = bodyStruct.Token
return true
}
func (a *Auth) GetUser() (ok bool) {
body, ok := a.httpRequest("POST", "https://auth.riotgames.com/userinfo", nil)
if !ok {
return false
}
bodyStruct := userInfoResp{}
if err := json.Unmarshal(body, &bodyStruct); err != nil {
return false
}
a.UserInfo = bodyStruct
return true
}
func (a *Auth) getRegion() (ok bool) {
body, ok := a.httpRequest("PUT", "https://riot-geo.pas.si.riotgames.com/pas/v1/product/valorant", regionReq{
IdToken: a.IdToken,
})
if !ok {
return false
}
bodyStruct := regionResp{}
if err := json.Unmarshal(body, &bodyStruct); err != nil {
return false
}
a.Region = bodyStruct.Affinities.Live
return true
}
func (a *Auth) getClientVersion() (ok bool) {
body, ok := a.httpRequest("GET", "https://valorant-api.com/v1/version", nil)
if !ok {
return false
}
bodyStruct := clientVersionResp{}
if err := json.Unmarshal(body, &bodyStruct); err != nil {
return false
}
a.Version = bodyStruct.Data.RiotClientVersion
return true
}
// Login to the Riot Games API
func New(username, password string) (*Auth, error) {
client := createClient()
auth := &Auth{
Client: client,
}
authHeaders = defaultHeaders
cookie, ok := auth.handshake()
if !ok {
return nil, fmt.Errorf("could not handshake")
}
authHeaders["Cookie"] = cookie
cookie, ok = auth.login(username, password)
if !ok {
return nil, fmt.Errorf("could not login")
}
delete(authHeaders, "Cookie")
authHeaders["Authorization"] = fmt.Sprintf("Bearer %s", auth.AccessToken)
if ok := auth.getRegion(); !ok {
return nil, fmt.Errorf("could not get region")
}
authHeaders["Cookie"] = cookie
auth.CookieJar = cookie
if ok := auth.getEntitlements(); !ok {
return nil, fmt.Errorf("could not get entitlements")
}
authHeaders["X-Riot-Entitlements-JWT"] = auth.Token
if ok := auth.getClientVersion(); !ok {
return nil, fmt.Errorf("could not get client version")
}
authHeaders["X-Riot-ClientVersion"] = auth.Version
if ok := auth.GetUser(); !ok {
return nil, fmt.Errorf("could not get user")
}
return auth, nil
}
func (a *Auth) Reauth() bool {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.Header.SetMethod("GET")
req.SetRequestURI("https://auth.riotgames.com/authorize?redirect_uri=https%3A%2F%2Fplayvalorant.com%2Fopt_in&client_id=play-valorant-web-prod&response_type=token%20id_token&nonce=1")
reauthHeaders := defaultHeaders
for k, v := range reauthHeaders {
req.Header.Add(k, v)
}
req.Header.Set("Cookie", a.CookieJar)
req.Header.Set("X-Riot-Entitlements-JWT", a.Token)
req.Header.Set("X-Riot-ClientVersion", a.Version)
req.Header.AddBytesV("Referer", req.URI().Host())
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := a.Client.Do(req, resp)
if err != nil {
return false
}
fmt.Println(resp.StatusCode())
if resp.StatusCode() != 303 {
return false
}
location := resp.Header.Peek("Location")
if location == nil {
return false
}
fmt.Println(string(location))
if ok := a.getTokens(string(location)); !ok {
return false
}
if a.AccessToken == "" || a.IdToken == "" || a.ExpiresIn == "" {
return false
}
return true
}
func CreateAuth(cookieJar, region, accessToken, idToken, expiresIn, token, version string) (*Auth, error) {
auth := &Auth{
Client: createClient(),
CookieJar: cookieJar,
Region: region,
AccessToken: accessToken,
IdToken: idToken,
ExpiresIn: expiresIn,
Token: token,
Version: version,
UserInfo: userInfoResp{},
}
authHeaders = defaultHeaders
authHeaders["Cookie"] = cookieJar
authHeaders["Authorization"] = fmt.Sprintf("Bearer %s", accessToken)
authHeaders["X-Riot-Entitlements-JWT"] = token
authHeaders["X-Riot-ClientVersion"] = version
if ok := auth.GetUser(); !ok {
return nil, fmt.Errorf("could not get user")
}
return auth, nil
}