From 566a6ce5e48f160fa3b969e9008ce69dde22c799 Mon Sep 17 00:00:00 2001 From: Octo8080X <64694349+Octo8080X@users.noreply.github.com> Date: Mon, 30 Mar 2026 04:43:52 +0900 Subject: [PATCH] feat: add IP filter middleware (#3035) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3011 --------- Co-authored-by: Bartek IwaƄczuk Co-authored-by: Claude Opus 4.6 (1M context) --- deno.json | 1 + deno.lock | 2 + docs/latest/plugins/ip-filter.md | 88 +++++++++++++ docs/toc.ts | 1 + packages/fresh/deno.json | 1 + packages/fresh/src/middlewares/ip_filter.ts | 124 ++++++++++++++++++ .../fresh/src/middlewares/ip_filter_test.ts | 93 +++++++++++++ packages/fresh/src/mod.ts | 5 + 8 files changed, 315 insertions(+) create mode 100644 docs/latest/plugins/ip-filter.md create mode 100644 packages/fresh/src/middlewares/ip_filter.ts create mode 100644 packages/fresh/src/middlewares/ip_filter_test.ts diff --git a/deno.json b/deno.json index ef74c4d7..4a18845b 100644 --- a/deno.json +++ b/deno.json @@ -48,6 +48,7 @@ "@std/collections": "jsr:@std/collections@^1.1.2", "@std/dotenv": "jsr:@std/dotenv@^0.225.5", "@std/http": "jsr:@std/http@^1.0.15", + "@std/net": "jsr:@std/net@^1.0.6", "@std/uuid": "jsr:@std/uuid@^1.0.7", "@supabase/postgrest-js": "npm:@supabase/postgrest-js@^1.21.4", "@types/mime-db": "npm:@types/mime-db@^1.43.6", diff --git a/deno.lock b/deno.lock index 3554f9a0..627762f3 100644 --- a/deno.lock +++ b/deno.lock @@ -4167,6 +4167,7 @@ "jsr:@std/http@^1.0.15", "jsr:@std/jsonc@1", "jsr:@std/media-types@1", + "jsr:@std/net@^1.0.6", "jsr:@std/path@1", "jsr:@std/semver@1", "jsr:@std/streams@1", @@ -4221,6 +4222,7 @@ "jsr:@std/http@^1.0.21", "jsr:@std/jsonc@^1.0.2", "jsr:@std/media-types@^1.1.0", + "jsr:@std/net@^1.0.6", "jsr:@std/path@^1.1.2", "jsr:@std/semver@^1.0.6", "jsr:@std/uuid@^1.0.9", diff --git a/docs/latest/plugins/ip-filter.md b/docs/latest/plugins/ip-filter.md new file mode 100644 index 00000000..cfa6657a --- /dev/null +++ b/docs/latest/plugins/ip-filter.md @@ -0,0 +1,88 @@ +--- +description: "Restrict access by IP address with the ipFilter middleware" +--- + +The `ipFilter()` middleware restricts access based on the client's IP address. +It supports deny lists, allow lists, and CIDR subnet matching. Deny rules always +take precedence over allow rules. + +```ts main.ts +import { App, ipFilter } from "fresh"; + +const app = new App() + .use(ipFilter({ + denyList: ["192.168.1.10", "10.0.0.0/8"], + allowList: ["192.168.1.0/24"], + })) + .get("/", () => new Response("hello")); +``` + +## Deny list + +Block specific IPs or subnets. Any request from a matching address receives a +403 Forbidden response: + +```ts main.ts +import { App, ipFilter } from "fresh"; + +const app = new App() + .use(ipFilter({ + denyList: ["192.168.1.10", "2001:db8::1", "10.0.0.0/8"], + })); +``` + +## Allow list + +When an allow list is provided, only matching IPs are permitted. All other +addresses are blocked: + +```ts main.ts +import { App, ipFilter } from "fresh"; + +const app = new App() + .use(ipFilter({ + allowList: ["203.0.113.0/24", "2001:db8::/32"], + })); +``` + +## Combined rules + +When both lists are provided, deny rules are checked first. An IP that appears +in both lists is blocked: + +```ts main.ts +import { App, ipFilter } from "fresh"; + +const app = new App() + .use(ipFilter({ + denyList: ["192.168.1.10"], + allowList: ["192.168.1.0/24"], + })); +``` + +In this example, all of `192.168.1.0/24` is allowed except `192.168.1.10`. + +## Custom blocked response + +By default, blocked requests receive a `403 Forbidden` response. Use the +`onBlocked` callback to customize this: + +```ts main.ts +import { App, ipFilter } from "fresh"; + +const app = new App() + .use(ipFilter({ + denyList: ["10.0.0.0/8"], + }, { + onBlocked: (remote, ctx) => { + console.log(`Blocked ${remote.addr} from ${ctx.url.pathname}`); + return new Response("Access denied", { status: 401 }); + }, + })); +``` + +The `onBlocked` callback receives: + +- `remote.addr` -- the client's IP address +- `remote.type` -- `"IPv4"` or `"IPv6"` +- `ctx` -- the request [context](/docs/concepts/context) diff --git a/docs/toc.ts b/docs/toc.ts index 953d10c2..acfb54e8 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -87,6 +87,7 @@ const toc: RawTableOfContents = { ["cors", "cors", "link:latest"], ["csrf", "csrf", "link:latest"], ["csp", "csp", "link:latest"], + ["ip-filter", "ipFilter", "link:latest"], ["trailing-slashes", "trailingSlashes", "link:latest"], ], }, diff --git a/packages/fresh/deno.json b/packages/fresh/deno.json index 3df30143..ab10f018 100644 --- a/packages/fresh/deno.json +++ b/packages/fresh/deno.json @@ -21,6 +21,7 @@ "@std/http": "jsr:@std/http@^1.0.21", "@std/jsonc": "jsr:@std/jsonc@^1.0.2", "@std/media-types": "jsr:@std/media-types@^1.1.0", + "@std/net": "jsr:@std/net@^1.0.6", "@std/path": "jsr:@std/path@^1.1.2", "@std/semver": "jsr:@std/semver@^1.0.6", "@std/uuid": "jsr:@std/uuid@^1.0.9", diff --git a/packages/fresh/src/middlewares/ip_filter.ts b/packages/fresh/src/middlewares/ip_filter.ts new file mode 100644 index 00000000..b17647de --- /dev/null +++ b/packages/fresh/src/middlewares/ip_filter.ts @@ -0,0 +1,124 @@ +import type { Context } from "../context.ts"; +import type { Middleware } from "./mod.ts"; +import { isIPv4, matchSubnets } from "@std/net/unstable-ip"; + +/** + * Configuration rules for IP restriction middleware. + */ +export interface IpFilterRules { + /** + * List of IP addresses or CIDR blocks to deny access. + * If an IP matches any entry in this list, access will be blocked. + * + * @example ["192.168.1.10", "10.0.0.0/8", "2001:db8::1"] + */ + denyList?: string[]; + + /** + * List of IP addresses or CIDR blocks to allow access. + * If specified, only IPs matching entries in this list will be allowed. + * If empty or undefined, all IPs are allowed (unless in denyList). + * + * @example ["192.168.1.0/24", "203.0.113.0/24", "2001:db8::/32"] + */ + allowList?: string[]; +} + +export interface IpFilterOptions { + /** + * Called when a request is blocked by the IP filter. + * + * The function receives the remote information and the current request + * context and should return a Response (or a Promise resolving to one) + * which will be sent back to the client. If not provided, a default + * 403 Forbidden response will be used. + * + * Parameters: + * - `remote.addr` - the remote IP address as a string. + * - `remote.type` - the network family: "IPv4" or "IPv6". + * - `ctx` - the request `Context` which can be used to inspect the + * request or produce a custom response. + * + * @example + * ```ts + * const options: IpFilterOptions = { + * onBlocked: (remote, ctx) => { + * console.log(`Blocked ${remote.addr} (${remote.type})`, ctx.url); + * return new Response("Access denied", { status: 401 }); + * }, + * }; + * ``` + */ + onBlocked?: ( + remote: { + addr: string; + type: Deno.NetworkInterfaceInfo["family"]; + }, + ctx: Context, + ) => Response | Promise; +} + +/** + * IP restriction Middleware for Fresh. + * + * @param rules Deny and allow rules object. + * @param options Options for the IP Restriction middleware. + * @returns The middleware handler function. + * + * Filters rule priority is denyList, then allowList. + * If an IP is in the denyList, it will be blocked regardless of the allowList. + * + * @example Basic usage (with defaults) + * ```ts + * const app = new App() + * + * app.use(ipFilter({ + * denyList: ["192.168.1.10", "2001:db8::1"] + * })); + * ``` + * + * @example Custom blocked handler + * ```ts + * app.use(ipFilter({ + * denyList: ["192.168.1.10", "2001:db8::1"] + * }, { + * onBlocked: (remote, ctx) => { + * console.log( + * `Request URL: ${ctx.url}, Blocked IP: ${remote.addr} of type ${remote.type}`, + * ); + * return new Response("Access denied", { status: 401 }); + * }, + * })); + * ``` + */ +export function ipFilter( + rules: IpFilterRules, + options?: IpFilterOptions, +): Middleware { + const onBlock = options?.onBlocked ?? + (() => new Response("Forbidden", { status: 403 })); + return function ipFilter(ctx: Context) { + if ( + ctx.info.remoteAddr.transport !== "udp" && + ctx.info.remoteAddr.transport !== "tcp" + ) { + return ctx.next(); + } + + const addr = ctx.info.remoteAddr.hostname; + const type = isIPv4(addr) ? "IPv4" : "IPv6"; + + if (matchSubnets(addr, rules.denyList || [])) { + return onBlock({ addr, type }, ctx); + } + + if ( + (rules.allowList || []).length === 0 || + matchSubnets(addr, rules.allowList || []) + ) { + return ctx.next(); + } + + return onBlock({ addr, type }, ctx); + }; +} diff --git a/packages/fresh/src/middlewares/ip_filter_test.ts b/packages/fresh/src/middlewares/ip_filter_test.ts new file mode 100644 index 00000000..e271bbf3 --- /dev/null +++ b/packages/fresh/src/middlewares/ip_filter_test.ts @@ -0,0 +1,93 @@ +import { App } from "../app.ts"; +import type { Context } from "../context.ts"; +import { + ipFilter, + type IpFilterOptions, + type IpFilterRules, +} from "./ip_filter.ts"; +import { expect } from "@std/expect"; + +function testHandler( + remoteAddr: string, + ipFilterRules: IpFilterRules, + options?: IpFilterOptions, +): (request: Request) => Promise { + function remoteHostOverride(ctx: Context) { + (ctx.info.remoteAddr as { hostname: string }).hostname = remoteAddr; + return ctx.next(); + } + + return new App() + .use(remoteHostOverride) + .use(ipFilter(ipFilterRules, options)) + .all("/", () => new Response("hello")) + .handler(); +} + +async function createTest( + addr: string, + ipFilterRules: IpFilterRules, + options?: IpFilterOptions, +): Promise { + const handler = testHandler(addr, ipFilterRules, options); + + const res = await handler(new Request("https://localhost/")); + + return res.status; +} + +Deno.test("ipFilter - no option", async () => { + expect(await createTest("192.168.1.10", {})).toBe(200); +}); +Deno.test("ipFilter - deny only", async () => { + const ipFilterRules = { + denyList: ["192.168.1.10", "2001:db8::1"], + }; + + expect(await createTest("192.168.1.10", ipFilterRules)).toBe(403); + expect(await createTest("192.168.1.11", ipFilterRules)).toBe(200); + expect(await createTest("2001:db8::1", ipFilterRules)).toBe(403); + expect(await createTest("2001:db8::2", ipFilterRules)).toBe(200); +}); + +Deno.test("ipFilter - allow only", async () => { + const ipFilterRules = { + allowList: ["192.168.1.10", "2001:db8::1"], + }; + expect(await createTest("192.168.1.10", ipFilterRules)).toBe(200); + expect(await createTest("192.168.1.11", ipFilterRules)).toBe(403); + expect(await createTest("2001:db8::1", ipFilterRules)).toBe(200); + expect(await createTest("2001:db8::2", ipFilterRules)).toBe(403); +}); + +// When both allow and deny are set, deny takes precedence +Deno.test("ipFilter - allow and deny", async () => { + const ipFilterRules = { + denyList: ["192.168.1.10", "2001:db8::1"], + allowList: ["192.168.1.10", "2001:db8::1"], + }; + expect(await createTest("192.168.1.10", ipFilterRules)).toBe(403); + expect(await createTest("2001:db8::1", ipFilterRules)).toBe(403); +}); + +Deno.test("ipFilter - subnet mask", async () => { + const ipFilterRules = { + denyList: ["192.168.1.0/24"], + }; + expect(await createTest("192.168.1.10", ipFilterRules)).toBe(403); +}); + +Deno.test("ipFilter - custom onBlocked", async () => { + const ipFilterRules = { + denyList: ["192.168.1.0/24"], + }; + + const options: IpFilterOptions = { + onBlocked: () => { + return new Response("custom blocked", { status: 401 }); + }, + }; + + expect(await createTest("192.168.1.10", ipFilterRules, options)) + .toBe(401); +}); diff --git a/packages/fresh/src/mod.ts b/packages/fresh/src/mod.ts index 283ed19f..0798a2bb 100644 --- a/packages/fresh/src/mod.ts +++ b/packages/fresh/src/mod.ts @@ -13,6 +13,11 @@ export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts"; export { staticFiles } from "./middlewares/static_files.ts"; export { csrf, type CsrfOptions } from "./middlewares/csrf.ts"; export { cors, type CORSOptions } from "./middlewares/cors.ts"; +export { + ipFilter, + type IpFilterOptions, + type IpFilterRules, +} from "./middlewares/ip_filter.ts"; export { csp, type CSPOptions } from "./middlewares/csp.ts"; export type { FreshConfig, ResolvedFreshConfig } from "./config.ts"; export type { Context, FreshContext, Island } from "./context.ts";