@@ -49,6 +49,31 @@ function logRequest(entry: LogEntry) {
4949
5050// --- Main Handler ---
5151
52+ function validateRequest ( url : URL ) : NextResponse | null {
53+ // Validate Query String Length
54+ if ( url . search . length > MAX_QUERY_STRING_LENGTH ) {
55+ return new NextResponse ( 'Query string too long' , { status : 414 } ) ;
56+ }
57+
58+ // Validate Domain Name (if present in 'name' param for JSON API)
59+ const nameParam = url . searchParams . get ( 'name' ) ;
60+
61+ // Strict Validation for 'name' param
62+ // If name parameter exists (even if empty), it must be valid and non-empty
63+ if ( url . searchParams . has ( 'name' ) ) {
64+ if ( ! nameParam || nameParam . length === 0 ) {
65+ return new NextResponse ( 'Invalid domain: empty' , { status : 400 } ) ;
66+ }
67+ if ( nameParam . length > 253 ) {
68+ return new NextResponse ( 'Invalid domain: too long' , { status : 400 } ) ;
69+ }
70+ if ( ! ALLOWED_DOMAIN_REGEX . test ( nameParam ) ) {
71+ return new NextResponse ( 'Invalid domain: invalid characters' , { status : 400 } ) ;
72+ }
73+ }
74+ return null ;
75+ }
76+
5277async function handleDoH ( request : NextRequest , providerId : string ) {
5378 const startTime = Date . now ( ) ;
5479 let upstreamEndpoint = '' ;
@@ -57,31 +82,10 @@ async function handleDoH(request: NextRequest, providerId: string) {
5782 try {
5883 // 1. Input Validation
5984 const url = new URL ( request . url ) ;
60-
61- // Validate Query String Length
62- if ( url . search . length > MAX_QUERY_STRING_LENGTH ) {
63- responseStatus = 414 ;
64- return new NextResponse ( 'Query string too long' , { status : 414 } ) ;
65- }
66-
67- // Validate Domain Name (if present in 'name' param for JSON API)
68- const nameParam = url . searchParams . get ( 'name' ) ;
69-
70- // Strict Validation for 'name' param
71- // If name parameter exists (even if empty), it must be valid and non-empty
72- if ( url . searchParams . has ( 'name' ) ) {
73- if ( ! nameParam || nameParam . length === 0 ) {
74- responseStatus = 400 ;
75- return new NextResponse ( 'Invalid domain: empty' , { status : 400 } ) ;
76- }
77- if ( nameParam . length > 253 ) {
78- responseStatus = 400 ;
79- return new NextResponse ( 'Invalid domain: too long' , { status : 400 } ) ;
80- }
81- if ( ! ALLOWED_DOMAIN_REGEX . test ( nameParam ) ) {
82- responseStatus = 400 ;
83- return new NextResponse ( 'Invalid domain: invalid characters' , { status : 400 } ) ;
84- }
85+ const validationError = validateRequest ( url ) ;
86+ if ( validationError ) {
87+ responseStatus = validationError . status ;
88+ return validationError ;
8589 }
8690
8791 // 2. Provider Logic
0 commit comments