Skip to content
Myr

index.ts

This file

Path

src/middleware/ip-restriction/index.ts

279 lines · 8.1 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–279why, one step back
1/**
2 * IP Restriction Middleware for Hono3 * @module4 */56import type { Context, MiddlewareHandler } from '../..'7import type { AddressType, GetConnInfo } from '../../helper/conninfo'8import { HTTPException } from '../../http-exception'9import type { InvalidIPAddressError } from '../../utils/ipaddr'10import {11 convertIPv4MappedIPv6ToIPv4,12 convertIPv4ToBinary,13 convertIPv6BinaryToString,14 convertIPv6ToBinary,15 distinctRemoteAddr,16 isIPv4MappedIPv6,17 INVALID_IP_ADDRESS_ERROR_CODE,18} from '../../utils/ipaddr'1920/**21 * Function to get IP Address22 */23type GetIPAddr = GetConnInfo | ((c: Context) => string)2425/**26 * ### IPv4 and IPv627 * - `*` match all28 *29 * ### IPv430 * - `192.168.2.0` static31 * - `192.168.2.0/24` CIDR Notation32 *33 * ### IPv634 * - `::1` static35 * - `::1/10` CIDR Notation36 */37type IPRestrictionRuleFunction = (addr: { addr: string; type: AddressType }) => boolean38export type IPRestrictionRule = string | ((addr: { addr: string; type: AddressType }) => boolean)3940const IS_CIDR_NOTATION_REGEX = /\/[^/]*$/41const parseCidrPrefix = (rule: string, prefix: string, max: number): number => {42 if (!/^[0-9]{1,3}$/.test(prefix)) {43 throw new TypeError(`Invalid rule: ${rule}`)44 }45 const parsedPrefix = parseInt(prefix)46 if (parsedPrefix > max) {47 throw new TypeError(`Invalid rule: ${rule}`)48 }49 return parsedPrefix50}51const buildMatcher = (52 rules: IPRestrictionRule[]53): ((addr: { addr: string; type: AddressType; isIPv4: boolean }) => boolean) => {54 const functionRules: IPRestrictionRuleFunction[] = []55 const staticRules: Set<string> = new Set()56 const staticIPv4Rules: Set<bigint> = new Set()57 const staticIPv6Rules: Set<bigint> = new Set()58 const cidrRules: [boolean, bigint, bigint][] = []59 const registerStaticRule = (rule: string): void => {60 const type = distinctRemoteAddr(rule)61 if (type === undefined) {62 throw new TypeError(`Invalid rule: ${rule}`)63 }64 if (type === 'IPv4') {65 const ipv4binary = convertIPv4ToBinary(rule)66 staticRules.add(rule)67 staticRules.add(`::ffff:${rule}`)68 staticIPv4Rules.add(ipv4binary)69 staticIPv6Rules.add((0xffffn << 32n) | ipv4binary)70 } else {71 const ipv6binary = convertIPv6ToBinary(rule)72 const ipv6Addr = convertIPv6BinaryToString(ipv6binary)73 staticRules.add(ipv6Addr)74 staticIPv6Rules.add(ipv6binary)75 if (isIPv4MappedIPv6(ipv6binary)) {76 staticRules.add(ipv6Addr.substring(7)) // remove ::ffff: prefix77 staticIPv4Rules.add(convertIPv4MappedIPv6ToIPv4(ipv6binary))78 }79 }80 }8182 for (let rule of rules) {83 if (rule === '*') {84 return () => true85 } else if (typeof rule === 'function') {86 functionRules.push(rule)87 } else {88 if (IS_CIDR_NOTATION_REGEX.test(rule)) {89 const separatedRule = rule.split('/')9091 const addrStr = separatedRule[0]92 const type = distinctRemoteAddr(addrStr)93 if (type === undefined) {94 throw new TypeError(`Invalid rule: ${rule}`)95 }9697 let isIPv4 = type === 'IPv4'98 let prefix = parseCidrPrefix(rule, separatedRule[1], isIPv4 ? 32 : 128)99100 if (isIPv4 ? prefix === 32 : prefix === 128) {101 // this rule is a static rule102 rule = addrStr103 } else {104 let addr = (isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(addrStr)105 if (type === 'IPv6' && isIPv4MappedIPv6(addr) && prefix >= 96) {106 isIPv4 = true107 addr = convertIPv4MappedIPv6ToIPv4(addr)108 prefix -= 96109 }110111 const mask = ((1n << BigInt(prefix)) - 1n) << BigInt((isIPv4 ? 32 : 128) - prefix)112113 cidrRules.push([isIPv4, addr & mask, mask] as [boolean, bigint, bigint])114 continue115 }116 }117118 registerStaticRule(rule)119 }120 }121122 return (remote: {123 addr: string124 type: AddressType125 isIPv4: boolean126 binaryAddr?: bigint127 }): boolean => {128 if (staticRules.has(remote.addr)) {129 return true130 }131 const remoteAddr = (remote.binaryAddr ||= (132 remote.isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary133 )(remote.addr))134 const remoteIPv4Addr =135 remote.isIPv4 || isIPv4MappedIPv6(remoteAddr)136 ? remote.isIPv4137 ? remoteAddr138 : convertIPv4MappedIPv6ToIPv4(remoteAddr)139 : undefined140 if ((remote.isIPv4 ? staticIPv4Rules : staticIPv6Rules).has(remoteAddr)) {141 return true142 }143 for (const [isIPv4, addr, mask] of cidrRules) {144 if (isIPv4) {145 if (remoteIPv4Addr === undefined) {146 continue147 }148 if ((remoteIPv4Addr & mask) === addr) {149 return true150 }151 continue152 }153 if (remote.isIPv4) {154 continue155 }156 if ((remoteAddr & mask) === addr) {157 return true158 }159 }160 for (const rule of functionRules) {161 if (rule({ addr: remote.addr, type: remote.type })) {162 return true163 }164 }165 return false166 }167}168169/**170 * Rules for IP Restriction Middleware171 */172export interface IPRestrictionRules {173 denyList?: IPRestrictionRule[]174 allowList?: IPRestrictionRule[]175}176177/**178 * IP Restriction Middleware for Hono.179 *180 * @see {@link https://hono.dev/docs/middleware/builtin/ip-restriction}181 *182 * @param {GetConnInfo | ((c: Context) => string)} getIP - A function to retrieve the client IP address. Use `getConnInfo` from the appropriate runtime adapter.183 * @param {IPRestrictionRules} rules - An object with optional `denyList` and `allowList` arrays of IP rules. Each rule can be a static IP, a CIDR range, or a custom function.184 * @param {(remote: { addr: string; type: AddressType }, c: Context) => Response | Promise<Response>} [onError] - Optional custom handler invoked when a request is blocked. Defaults to returning a 403 Forbidden response.185 * @returns {MiddlewareHandler} The middleware handler function.186 *187 * @example188 * ```ts189 * import { Hono } from 'hono'190 * import { ipRestriction } from 'hono/ip-restriction'191 * import { getConnInfo } from 'hono/cloudflare-workers'192 *193 * const app = new Hono()194 *195 * app.use(196 * '*',197 * ipRestriction(getConnInfo, {198 * // Block a specific IP and an entire subnet199 * denyList: ['192.168.0.5', '10.0.0.0/8'],200 * // Only allow requests from localhost and a private range201 * allowList: ['127.0.0.1', '::1', '192.168.1.0/24'],202 * })203 * )204 *205 * // With a custom error handler206 * app.use(207 * '/admin/*',208 * ipRestriction(209 * getConnInfo,210 * { allowList: ['203.0.113.0/24'] },211 * (remote, c) => c.text(`Access denied for ${remote.addr}`, 403)212 * )213 * )214 *215 * app.get('/', (c) => c.text('Hello!'))216 * ```217 */218export const ipRestriction = (219 getIP: GetIPAddr,220 { denyList = [], allowList = [] }: IPRestrictionRules,221 onError?: (222 remote: { addr: string; type: AddressType },223 c: Context224 ) => Response | Promise<Response>225): MiddlewareHandler => {226 const allowLength = allowList.length227228 const denyMatcher = buildMatcher(denyList)229 const allowMatcher = buildMatcher(allowList)230231 const blockError = (c: Context): HTTPException =>232 new HTTPException(403, {233 res: c.text('Forbidden', {234 status: 403,235 }),236 })237238 return async function ipRestriction(c, next) {239 const connInfo = getIP(c)240 const addr = typeof connInfo === 'string' ? connInfo : connInfo.remote.address241 if (!addr) {242 throw blockError(c)243 }244 const type =245 (typeof connInfo !== 'string' && connInfo.remote.addressType) || distinctRemoteAddr(addr)246247 const remoteData = { addr, type, isIPv4: type === 'IPv4' }248249 try {250 if (denyMatcher(remoteData)) {251 if (onError) {252 return onError({ addr, type }, c)253 }254 throw blockError(c)255 }256 if (allowMatcher(remoteData)) {257 return await next()258 }259 } catch (e) {260 if (261 e instanceof TypeError &&262 (e as InvalidIPAddressError).code === INVALID_IP_ADDRESS_ERROR_CODE263 ) {264 // If an invalid IP address is specified, treat it as if no IP address was specified265 throw blockError(c)266 }267 throw e268 }269270 if (allowLength === 0) {271 return await next()272 } else {273 if (onError) {274 return await onError({ addr, type }, c)275 }276 throw blockError(c)277 }278 }279}