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";
|
2024-12-18 20:42:40 +01:00
|
|
|
import { createMiddleware } from "hono/factory";
|
2024-05-06 10:19:42 +02:00
|
|
|
import { matches } from "ip-matching";
|
2025-04-10 19:15:31 +02:00
|
|
|
import { sentry } from "@/sentry";
|
2024-12-30 18:00:23 +01:00
|
|
|
import { ApiError } from "~/classes/errors/api-error";
|
2025-02-15 02:47:29 +01:00
|
|
|
import { config } from "~/config.ts";
|
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-12-30 18:00:23 +01:00
|
|
|
throw new ApiError(403, "Forbidden");
|
2024-05-06 10:19:42 +02:00
|
|
|
}
|
|
|
|
|
} 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
|
|
|
|
2024-08-19 21:03:59 +02:00
|
|
|
return context.json(
|
|
|
|
|
{ error: `A server error occured: ${(e as Error).message}` },
|
2024-05-06 10:19:42 +02:00
|
|
|
500,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await next();
|
2025-05-23 17:29:27 +02:00
|
|
|
return;
|
2024-05-06 10:19:42 +02:00
|
|
|
});
|