2024-05-29 02:59:49 +02:00
|
|
|
import { errorResponse } from "@/response";
|
2024-07-24 19:04:00 +02:00
|
|
|
import { sentry } from "@/sentry";
|
2024-07-11 12:56:28 +02:00
|
|
|
import { createMiddleware } from "@hono/hono/factory";
|
2024-06-27 01:11:39 +02:00
|
|
|
import { getLogger } from "@logtape/logtape";
|
2024-05-06 10:19:42 +02:00
|
|
|
import type { SocketAddress } from "bun";
|
|
|
|
|
import { matches } from "ip-matching";
|
2024-05-29 02:59:49 +02:00
|
|
|
import { config } from "~/packages/config-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) {
|
2024-06-27 01:11:39 +02:00
|
|
|
const logger = getLogger("server");
|
|
|
|
|
|
|
|
|
|
logger.error`Error while parsing banned IP "${ip}" `;
|
|
|
|
|
logger.error`${e}`;
|
2024-07-24 19:04:00 +02:00
|
|
|
sentry?.captureException(e);
|
2024-05-06 10:19:42 +02:00
|
|
|
|
|
|
|
|
return errorResponse(
|
|
|
|
|
`A server error occured: ${(e as Error).message}`,
|
|
|
|
|
500,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await next();
|
|
|
|
|
});
|