refactor(api): 🎨 Simplify bait middleware

This commit is contained in:
Jesse Wierzbinski 2024-06-12 19:38:57 -10:00
parent d301d4da09
commit 36d70fb612
No known key found for this signature in database

View file

@ -1,71 +1,53 @@
import { logger } from "@/loggers"; import { logger } from "@/loggers";
import { errorResponse, response } from "@/response"; import { response } from "@/response";
import type { SocketAddress } from "bun"; import type { SocketAddress } from "bun";
import { createMiddleware } from "hono/factory"; import { createMiddleware } from "hono/factory";
import { matches } from "ip-matching"; import { matches } from "ip-matching";
import { config } from "~/packages/config-manager"; import { config } from "~/packages/config-manager";
import { LogLevel } from "~/packages/log-manager"; import { LogLevel } from "~/packages/log-manager";
const baitFile = async () => {
const file = Bun.file(config.http.bait.send_file || "./beemovie.txt");
if (await file.exists()) {
return file;
}
await logger.log(
LogLevel.Error,
"Server.Bait",
`Bait file not found: ${config.http.bait.send_file}`,
);
};
export const bait = createMiddleware(async (context, next) => { export const bait = createMiddleware(async (context, next) => {
const requestIp = context.env?.ip as SocketAddress | undefined | null; const requestIp = context.env?.ip as SocketAddress | undefined | null;
if (config.http.bait.enabled) { if (!config.http.bait.enabled) {
// Check for bait IPs return await next();
if (requestIp?.address) { }
for (const ip of config.http.bait.bait_ips) {
try {
if (matches(ip, requestIp.address)) {
const file = Bun.file(
config.http.bait.send_file || "./beemovie.txt",
);
if (await file.exists()) { const file = await baitFile();
return response(file);
}
await logger.log(
LogLevel.Error,
"Server.Bait",
`Bait file not found: ${config.http.bait.send_file}`,
);
}
} catch (e) {
logger.log(
LogLevel.Error,
"Server.IPCheck",
`Error while parsing bait IP "${ip}" `,
);
logger.logError(
LogLevel.Error,
"Server.IPCheck",
e as Error,
);
return errorResponse( if (!file) {
`A server error occured: ${(e as Error).message}`, return await next();
500, }
);
} // Check for bait IPs
if (requestIp?.address) {
for (const ip of config.http.bait.bait_ips) {
if (matches(ip, requestIp.address)) {
return response(file);
} }
} }
}
// Check for bait user agents (regex) // Check for bait user agents (regex)
const ua = context.req.header("user-agent") ?? ""; const ua = context.req.header("user-agent") ?? "";
for (const agent of config.http.bait.bait_user_agents) { for (const agent of config.http.bait.bait_user_agents) {
if (new RegExp(agent).test(ua)) { if (new RegExp(agent).test(ua)) {
const file = Bun.file( return response(file);
config.http.bait.send_file || "./beemovie.txt",
);
if (await file.exists()) {
return response(file);
}
await logger.log(
LogLevel.Error,
"Server.Bait",
`Bait file not found: ${config.http.bait.send_file}`,
);
}
} }
} }