1+ import ipRangeCheck from "ip-range-check" ;
12import { type NextRequest , NextResponse } from "next/server" ;
23import ProxyCheck from "proxycheck-ts" ;
34
@@ -10,6 +11,7 @@ import {
1011 BLOCKED_REGIONS ,
1112 GOVERNANCE_ONLY_REGIONS ,
1213 PROXYCHECK_API_KEY ,
14+ IP_ALLOWLIST ,
1315} from "./config/server" ;
1416
1517const GEO_BLOCKED_PATH = `/${ GEO_BLOCKED_SEGMENT } ` ;
@@ -21,22 +23,32 @@ const proxyCheckClient = PROXYCHECK_API_KEY
2123 : undefined ;
2224
2325export const middleware = async ( request : NextRequest ) => {
24- if ( await isProxyBlocked ( request ) ) {
25- return rewrite ( request , VPN_BLOCKED_PATH ) ;
26- } else if ( isGovernanceOnlyRegion ( request ) ) {
27- return rewrite ( request , GOVERNANCE_ONLY_PATH ) ;
28- } else if ( isRegionBlocked ( request ) ) {
29- return rewrite ( request , GEO_BLOCKED_PATH ) ;
30- } else if ( isBlockedSegment ( request ) ) {
31- return rewrite ( request , "/not-found" ) ;
26+ if ( isIpAllowlisted ( request ) ) {
27+ return isBlockedSegment ( request )
28+ ? rewrite ( request , "/not-found" )
29+ : undefined ;
3230 } else {
33- return ;
31+ if ( await isProxyBlocked ( request ) ) {
32+ return rewrite ( request , VPN_BLOCKED_PATH ) ;
33+ } else if ( isGovernanceOnlyRegion ( request ) ) {
34+ return rewrite ( request , GOVERNANCE_ONLY_PATH ) ;
35+ } else if ( isRegionBlocked ( request ) ) {
36+ return rewrite ( request , GEO_BLOCKED_PATH ) ;
37+ } else if ( isBlockedSegment ( request ) ) {
38+ return rewrite ( request , "/not-found" ) ;
39+ } else {
40+ return ;
41+ }
3442 }
3543} ;
3644
3745const rewrite = ( request : NextRequest , path : string ) =>
3846 NextResponse . rewrite ( new URL ( path , request . url ) ) ;
3947
48+ const isIpAllowlisted = ( { ip } : NextRequest ) =>
49+ ip !== undefined &&
50+ IP_ALLOWLIST . some ( ( allowedRange ) => ipRangeCheck ( ip , allowedRange ) ) ;
51+
4052const isGovernanceOnlyRegion = ( { geo } : NextRequest ) =>
4153 geo ?. country !== undefined &&
4254 GOVERNANCE_ONLY_REGIONS . includes ( geo . country . toLowerCase ( ) ) ;
0 commit comments