File tree Expand file tree Collapse file tree
projects/client/src/lib/features/bot-verification/utils Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -17,6 +17,7 @@ function makeFetchMock(
1717 const urlStr = String ( url ) ;
1818 if ( urlStr . includes ( 'type=PTR' ) ) {
1919 return Promise . resolve ( {
20+ ok : true ,
2021 json : ( ) =>
2122 Promise . resolve ( {
2223 Answer : ptrHostname
@@ -26,6 +27,7 @@ function makeFetchMock(
2627 } ) ;
2728 }
2829 return Promise . resolve ( {
30+ ok : true ,
2931 json : ( ) =>
3032 Promise . resolve ( {
3133 Answer : aAddress ? [ { data : aAddress } ] : undefined ,
@@ -114,4 +116,12 @@ describe('isLegitimateBot', () => {
114116 ) ;
115117 expect ( await isLegitimateBot ( GOOGLEBOT_UA , '66.249.77.140' ) ) . toBe ( false ) ;
116118 } ) ;
119+
120+ it ( 'should return false when the DoH endpoint returns a non-OK response' , async ( ) => {
121+ vi . stubGlobal (
122+ 'fetch' ,
123+ vi . fn ( ) . mockResolvedValue ( { ok : false , status : 503 } ) ,
124+ ) ;
125+ expect ( await isLegitimateBot ( GOOGLEBOT_UA , '66.249.77.140' ) ) . toBe ( false ) ;
126+ } ) ;
117127} ) ;
Original file line number Diff line number Diff line change @@ -23,11 +23,16 @@ function identifyBotType(userAgent: string): BotType | null {
2323
2424async function reverseIpLookup ( ip : string ) : Promise < string > {
2525 const ptr = ip . split ( '.' ) . reverse ( ) . join ( '.' ) + '.in-addr.arpa' ;
26- const url = `${ DOH_ENDPOINT } ?name=${ ptr } &type=PTR` ;
26+ const url = `${ DOH_ENDPOINT } ?name=${ encodeURIComponent ( ptr ) } &type=PTR` ;
2727
2828 const response = await fetch ( url , {
2929 headers : { accept : 'application/dns-json' } ,
3030 } ) ;
31+
32+ if ( ! response . ok ) {
33+ throw new Error ( `DNS PTR query failed: ${ response . status } ` ) ;
34+ }
35+
3136 const data = await response . json < { Answer ?: { data : string } [ ] } > ( ) ;
3237 const hostname = data . Answer ?. at ( 0 ) ?. data ?. replace ( / \. $ / , '' ) ;
3338
@@ -39,11 +44,16 @@ async function reverseIpLookup(ip: string): Promise<string> {
3944}
4045
4146async function forwardDnsLookup ( hostname : string ) : Promise < string > {
42- const url = `${ DOH_ENDPOINT } ?name=${ hostname } &type=A` ;
47+ const url = `${ DOH_ENDPOINT } ?name=${ encodeURIComponent ( hostname ) } &type=A` ;
4348
4449 const response = await fetch ( url , {
4550 headers : { accept : 'application/dns-json' } ,
4651 } ) ;
52+
53+ if ( ! response . ok ) {
54+ throw new Error ( `DNS A query failed: ${ response . status } ` ) ;
55+ }
56+
4757 const data = await response . json < { Answer ?: { data : string } [ ] } > ( ) ;
4858 const address = data . Answer ?. at ( 0 ) ?. data ;
4959
You can’t perform that action at this time.
0 commit comments