Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
571b272
Refactor IP restriction middleware: clean up debug logs and improve flow
Octo8080X Jun 14, 2025
194b59e
Remove unnecessary comments and console.log statements from IP restri…
Octo8080X Jun 14, 2025
8362db1
Remove unnecessary comments and console.log statements from IP restri…
Octo8080X Jun 14, 2025
167feba
Update exports in mod.ts for ipRestriction and related types
Octo8080X Jun 14, 2025
7ae6fc3
Export IPRestrictionRules type from ip_restriction in mod.ts
Octo8080X Jun 14, 2025
0eb73c3
Rename test file to ip_restriction_test.ts for consistency with sourc…
Octo8080X Jun 14, 2025
72ae3bd
Export getIP from ip_restriction in mod.ts for middleware completeness
Octo8080X Jun 14, 2025
5987fc8
Fix ipRestriction middleware tests and improve coverage
Octo8080X Jun 14, 2025
2e93114
Export IPRestrictionRules type from ip_restriction module
Octo8080X Jun 14, 2025
2deeb7c
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Jun 21, 2025
25c2cdb
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Aug 6, 2025
4e5ae78
update
Octo8080X Oct 6, 2025
caae853
use @std/net
Octo8080X Oct 6, 2025
9db23e6
update export
Octo8080X Oct 6, 2025
c93fd79
update docs
Octo8080X Oct 6, 2025
8e79b17
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Oct 7, 2025
bc7f51e
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Oct 14, 2025
53612b9
fix
Octo8080X Oct 20, 2025
2645569
Merge branch 'feature/add_ip_restriction_middleware' of github.com:Oc…
Octo8080X Oct 20, 2025
abd6665
fix
Octo8080X Oct 20, 2025
f14e7dc
fix
Octo8080X Oct 20, 2025
1468cde
rename and fix
Octo8080X Oct 21, 2025
e37ad41
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Oct 21, 2025
25d5d2d
fix
Octo8080X Oct 21, 2025
dfe28d4
fix
Octo8080X Oct 21, 2025
a7ab3de
fix
Octo8080X Oct 21, 2025
df3b5da
fix
Octo8080X Oct 21, 2025
c22c4bf
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Oct 21, 2025
7236b07
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Nov 11, 2025
3f3d37d
merge main
Octo8080X Nov 11, 2025
007e150
fix
Octo8080X Nov 11, 2025
4b15afe
add document
Octo8080X Nov 11, 2025
4c2f7a6
organized method
Octo8080X Nov 11, 2025
9ef84c7
Merge branch 'denoland:main' into feature/add_ip_restriction_middleware
Octo8080X Nov 22, 2025
5383f74
logic update
Octo8080X Nov 22, 2025
75805b8
logic update
Octo8080X Nov 22, 2025
f50aa69
logic update
Octo8080X Nov 22, 2025
5e2be56
logic update
Octo8080X Nov 22, 2025
ab623c8
update coments
Octo8080X Nov 22, 2025
34407e8
restore lockfile
Octo8080X Nov 22, 2025
ef5ff80
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Dec 23, 2025
4328d63
Merge branch 'main' into feature/add_ip_restriction_middleware
Octo8080X Jan 22, 2026
4e16d46
add @std/net
Octo8080X Jan 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,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",
Expand Down
32 changes: 28 additions & 4 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/fresh/deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
126 changes: 126 additions & 0 deletions packages/fresh/src/middlewares/ip_filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
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", "IPv6", or `undefined`.
* - `ctx` - the request `Context` which can be used to inspect the
* request or produce a custom response.
*
* @example
* ```ts
* const options: ipFilterOptions = {
* onError: (remote, ctx) => {
* console.log(`Blocked ${remote.addr} (${remote.type})`, ctx.url);
* return new Response("Access denied", { status: 401 });
* },
* };
* ```
*/
onError?: <State>(
remote: {
addr: string;
type: Deno.NetworkInterfaceInfo["family"] | undefined;
},
ctx: Context<State>,
) => Response | Promise<Response>;
}
Comment on lines +27 to +59
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This interface and its properties need documentation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have addressed this matter.


/**
* IP restriction Middleware for Fresh.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should explain this filter. I.e. the precedence of rules. So deny rules take precedence over allow rules and traffic not matching any rule is denied by default (implicit deny).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mentioned this matter.

Thankyou

*
* @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 error handling
* ```ts
* const customOnError: ipFilterOptions = {
* onError: (remote, ctx) => {
* console.log(
* `Request URL: ${ctx.url}, Blocked IP: ${remote.addr} of type ${remote.type}`,
* );
*
* return new Response("custom onError", { status: 401 });
* },
* };
* app.use(ipFilter({
* denyList: ["192.168.1.10", "2001:db8::1"]
* }, customOnError));
* ```
*/
export function ipFilter<State>(
rules: IpFilterRules,
options?: ipFilterOptions,
): Middleware<State> {
const onBlock = options?.onError ??
(() => 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();
}
Comment on lines +103 to +108
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A good question to ask is "does Fresh allow other traffic besides UDP and TCP?" If the answer is no, this section can be removed, as the conditional will never evaluate to true.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 'transport' can be one of five options: "tcp", "udp", "unix", "unixpacket", or "vsock". Since 'hostname' is only available for "tcp" and "udp", I believe this handling process is necessary.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, to correct my stance, yes, we should return early if not UDP or TCP traffic, because an IP address isn't being used. But I don't think throwing is the correct behaviour. Instead, we should just pass through. See my suggestion above.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ve set it up so that traffic passes through if it's neither UDP nor TCP.


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);
};
}
105 changes: 105 additions & 0 deletions packages/fresh/src/middlewares/ip_filter_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
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>(
remortAddr: string,
ipFilterRules: IpFilterRules,
options?: ipFilterOptions,
): (request: Request) => Promise<Response> {
function remoteHostOverRide(ctx: Context<T>) {
(ctx.info.remoteAddr as { hostname: string }).hostname = remortAddr;
return ctx.next();
}

if (!options) {
return new App<T>()
.use(remoteHostOverRide)
.use(ipFilter(ipFilterRules))
.all("/", () => new Response("hello"))
.handler();
}

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 - set ipFilterRules 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 - set ipFilterRules arrow 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);
});

// arrow and deny
// deny の方が優先されるを英語で
// When both allow and deny are set, deny takes precedence
Deno.test("ipFilter - set ipFilterRules arrow 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);
});

// adapt subnet mask
Deno.test("ipFilter - adapt subnet mask", async () => {
const ipFilterRules = {
denyList: ["192.168.1.0/24"],
};
expect(await createTest("192.168.1.10", ipFilterRules)).toBe(403);
});

// onError
Deno.test("ipFilter - custom onError", async () => {
const ipFilterRules = {
denyList: ["192.168.1.0/24"],
};

const customOnError: ipFilterOptions = {
onError: () => {
return new Response("custom onError", { status: 401 });
},
};

expect(await createTest("192.168.1.10", ipFilterRules, customOnError))
.toBe(401);
});
1 change: 1 addition & 0 deletions packages/fresh/src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ 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 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";
Expand Down
Loading