-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.ts
228 lines (181 loc) · 8.08 KB
/
auth.ts
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
#!/usr/bin/env node
import { Argument, Option, program } from 'commander'
const pkg = require('../../package.json')
import { Xal, Msal, TokenRefreshError } from '../lib'
import TokenStore from '../tokenstore'
class Auth {
_options = {
file: {
default: '.xbox.tokens.json',
description: 'Load a different token file',
name: '-F, --file <path>',
},
auth: {
default: 'xal',
description: 'Choose authentication method. (choices: xal, msal)',
name: '-a, --auth <xal|msal>',
},
// output: {
// default: 'text',
// description: 'Sets the output format',
// name: '-O, --output <path>',
// choices: ['text', 'json'],
// },
}
_commander:typeof program
_tokenStore:TokenStore
_xal:Xal
_msal:Msal
_state
_deviceToken
constructor(){
this._commander = program
.version(pkg.version)
.addArgument(new Argument('command', 'Command to run').choices(['auth', 'show', 'refresh', 'tokens', 'logout']).default('auth'))
for(const arg in this._options){
const argData = this._options[arg]
const option = new Option(argData.name, argData.description)
if(argData.default)
option.default(argData.default)
if(argData.choices)
option.choices(argData.choices)
this._commander.addOption(option)
}
program.addHelpText('after', `
Example commands:
$ xbox-xal-auth auth
$ xbox-xal-auth show
$ xbox-xal-auth refresh
$ xbox-xal-auth logout`);
this._commander.parse();
// Load tokenstore
this._tokenStore = new TokenStore()
this._tokenStore.load(this._commander.opts().file, true)
// Load XAL
this._xal = new Xal(this._tokenStore)
this._msal = new Msal(this._tokenStore)
}
run(){
if(this._commander.args[0] == 'auth'){
if(this._tokenStore.hasValidAuthTokens()){
console.log('You are already authenticated. To show the tokens, run `xbox-xal-auth show`. To re-authenticate, run `xbox-xal-auth logout` first.')
return
}
if(this._commander.opts().auth === 'xal'){
console.log('Starting authentiction using XAL method...')
this._xal.getRedirectUri().then((redirect) => {
if(redirect){
console.log('Please authenticate using the following url:', redirect.sisuAuth.MsaOauthRedirect)
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
readline.question('Enter redirect uri: ', async redirectUri => {
readline.close()
// await this.loadTokensUsingCode(redirectUri, result.SessionId)
const loggedIn = await this._xal.authenticateUser(redirect, redirectUri)
if(loggedIn === true){
this._xal.refreshTokens()
console.log('Authentication succeeded!')
} else {
console.log('Authentication failed!')
}
})
}
}).catch((error) => {
console.log('error', error)
})
} else if(this._commander.opts().auth === 'msal'){
console.log('Starting authentiction using MSAL method...')
this._msal.doDeviceCodeAuth().then((deviceCodeDetails:any) => {
if(deviceCodeDetails){
console.log('Please follow the instructions below:')
console.log(deviceCodeDetails.message)
this._msal.doPollForDeviceCodeAuth(deviceCodeDetails.device_code).then((tokens:any) => {
console.log('Authentication succeeded!')
this._msal.refreshUserToken().then((tokens:any) => {
// console.log('Tokens:', tokens)
}).catch((error) => {
console.log('Failed to refresh token:', error)
})
})
}
}).catch((error) => {
console.log('error', error)
})
} else {
console.log('Unknown authentication method:', this._commander.opts().auth)
}
} else if(this._commander.args[0] == 'show'){
this.actionShow()
} else if(this._commander.args[0] == 'refresh'){
this.actionRefresh()
} else if(this._commander.args[0] == 'logout'){
this.actionLogout()
} else if(this._commander.args[0] == 'tokens'){
this.actionTokens()
}
}
actionShow(){
console.log('Current authentication status:')
console.log(' Authentication method:', this._tokenStore.getAuthenticationMethod().toUpperCase())
console.log(' UserToken: isAuthenticated('+this._tokenStore._userToken?.isValid()+') Seconds remaining:', this._tokenStore._userToken?.getSecondsValid())
if(this._tokenStore.getAuthenticationMethod() === 'xal'){
console.log(' SisuToken: isAuthenticated('+this._tokenStore._sisuToken?.isValid()+') Seconds remaining:', this._tokenStore._sisuToken?.getSecondsValid())
console.log(' ')
console.log(' User Hash:', this._tokenStore._sisuToken?.getUserHash())
console.log(' Gamertag:', this._tokenStore._sisuToken?.getGamertag())
}
}
actionRefresh(){
if(this._tokenStore.getUserToken() === undefined){
console.log('Please authenticate first using `xbox-auth auth`.')
return
}
let refreshMethod:Promise<any>
if(this._tokenStore.getAuthenticationMethod() === 'msal'){
refreshMethod = this._msal.refreshUserToken()
} else {
refreshMethod = this._xal.refreshTokens()
}
refreshMethod.then((token) => {
console.log('Tokens have been refreshed')
}).catch((error) => {
console.log('Failed to refresh token:', error)
})
}
actionLogout(){
this._tokenStore.removeAll()
console.log('Login data has been removed. You are now logged out.')
}
actionTokens(){
this.retrieveTokens().then((tokens) => {
console.log('Tokens:\n- MSAL Token:', JSON.stringify(tokens.msalToken, null, 4), '\n- Web Token:', JSON.stringify(tokens.webToken, null, 4))
console.log('Offering tokens:\n- xHome:', JSON.stringify(tokens.xhomeToken, null, 4), '\n- xCloud:', JSON.stringify(tokens.gpuToken, null, 4))
}).catch((error) => {
if(error instanceof TokenRefreshError){
console.log('Failed to refresh user token. Please re-authenticate again using `xbox-auth auth`.\n Details:', error)
} else {
console.log('Failed to retrieve tokens. Please try again later.\n Details:', error)
}
})
}
async retrieveTokens(){
let msalToken
let webToken
let streamingTokens
if(this._tokenStore.getAuthenticationMethod() === 'msal'){
msalToken = await this._msal.getMsalToken()
webToken = await this._msal.getWebToken()
streamingTokens = await this._msal.getStreamingTokens()
} else {
msalToken = await this._xal.getMsalToken()
webToken = await this._xal.getWebToken()
streamingTokens = await this._xal.getStreamingTokens()
}
const gpuToken = streamingTokens.xCloudToken
const xhomeToken = streamingTokens.xHomeToken
return { msalToken, webToken, xhomeToken, gpuToken }
}
}
new Auth().run()