From 36d70fb612c7fdab5333f08b5946fb3a82e05cd9 Mon Sep 17 00:00:00 2001 From: Jesse Wierzbinski Date: Wed, 12 Jun 2024 19:38:57 -1000 Subject: [PATCH] refactor(api): :art: Simplify bait middleware --- middlewares/bait.ts | 86 ++++++++++++++++++--------------------------- 1 file changed, 34 insertions(+), 52 deletions(-) diff --git a/middlewares/bait.ts b/middlewares/bait.ts index 11efc27b..9c08ea2e 100644 --- a/middlewares/bait.ts +++ b/middlewares/bait.ts @@ -1,71 +1,53 @@ import { logger } from "@/loggers"; -import { errorResponse, response } from "@/response"; +import { response } from "@/response"; import type { SocketAddress } from "bun"; import { createMiddleware } from "hono/factory"; import { matches } from "ip-matching"; import { config } from "~/packages/config-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) => { const requestIp = context.env?.ip as SocketAddress | undefined | null; - if (config.http.bait.enabled) { - // Check for bait IPs - 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 (!config.http.bait.enabled) { + return await next(); + } - if (await file.exists()) { - 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, - ); + const file = await baitFile(); - return errorResponse( - `A server error occured: ${(e as Error).message}`, - 500, - ); - } + if (!file) { + return await next(); + } + + // 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) - const ua = context.req.header("user-agent") ?? ""; + // Check for bait user agents (regex) + const ua = context.req.header("user-agent") ?? ""; - for (const agent of config.http.bait.bait_user_agents) { - if (new RegExp(agent).test(ua)) { - const file = Bun.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}`, - ); - } + for (const agent of config.http.bait.bait_user_agents) { + if (new RegExp(agent).test(ua)) { + return response(file); } }