2025-06-15 04:38:20 +02:00
|
|
|
import { config } from "@versia-server/config";
|
2025-06-15 23:50:34 +02:00
|
|
|
import { ApiError } from "@versia-server/kit";
|
2025-06-22 18:43:03 +02:00
|
|
|
import { serverLogger } from "@versia-server/logging";
|
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";
|
|
|
|
|
|
|
|
|
|
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) {
|
2025-06-22 18:43:03 +02:00
|
|
|
serverLogger.error`Error while parsing banned IP "${ip}" `;
|
|
|
|
|
serverLogger.error`${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
|
|
|
});
|