all repos — stealth-developers @ 9b885fe8c0d7c22dd2e256a7f9db5bafcf9bdc4d

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
import { desc, eq, asc } from "drizzle-orm";
import type { BunRequest } from "bun";

import _logger from "@/utils/logging";
import config from "@/config";
import { db, tickets, ticketMessages, moderators, sessions } from "@/database";
import { getUser, getUsers, hydrateTickets } from "./discord";

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

const CLIENT_ID = config.discord.app_id;
const CLIENT_SECRET = config.discord.client_secret;
const REDIRECT_URI = "http://127.0.0.1:3000/auth/callback";

const FRONTEND_URL = process.env.FRONTEND_URL || "http://127.0.0.1:5173";

async function getSessionUser(req: BunRequest) {
	const cookieHeader = req.headers.get("Cookie");
	if (!cookieHeader) return null;
	const sessionCookie = cookieHeader.split("; ").find((c) => c.startsWith("session="));
	if (!sessionCookie) return null;
	const sessionId = sessionCookie.split("=")[1];

	const sessionList = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);
	if (sessionList.length === 0) return null;

	return { id: sessionList[0].userId, username: sessionList[0].username };
}

const server = Bun.serve({
	hostname: "127.0.0.1",

	routes: {
		"/login": () => {
			const redirectUri =
				"https://discord.com/oauth2/authorize?client_id=1350116449611677770&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A3000%2Fauth%2Fcallback&scope=identify+guilds";

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

				const params = new URLSearchParams();
				params.append("client_id", CLIENT_ID);
				params.append("client_secret", CLIENT_SECRET);
				params.append("grant_type", "authorization_code");
				params.append("code", code);
				params.append("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, statusText: data.error });

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

				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`,
					},
				});
			},
		},
		"/me": {
			GET: async (req: BunRequest) => {
				const user = await getSessionUser(req);
				if (!user) return new Response("Unauthorized", { status: 401 });

				const modCheck = await db
					.select()
					.from(moderators)
					.where(eq(moderators.user_id, user.id))
					.limit(1);
				const isMod = modCheck.length > 0;

				const profile = await getUser(user.id);

				return new Response(JSON.stringify({ profile, isMod }), {
					headers: { "Content-Type": "application/json" },
				});
			},
		},
		"/tickets": {
			GET: async (req: BunRequest) => {
				const user = await getSessionUser(req);
				if (!user) return new Response(null, { status: 302, headers: { Location: "/login" } });

				const modCheck = await db
					.select()
					.from(moderators)
					.where(eq(moderators.user_id, user.id))
					.limit(1);
				if (modCheck.length === 0) {
					return new Response("Forbidden: You must be a moderator to view tickets.", {
						status: 403,
					});
				}

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

				const allTickets = await db
					.select()
					.from(tickets)
					.limit(limit)
					.orderBy(desc(tickets.createdAt));

				const hydratedTickets = await hydrateTickets(allTickets);

				return new Response(JSON.stringify(hydratedTickets), {
					headers: { "Content-Type": "application/json" },
				});
			},
		},
		"/tickets/:id": {
			GET: async (req: BunRequest) => {
				const user = await getSessionUser(req);
				if (!user) return new Response(null, { status: 302, headers: { Location: "/login" } });

				const modCheck = await db
					.select()
					.from(moderators)
					.where(eq(moderators.user_id, user.id))
					.limit(1);
				if (modCheck.length === 0)
					return new Response("Forbidden: You must be a moderator to view tickets.", {
						status: 403,
					});

				const { id } = req.params;
				const ticketId = parseInt(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 });

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

				const idsToFetch = [
					_ticket.authorId,
					_ticket.openedBy,
					_ticket.claimedBy,
					...messages.map((m) => m.authorId),
				].filter(Boolean) as string[];

				await getUsers(idsToFetch);

				const [ticket] = await hydrateTickets([_ticket]);

				const newMessages = await Promise.all(
					messages.map(async (message) => {
						const author = await getUser(message.authorId);
						return { ...message, author };
					}),
				);

				return new Response(JSON.stringify({ ticket, messages: newMessages }), {
					headers: { "Content-Type": "application/json" },
				});
			},
			DELETE: async (req: BunRequest) => {
				const user = await getSessionUser(req);
				if (!user) return new Response("Unauthorized", { status: 401 });

				const modCheck = await db
					.select()
					.from(moderators)
					.where(eq(moderators.user_id, user.id))
					.limit(1);
				if (modCheck.length === 0)
					return new Response("Forbidden: You must be a moderator to delete tickets.", {
						status: 403,
					});

				const { id } = req.params;
				const ticketId = parseInt(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 new Response(JSON.stringify({ success: true }), {
					headers: { "Content-Type": "application/json" },
				});
			},
		},
		"/moderators": {
			GET: async (req: BunRequest) => {
				const user = await getSessionUser(req);
				if (!user) return new Response("Unauthorized", { status: 401 });

				const modCheck = await db
					.select()
					.from(moderators)
					.where(eq(moderators.user_id, user.id))
					.limit(1);
				if (modCheck.length === 0) return new Response("Forbidden", { status: 403 });

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

				await getUsers(ids);

				const hydrated = await Promise.all(
					mods.map(async (mod) => {
						const profile = await getUser(mod.user_id);
						return { ...profile, pronouns: mod };
					}),
				);

				return new Response(JSON.stringify(hydrated), {
					headers: { "Content-Type": "application/json" },
				});
			},
		},
	},
});

const PORT = process.env.PORT || 3000;
logger.info(`server is running at ${server.hostname}:${PORT}`);