2024-05-29 02:59:49 +02:00
|
|
|
import { logger } from "@/loggers";
|
|
|
|
|
import { errorResponse } from "@/response";
|
2024-05-06 10:19:42 +02:00
|
|
|
import type { SocketAddress } from "bun";
|
|
|
|
|
import { createMiddleware } from "hono/factory";
|
|
|
|
|
import { matches } from "ip-matching";
|
2024-05-29 02:59:49 +02:00
|
|
|
import { config } from "~/packages/config-manager";
|
|
|
|
|
import { LogLevel } from "~/packages/log-manager";
|
2024-05-06 10:19:42 +02:00
|
|
|
|
|
|
|
|
export const ipBans = createMiddleware(async (context, next) => {
|
|
|
|
|
// Check for banned IPs
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
const requestIp = context.env?.ip as SocketAddress | undefined | null;
|
2024-05-06 10:19:42 +02:00
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!requestIp?.address) {
|
2024-05-06 10:19:42 +02:00
|
|
|
await next();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (const ip of config.http.banned_ips) {
|
|
|
|
|
try {
|
2024-06-13 04:26:43 +02:00
|
|
|
if (matches(ip, requestIp?.address)) {
|
2024-05-06 10:19:42 +02:00
|
|
|
return errorResponse("Forbidden", 403);
|
|
|
|
|
}
|
|
|
|
|
} catch (e) {
|
|
|
|
|
logger.log(
|
2024-06-13 04:26:43 +02:00
|
|
|
LogLevel.Error,
|
2024-05-06 10:19:42 +02:00
|
|
|
"Server.IPCheck",
|
|
|
|
|
`Error while parsing banned IP "${ip}" `,
|
|
|
|
|
);
|
2024-06-13 04:26:43 +02:00
|
|
|
logger.logError(LogLevel.Error, "Server.IPCheck", e as Error);
|
2024-05-06 10:19:42 +02:00
|
|
|
|
|
|
|
|
return errorResponse(
|
|
|
|
|
`A server error occured: ${(e as Error).message}`,
|
|
|
|
|
500,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await next();
|
|
|
|
|
});
|