@@ -22,7 +22,7 @@ import './plugins/instrument';
2222import { ApolloServer , ApolloServerPlugin } from '@apollo/server' ;
2323import { expressMiddleware } from '@apollo/server/express4' ;
2424import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer' ;
25- import express , { Request , Response } from 'express' ;
25+ import express , { NextFunction , Request , Response } from 'express' ;
2626import http from 'http' ;
2727import cors from 'cors' ;
2828import { resolvers } from './resolvers' ;
@@ -477,6 +477,30 @@ export async function startGraphqlServer() {
477477 } ,
478478 wsServer ,
479479 ) ;
480+
481+ /**
482+ * Middleware to handle malformed URIs before they cause URIError
483+ *
484+ * This middleware intercepts requests with potentially malformed URIs and validates
485+ * them before Express tries to decode them. It prevents URIError exceptions by
486+ * catching malformed URLs early and returning a proper 400 Bad Request response.
487+ */
488+ app . use ( ( req : Request , res : Response , next : NextFunction ) => {
489+ try {
490+ // Test if the URL can be properly decoded
491+ decodeURIComponent ( req . url ) ;
492+ next ( ) ;
493+ } catch ( error ) {
494+ if ( error instanceof URIError ) {
495+ return res . status ( 400 ) . json ( {
496+ error : 'Bad Request' ,
497+ message : 'Malformed URI' ,
498+ } ) ;
499+ }
500+ next ( error ) ;
501+ }
502+ } ) ;
503+
480504 app . use ( express . json ( ) ) ;
481505
482506 /**
@@ -486,7 +510,7 @@ export async function startGraphqlServer() {
486510 * This endpoint can be used by load balancers, monitoring tools, and
487511 * container orchestration platforms to verify service availability.
488512 */
489- app . get ( '/health' , ( req : Request , res : Response ) => {
513+ app . get ( '/health' , ( _req : Request , res : Response ) => {
490514 res . status ( 200 ) . json ( { status : 'OK' } ) ;
491515 } ) ;
492516
@@ -563,6 +587,18 @@ export async function startGraphqlServer() {
563587 }
564588 } ) ;
565589
590+ /**
591+ * Handle 404 Not Found errors for all other routes
592+ *
593+ * This middleware catches all requests that don't match any other routes
594+ * and returns a 404 Not Found response. It's a critical component of the
595+ * error handling system that ensures clients receive clear feedback when
596+ * accessing non-existent resources.
597+ */
598+ app . get ( '/*' , ( _req : Request , res : Response ) => {
599+ res . status ( 404 ) . end ( ) ;
600+ } ) ;
601+
566602 // Initialize cache and start the server
567603 await initCache ( context ) ;
568604 await new Promise < void > ( resolve => httpServer . listen ( { port : KADENA_GRAPHQL_API_PORT } , resolve ) ) ;
0 commit comments