@@ -4,6 +4,11 @@ import ip6addr from 'ip6addr';
44
55const DEV_MODE = process . env ?. [ 'NODE_ENV' ] == 'development' ;
66
7+ interface MaintenanceFile {
8+ whitelist : Array < string > ;
9+ sites : Record < string , boolean > ;
10+ }
11+
712export function maintenanceModePlugin ( maintenanceFilePath : string ) : Plugin {
813 return {
914 onRequest ( { request, fetchAPI, endResponse } ) {
@@ -15,27 +20,36 @@ export function maintenanceModePlugin(maintenanceFilePath: string): Plugin {
1520 return ;
1621 }
1722
23+ const maintFile = getMaintenanceFile ( maintenanceFilePath ) ;
1824 const requestIp = request . headers . get ( 'x-forwarded-for' ) ?. split ( ',' ) [ 0 ] ;
25+ const host = request . headers . get ( 'host' ) || 'default' ;
1926
20- if ( requestIp ) {
21- const allowedIpAddresses = readFileSync ( maintenanceFilePath , {
22- encoding : 'utf-8' ,
23- } ) . split ( ',' ) ;
27+ if ( inMaintenanceMode ( maintFile , host ) ) {
28+ if ( requestIp ) {
29+ if ( isIpInWhiteList ( maintFile . whitelist , requestIp ) ) {
30+ return ;
31+ }
32+ }
2433
25- if ( isIpInWhiteList ( allowedIpAddresses , requestIp ) ) {
26- return ;
27- }
34+ endResponse (
35+ new fetchAPI . Response ( 'In Maintenance Mode' , {
36+ status : 503 ,
37+ } )
38+ ) ;
2839 }
29-
30- endResponse (
31- new fetchAPI . Response ( 'In Maintenance Mode' , {
32- status : 503 ,
33- } )
34- ) ;
3540 } ,
3641 } ;
3742}
3843
44+ const getMaintenanceFile = ( filePath : string ) : MaintenanceFile => {
45+ const fileContents = readFileSync ( filePath , "utf-8" ) ;
46+ return JSON . parse ( fileContents ) as MaintenanceFile ;
47+ } ;
48+
49+ const inMaintenanceMode = ( maintFile : MaintenanceFile , host : string ) : boolean => {
50+ return maintFile . sites [ host ] === true ;
51+ } ;
52+
3953function isCIDR ( str : string ) {
4054 const cidrRegex = / ^ ( ( [ 0 - 9 ] { 1 , 3 } \. ) { 3 } [ 0 - 9 ] { 1 , 3 } | ( [ a - f A - F 0 - 9 : ] + ) ) \/ \d + $ / ;
4155 return cidrRegex . test ( str ) ;
0 commit comments