-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathapp.js
646 lines (569 loc) · 18.4 KB
/
app.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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
const importModule = async (module, path) => {
const { crons, definitions } = await import(`${path}/index.mjs`);
if (definitions) {
await module.importData(definitions);
}
else if (crons) {
sb.crons = crons;
}
};
(async function () {
"use strict";
const core = await import("supi-core");
const Query = new core.Query({
user: process.env.MARIA_USER,
password: process.env.MARIA_PASSWORD,
host: process.env.MARIA_HOST,
connectionLimit: Number(process.env.MARIA_CONNECTION_LIMIT)
});
globalThis.sb = {
Date: core.Date,
Error: core.Error,
Promise: core.Promise,
Got: core.Got,
Query,
Cache: new core.Cache(process.env.REDIS_URL),
// Metrics: new core.Metrics(),
Utils: new core.Utils()
};
await Promise.all([
importModule(sb.Got,"./crons"),
importModule(sb.Got, "./gots")
]);
const WebUtils = require("./utils/webutils.js");
const subroutes = [
"api",
"bot",
"contact",
"crypto-game",
"cytube",
"data",
"gachi",
"osrs",
"relay",
"rss",
"stream",
"teapot",
"track",
"user"
];
const port = 80;
const bodyParser = require("body-parser");
const Express = require("express");
require("express-async-errors");
const Session = require("express-session");
const Passport = require("passport");
const { OAuth2Strategy } = require("passport-oauth");
// const CacheController = require("express-cache-controller");
const MySQLStore = require("express-mysql-session")(Session);
// methods `userProfile` is called internally to resolve the auth
// noinspection JSUnusedGlobalSymbols
class TwitchStrategy extends OAuth2Strategy {
async userProfile (accessToken, done) {
const response = await sb.Got.get("Global")({
method: "GET",
throwHttpErrors: false,
responseType: "json",
url: "https://api.twitch.tv/helix/users",
headers: {
Authorization: `Bearer ${accessToken}`,
"Client-ID": process.env.WEBSITE_TWITCH_CLIENT_ID
}
});
if (response.ok) {
done(null, response.body);
}
else {
done(response.body);
}
}
}
// methods `userProfile` is called internally to resolve the auth
// noinspection JSUnusedGlobalSymbols
class GithubStrategy extends OAuth2Strategy {
async userProfile (accessToken, done) {
const { statusCode, body } = await sb.Got.get("Global")({
method: "GET",
throwHttpErrors: false,
url: "https://api.github.com/user",
headers: {
Authorization: `token ${accessToken}`
},
responseType: "json"
});
if (statusCode === 200) {
done(null, body);
}
else {
done(body);
}
}
}
/** @type {Express} */
const app = Express();
const qs = require("qs");
app.set("query parser", (string) => {
const result = qs.parse(string, {
depth: 0,
parseArrays: false, // doesn't actually affect top-level arrays
plainObject: true
});
for (const key of Object.keys(result)) {
const value = result[key];
if (!Array.isArray(value)) {
continue;
}
result[key] = value.join(",");
}
return result;
});
app.use(require("cookie-parser")());
if (process.env.WEBSITE_SESSION_SECRET) {
app.use(Session({
secret: process.env.WEBSITE_SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 14 * 864e5
},
store: new MySQLStore({
user: process.env.MARIA_USER,
host: process.env.MARIA_HOST,
password: process.env.MARIA_PASSWORD,
database: "supinic.com",
schema: {
tableName: "Session",
columnNames: {
session_id: "SID",
expires: "Expires",
data: "Data"
}
}
})
}));
}
else {
console.warn("Env WEBSITE_SESSION_SECRET is not set up, login sessions are not available");
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.enable("trust proxy");
app.use("/public", Express.static(`${__dirname}/static/`, {
etag: true,
maxAge: "1 day",
lastModified: true
}));
app.use("/static", Express.static(`${__dirname}/static/`, {
etag: true,
maxAge: "1 day",
lastModified: true
}));
app.use("/api", Express.static(`${__dirname}/apidocs/`));
// app.use(CacheController({
// noCache: true
// }));
app.use(Passport.initialize({}));
app.use(Passport.session({}));
app.locals.navitems = [
{
name: "Supibot",
items: [
{ name: "FAQ", link: "data/faq/list" },
{ name: "Request Supibot", link: "bot/request-bot/form" },
{ name: "Allow Supibot in your channel", link: "bot/twitch-auth" },
{ name: "Run a Supibot command", link: "bot/command/run" },
{ separator: true },
{ name: "Cookie stats", link: "bot/cookie/list" },
{ name: "Fishing stats", link: "bot/fish/list" },
{ separator: true },
{ name: "Aliases - find by user", link: "bot/user/alias/find" },
{ name: "Channel list", link: "bot/channel/list" },
{ name: "Commands", link: "bot/command/list" },
{ name: "Emote origins", link: "data/origin/list" },
{ name: "Slots winners list", link: "data/slots-winner/leaderboard" },
{ name: "Suggestions - active", link: "data/suggestion/list/active" },
{ name: "Suggestions - inactive", link: "data/suggestion/list/resolved" },
{ separator: true },
{ name: "Bot stats", link: "bot/stats" },
{ name: "Changelog", link: "data/changelog/list" },
{ name: "Suggestion stats", link: "data/suggestion/stats" }
]
},
{
name: "Make-a-bot",
items: [
{ name: "Readme", link: "bot/channel-bots/readme" },
{ name: "Bots", link: "bot/channel-bots/list" },
{ name: "Badges", link: "bot/channel-bots/badges" },
{ name: "Levels", link: "bot/channel-bots/levels" }
]
},
{
name: "Music",
items: [
{ name: "Gachi list", link: "track/gachi/list" },
{ name: "Todo list", link: "track/todo/list" },
{ name: "Favourites - find by user", link: "track/favourite/find" },
{ separator: true },
{ name: "Archives", link: "gachi/archive" },
{ name: "Legacy list", link: "gachi/list" }
// { name: "Add new", link: "add" },
// { name: "Guidelines", link: "guidelines" },
// { name: "Todo list", link: "todo" },
// { name: "Resources", link: "resources" }
]
},
{
name: "Stream",
items: [
{ name: "Cooking streams", link: "stream/recipe/list" },
{ name: "Cytube history", link: "cytube/video-request/history" },
{ name: "Playsounds", link: "stream/playsound/list" },
{ name: "Stream games", link: "stream/game/list" },
{ name: "Video request queue", link: "stream/song-request/queue" },
{ name: "Video request history", link: "stream/song-request/history" }
]
},
{
name: "Other",
items: [
{ name: "Bad Apple!!", link: "data/bad-apple/list" },
{ name: "DALL-E images", link: "data/dall-e/list" },
{ name: "OSRS Raids 3 calculator", link: "osrs/toa/calculator" },
{ name: "OSRS Prayer costs", link: "osrs/prayer/comparisons" }
]
},
{
name: "API",
items: [
{ name: "Documentation", link: "api" },
{ name: "Get API key", link: "user/auth-key" }
]
},
{
name: "Contact",
link: "contact"
}
];
app.locals.loginItems = [
{ name: "Command aliases", link: "user/alias/list" },
{ separator: true },
{ name: "Reminders - active", link: "bot/reminder/list" },
{ name: "Reminders - history", link: "bot/reminder/history" },
{ separator: true },
{ name: "Suggestions - active", link: "data/suggestion/user/list/active" },
{ name: "Suggestions - resolved", link: "data/suggestion/user/list/resolved" },
{ name: "Suggestion - stats", link: "data/suggestion/user/stats" },
{ separator: true },
{ name: "Data within Supibot", link: "user/data/list" },
{ name: "Favourite tracks", link: "track/favourite/list" },
{ name: "Github link", link: "auth/github" },
{ name: "Backup Supibot restart", link: "bot/restart" },
{ separator: true },
{ name: "Log out", link: "user/logout" }
];
app.set("query parser", "simple");
app.set("view engine", "pug");
// robots.txt - disallow everything
app.get("/robots.txt", (req, res) => {
res.type("text/plain");
res.send("User-agent: *\nDisallow: /\n");
});
app.get("/riot.txt", (req, res) => {
res.type("text/plain");
res.send("6838d447-8257-45ab-a40a-18ecd1637c8d");
});
app.all("*", async (req, res, next) => {
const routeType = (req.originalUrl.includes("api")) ? "API" : "View";
const log = await WebUtils.logRequest(req, routeType);
const requestLogSymbol = Symbol.for("request-log-symbol");
req[requestLogSymbol] = log.insertId;
res.header("X-Robots-Tag", "noindex, nofollow, nosnippet, noarchive, noimageindex");
const blockedUserAgents = require("./blocked-user-agents.json");
if (blockedUserAgents.includes(req.header("user-agent"))) {
res.status(418).send("NOT OK");
return;
}
if (!req.originalUrl.includes("api")) {
const columnValues = Object.keys(req.query).filter(i => /column[\d\w]+/.test(i));
if (columnValues.length !== 0) {
app.locals.columnValues = columnValues.map(key => ({
position: Number(key.match(/column(\d+)/)?.[1]) ?? null,
title: key.replace(/_/g, " ").match(/column(\w+)/)?.[1] ?? null,
value: req.query[key]
}));
}
else {
app.locals.columnValues = [];
}
app.locals.currentLocation = encodeURIComponent(req.originalUrl);
}
if (req.session.passport?.user?.source === "twitch") {
const User = require("./modules/chat-data/user-alias.js");
const data = req.session.passport.user.data[0];
const userData = await User.getByName(data.login);
if (!userData) {
return res.status(401).render("error", {
error: "202 Accepted",
message: `Your Twitch account has not been seen by Supibot before. Make sure to send at least one message in a channel with Supibot before continuing. This page will automatically refresh in 30 seconds.`,
extraScript: `window.onload = () => setTimeout(() => location.reload(), 30000);`
});
}
res.locals.authUser = {
login: data.login,
display: data.display_name,
id: data.id,
image: data.profile_image_url,
userData
};
}
next();
});
app.get("/", async (req, res) => {
let streamData = [];
if (process.env.TWITCH_CLIENT_ID && process.env.ADMIN_USER_ID) {
const adminUserID = process.env.ADMIN_USER_ID;
const streamResponse = await sb.Got.get("Helix")({
url: "streams",
searchParams: {
user_id: adminUserID
}
});
streamData = streamResponse.body.data ?? [];
}
const [stream] = streamData;
res.render("index", {
game: stream?.game_name || null, // when no game is set, the game field is an empty string - || operator accounts for this
viewers: stream?.viewer_count ?? null
});
});
for (const route of subroutes) {
app.use(`/${route}`, require(`./routes/${route}`));
}
const availableTwitchConfigs = [
process.env.WEBSITE_TWITCH_CLIENT_ID,
process.env.WEBSITE_TWITCH_CLIENT_SECRET,
process.env.WEBSITE_TWITCH_CALLBACK_URL
];
if (availableTwitchConfigs.every(Boolean)) {
Passport.serializeUser((user, done) => done(null, user));
Passport.deserializeUser((user, done) => done(null, user));
Passport.use("twitch", new TwitchStrategy(
{
authorizationURL: "https://id.twitch.tv/oauth2/authorize",
tokenURL: "https://id.twitch.tv/oauth2/token",
clientID: process.env.WEBSITE_TWITCH_CLIENT_ID,
clientSecret: process.env.WEBSITE_TWITCH_CLIENT_SECRET,
callbackURL: process.env.WEBSITE_TWITCH_CALLBACK_URL
// state: true
},
(access, refresh, profile, done) => {
profile.accessToken = access;
profile.refreshToken = refresh;
profile.source = "twitch";
done(null, profile);
}
));
app.get("/auth/twitch", (req, res, next) => {
const { returnTo } = req.query;
const state = (returnTo)
? Buffer.from(JSON.stringify({ returnTo })).toString("base64")
: undefined;
const authenticator = Passport.authenticate("twitch", { scope: "", state });
authenticator(req, res, next);
});
app.get(
"/auth/twitch/callback",
Passport.authenticate("twitch", { failureRedirect: "/wcs" }),
async (req, res) => {
try {
const { state } = req.query;
const { returnTo } = JSON.parse(Buffer.from(state, "base64").toString());
if (typeof returnTo === "string" && returnTo.startsWith("/")) {
return res.redirect(returnTo);
}
}
catch {
console.warn("Redirect not applicable", res);
}
res.redirect("/contact");
}
);
}
else {
console.warn("Twitch auth configs are not set up, Twitch login is not available", {
configs: ["WEBSITE_TWITCH_CLIENT_ID", "WEBSITE_TWITCH_CLIENT_SECRET", "WEBSITE_TWITCH_CALLBACK_URL"]
});
}
const availableGithubConfigs = [
process.env.WEBSITE_GITHUB_CLIENT_ID,
process.env.WEBSITE_GITHUB_CLIENT_SECRET,
process.env.WEBSITE_GITHUB_CALLBACK_URL
];
if (availableGithubConfigs.every(Boolean)) {
Passport.use("github", new GithubStrategy(
{
authorizationURL: "https://github.com/login/oauth/authorize",
tokenURL: "https://github.com/login/oauth/access_token",
clientID: process.env.WEBSITE_GITHUB_CLIENT_ID,
clientSecret: process.env.WEBSITE_GITHUB_CLIENT_SECRET,
callbackURL: process.env.WEBSITE_GITHUB_CALLBACK_URL,
passReqToCallback: true
},
(req, access, refresh, profile, done) => {
profile.accessToken = access;
profile.refreshToken = refresh;
profile.source = "github";
req[Symbol.for("github-profile")] = { profile };
done(null, profile);
}
));
app.get("/auth/github", (req, res, next) => {
const { userData } = res.locals.authUser ?? {};
if (!userData) {
return res.status(401).render("error", {
message: "401 Unauthorized",
error: "You must be logged first in order in to link your Github account"
});
}
const authenticator = Passport.authenticate("github");
authenticator(req, res, next);
});
app.get(
"/auth/github/callback",
Passport.authenticate("github",{ session: false }),
async (req, res) => {
const User = require("./modules/chat-data/user-alias.js");
const { userData } = res.locals.authUser ?? {};
if (!userData) {
return res.status(401).render("error", {
message: "401 Unauthorized",
error: "You must be logged first in order in to link your Github account"
});
}
const { profile } = req[Symbol.for("github-profile")];
if (!profile) {
throw new sb.Error({
message: "No github profile available in callback",
args: { req }
});
}
const rawGithubData = await User.getDataProperty(userData.ID, "github");
const githubData = (rawGithubData) ? JSON.parse(rawGithubData) : {};
if (githubData.login === profile.login) {
return res.render("generic", {
data: sb.Utils.tag.trim `
<div class="pt-3 text-center">
<h4>Your user profile is already connected to this Github profile 🙂</h4>
</div>
`
});
}
const previousString = (githubData)
? `Your Twitch account was previously connected to ${githubData.login}.`
: "";
await User.setDataProperty(userData.ID, "github", JSON.stringify({
created: new sb.Date(profile.created_at).valueOf(),
login: profile.login,
type: profile.type
}));
await sb.Got.get("Supibot")({
url: "user/invalidateCache",
searchParams: {
name: userData.Name
}
});
return res.render("generic", {
data: sb.Utils.tag.trim `
<div class="pt-3 text-center">
<h4>Github connection completed succesfully!</h4>
Connected Twitch user
<a target="_blank" href="//twitch.tv/${userData.Name}">${userData.Name}</a>
to Github user
<a target="_blank" href="//github.com/${profile.login}">${profile.login}</a>
${previousString}
</div>
`
});
}
);
}
else {
console.warn("Github auth configs are not set up, Github login is not available", {
configs: ["WEBSITE_GITHUB_CLIENT_ID", "WEBSITE_GITHUB_CLIENT_SECRET", "WEBSITE_GITHUB_CALLBACK_URL"]
});
}
// 4 params are required (next is unused) - express needs this to recognize the callback as middleware
// noinspection JSUnusedLocalSymbols
app.use(async (err, req, res, next) => {
// first - manage URIErrors caused by malformed path params
// this is not an error, so no error will be printed.
if (err instanceof URIError) {
if (req.path.includes("/api")) {
res.set("Content-Type", "application/json");
return WebUtils.apiFail(res, 400, "Malformed URI parameter(s)");
}
else {
res.set("Content-Type", "text/html");
return res.status(400).render("error", {
message: "404 Not found",
error: "Malformed URI - endpoint was not found"
});
}
}
console.error("Website error", { err, req, res });
// In the case of "internal auth error" from Twitch - where the user clicks the "Redirect now" button
// on the Twitch auth callback page, simply redirect to main page. I assume this error only happens
// because the Passport module is trying to auth an already authed user, but I wasn't able to find any
// more info about this specific scenario.
if (req.url.includes("twitch/callback") && err?.name === "InternalOAuthError") {
res.redirect("/");
return;
}
const requestLogSymbol = Symbol.for("request-log-symbol");
try {
if (err instanceof OAuth2Strategy.AuthorizationError) {
const insertId = await WebUtils.logError("View", err, req[requestLogSymbol]);
res.set("Content-Type", "text/html");
return res.status(401).render("error", {
error: "401 Unauthorized",
message: `Your authorization failed due to a third party error (error ID ${insertId})`
});
}
else {
let insertId;
if (typeof err.message !== "string" || !err.message.includes("retrieve connection from pool timeout")) {
insertId = await WebUtils.logError("View", err, req[requestLogSymbol]);
}
res.set("Content-Type", "text/html");
return res.status(500).render("error", {
error: "500 Internal Error",
message: (insertId)
? `Internal server error encountered (error ID ${insertId})`
: `Internal server error encountered`
});
}
}
catch (e) {
console.error("Error while trying to save error", e);
res.set("Content-Type", "text/html");
return res.status(500).render("error", {
error: "500 Internal Error",
message: `Internal server error`
});
}
});
// eslint-enable no-unused-vars
// 404
app.get("*", (req, res) => res.status(404).render("error", {
message: "404 Not found",
error: "Endpoint was not found"
}));
app.listen(port, () => console.log("Listening..."));
sb.App = app;
sb.App.data = {
/** @type {Map<string, Object>} */
deprecation: new Map()
};
})();