-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
608 lines (572 loc) · 18.9 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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
const OAuth2Strategy = require("passport-oauth2");
const { InternalOAuthError } = require("passport-oauth2");
const url = require("node:url");
const utils = require("passport-oauth2/lib/utils");
const base64url = require("base64url");
const crypto = require("crypto");
const API_BASE = "https://discord.com/api/";
/**
* Represents the Discord OAuth2 strategy for Passport.
* Extends the base OAuth2Strategy to provide custom behavior for Discord's API.
* @param {Object} options - Configuration options for the strategy.
* @param {Function} verify - Verification callback for the strategy.
* @throws Will throw an error if required options are missing.
*/
class Strategy extends OAuth2Strategy {
constructor(options, verify) {
options = options || {};
options.authorizationURL =
options.authorizationURL || "https://discord.com/api/oauth2/authorize";
options.tokenURL =
options.tokenURL || "https://discord.com/api/oauth2/token";
options.scopeSeparator = options.scopeSeparator || " ";
options.scope = options.scope || ["identify", "email"];
if (!options.callbackURL) throw new Error("Missing callbackURL property");
if (!options.clientID) throw new Error("Missing clientID property");
if (!options.clientSecret) throw new Error("Missing clientSecret property");
super(options, verify);
this.options = options;
this.verify = verify;
this.name = "discord";
this._oauth2.useAuthorizationHeaderforGET(true);
}
/**
* Fetches the user profile from Discord using the provided access token.
* @param {string} accessToken - The access token for the user.
* @param {Function} done - Callback to handle the user profile.
*/
async userProfile(accessToken, done) {
try {
const profile = await this.resolveApi("users/@me", accessToken);
const consumable = {
guilds: this.getGuilds.bind(this, profile, accessToken),
guildJoiner: this.guildJoiner.bind(this, profile, accessToken),
connections: this.getConnection.bind(this, profile, accessToken),
member: this.getMember.bind(this, profile, accessToken),
linkedRole: {
get: this.getRoleConnectionMetadata.bind(this, profile, accessToken),
set: this.setRoleConnectionMetadata.bind(this, profile, accessToken),
},
complexResolver: this._oauth2._request,
profile: () => profile,
resolver: async (key, api) => {
return new Promise(async (resolve, reject) => {
try {
const data = await this.resolveApi(api, accessToken);
profile[key] = data;
resolve(profile);
} catch (err) {
reject(err);
}
});
},
resolverCallbackBased: async (key, api, done) => {
try {
const data = await this.resolveApi(api, accessToken);
profile[key] = data;
done(null, profile);
} catch (err) {
done(err, null);
}
},
};
profile.avatarUrl = profile.avatar
? `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}`
: undefined;
done(null, { profile, consumable });
} catch (e) {
done(e, null);
}
}
/**
* Retrieves the connections associated with the user's Discord account.
* @param {Object} profile - The user's profile.
* @param {string} accessToken - The access token for the user.
* @throws Will throw an error if the required scope is not included.
*/
async getConnection(profile, accessToken, done) {
if (!this.options.scope || !this.options.scope.includes("connections")) {
throw new Error("Missing Scope, 'connections'");
}
try {
const connections = await this.resolveApi(
"users/@me/connections",
accessToken
);
profile.connections = connections;
if (done) done(null, profile);
} catch (e) {
if (done) return done(e, null);
return e;
}
}
/**
* Retrieves the guilds associated with the user's Discord account.
* @param {Object} profile - The user's profile.
* @param {string} accessToken - The access token for the user.
* @throws Will throw an error if the required scope is not included.
*/
async getGuilds(profile, accessToken, done) {
if (!this.options.scope || !this.options.scope.includes("guilds")) {
throw new Error("Missing Scope, 'guilds'");
}
try {
const guilds = await this.resolveApi("users/@me/guilds", accessToken);
profile.guilds = guilds;
if (done) done(null, profile);
} catch (e) {
if (done) return done(e, null);
return e;
}
}
async getMember(profile, accessToken, guild_id, done) {
if (
!this.options.scope ||
!this.options.scope.includes("guilds.members.read")
) {
throw new Error("Missing Scope, 'guilds.members.read'");
}
if (!profile.member) {
profile.member = {};
}
try {
const member = await this.resolveApi(
`users/@me/guilds/${guild_id}/member`,
accessToken
);
profile.member[guild_id] = member;
if (done) done(null, profile);
} catch (e) {
if (JSON.parse(e.data)?.code == 10004) {
profile.member[guild_id] = null;
e = null;
} else {
if (done) return done(e, profile);
return e;
}
}
}
/**
* Adds a user to a guild with the specified roles and nickname.
* @param {Object} profile - The user's profile.
* @param {string} accessToken - The access token for the user.
* @param {string} botToken - The bot token for guild authorization.
* @param {string} serverId - The ID of the server to join.
* @param {string} nick - The nickname to assign to the user.
* @param {string[]} roles - The roles to assign to the user.
* @param {Function} done - Callback for handling the result.
*/
async guildJoiner(
profile,
accessToken,
botToken,
serverId,
nick,
roles,
done
) {
if (!this.options.scope || !this.options.scope.includes("guilds.join")) {
done(new Error("Missing Scope, 'guilds.join'"));
return;
}
const body = {
access_token: accessToken,
nick,
roles,
};
try {
const res = await new Promise((resolve, reject) => {
this._oauth2._request(
"PUT",
`${API_BASE}guilds/${serverId}/members/${profile.id}`,
{
Authorization: `Bot ${botToken}`,
"content-type": "application/json",
},
JSON.stringify(body),
null,
(err, result, response) => {
if (err) {
reject(err);
} else {
resolve(response);
}
}
);
});
if (res.statusCode === 201 || res.statusCode === 204) {
done(null, null);
} else {
done(null, res.statusCode);
}
} catch (error) {
done(error);
}
}
/**
* Retrieves the linked role metadata associated with the user's Discord account.
* @param {string} profile - The user's profile.
* @param {string} accessToken - The access token for the user.
* @returns {Promise<Object>} The resolved data.
* @throws Will throw an error for request or parsing issues.
*/
async getRoleConnectionMetadata(profile, accessToken, done) {
if (
!this.options.scope ||
!this.options.scope.includes("role_connections.write")
) {
throw new Error("Missing Scope, 'role_connections.write'");
}
if (!profile.linkedRole) {
profile.linkedRole = {};
}
try {
const metadata = await this.resolveApi(
`users/@me/applications/${this.options.clientID}/role-connection`,
accessToken
);
profile.linkedRole.get = metadata;
if (done) return done(null, profile);
} catch (e) {
if (done) return done(e, null);
return e;
}
}
/**
* updated the linked role metadata associated with the user's Discord account.
* @param {string} profile - The user's profile.
* @param {string} accessToken - The access token for the user.
* @param {string} platform_name - The vanity name of the platform a bot has connected (max 50 characters)
* @param {string} platform_username - The username on the platform a bot has connected (max 100 characters)
* @typedef {Object} metadata
* @property {string} property1 - Description for property1.
* @property {number} property2 - Description for property2.
* @property {boolean} property3 - Description for property3.
* @returns {Promise<Object>} The resolved data.
* @throws Will throw an error for request or parsing issues.
*/
async setRoleConnectionMetadata(
profile,
accessToken,
platform_name,
platform_username,
metadata,
done
) {
if (
!this.options.scope ||
!this.options.scope.includes("role_connections.write")
) {
throw new Error("Missing Scope, 'role_connections.write'");
}
if (!profile.linkedRole) {
profile.linkedRole = {};
}
try {
const role = await new Promise((resolve, reject) => {
this._oauth2._request(
"PUT",
`${API_BASE}/users/@me/applications/${this.options.clientID}/role-connection`,
{
Authorization: `Bearer ${accessToken}`,
"content-type": "application/json",
},
JSON.stringify({
platform_name,
platform_username,
metadata,
}),
null,
(err, result, response) => {
if (err) {
reject(err);
} else {
resolve(JSON.parse(result));
}
}
);
});
profile.linkedRole.set = role;
if (done) return done(null, profile);
} catch (e) {
if (e instanceof SyntaxError) {
reject(new Error("Failed to parse the user profile."));
}
if (done) return done(e, null);
return e;
}
}
/**
* Resolves an API endpoint and parses the response.
* @param {string} api - The API endpoint to resolve.
* @param {string} accessToken - The access token for the user.
* @returns {Promise<Object>} The resolved data.
* @throws Will throw an error for request or parsing issues.
*/
async resolveApi(api, accessToken) {
return new Promise(async (res, rej) => {
try {
const result = await new Promise((resolve, reject) => {
this._oauth2.get(`${API_BASE}${api}`, accessToken, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
res(JSON.parse(result));
} catch (err) {
if (err instanceof SyntaxError) {
reject(new Error("Failed to parse the user profile."));
}
// throw new InternalOAuthError("Failed to resolve API", err);
rej(err);
}
});
}
/**
* Authenticate the request.
* @param {Object} req - The request object.
* @param {Object} options - Authentication options.
*/
authenticate = function (req, options) {
options = options || {};
var self = this;
if (req.query && req.query.error) {
if (req.query.error == "access_denied") {
return this.fail({ message: req.query.error_description });
} else {
return this.error(
new AuthorizationError(
req.query.error_description,
req.query.error,
req.query.error_uri
)
);
}
}
var callbackURL = options.callbackURL || this._callbackURL;
if (callbackURL) {
var parsed = url.parse(callbackURL);
if (!parsed.protocol) {
// The callback URL is relative, resolve a fully qualified URL from the
// URL of the originating request.
callbackURL = url.resolve(
utils.originalURL(req, { proxy: this._trustProxy }),
callbackURL
);
}
}
var meta = {
authorizationURL: this._oauth2._authorizeUrl,
tokenURL: this._oauth2._accessTokenUrl,
clientID: this._oauth2._clientId,
callbackURL: callbackURL,
};
if ((req.query && req.query.code) || (req.body && req.body.code)) {
function loaded(err, ok, state) {
if (err) {
return self.error(err);
}
if (!ok) {
return self.fail(state, 403);
}
var code = (req.query && req.query.code) || (req.body && req.body.code);
var params = self.tokenParams(options);
params.grant_type = "authorization_code";
if (callbackURL) {
params.redirect_uri = callbackURL;
}
if (typeof ok == "string") {
// PKCE
params.code_verifier = ok;
}
self._oauth2.getOAuthAccessToken(
code,
params,
function (err, accessToken, refreshToken, params) {
if (err) {
return self.error(
self._createOAuthError("Failed to obtain access token", err)
);
}
if (!accessToken) {
return self.error(new Error("Failed to obtain access token"));
}
self._loadUserProfile(
accessToken,
function (err, { profile, consumable }) {
if (err) {
return self.error(err);
}
function verified(err, user, info) {
if (err) {
return self.error(err);
}
if (!user) {
return self.fail(info);
}
info = info || {};
if (state) {
info.state = state;
}
self.success(user, info);
}
try {
if (self._passReqToCallback) {
var arity = self._verify.length;
if (arity == 7) {
self._verify(
req,
accessToken,
refreshToken,
params,
profile,
verified,
consumable
);
} else {
// arity == 6
self._verify(
req,
accessToken,
refreshToken,
profile,
verified,
consumable
);
}
} else {
var arity = self._verify.length;
if (arity == 6) {
self._verify(
accessToken,
refreshToken,
params,
profile,
verified,
consumable
);
} else {
// arity == 5
self._verify(
accessToken,
refreshToken,
profile,
verified,
consumable
);
}
}
} catch (ex) {
return self.error(ex);
}
}
);
}
);
}
var state =
(req.query && req.query.state) || (req.body && req.body.state);
try {
var arity = this._stateStore.verify.length;
if (arity == 4) {
this._stateStore.verify(req, state, meta, loaded);
} else {
// arity == 3
this._stateStore.verify(req, state, loaded);
}
} catch (ex) {
return this.error(ex);
}
} else {
var params = this.authorizationParams(options);
params.response_type = "code";
if (callbackURL) {
params.redirect_uri = callbackURL;
}
var scope = options.scope || this._scope;
if (scope) {
if (Array.isArray(scope)) {
scope = scope.join(this._scopeSeparator);
}
params.scope = scope;
}
var verifier, challenge;
if (this._pkceMethod) {
verifier = base64url(crypto.pseudoRandomBytes(32));
switch (this._pkceMethod) {
case "plain":
challenge = verifier;
break;
case "S256":
challenge = base64url(
crypto.createHash("sha256").update(verifier).digest()
);
break;
default:
return this.error(
new Error(
"Unsupported code verifier transformation method: " +
this._pkceMethod
)
);
}
params.code_challenge = challenge;
params.code_challenge_method = this._pkceMethod;
}
var state = options.state;
if (state && typeof state == "string") {
// NOTE: In passport-oauth2@1.5.0 and earlier, `state` could be passed as
// an object. However, it would result in an empty string being
// serialized as the value of the query parameter by `url.format()`,
// effectively ignoring the option. This implies that `state` was
// only functional when passed as a string value.
//
// This fact is taken advantage of here to fall into the `else`
// branch below when `state` is passed as an object. In that case
// the state will be automatically managed and persisted by the
// state store.
params.state = state;
var parsed = url.parse(this._oauth2._authorizeUrl, true);
utils.merge(parsed.query, params);
parsed.query["client_id"] = this._oauth2._clientId;
delete parsed.search;
var location = url.format(parsed);
this.redirect(location);
} else {
function stored(err, state) {
if (err) {
return self.error(err);
}
if (state) {
params.state = state;
}
var parsed = url.parse(self._oauth2._authorizeUrl, true);
utils.merge(parsed.query, params);
parsed.query["client_id"] = self._oauth2._clientId;
delete parsed.search;
var location = url.format(parsed);
self.redirect(location);
}
try {
var arity = this._stateStore.store.length;
if (arity == 5) {
this._stateStore.store(req, verifier, state, meta, stored);
} else if (arity == 4) {
this._stateStore.store(req, state, meta, stored);
} else if (arity == 3) {
this._stateStore.store(req, meta, stored);
} else {
// arity == 2
this._stateStore.store(req, stored);
}
} catch (ex) {
return this.error(ex);
}
}
}
};
}
module.exports = Strategy;