all repos — stealth-developers @ 9ad6d6ff214141cd385a8931dcbf25abd5b74861

pkgs/bot/src/server/index.ts (view raw)

 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
import type { BunRequest } from "bun";
import { desc, eq, asc, lt, and, isNotNull, ne, gte, inArray, or } from "drizzle-orm";
import { nanoid } from "nanoid";

import _logger from "@/utils/logging";
import config, { isProd } from "@/config";
import { db, tickets, ticketMessages, moderators, sessions, attachments } from "@/database";
import { getUser, getUsers, hydrateTickets, notify } from "./discord";
import { intoApiAttachment } from "./api";
import { getPublicUrl, getPresignedUrl } from "@/utils/s3";

import type {
	TicketResponse,
	TicketsResponse,
	MeResponse,
	ModeratorsResponse,
	OverallStatsResponse,
	LeaderboardResponse,
	Message,
	User,
	Statistic,
} from "@stealth-developers/api";

const logger = _logger.child({ name: "server" });

const CLIENT_ID = config.discord.app_id;
const CLIENT_SECRET = config.discord.client_secret;

const HOST = isProd ? "https://tickets.vt3e.cat" : "http://127.0.0.1:3000";
const REDIRECT_URI = `${HOST}/auth/callback`;
const FRONTEND_URL = isProd ? HOST : "http://127.0.0.1:5173";

async function authenticate(req: BunRequest) {
	const cookieHeader = req.headers.get("Cookie");
	if (!cookieHeader) return { user: null, isMod: false };

	const sessionCookie = cookieHeader.split("; ").find((c) => c.startsWith("session="));
	if (!sessionCookie) return { user: null, isMod: false };

	const sessionId = sessionCookie.split("=")[1];
	const sessionList = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);
	if (sessionList.length === 0) return { user: null, isMod: false };

	const userId = sessionList[0].userId;
	const modCheck = await db
		.select()
		.from(moderators)
		.where(eq(moderators.user_id, userId))
		.limit(1);

	return {
		user: { id: userId, username: sessionList[0].username },
		isMod: modCheck.length > 0,
	};
}

function calculateStats(durations: number[]): { mean: number; median: number; count: number } {
	if (durations.length === 0) return { mean: 0, median: 0, count: 0 };
	const sum = durations.reduce((a, b) => a + b, 0);
	const sorted = [...durations].sort((a, b) => a - b);
	const mid = Math.floor(sorted.length / 2);

	return {
		mean: sum / durations.length,
		median: sorted.length % 2 !== 0 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2,
		count: durations.length,
	};
}

const server = Bun.serve({
	hostname: "127.0.0.1",
	port: process.env.PORT || 3000,

	routes: {
		"/api/login": () => {
			const redirectUri = `https://discord.com/oauth2/authorize?client_id=${CLIENT_ID}&response_type=code&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=identify+guilds`;
			return Response.redirect(redirectUri, 302);
		},

		"/auth/callback": {
			GET: async (req: BunRequest) => {
				const url = new URL(req.url);
				const code = url.searchParams.get("code");
				if (!code) return new Response("No code provided", { status: 400 });

				const params = new URLSearchParams({
					client_id: CLIENT_ID,
					client_secret: CLIENT_SECRET,
					grant_type: "authorization_code",
					code,
					redirect_uri: REDIRECT_URI,
				});

				const tokenResponse = await fetch("https://discord.com/api/oauth2/token", {
					method: "POST",
					body: params,
					headers: { "Content-Type": "application/x-www-form-urlencoded" },
				});

				const data = await tokenResponse.json();
				if (data.error) return new Response(data.error_description, { status: 400 });

				const userResponse = await fetch("https://discord.com/api/users/@me", {
					headers: { Authorization: `Bearer ${data.access_token}` },
				});

				const userData = await userResponse.json();
				const sessionId = crypto.randomUUID();

				await db.insert(sessions).values({
					id: sessionId,
					userId: userData.id,
					username: userData.username,
				});

				return new Response(null, {
					status: 302,
					headers: {
						Location: `${FRONTEND_URL}/tickets`,
						"Set-Cookie": `session=${sessionId}; Path=/; HttpOnly; SameSite=Lax`,
					},
				});
			},
		},

		"/api/me": {
			GET: async (req: BunRequest) => {
				const { user, isMod } = await authenticate(req);
				if (!user) return new Response("Unauthorized", { status: 401 });

				const profile = await getUser(user.id);
				if (!profile) return new Response("Profile not found", { status: 404 });

				const response: MeResponse = { ...profile, isModerator: isMod };
				return Response.json(response);
			},
		},

		"/api/tickets": {
			GET: async (req: BunRequest) => {
				const { user, isMod } = await authenticate(req);
				if (!user) return Response.redirect("/login", 302);

				const url = new URL(req.url);
				const limit = Number.parseInt(url.searchParams.get("limit") || "20", 10);
				const cursor = url.searchParams.get("cursor");

				const filters = [];
				if (!isMod) filters.push(eq(tickets.authorId, user.id));

				if (cursor) {
					const cursorValue = new Date(cursor);
					filters.push(lt(tickets.createdAt, cursorValue));
				}

				const allTickets = await db
					.select()
					.from(tickets)
					.where(filters.length > 0 ? and(...filters) : undefined)
					.orderBy(desc(tickets.createdAt))
					.limit(limit + 1);

				let nextCursor: string | undefined;
				if (allTickets.length > limit) {
					allTickets.pop();

					const lastTicket = allTickets[allTickets.length - 1];
					nextCursor =
						lastTicket.createdAt instanceof Date
							? lastTicket.createdAt.toISOString()
							: String(lastTicket.createdAt);
				}

				const hydratedTickets = await hydrateTickets(allTickets);

				const response: TicketsResponse = {
					tickets: hydratedTickets,
					cursor: nextCursor,
				};

				return Response.json(response);
			},
		},

		"/api/tickets/:id": {
			GET: async (req: BunRequest) => {
				const { user, isMod } = await authenticate(req);
				if (!user) return Response.redirect("/login", 302);

				const ticketId = Number.parseInt(req.params.id, 10);
				if (isNaN(ticketId)) return new Response("Invalid ID", { status: 400 });

				const ticketList = await db.select().from(tickets).where(eq(tickets.id, ticketId)).limit(1);
				const _ticket = ticketList[0];
				if (!_ticket) return new Response("Ticket not found", { status: 404 });

				if (!isMod && _ticket.authorId !== user.id) {
					return new Response("Forbidden", { status: 403 });
				}

				const messages = await db
					.select()
					.from(ticketMessages)
					.where(eq(ticketMessages.ticketId, ticketId))
					.orderBy(asc(ticketMessages.createdAt));

				const mentionRegex = /<@!?(\d+)>/g;
				const mentionedIds = messages.flatMap((m) =>
					[...m.content.matchAll(mentionRegex)].map((match) => match[1]),
				);

				const idsToFetch = [
					_ticket.authorId,
					_ticket.openedBy,
					_ticket.claimedBy,
					...messages.map((m) => m.authorId),
					...mentionedIds,
				];

				await getUsers(idsToFetch);

				const [hydratedTicket] = await hydrateTickets([_ticket]);
				const messageIds = messages.map((m) => m.id);

				const ticketAttachments = await db
					.select()
					.from(attachments)
					.where(
						or(
							and(eq(attachments.ownerType, "ticket"), eq(attachments.ownerId, ticketId)),
							messageIds.length > 0
								? and(
										eq(attachments.ownerType, "ticket_message"),
										inArray(attachments.ownerId, messageIds),
									)
								: undefined,
						),
					);

				const ticketLevelAttachments = ticketAttachments.filter(
					(a) => a.ownerType === "ticket" && a.ownerId === ticketId,
				);
				const hydratedTicketWithAttachments = {
					...hydratedTicket,
					attachments: await Promise.all(ticketLevelAttachments.map(intoApiAttachment)),
				};

				const newMessages: Message[] = await Promise.all(
					messages.map(async (message) => {
						const author = await getUser(message.authorId);
						const _attachments = ticketAttachments.filter(
							(a) => a.ownerType === "ticket_message" && a.ownerId === message.id,
						);

						const mentions: Record<string, User> = {};
						for (const match of message.content.matchAll(mentionRegex)) {
							const id = match[1];
							if (!mentions[id]) {
								const matchedUser = await getUser(id);
								if (matchedUser) mentions[id] = matchedUser;
							}
						}

						return {
							id: message.id,
							messageId: message.messageId,
							createdAt: message.createdAt.toUTCString(),
							updatedAt: message.editedAt ? message.editedAt?.toUTCString() : null,
							deletedAt: message.deletedAt ? message.deletedAt?.toUTCString() : null,
							author: author as User,
							authorType: message.authorType as "user" | "staff" | "system",
							content: message.content,
							attachments: await Promise.all(_attachments.map(intoApiAttachment)),
							mentions: Object.values(mentions),
						};
					}),
				);

				const response: TicketResponse = {
					ticket: hydratedTicketWithAttachments as any,
					messages: newMessages,
				};

				return Response.json(response);
			},

			DELETE: async (req: BunRequest) => {
				const { user, isMod } = await authenticate(req);
				if (!user) return new Response("Unauthorized", { status: 401 });
				if (!isMod) return new Response("Forbidden", { status: 403 });

				const ticketId = Number.parseInt(req.params.id, 10);
				if (isNaN(ticketId)) return new Response("Invalid ID", { status: 400 });

				const deleted = await db.delete(tickets).where(eq(tickets.id, ticketId)).returning();
				if (deleted.length === 0) return new Response("Ticket not found", { status: 404 });

				return Response.json({ success: true });
			},
		},

		"/api/tickets/:id/presign": {
			POST: async (req: BunRequest) => {
				const { user, isMod } = await authenticate(req);
				if (!user) return new Response("Unauthorized", { status: 401 });

				const ticketId = Number.parseInt(req.params.id, 10);
				if (isNaN(ticketId)) return new Response("Invalid ID", { status: 400 });

				const ticketList = await db.select().from(tickets).where(eq(tickets.id, ticketId)).limit(1);
				const ticket = ticketList[0];
				if (!ticket) return new Response("Ticket not found", { status: 404 });

				if (!isMod && ticket.authorId !== user.id)
					return new Response("Forbidden", { status: 403 });

				let body: any = {};
				try {
					body = await req.json();
				} catch {}

				const fileName = body?.fileName || body?.name;
				if (!fileName) return new Response("fileName required", { status: 400 });

				const safeName = String(fileName)
					.replace(/[^a-zA-Z0-9._-]/g, "_")
					.slice(0, 200);

				const key = `${ticket.publicId}/web/${nanoid(8)}_${safeName}`;

				const requestedMethod = (body?.method || "PUT").toUpperCase();
				const allowed = ["PUT", "POST", "GET", "DELETE"];
				if (!allowed.includes(requestedMethod))
					return new Response("invalid method", { status: 400 });

				const contentType = body?.contentType;
				const headers: Record<string, string> | undefined = contentType
					? { "content-type": contentType }
					: undefined;

				const url = getPresignedUrl(key, { method: requestedMethod as any, headers });

				if (ticket.channelId)
					notify(ticket.channelId, `Attachment being uploaded by <@${user.id}>...`);

				return Response.json({
					url,
					key,
					bucket: config.s3.bucket,
					method: requestedMethod,
					headers,
				});
			},
		},

		"/api/tickets/:id/attachments": {
			POST: async (req: BunRequest) => {
				const { user, isMod } = await authenticate(req);
				if (!user) return new Response("Unauthorized", { status: 401 });

				const ticketId = Number.parseInt(req.params.id, 10);
				if (isNaN(ticketId)) return new Response("Invalid ID", { status: 400 });

				const ticketList = await db.select().from(tickets).where(eq(tickets.id, ticketId)).limit(1);
				const ticket = ticketList[0];
				if (!ticket) return new Response("Ticket not found", { status: 404 });

				if (!isMod && ticket.authorId !== user.id)
					return new Response("Forbidden", { status: 403 });

				let body: any = {};
				try {
					body = await req.json();
				} catch {}

				const { id, fileName, contentType, size, bucket, key } = body || {};
				if (!id || !fileName || !contentType || !size || !bucket || !key)
					return new Response("missing fields", { status: 400 });

				const finalUrl = getPublicUrl(key);
				await db.insert(attachments).values({
					id,
					ownerType: "ticket",
					ownerId: ticketId,
					authorId: user.id,
					fileName,
					contentType,
					size,
					bucket,
					key,
					url: finalUrl,
				});

				const att = await db.select().from(attachments).where(eq(attachments.id, id)).limit(1);
				if (att.length === 0) return new Response("failed to insert", { status: 500 });
				const apiAtt = await intoApiAttachment(att[0]);

				if (ticket.channelId)
					notify(ticket.channelId, `[Attachment uploaded](${finalUrl}) by <@${user.id}>`);

				return Response.json(apiAtt);
			},
		},

		"/api/moderators": {
			GET: async (req: BunRequest) => {
				const { user, isMod } = await authenticate(req);
				if (!user) return new Response("Unauthorized", { status: 401 });
				if (!isMod) return new Response("Forbidden", { status: 403 });

				const mods = await db.select().from(moderators);
				await getUsers(mods.map((mod) => mod.user_id));

				const response: ModeratorsResponse = await Promise.all(
					mods.map(async (mod) => (await getUser(mod.user_id)) as User),
				);

				return Response.json(response);
			},
		},

		"/api/stats/overall": {
			GET: async (req: BunRequest) => {
				const url = new URL(req.url);
				const days = Number.parseInt(url.searchParams.get("days") || "0", 10);
				const guildId = url.searchParams.get("guildId");
				const cutoffDate = days ? new Date(Date.now() - days * 86400000) : null;

				const closedTickets = await db
					.select()
					.from(tickets)
					.where(
						and(
							isNotNull(tickets.closedAt),
							isNotNull(tickets.closedBy),
							ne(tickets.closedBy, "reporter"),
							ne(tickets.closedBy, "system"),
							guildId ? eq(tickets.guildId, guildId) : undefined,
							cutoffDate ? gte(tickets.closedAt, cutoffDate) : undefined,
						),
					);

				const allDurations = closedTickets.map(
					(t) => t.closedAt!.getTime() - t.createdAt.getTime(),
				);
				const hourlyDurations = new Map<number, number[]>();

				for (const t of closedTickets) {
					const hour = t.closedAt!.getHours();
					if (!hourlyDurations.has(hour)) hourlyDurations.set(hour, []);
					hourlyDurations.get(hour)!.push(t.closedAt!.getTime() - t.createdAt.getTime());
				}

				const response: OverallStatsResponse = {
					global: calculateStats(allDurations),
					hourly: Array.from(
						{ length: 24 },
						(_, hour) =>
							({
								hour,
								...calculateStats(hourlyDurations.get(hour) || []),
							}) as Statistic & { hour: number },
					).filter((h) => h.count > 0),
				};

				return Response.json(response);
			},
		},

		"/api/stats/leaderboard": {
			GET: async (req: BunRequest) => {
				const url = new URL(req.url);
				const days = Number.parseInt(url.searchParams.get("days") || "0", 10);
				const guildId = url.searchParams.get("guildId");
				const orderBy = url.searchParams.get("order_by") || "median";
				const cutoffDate = days ? new Date(Date.now() - days * 86400000) : null;

				const closedTickets = await db
					.select()
					.from(tickets)
					.where(
						and(
							isNotNull(tickets.closedAt),
							isNotNull(tickets.closedBy),
							ne(tickets.closedBy, "reporter"),
							ne(tickets.closedBy, "system"),
							guildId ? eq(tickets.guildId, guildId) : undefined,
							cutoffDate ? gte(tickets.closedAt, cutoffDate) : undefined,
						),
					);

				const modDurations = new Map<string, number[]>();
				for (const t of closedTickets) {
					const modId = t.closedBy!;
					if (!modDurations.has(modId)) modDurations.set(modId, []);
					modDurations.get(modId)!.push(t.closedAt!.getTime() - t.createdAt.getTime());
				}

				const modStats = Array.from(modDurations.entries()).map(([modId, durations]) => ({
					modId,
					...calculateStats(durations),
				}));

				if (orderBy === "mean") modStats.sort((a, b) => a.mean - b.mean);
				else if (orderBy === "count") modStats.sort((a, b) => b.count - a.count);
				else modStats.sort((a, b) => a.median - b.median);

				await getUsers(modStats.map((m) => m.modId));

				const response: LeaderboardResponse = await Promise.all(
					modStats.map(async (mod, i) => ({
						rank: i + 1,
						user: (await getUser(mod.modId)) as User,
						mean: mod.mean,
						median: mod.median,
						count: mod.count,
					})),
				);

				return Response.json(response);
			},
		},

		"/api/health": () => {
			return Response.json({ status: "ok" });
		},

		"/api/*": () => new Response(null, { status: 404 }),

		"/*": async (request: BunRequest) => {
			const { pathname } = new URL(request.url);

			const file = Bun.file(`../frontend/dist/${pathname}`);
			if (await file.exists()) return new Response(file);

			return new Response(Bun.file(`../frontend/dist/index.html`));
		},
	},
});

logger.info(`server is running at ${server.hostname}:${server.port}`);