-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
700 lines (597 loc) · 20.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
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
require("dotenv").config();
const fetch = require("node-fetch");
const crypto = require("crypto");
const express = require("express");
const db = require("monk")(
process.env.MONGO_URL || "localhost/my-ocular-other",
);
const users = db.get("users");
const stars = db.get("stars");
const reactions = db.get("reactions");
const persistedSessions = db.get("sessions"); // used to store user sessions. it gets updated in sync with the sesions array but it is only used to persist sessions over restarts. it is only read from when server starts,
users.createIndex("name", { unique: true });
const app = express();
const port = 8081;
let cors = require("cors");
const jokes = require("./jokes.json");
const frontendURL = process.env.FRONTEND_URL || "http://localhost:8000";
const whitelist = [
"http://localhost:8000",
"http://localhost:8081",
"https://my-ocular.jeffalo.net",
"https://ocular.jeffalo.net",
];
const emojis = ["👍", "👎", "😄", "🎉", "😕", "❤️", "🚀", "👀"]; // stolen from github. TODO: use emojis that make sense for the forums
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
};
app.use(express.json()); //Used to parse JSON bodies
app.options("/api/users", cors(corsOptions)); // enable pre-flight request for user list
app.get("/api/users", cors(corsOptions), async (req, res) => {
// const page = parseInt(req.query.page) || 0;
// let userList = await users.find({}, { sort: { _id: -1 }, limit: 15, skip: page * 15 })
if (!req.headers.authorization) {
res.json({ error: "you need auth" });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.json({ error: "invalid auth" });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin) {
return res.json({ error: `only admins can get a list of users.` });
}
let userList = await users.find(
{},
{ sort: { "meta.updated": -1, _id: -1 } },
); // TODO: pagination (see above)
res.json(userList);
}
});
app.get("/api/user/:name", cors(), async (req, res) => {
let noReplace = req.query.noReplace;
let user = await getUserData(req.params.name.replace("*", ""));
let allUsers = await users.find();
if (!noReplace && user) {
user.status = user.status.replace(
/(?<!\\){joke}/g,
jokes[Math.floor(Math.random() * jokes.length)],
);
user.status = user.status.replace(/\\({joke})/g, "$1");
user.status = user.status.replace(/(?<!\\){online}/g, sessions.length);
user.status = user.status.replace(/\\({online})/g, "$1");
user.status = user.status.replace(/(?<!\\){total}/g, allUsers.length);
user.status = user.status.replace(/\\({total})/g, "$1");
if (user.status.match(/(?<!\\){count}/)) {
let count = "error";
try {
const controller = new AbortController();
setTimeout(() => {
controller.abort();
}, 5000);
const apiRes = await fetch(
`https://scratchdb.lefty.one/v3/forum/user/info/${user.name}`,
{
signal: controller.signal,
},
);
if (apiRes.ok) {
const data = await apiRes.json();
count = data?.counts?.total?.count;
}
} catch {}
user.status = user.status.replace(/(?<!\\){count}/g, count || "error");
user.status = user.status.replace(/\\({count})/g, "$1");
}
}
user ? res.json(user) : res.json({ error: "no user found" });
});
app.options("/api/user/:name", cors(corsOptions)); // enable pre-flight request for updating user
app.put("/api/user/:name", cors(), async (req, res) => {
if (!req.headers.authorization) {
res.json({ error: "you need auth" });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.json({ error: "invalid auth" });
}
let sessionUser = await getUserData(session.name);
if (
session.name.toLowerCase() !== req.params.name.toLowerCase() &&
!sessionUser.admin
) {
return res.json({ error: `editing someone else's status i see.` });
}
let user = await getUserData(req.params.name);
// temporary security fix
// return res.json({ error: 'for security reasons ocular statuses can not be updated at this time. sorry for the inconvenience' })
if (user) {
if (user.banned && !sessionUser.admin)
return res.json({
error: `you are banned from ocular. visit https://my-ocular.jeffalo.net/ban-info/${user.name} for more information.`,
});
let now = new Date();
if (sessionUser.admin) {
// ban user
if (req.body.banned) {
await users.update(
{ name: user.name },
{ $set: { banned: Boolean(req.body.banned) } },
);
} else {
await users.update({ name: user.name }, { $unset: { banned: "" } });
}
}
if (String(req.body.status).length > 300) {
return res.json({ error: "status length exceeds 300 characters" });
}
await users.update(
{ name: user.name },
{
$set: {
status: String(req.body.status),
color: String(req.body.color),
"meta.updatedBy": sessionUser.name,
"meta.updated": now.toISOString(),
},
},
);
res.json({ ok: "user updated" });
} else {
// this is an admin trying to update the status of a non-existent user. we should create that user with the specified data.
let scratchResponse = await fetch(
`https://api.scratch.mit.edu/users/${req.params.name}/`,
); // get the proper case of the username instead of whatever admin inputted
let scratchData = await scratchResponse.json();
if (!scratchData.username) {
return res.json({ error: "user not found on scratch" });
}
let now = new Date();
await users.insert({
name: scratchData.username,
status: req.body.status,
color: req.body.color,
meta: {
updated: now.toISOString(),
updatedBy: session.name,
},
});
res.json({ ok: "user added" });
}
}
});
app.delete("/api/user/:name", cors(), async (req, res) => {
if (!req.headers.authorization) {
return res.json({ error: "you need auth" });
}
let session = findSession(req.headers.authorization);
if (!session) {
return res.json({ error: "invalid auth" });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin) {
return res.json({ error: "this action can only be performed by an admin" });
}
let user = await getUserData(req.params.name);
if (!user) {
return res.json({ error: "no user found. cannot delete" });
}
console.log(`${sessionUser.name} is deleting all data for ${user.name}`);
await reactions.remove({ name: user.name });
await persistedSessions.remove({ name: user.name });
await stars.remove({ name: user.name });
await users.remove({ name: user.name });
res.json({ ok: "user gone. :(" });
});
app.get("/api/user/:user/picture", cors(), async (req, res) => {
let scratchResponse = await fetch(
`https://api.scratch.mit.edu/users/${req.params.user}/`,
);
let scratchData = await scratchResponse.json();
let pictureURL = "https://cdn2.scratch.mit.edu/get_image/user/0_90x90.png";
if (scratchData.profile) pictureURL = scratchData.profile.images["90x90"];
res.redirect(pictureURL);
});
app.options("/api/starred/:id", cors(corsOptions)); // enable pre-flight request for getting star data
app.get("/api/starred/:id", cors(corsOptions), async (req, res) => {
// returns whether the logged in user starred a post
if (!req.headers.authorization) {
res.json({ error: "you need auth" });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.json({ error: "invalid auth" });
}
let user = await getUserData(session.name);
if (!user) {
return res.json({ error: "invalid auth no user found" });
}
let starredPost = await stars.findOne({
post: req.params.id,
user: user.name,
});
// console.log({ starredPost, post: req.params.id, user: user.name})
starredPost ? res.json({ starred: true }) : res.json({ starred: false });
}
});
app.options("/api/star/:id", cors(corsOptions)); // enable pre-flight request starring post
app.post("/api/star/:id", cors(corsOptions), async (req, res) => {
// stars a post
if (!req.headers.authorization) {
res.json({ error: "you need auth" });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.json({ error: "invalid auth" });
}
let checkRes = await fetch(
`https://scratch.mit.edu/discuss/post/${req.params.id}/source/`,
); // check if the post really exists
if (!checkRes.ok) {
return res.json({ error: "post doesnt exist" });
}
let user = await getUserData(session.name);
if (!user) {
return res.json({ error: "invalid auth no user found" });
}
let starredPost = await stars.findOne({
post: req.params.id,
user: user.name,
});
if (starredPost) {
// remove star
await stars.remove(starredPost._id);
res.json({ starred: false });
} else {
// add star
starredPost = await stars.insert({
post: req.params.id,
user: user.name,
});
res.json({ starred: true });
}
}
});
app.options("/api/starred", cors(corsOptions)); // enable pre-flight request for starred post list
app.get("/api/starred", cors(corsOptions), async (req, res) => {
// returns list of starred posts
if (!req.headers.authorization) {
res.json({ error: "you need auth" });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.json({ error: "invalid auth" });
}
let user = await getUserData(session.name);
if (!user) {
return res.json({ error: "invalid auth no user found" });
}
const page = parseInt(req.query.page) || 0;
let starredPosts = await stars.find(
{ user: user.name },
{ sort: { _id: -1 }, limit: 15, skip: page * 15 },
);
let ids = starredPosts.map((data) => data.post);
let postsToReturn = [];
let stop = false;
let requests = ids.map(async (id) => {
try {
const controller = new AbortController();
setTimeout(() => {
controller.abort();
stop = true;
}, 5000);
const resp = await fetch(
`https://scratchdb.lefty.one/search/indexes/forum_posts/search?filter=id=${id}`,
{
headers: {
authorization:
"Bearer 3396f61ef5b02abf801096be5f0b0ee620de304dd92fc6045aeb99539cd0bec4",
},
signal: controller.signal,
},
);
if (resp.ok) {
const post = await resp.json();
return post.hits[0];
}
} catch {
stop = true;
}
});
if (stop) {
return res.json({ error: "scratchdb is down" });
}
Promise.all(requests)
.then((responses) => {
//this gets called when all the promises have resolved/rejected.
responses.forEach((response) => {
if (response) postsToReturn.push(response);
});
res.json(postsToReturn);
})
.catch((err) => console.log(err));
}
});
app.get("/api/reactions/:id", cors(), async (req, res) => {
// returns all of the reactions for a post
let postReactions = await getPostReactions(req.params.id);
res.json(postReactions);
});
app.options("/api/reactions/:id", cors(corsOptions)); // enable pre-flight request for reacting to a post
app.post("/api/reactions/:id", cors(corsOptions), async (req, res) => {
// reacts to a post, then returns new reaction list
if (!req.headers.authorization) {
res.json({ error: "you need auth" });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.json({ error: "invalid auth" });
}
let user = await getUserData(session.name);
if (!user) {
return res.json({ error: "invalid auth no user found" });
}
let checkRes = await fetch(
`https://scratch.mit.edu/discuss/post/${req.params.id}/source/`,
); // check if the post really exists
if (!checkRes.ok) {
return res.json({ error: "post doesnt exist" });
}
if (!emojis.includes(req.body.emoji)) {
let reactionWithEmoji = await reactions.findOne({
post: req.params.id,
emoji: req.body.emoji,
}); // find a reaction with that emoji to check if thats a valid reaction option (its set by admin if invalid)
if (!reactionWithEmoji && !user.admin)
return res.json({ error: "invalid emoji" });
}
let postReaction = await reactions.findOne({
post: req.params.id,
emoji: req.body.emoji,
user: user.name,
});
if (postReaction) {
// remove reaction
await reactions.remove(postReaction._id);
} else {
// add reaction
await reactions.insert({
post: req.params.id,
user: user.name,
emoji: req.body.emoji,
});
}
// finally return all reactions
let postReactions = await getPostReactions(req.params.id);
res.json(postReactions);
}
});
app.get("/auth/begin", (req, res) => {
if (req.get("host") == "localhost:8081") {
res.redirect(
`https://auth.itinerary.eu.org/auth/?redirect=bG9jYWxob3N0OjgwODEvYXV0aC9oYW5kbGU=&name=ocular`,
);
} else {
res.redirect(
`https://auth.itinerary.eu.org/auth/?redirect=bXktb2N1bGFyLmplZmZhbG8ubmV0L2F1dGgvaGFuZGxl&name=ocular`,
);
}
});
app.get("/auth/handle", async (req, res) => {
// return res.send("ocular authentication is currently disabled due to an ocular authentication 0-day on the forums. we take security issues pretty seriously, so this functionality has been temporarily disabled until we can verify that any potential danger has been fixed. you can continue to use ocular logged out until then.")
// the user is back from hampton's thing.
const private = req.query.privateCode;
let authResponse = await fetch(
"https://auth.itinerary.eu.org/api/auth/verifyToken?privateCode=" +
encodeURIComponent(private) +
"&redirect=bXktb2N1bGFyLmplZmZhbG8ubmV0L2F1dGgvaGFuZGxl",
);
let authData = await authResponse.json();
if (authData.valid) {
// get the proper case of the username instead of url case
// ensure that redirect was either localhost:8081/auth/handle or my-ocular.jeffalo.net/auth/handle
let redirect = authData.redirect;
if (
redirect != "localhost:8081/auth/handle" &&
redirect != "my-ocular.jeffalo.net/auth/handle"
) {
return res.send("invalid redirect");
}
let scratchResponse = await fetch(
`https://api.scratch.mit.edu/users/${authData.username}/`,
);
let scratchData = await scratchResponse.json();
if (!scratchData.username) {
return res.json({ error: "user not found on scratch" });
}
//TODO: don't assume the scratch user was found
let foundUser = await getUserData(scratchData.username);
if (!foundUser) {
let now = new Date();
foundUser = await users.insert({
name: scratchData.username,
status: "",
color: null,
meta: {
updated: now.toISOString(),
updatedBy: "new user",
},
});
}
const token = await generateToken();
const oneTimeToken = await generateToken(); //
addSession(token, scratchData.username, oneTimeToken);
//console.log({ token, name: scratchData.username })
res.redirect(`${frontendURL}/confirm-login?token=${oneTimeToken}`);
} else {
res.redirect(`${frontendURL}/login?error=${0}`); // failed fluffyscratch auth
// res.json({ error: 'failed fluffyscratch auth' }) // commented out because showing users json for a common error isnt great. instead redirecting to the frontend where they can easily log in again is best
}
});
app.get("/auth/info", cors(corsOptions), async (req, res) => {
if (req.query.token) {
let session = findSessionByOneTimeToken(req.query.token);
if (session) {
res.json({ name: session.name, token: session.token });
await persistedSessions.update(
{ oneTimeToken: req.query.token },
{ $set: { oneTimeToken: null } },
);
session.oneTimeToken = null;
} else {
res.json({
error: "no session found. invalid or expired one time token",
});
}
} else {
res.json({ error: "requires query parameter token" });
}
});
app.post("/auth/remove", cors(corsOptions), async (req, res) => {
// used when logging out or cancelling login. discards the session
if (req.query.token) {
let session = findSession(req.query.token);
if (session) {
let name = session.name;
removeSession(req.query.token);
res.json({ ok: `removed session for ${name}` });
} else {
res.json({
error: "the session from the token is already invalid/expired.",
});
}
} else {
res.json({ error: "requires query parameter token" });
}
});
app.options("/auth/me", cors(corsOptions)); // enable pre-flight request for getting user
app.get("/auth/me", cors(corsOptions), async (req, res) => {
if (!req.headers.authorization) {
res.json({ error: "you need auth" });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.json({ error: "invalid auth" });
}
let user = await getUserData(session.name);
user
? res.json(user)
: res.json({ error: "no user found.. this shouldn't happen" });
}
});
app.get("/ban-info/:name", (req, res) => {
// TODO: verify user is banned and perform some sort of authentication on this route to allow for ban message
res.send(
"you've been banned from ocular due to repeated misuse of the service. you can continue to use ocular logged out.",
);
});
// 404. catch all which redirects to frontend
app.use((req, res, next) => {
res.redirect(`${frontendURL}${req.path}`);
});
function getUserData(name) {
var regexName = "^" + escapeRegExp(name) + "$";
return new Promise(async (resolve, reject) => {
try {
var user = await users.findOne({
name: { $regex: new RegExp(regexName, "i") },
});
resolve(user);
} catch (error) {
reject(Error(error));
}
});
}
async function getPostReactions(id) {
/* format:
[
{
emoji: "😀",
reactions: [
(stuff from db, but really just needs username)
]
},
etc etc
]
*/
return new Promise(async (resolve, reject) => {
let postReactions = await reactions.find({ post: id });
let grouped = [];
let postEmojis = emojis.slice(); // .slice so the original cant be edited
postReactions.forEach((reaction) => {
if (!postEmojis.includes(reaction.emoji)) postEmojis.push(reaction.emoji);
});
postEmojis.forEach((emoji) => {
grouped.push({
emoji,
reactions: postReactions.filter((r) => r.emoji == emoji),
});
});
resolve(grouped);
});
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
const groupByKey = (list, key) =>
list.reduce(
(hash, obj) => ({
...hash,
[obj[key]]: (hash[obj[key]] || []).concat(obj),
}),
{},
);
// session management below
let sessions = [];
(async () => {
sessions = await persistedSessions.find({});
})();
async function generateToken() {
const buffer = await new Promise((resolve, reject) => {
crypto.randomBytes(256, function (ex, buffer) {
if (ex) {
reject("error generating token");
}
resolve(buffer);
});
});
const token = crypto.createHash("sha1").update(buffer).digest("hex");
return token;
}
async function addSession(token, name, oneTimeToken, time = false) {
// defaults to 6 hours
// one time token is used for the confirm login screen, this prevents someone from reading the url and logging in. i know its not a perfect solution but its the best i can do
sessions.push({ name, token, oneTimeToken });
await persistedSessions.insert({ name, token, oneTimeToken });
if (time) {
// i doubt any sessions will be set with a time, because auth isnt fun to do. sessions should last "forever"
setTimeout(() => {
// remove token after time seconds
removeSession(token);
}, time);
}
}
async function removeSession(token) {
sessions = sessions.filter((obj) => {
return obj.token !== token;
});
await persistedSessions.remove({ token });
}
function findSession(token) {
const session = sessions.find((f) => f.token == token);
return session;
}
function findSessionByOneTimeToken(oneTimeToken) {
const session = sessions.find((f) => f.oneTimeToken == oneTimeToken);
return session;
}
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`);
});