Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
411 changes: 197 additions & 214 deletions bun.lock

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@
"db:studio": "bun drizzle-kit studio"
},
"dependencies": {
"@elysiajs/cors": "^1.4.1",
"@elysia/openapi": "^1.4.16",
"@elysiajs/cors": "^1.4.2",
"discord.js": "^14.26.2",
"dotenv-flow": "^4.1.0",
"drizzle-orm": "^0.45.2",
"elysia": "^1.4.28",
"elysia": "^1.4.30",
"ms": "^2.1.3",
"redis": "^5.11.0",
"winston": "^3.19.0",
Expand Down
19 changes: 17 additions & 2 deletions src/api/controllers/global.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
import { triggerController } from "./trigger.controller";
import { publicController } from "./public.controller";
import { infoController } from "./info.controller";
import { Elysia } from "elysia";
import { Elysia, t } from "elysia";
import { env } from "#env";

export const api = new Elysia({
prefix: "/api/v1",
name: "api:root"
})
.guard({
headers: t.Object({
authorization: t.String({
description: "Trusted User Authorization Token",
}),
}),
response: {
401: t.Object({
message: t.String(),
}),
},
detail: {
security: [{ BearerAuth: [] }],
},
beforeHandle({ set, headers }) {
if (!headers.authorization || !env().TRUSTED_USERS.includes(headers.authorization)) {
set.status = 401;
Expand All @@ -19,4 +32,6 @@ export const api = new Elysia({
(app) =>
app.use(triggerController)
.use(infoController)
).use(publicController)
).use(publicController)

export type Api = typeof api;
74 changes: 42 additions & 32 deletions src/api/controllers/info.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Elysia, t } from "elysia";
import { db, tables } from "#database/db";
import { getStats } from "#utils/botStats";
import { srcPath } from "#utils/paths";
import { LogEntrySchema } from "#src/utils/logger";

export const infoController = new Elysia({
prefix: "/info",
Expand All @@ -16,25 +17,47 @@ export const infoController = new Elysia({
set.status = 200;
return readLogFile();
},
{ response: t.Array(t.Object({ date: t.String(), user: t.String(), info: t.String() })) },
{
detail: {
summary: "Get Audit Logs",
description: "Retrieves Winston log entries typed by LogLevel and LogMeta variants.",
tags: ["Protected / Info"],
},
response: {
200: t.Array(LogEntrySchema),
401: t.Object({ message: t.String() }),
},
}
)
.get(
"/announcements",
async ({ set }) => {
set.headers["content-type"] = "application/json";
set.status = 200;
return db.query.announcementModel.findMany({ orderBy: desc(tables.announcementModel.id) });

const announcements = await db.query.announcementModel.findMany({
orderBy: desc(tables.announcementModel.id),
});

return announcements.map((a) => ({
...a,
date: a.date instanceof Date ? a.date.toISOString() : String(a.date),
}));
},
{
response: t.Array(
t.MaybeEmpty(
detail: {
summary: "List Announcements",
tags: ["Protected / Info"],
},
response: {
200: t.Array(
t.Object({
id: t.Number(),
announcement: t.String(),
date: t.Date(),
}),
date: t.String(),
})
),
),
},
},
)
.get(
Expand All @@ -44,36 +67,23 @@ export const infoController = new Elysia({
set.status = 200;
return await getStats();
},
{ response: t.Object({ servers: t.Number(), members: t.Number(), registered: t.Number() }) },
)
.get(
"/rsa",
async ({ set }) => {
set.headers["content-type"] = "text/plain";
set.status = 200;
return fs.readFileSync(srcPath("RSA", "id_rsa.pub"), "utf-8");
{
detail: {
summary: "Get Bot Metrics",
tags: ["Protected / Info"],
}, response: {
200: t.Object({
servers: t.Number(),
members: t.Number(),
registered: t.Number(),
}),
},
},
{ response: t.String(), }
)
.post(
"/create-announcement",
async ({ body, set }) => {
const entryDate = new Date(body.date);
const dbEntry = {
announcement: body.announcement,
date: entryDate,
};

const announcementID = (await db.insert(tables.announcementModel).values(dbEntry).returning({ id: tables.announcementModel.id }))[0];
set.status = 201;

return { message: `Succesfully created announcement #${announcementID?.id || "Unknown"}!` };
},
{ body: t.Object({ announcement: t.String(), date: t.String() }), response: t.Object({ message: t.String() }) },
);

function readLogFile() {
const logPath = srcPath("logging", "logs.json");
const lines = fs.readFileSync(logPath, "utf-8").split("\n").filter(Boolean);
return lines.map((line) => JSON.parse(line));
}
}
39 changes: 31 additions & 8 deletions src/api/controllers/public.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { srcPath } from "#utils/paths";
import { db } from "#database/db";
import { aniListUser } from "#database/models";
import { eq } from "drizzle-orm";
import { logger } from "#src/utils/logger";

export const publicController = new Elysia({
prefix: "/public",
Expand All @@ -18,31 +19,53 @@ export const publicController = new Elysia({
set.status = 200;
return fs.readFileSync(srcPath("RSA", "id_rsa.pub"), "utf-8");
},
{ response: t.String(), }
{
response: { 200: t.String({ description: "PEM-encoded public key string" }) }, detail: {
summary: "Get Public RSA Key",
description: "Retrieves the public RSA key used for client-side token encryption.",
tags: ["Public"]
}
}
)
.post(
"/register",
async ({ body, set, headers }) => {
set.status = 400;
const discordId = headers.authorization;
const encryptedToken = body.token;
if (encryptedToken.length < 1000) return { message: "Invalid token" };

if (encryptedToken.length < 1000) {
set.status = 400;
return { message: "Invalid token" }
};

const rsa = new RSA();
const decryptedToken = await rsa.decrypt(encryptedToken);
const { Viewer: data } = (await graphQLRequest("Viewer", {}, decryptedToken)).data;
if (!data) return { message: "Invalid token" };

if (!data) {
set.status = 400;
return { message: "Invalid token" };
}

const existingUser = (await db.select().from(aniListUser).where(eq(aniListUser.discordId, discordId)).limit(1))[0];
if (existingUser) return { message: "User already registered" };
await db.insert(aniListUser).values({ discordId, aniListToken: encryptedToken, aniListId: data.id });

console.log(`Registered ${discordId} as ${data.name}`);
logger.debug(`Registered ${discordId} as ${data.name}`);
set.status = 201;
return { message: `Registered as ${data.name}!` };
},
{
response: t.Object({ message: t.String() }),
body: t.Object({ token: t.String() }),
headers: t.Object({ authorization: t.String() })
body: t.Object({ token: t.String({ description: "RSA-encrypted AniList JWT" }) }),
headers: t.Object({ authorization: t.String({ description: "Discord User ID" }) }),
detail: {
summary: "Register AniList Account",
description: "Decrypts the provided AniList token, checks registration status, and creates a user entry linked to the discord user ID.",
tags: ["Public"]
},
response: {
201: t.Object({ message: t.String() }),
400: t.Object({ message: t.String() }),
},
}
)
52 changes: 47 additions & 5 deletions src/api/controllers/trigger.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { execSync, spawnSync } from "child_process";
import { Elysia, t } from "elysia";
import { sqlite } from "#database/db";
import { db, sqlite, tables } from "#database/db";
import fs from "fs";
import { srcPath } from "#utils/paths";

Expand All @@ -17,19 +17,61 @@ export const triggerController = new Elysia({
return { message: "Successfully restarted the bot!" };
},
{
detail: {
summary: "Trigger Bot & API Restart",
description: "Executes update script, closes database connection, and restarts PM2 processes.",
tags: ["Protected / Admin"],
},
afterHandle() {
execSync('pm2 restart "Yuuko Production"', { encoding: "utf-8" });
setTimeout(() => execSync('pm2 restart "Yuuko Production API"', { encoding: "utf-8" }), 500);
},
response: t.Object({ message: t.String() }),
response: {
202: t.Object({ message: t.String() }),
},
},
)
.post(
"/wipe-logs",
async () => {
async ({ set }) => {
const logPath = srcPath("logging", "logs.json");
fs.writeFileSync(logPath, JSON.stringify([]), "utf8");

if (fs.existsSync(logPath)) {
fs.writeFileSync(logPath, "", "utf8");
}

set.status = 200;
return { message: "Wiped all logs!" };
},
{ response: t.Object({ message: t.String() }) },
{
detail: {
summary: "Wipe Audit Logs",
description: "Truncates the logs.json file.",
tags: ["Protected / Admin"],
}, response: {
200: t.Object({ message: t.String() }),
},
},
).post(
"/create-announcement",
async ({ body, set }) => {
const entryDate = new Date(body.date);
const dbEntry = {
announcement: body.announcement,
date: entryDate,
};

const announcementID = (await db.insert(tables.announcementModel).values(dbEntry).returning({ id: tables.announcementModel.id }))[0];
set.status = 201;

return { message: `Succesfully created announcement #${announcementID?.id || "Unknown"}!` };
},
{
detail: {
summary: "Create Announcement",
tags: ["Protected / Admin"],
}, body: t.Object({ announcement: t.String(), date: t.String() }), response: {
201: t.Object({ message: t.String() }),
},
},
);
34 changes: 30 additions & 4 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,48 @@
import { api } from '#api/controllers/global.controller'
import { RSA } from '#utils/rsaEncryption';
import { cors } from '@elysiajs/cors'
import { Elysia } from 'elysia'
import { cors } from '@elysiajs/cors';
import { openapi } from '@elysia/openapi';
import { Elysia } from 'elysia';
import { env } from "#env";
import { logger } from "#src/utils/logger";

export async function startApi() {
const port = env().API_PORT;

await RSA.loadKeys();

new Elysia().onError(({ error }) => {
const err = new Response(error.toString());
console.error(err);
logger.error(error.toString());

return err;
}).use(cors({
origin: /.*\.yuuko\.dev$/,
methods: ["POST", "GET"]
})).use(openapi({
documentation: {
info: {
title: "Yuuko API",
version: "1.0.0",
description: "API documentation for Yuuko services",
},
tags: [
{ name: "Public", description: "Unauthenticated public endpoints" },
{ name: "Protected / Info", description: "Internal status and management endpoints" }
],
components: {
securitySchemes: {
"BearerAuth": {
type: "apiKey",
in: "header",
name: "authorization",
description: "Trusted User Token"
}
}
}
}
})).use(api).listen(port)

console.log(`API is open on port ${port}`)
logger.info(`API is open on port ${port}`);
logger.info(`OpenAPI UI available at http://localhost:${port}/openapi`);
}
3 changes: 2 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { runChecks } from "#checks/run";
import { syncAnilistUsers, type WorkerResponseUnion } from "#workers/index";
import { env } from "#env";
import { eq, sql } from "drizzle-orm";
import { logger } from "#src/utils/logger";

dotenvFlow.config({ silent: true });

Expand Down Expand Up @@ -56,7 +57,7 @@ workerManager.onmessage = async (e) => {

switch (data.type) {
case 'LOG': {
client.logger.log(data.level, data.text);
logger.log(data.level, data.text);
break;
}
case "SYNC": {
Expand Down
Loading
Loading