feat: add IP filter middleware (#3035)
Closes #3011 --------- Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Bartek Iwańczuk
Claude Opus 4.6
parent
e0ee53d458
commit
566a6ce5e4
@@ -48,6 +48,7 @@
|
|||||||
"@std/collections": "jsr:@std/collections@^1.1.2",
|
"@std/collections": "jsr:@std/collections@^1.1.2",
|
||||||
"@std/dotenv": "jsr:@std/dotenv@^0.225.5",
|
"@std/dotenv": "jsr:@std/dotenv@^0.225.5",
|
||||||
"@std/http": "jsr:@std/http@^1.0.15",
|
"@std/http": "jsr:@std/http@^1.0.15",
|
||||||
|
"@std/net": "jsr:@std/net@^1.0.6",
|
||||||
"@std/uuid": "jsr:@std/uuid@^1.0.7",
|
"@std/uuid": "jsr:@std/uuid@^1.0.7",
|
||||||
"@supabase/postgrest-js": "npm:@supabase/postgrest-js@^1.21.4",
|
"@supabase/postgrest-js": "npm:@supabase/postgrest-js@^1.21.4",
|
||||||
"@types/mime-db": "npm:@types/mime-db@^1.43.6",
|
"@types/mime-db": "npm:@types/mime-db@^1.43.6",
|
||||||
|
|||||||
@@ -4167,6 +4167,7 @@
|
|||||||
"jsr:@std/http@^1.0.15",
|
"jsr:@std/http@^1.0.15",
|
||||||
"jsr:@std/jsonc@1",
|
"jsr:@std/jsonc@1",
|
||||||
"jsr:@std/media-types@1",
|
"jsr:@std/media-types@1",
|
||||||
|
"jsr:@std/net@^1.0.6",
|
||||||
"jsr:@std/path@1",
|
"jsr:@std/path@1",
|
||||||
"jsr:@std/semver@1",
|
"jsr:@std/semver@1",
|
||||||
"jsr:@std/streams@1",
|
"jsr:@std/streams@1",
|
||||||
@@ -4221,6 +4222,7 @@
|
|||||||
"jsr:@std/http@^1.0.21",
|
"jsr:@std/http@^1.0.21",
|
||||||
"jsr:@std/jsonc@^1.0.2",
|
"jsr:@std/jsonc@^1.0.2",
|
||||||
"jsr:@std/media-types@^1.1.0",
|
"jsr:@std/media-types@^1.1.0",
|
||||||
|
"jsr:@std/net@^1.0.6",
|
||||||
"jsr:@std/path@^1.1.2",
|
"jsr:@std/path@^1.1.2",
|
||||||
"jsr:@std/semver@^1.0.6",
|
"jsr:@std/semver@^1.0.6",
|
||||||
"jsr:@std/uuid@^1.0.9",
|
"jsr:@std/uuid@^1.0.9",
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -87,6 +87,7 @@ const toc: RawTableOfContents = {
|
|||||||
["cors", "cors", "link:latest"],
|
["cors", "cors", "link:latest"],
|
||||||
["csrf", "csrf", "link:latest"],
|
["csrf", "csrf", "link:latest"],
|
||||||
["csp", "csp", "link:latest"],
|
["csp", "csp", "link:latest"],
|
||||||
|
["ip-filter", "ipFilter", "link:latest"],
|
||||||
["trailing-slashes", "trailingSlashes", "link:latest"],
|
["trailing-slashes", "trailingSlashes", "link:latest"],
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
"@std/http": "jsr:@std/http@^1.0.21",
|
"@std/http": "jsr:@std/http@^1.0.21",
|
||||||
"@std/jsonc": "jsr:@std/jsonc@^1.0.2",
|
"@std/jsonc": "jsr:@std/jsonc@^1.0.2",
|
||||||
"@std/media-types": "jsr:@std/media-types@^1.1.0",
|
"@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/path": "jsr:@std/path@^1.1.2",
|
||||||
"@std/semver": "jsr:@std/semver@^1.0.6",
|
"@std/semver": "jsr:@std/semver@^1.0.6",
|
||||||
"@std/uuid": "jsr:@std/uuid@^1.0.9",
|
"@std/uuid": "jsr:@std/uuid@^1.0.9",
|
||||||
|
|||||||
@@ -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?: <State>(
|
||||||
|
remote: {
|
||||||
|
addr: string;
|
||||||
|
type: Deno.NetworkInterfaceInfo["family"];
|
||||||
|
},
|
||||||
|
ctx: Context<State>,
|
||||||
|
) => Response | Promise<Response>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<State>()
|
||||||
|
*
|
||||||
|
* 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<State>(
|
||||||
|
rules: IpFilterRules,
|
||||||
|
options?: IpFilterOptions,
|
||||||
|
): Middleware<State> {
|
||||||
|
const onBlock = options?.onBlocked ??
|
||||||
|
(() => new Response("Forbidden", { status: 403 }));
|
||||||
|
return function ipFilter<State>(ctx: Context<State>) {
|
||||||
|
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);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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<T>(
|
||||||
|
remoteAddr: string,
|
||||||
|
ipFilterRules: IpFilterRules,
|
||||||
|
options?: IpFilterOptions,
|
||||||
|
): (request: Request) => Promise<Response> {
|
||||||
|
function remoteHostOverride(ctx: Context<T>) {
|
||||||
|
(ctx.info.remoteAddr as { hostname: string }).hostname = remoteAddr;
|
||||||
|
return ctx.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new App<T>()
|
||||||
|
.use(remoteHostOverride)
|
||||||
|
.use(ipFilter(ipFilterRules, options))
|
||||||
|
.all("/", () => new Response("hello"))
|
||||||
|
.handler();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createTest(
|
||||||
|
addr: string,
|
||||||
|
ipFilterRules: IpFilterRules,
|
||||||
|
options?: IpFilterOptions,
|
||||||
|
): Promise<number> {
|
||||||
|
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);
|
||||||
|
});
|
||||||
@@ -13,6 +13,11 @@ export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts";
|
|||||||
export { staticFiles } from "./middlewares/static_files.ts";
|
export { staticFiles } from "./middlewares/static_files.ts";
|
||||||
export { csrf, type CsrfOptions } from "./middlewares/csrf.ts";
|
export { csrf, type CsrfOptions } from "./middlewares/csrf.ts";
|
||||||
export { cors, type CORSOptions } from "./middlewares/cors.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 { csp, type CSPOptions } from "./middlewares/csp.ts";
|
||||||
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
||||||
export type { Context, FreshContext, Island } from "./context.ts";
|
export type { Context, FreshContext, Island } from "./context.ts";
|
||||||
|
|||||||
Reference in New Issue
Block a user