1
+ import ipRangeCheck from "ip-range-check" ;
1
2
import { type NextRequest , NextResponse } from "next/server" ;
2
3
import ProxyCheck from "proxycheck-ts" ;
3
4
@@ -10,6 +11,7 @@ import {
10
11
BLOCKED_REGIONS ,
11
12
GOVERNANCE_ONLY_REGIONS ,
12
13
PROXYCHECK_API_KEY ,
14
+ IP_ALLOWLIST ,
13
15
} from "./config/server" ;
14
16
15
17
const GEO_BLOCKED_PATH = `/${ GEO_BLOCKED_SEGMENT } ` ;
@@ -21,22 +23,32 @@ const proxyCheckClient = PROXYCHECK_API_KEY
21
23
: undefined ;
22
24
23
25
export 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 ;
32
30
} 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
+ }
34
42
}
35
43
} ;
36
44
37
45
const rewrite = ( request : NextRequest , path : string ) =>
38
46
NextResponse . rewrite ( new URL ( path , request . url ) ) ;
39
47
48
+ const isIpAllowlisted = ( { ip } : NextRequest ) =>
49
+ ip !== undefined &&
50
+ IP_ALLOWLIST . some ( ( allowedRange ) => ipRangeCheck ( ip , allowedRange ) ) ;
51
+
40
52
const isGovernanceOnlyRegion = ( { geo } : NextRequest ) =>
41
53
geo ?. country !== undefined &&
42
54
GOVERNANCE_ONLY_REGIONS . includes ( geo . country . toLowerCase ( ) ) ;
0 commit comments