-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
386 lines (335 loc) · 10.1 KB
/
index.js
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
import diagnostics from 'diagnostics';
import TickTock from 'tick-tock';
import failure from 'failure';
import request from 'request';
import URL from 'url-parse';
import uuid from 'uuid/v4';
//
// Setup our debug utility so we can figure out what is going on in with the
// module internals.
//
const debug = diagnostics('bungie-auth');
/**
* Access oAuth from Bungie.net
*
* @param {Object} opts Configuration.
* @constructor
* @public
*/
export default class Bungo {
constructor(opts) {
opts = Object.assign({}, Bungo.defaults, opts || {});
//
// References to the API responses from Bungie.net
//
this.refreshToken = opts.refreshToken || null;
this.accessToken = opts.accessToken || null;
this.redirectURL = opts.redirectURL;
this.timers = new TickTock(this);
this.config = opts;
this.state = null;
if (this.accessToken && this.refreshToken) {
debug('had a pre-existing access and refresh token. Starting timeout');
this.setTimeout();
}
}
/**
* Open a new browser window for the oAuth authorization flow.
*
* @param {Function} fn Completion callback.
* @private
*/
open(fn) {
return fn(failure('Left as implementation excercise for developers.'));
}
/**
* Generate the URL that starts the oAuth flow.
*
* @returns {URL} Our URL instance, that can toString in to an URL.
* @public
*/
url() {
const target = new URL(this.config.url, true);
this.state = uuid();
target.set('query', { state: this.state });
debug('created a oauth URL %s', target.href);
return target.href;
}
/**
* Check if the received URL is valid and secure enough to continue with our
* authentication steps.
*
* @param {String} url URL we need to check for possible miss matches.
* @returns {Boolean} Passed or failed our test.
* @public
*/
secure(url) {
const target = new URL(url, true);
return this.state === target.query.state;
}
/**
* Request accessToken.
*
* @param {Function} fn Completion callback
* @public
*/
request(fn) {
this.open(this.redirectURL, (err, url) => {
if (err) {
debug('failed to open the authorization window');
return fn(err);
}
debug('processing redirection URL', url);
const target = new URL(url, true);
if (!target.query.code) {
debug('the user as declined the oauth access, no code was received from bungie');
return fn(new Error('User as declined the oAuth request'));
}
this.send('GetAccessTokensFromCode', {
code: target.query.code
}, this.capture(fn));
});
}
/**
* Get the access token from the API, if we don't have a refresh token we want
* to request access to the user's details.
*
* @param {Function} fn Completion callback.
* @public
*/
token(fn) {
//
// 1:
//
// Look if we have a stored accessToken and check if it's still somewhat
// valid.
//
if (!this.expired(this.accessToken)) {
debug('accessToken is not yet expired, using cached access token');
return fn(undefined, this.payload());
}
//
// 2:
//
// If we still have a refresh token, use it to generate a new access token.
//
if (!this.expired(this.refreshToken)) {
debug('refreshToken is not yet expired, using cached refresh token');
return this.refresh(fn);
}
//
// 3:
//
// Abandon all hope, ask for another sign in as we have no token, no refresh
// token, no nothing. The world is a sad place, and addition user actions
// have to be taken.
//
debug('no working access and refresh tokens found, starting oauth flow');
this.request(fn);
}
/**
* Check if our given token is alive and kicking or if it's expired.
*
* @param {Object} token Token object received from Bungie.net
* @returns {Boolean}
* @public
*/
expired(token) {
if (!token || typeof token !== 'object' || !token.value || !token.epoch || !token.expires) {
debug('no valid token received assume its expired');
return true;
}
//
// We transform the difference in epoch to seconds and remove a small amount
// of buffering so people actually have some time to do an API request with
// the returned token.
//
const diff = this.alive(token) + (this.config.buffer / 2);
const canbeused = token.expires < diff;
debug('token expires %j/%j seconds, expired:', diff, token.expires, canbeused);
return canbeused;
}
/**
* Calculate the time in seconds that the token has been alive.
*
* @returns {Number} time in seconds the token has been alive
* @public
*/
alive(token) {
const now = Date.now();
return Math.ceil((now - token.epoch) / 1000);
}
/**
* Send a token request to Bungie.net.
*
* @param {String} pathname Pathname we need to hit.
* @param {Object} body Request body.
* @param {Function} fn Completion callback.
* @public
*/
send(pathname, body, fn) {
const url = 'https://www.bungie.net/Platform/App/'+ pathname +'/';
debug('sending API request to %s', url);
request({
url: url,
json: true,
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-API-Key': this.config.key,
'Accept': 'application/json',
}
}, (err, res, body) => {
if (err) {
debug('received an error while making an API request', err);
return fn(err);
}
//
// Handle invalid responses because the site is down.
//
if (res.statusCode !== 200 || typeof body !== 'object') {
debug('invalid response received from bungie server', res.statusCode, body);
return fn(failure('Bungie API returned an error, try again later.'), {
statusCode: res.statusCode
});
}
fn(undefined, body);
});
}
/**
* Refresh the token.
*
* @param {String} token Optional refresh token. Will used last known.
* @param {Function} fn Completion callback.
* @public
*/
refresh(token, fn) {
if ('function' === typeof token) {
fn = token;
token = null;
if (this.refreshToken) {
token = this.refreshToken;
}
}
//
// @TODO when we don't have a token, do we want to trigger another
// authentication request?
//
if (!token) {
return fn(failure('Missing refresh token'));
}
return this.send('GetAccessTokensFromRefreshToken', {
refreshToken: token.value
}, this.capture(fn));
}
/**
* Try to keep the internally cached accessToken as fresh as possible so
* our `.token` method is as fast as it can be. We want to make sure that
* we give our API some extra time to do the lookup so we'll subtract 60
* seconds from the expiree.
*
* @private
*/
setTimeout() {
if (!this.config.fresh) return;
this.timers.clear('refresh');
let remaining = this.accessToken.expires - this.alive(this.accessToken);
//
// Remove the time from our buffer so we have spare time to refresh the
// token without disrupting the application. But we need to make sure
// that we still keep a positive integer when setting our timeout so
// default to 0.
//
remaining = remaining - this.config.buffer;
if (remaining < 0) remaining = 0;
debug('updating setTimeout for refreshToken in %s seconds', remaining);
this.timers.setTimeout('refresh', () => {
debug('our refreshToken is about to expire, initating auto-refresh');
this.refresh(this.config.fresh);
}, remaining + ' seconds');
}
/**
* Capture the response from the Bungie servers so we can apply some
* additional processing.
*
* @param {Function} fn Completion callback.
* @returns {Function} Interception callback.
* @private
*/
capture(fn) {
return (err, body = {}) => {
if (err) {
debug('Bungie API request failed hard: %s', err.message);
return fn(err);
}
//
// Handle various of failures.
//
if (!('Response' in body) || 'Success' !== body.ErrorStatus) {
const message = body.Message || 'Invalid data received from Bungie.net';
//
// The internal authorizationCode is invalid, we should ask the user to
// login again.
//
if (body.ErrorStatus === 'AuthorizationCodeInvalid') {
this.refreshToken = null;
this.accessToken = null;
debug('our authorization code is invalid, whipe and re-authenticate');
return this.request(fn);
}
debug('Invalid response received from Bungie servers: %s', message);
return fn(failure(message, { status: body.ErrorStatus }));
}
const refreshToken = this.refreshToken;
const data = body.Response;
const now = Date.now();
//
// The API responses only have a `expires` and `readyin` values which
// started when the API request was made. So if you store these values you
// really have no clue if you can still use the accessToken or
// refreshToken.
//
data.refreshToken.epoch = now
data.accessToken.epoch = now;
this.refreshToken = data.refreshToken;
this.accessToken = data.accessToken;
const payload = this.payload();
//
// Check if we previously already had data or if this is actually the
// first time we received data because in that case we also want to
// trigger the fresh function so it can be used as storage callback for
// applications
//
if (this.config.fresh && !refreshToken) {
debug('first time calling refresh as we didnt have a token before');
this.config.fresh(err, payload);
}
this.setTimeout();
fn(err, payload);
};
}
/**
* The payload that is returned to the user.
*
* @returns {Object} The API payload.
* @public
*/
payload() {
return {
refreshToken: this.refreshToken,
accessToken: this.accessToken
};
}
}
/**
* Default options.
*
* @type {Object}
* @private
*/
Bungo.defaults = {
url: 'https://www.bungie.net/en/Application/Authorize/',
buffer: 60,
fresh: false
};