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
|
import Cookies, { CookieSetOptions } from "universal-cookie";
import { AxiosResponse } from "axios";
import { startAuthorizing, finishAuthorizing } from "../slices/authorization";
import formsStore from "../store";
import * as Sentry from "@sentry/react";
import APIClient from "./client";
const OAUTH2_CLIENT_ID = process.env.REACT_APP_OAUTH2_CLIENT_ID;
const PRODUCTION = process.env.NODE_ENV !== "development";
const STATE_LENGTH = 64;
/**
* Authorization result as returned from the backend.
*/
interface AuthResult {
username: string,
expiry: string
}
/**
* Name properties for authorization cookies.
*/
export enum CookieNames {
Scopes = "DiscordOAuthScopes",
Username = "DiscordUsername"
}
export interface APIErrors {
Message: APIErrorMessages,
Error: any, /* eslint-disable-line @typescript-eslint/no-explicit-any */
}
export enum APIErrorMessages {
BackendValidation = "Backend could not authorize with Discord. Please contact the forms team.",
BackendValidationDev = "Backend could not authorize with Discord, possibly due to being on a preview branch. Please contact the forms team.",
BackendUnresponsive = "Unable to reach the backend, please retry, or contact the forms team.",
BadResponse = "The server returned a bad response, please contact the forms team.",
AccessRejected = "Authorization was cancelled.",
Unknown = "An unknown error occurred, please contact the forms team."
}
/**
* [Reference]{@link https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes}
*
* Commented out enums are locked behind whitelists.
*/
export enum OAuthScopes {
Connections = "connections",
Email = "email",
Identify = "identify",
Guilds = "guilds"
}
/**
* Helper method to ensure the minimum required scopes
* for the application to function exist in a list.
*/
function ensureMinimumScopes(scopes: unknown, expected: OAuthScopes | OAuthScopes[]): OAuthScopes[] {
let result: OAuthScopes[] = [];
if (scopes && Array.isArray(scopes)) {
result = scopes;
}
if (Array.isArray(expected)) {
expected.forEach(scope => { if (!result.includes(scope)) result.push(scope); });
} else {
if (!result.includes(expected)) result.push(expected);
}
return result;
}
/**
* Return true if the program has the requested scopes or higher.
*/
export function checkScopes(scopes?: OAuthScopes[]): boolean {
const cleanedScopes = ensureMinimumScopes(scopes, OAuthScopes.Identify);
// Get Active Scopes And Ensure Type
const cookies = new Cookies().get(CookieNames.Scopes);
if (!cookies || !Array.isArray(cookies)) {
return false;
}
// Check For Scope Existence
for (const scope of cleanedScopes) {
if (!cookies.includes(scope)) {
return false;
}
}
return true;
}
/***
* Request authorization code from the discord api with the provided scopes.
*
* @returns {code, cleanedScopes} The discord authorization code and the scopes the code is granted for.
* @throws {Error} Indicates that an integrity check failed.
*/
export async function getDiscordCode(scopes: OAuthScopes[], disableFunction?: (disable: boolean) => void): Promise<{code: string | null, cleanedScopes: OAuthScopes[]}> {
const cleanedScopes = ensureMinimumScopes(scopes, OAuthScopes.Identify);
// Generate a new user state
const stateBytes = new Uint8Array(STATE_LENGTH);
crypto.getRandomValues(stateBytes);
let state = "";
for (let i = 0; i < stateBytes.length; i++) {
state += stateBytes[i].toString(16).padStart(2, "0");
}
const scopeString = encodeURIComponent(cleanedScopes.join(" "));
const redirectURI = encodeURIComponent(document.location.protocol + "//" + document.location.host + "/callback");
const windowHeight = screen.availHeight;
const windowWidth = screen.availWidth;
const requestHeight = Math.floor(windowHeight * 0.75);
const requestWidth = Math.floor(windowWidth * 0.4);
// Open login window
const windowRef = window.open(
`https://discord.com/api/oauth2/authorize?client_id=${OAUTH2_CLIENT_ID}&state=${state}&response_type=code&scope=${scopeString}&redirect_uri=${redirectURI}&prompt=consent`,
"_blank",
`popup=true,height=${requestHeight},left=0,top=0,width=${requestWidth}`
);
formsStore.dispatch(startAuthorizing());
// Clean up on login
const interval = setInterval(() => {
if (windowRef?.closed) {
clearInterval(interval);
formsStore.dispatch(finishAuthorizing());
if (disableFunction) { disableFunction(false); }
}
}, 500);
// Handle response
const code = await new Promise<string>(resolve => {
window.onmessage = (message: MessageEvent) => {
if (message.data.source) {
// React DevTools has a habit of sending messages, ignore them.
return;
}
if (message.data.pydis_source !== "oauth2_callback") {
// Ignore messages not from the callback
return;
}
if (message.isTrusted) {
windowRef?.close();
formsStore.dispatch(finishAuthorizing());
clearInterval(interval);
// State integrity check
if (message.data.state !== state.toString()) {
// This indicates a lack of integrity
throw Error(`Integrity check failed. Expected state of ${state}, received ${JSON.stringify(message.data)}`);
}
// Remove handler
window.onmessage = null;
resolve(message.data.code);
}
};
});
return {code: code, cleanedScopes: cleanedScopes};
}
/**
* Sends a discord code to the backend, which sets an authentication JWT
* and returns the Discord username.
*
* @throws { APIErrors } On error, the APIErrors.Message is set, and an APIErrors object is thrown.
*/
export async function requestBackendJWT(code: string): Promise<{username: string, maxAge: number}> {
const reason: APIErrors = { Message: APIErrorMessages.Unknown, Error: null };
let result;
try {
result = await APIClient.post("/auth/authorize", {token: code})
.catch(error => {
reason.Error = error;
if (error.response) {
// API Responded with a non-2xx Response
if (error.response.status === 400) {
reason.Message = process.env.CONTEXT === "deploy-preview" ? APIErrorMessages.BackendValidationDev : APIErrorMessages.BackendValidation;
}
} else if (error.request) {
// API did not respond
reason.Message = APIErrorMessages.BackendUnresponsive;
}
throw error;
}).then((response: AxiosResponse<AuthResult>) => {
const expiry = Date.parse(response.data.expiry);
return {username: response.data.username, maxAge: (expiry - Date.now()) / 1000};
});
} catch (e) {
if (reason.Error === null) {
reason.Error = e;
}
throw reason;
}
if (!result || !result.username || !result.maxAge) {
reason.Message = APIErrorMessages.BadResponse;
throw reason;
}
return result;
}
/**
* Refresh the backend authentication JWT. Returns the success of the operation, and silently handles denied requests.
*/
export async function refreshBackendJWT(): Promise<boolean> {
const cookies = new Cookies();
let pass = true;
APIClient.post("/auth/refresh").then((response: AxiosResponse<AuthResult>) => {
cookies.set(CookieNames.Username, response.data.username, {sameSite: "strict", secure: PRODUCTION, path: "/", expires: new Date(3000, 1)});
Sentry.setUser({
username: response.data.username
});
const expiry = Date.parse(response.data.expiry);
setTimeout(refreshBackendJWT, ((expiry - Date.now()) / 1000 * 0.9));
}).catch(() => {
pass = false;
cookies.remove(CookieNames.Scopes, {path: "/"});
});
return new Promise(resolve => resolve(pass));
}
/**
* Clear the auth state.
*/
export function clearAuth(): void {
const cookies = new Cookies();
Sentry.setUser(null);
cookies.remove(CookieNames.Scopes, {path: "/"});
cookies.remove(CookieNames.Username, {path: "/"});
}
/**
* Handle a full authorization flow. Sets a cookie with the JWT and scopes.
*
* @param scopes The scopes that should be authorized for the application.
* @param disableFunction An optional function that can disable a component while processing.
* @param refresh If true, the token refresh will be scehduled automatically
*
* @throws { APIErrors } See documentation on { requestBackendJWT }.
*/
export default async function authorize(scopes: OAuthScopes[] = [], disableFunction?: (newState: boolean) => void, refresh = true): Promise<void> {
if (checkScopes(scopes)) {
return;
}
const cookies = new Cookies;
cookies.remove(CookieNames.Scopes, {path: "/"});
if (disableFunction) { disableFunction(true); }
await getDiscordCode(scopes, disableFunction).then(async discord_response =>{
if (!discord_response.code) {
throw {
Message: APIErrorMessages.AccessRejected,
Error: null
};
}
await requestBackendJWT(discord_response.code).then(backend_response => {
const options: CookieSetOptions = {sameSite: "strict", secure: PRODUCTION, path: "/", expires: new Date(3000, 1)};
cookies.set(CookieNames.Username, backend_response.username, options);
Sentry.setUser({
username: backend_response.username,
});
options.maxAge = backend_response.maxAge;
cookies.set(CookieNames.Scopes, discord_response.cleanedScopes, options);
if (refresh) {
// Schedule refresh after 90% of it's age
setTimeout(refreshBackendJWT, (backend_response.maxAge * 0.9) * 1000);
}
});
}).finally(() => {
if (disableFunction) { disableFunction(false); }
});
return new Promise<void>(resolve => resolve());
}
|