diff --git a/src/index.ts b/src/index.ts index 3973e68..fd389f5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,12 @@ import { Hono } from "hono"; import { portRoute } from "./routes/port"; +import realIP from "./middlewares/real-ip"; const app = new Hono(); app.route("/", portRoute); Bun.serve({ - ...app, - idleTimeout: 90, -}) + ...app, + idleTimeout: 90, +}); diff --git a/src/middlewares/real-ip.ts b/src/middlewares/real-ip.ts new file mode 100644 index 0000000..a0e7bf9 --- /dev/null +++ b/src/middlewares/real-ip.ts @@ -0,0 +1,22 @@ +import { getConnInfo } from "hono/bun"; +import { createMiddleware } from "hono/factory"; + +const realIP = createMiddleware<{ + Variables: { + ip: string; + }; +}>(async (context, next) => { + const ip = + context.req.header("x-forwarded-for") || + getConnInfo(context).remote.address; + + if (!ip) { + return context.json({ error: "Your IP could not be found" }, 401); + } + + context.set("ip", ip); + + await next(); +}); + +export default realIP; diff --git a/src/routes/port.ts b/src/routes/port.ts index 4c65d57..5b15585 100644 --- a/src/routes/port.ts +++ b/src/routes/port.ts @@ -3,6 +3,7 @@ import { getConnInfo } from "hono/bun"; import connectToAddress from "../utils/connect-to-address"; import { z } from "zod"; import * as IP from "ip"; +import realIP from "../middlewares/real-ip"; export const portRoute = new Hono(); @@ -33,15 +34,12 @@ const schema = z.object({ .pipe(z.number().min(100).max(60_000)), }); -portRoute.get("/:port", async context => { - const info = getConnInfo(context); +portRoute.get("/:port", realIP, async context => { const rawData = { - ip: info.remote.address || "", + ip: context.get("ip"), port: context.req.param("port"), timeout: context.req.query("timeout") || context.req.query("t") || "", }; - console.log(info.remote.address); - console.log(context.req.header()); const parsedData = schema.safeParse(rawData); if (!parsedData.success) {