constfs=require('fs');functionlogin(username,password){// Validate the username and passwordif(username==='admin'&&password==='password123'){// Log the successful loginfs.appendFileSync('logs.txt',`Successful login: ${username}`);returntrue;}else{// Log the failed loginfs.appendFileSync('logs.txt',`Failed login: ${username}`);returnfalse;}}
✅ compliance
constfs=require('fs');functionlogin(username,password){// Validate the username and passwordif(username==='admin'&&password==='password123'){// Log the successful login without sensitive informationfs.appendFileSync('logs.txt','Successful login');returntrue;}else{// Log the failed login without sensitive informationfs.appendFileSync('logs.txt','Failed login');returnfalse;}}
Insertion of Sensitive Information Into Sent Data
🐞 non-compliance
constexpress=require('express');constapp=express();app.get('/user',(req,res)=>{constuserId=req.query.id;constuserData=getUserData(userId);// Include sensitive information in the responseres.json({id:userId,username:userData.username,email:userData.email,password:userData.password});});app.listen(3000,()=>{console.log('Server is running on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();app.get('/user',(req,res)=>{constuserId=req.query.id;constuserData=getUserData(userId);// Exclude sensitive information from the responseconst{id,username,email}=userData;res.json({id,username,email});});app.listen(3000,()=>{console.log('Server is running on port 3000');});
Cross-Site Request Forgery (CSRF)
🐞 non-compliance
constexpress=require('express');constapp=express();app.get('/transfer-money',(req,res)=>{constamount=req.query.amount;consttoAccount=req.query.to;// Transfer money to the specified accounttransferMoney(amount,toAccount);res.send('Money transferred successfully!');});app.listen(3000,()=>{console.log('Server is running on port 3000');});
✅ compliance
constexpress=require('express');constcsrf=require('csurf');constapp=express();// Enable CSRF protection middlewareconstcsrfProtection=csrf({cookie:true});// Generate and send CSRF token to the clientapp.get('/csrf-token',csrfProtection,(req,res)=>{res.json({csrfToken:req.csrfToken()});});// Transfer money only for valid CSRF-protected requestsapp.post('/transfer-money',csrfProtection,(req,res)=>{constamount=req.body.amount;consttoAccount=req.body.to;// Transfer money to the specified accounttransferMoney(amount,toAccount);res.send('Money transferred successfully!');});app.listen(3000,()=>{console.log('Server is running on port 3000');});
Use of Hard-coded Password
🐞 non-compliance
constbcrypt=require('bcrypt');constsaltRounds=10;constpassword='myHardcodedPassword';bcrypt.hash(password,saltRounds,(err,hash)=>{if(err){console.error('Error hashing password:',err);return;}// Store the hashed password in the databasestorePasswordInDatabase(hash);});
✅ compliance
constbcrypt=require('bcrypt');constsaltRounds=10;functionhashPassword(password,callback){bcrypt.hash(password,saltRounds,(err,hash)=>{if(err){console.error('Error hashing password:',err);returncallback(err);}// Store the hashed password in the databasestorePasswordInDatabase(hash,callback);});}// Usageconstpassword='myPassword';hashPassword(password,(err)=>{if(err){console.error('Failed to hash password:',err);return;}console.log('Password hashed and stored successfully');});
constbcrypt=require('bcrypt');constsaltRounds=10;functionhashPassword(password,callback){bcrypt.hash(password,saltRounds,(err,hash)=>{if(err){console.error('Error hashing password:',err);returncallback(err);}returncallback(null,hash);});}// Usageconstpassword='myPassword';hashPassword(password,(err,hashedPassword)=>{if(err){console.error('Failed to hash password:',err);return;}console.log('Hashed password:',hashedPassword);});
Insufficient Entropy
🐞 non-compliance
functiongenerateApiKey(){constlength=32;constchars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';letapiKey='';for(leti=0;i<length;i++){constrandomIndex=Math.floor(Math.random()*chars.length);apiKey+=chars.charAt(randomIndex);}returnapiKey;}// UsageconstapiKey=generateApiKey();console.log('Generated API key:',apiKey);
✅ compliance
constcrypto=require('crypto');functiongenerateApiKey(){constlength=32;constbuffer=crypto.randomBytes(length);constapiKey=buffer.toString('hex');returnapiKey;}// UsageconstapiKey=generateApiKey();console.log('Generated API key:',apiKey);
XSS
🐞 non-compliance
constexpress=require('express');constapp=express();app.get('/search',(req,res)=>{constquery=req.query.q;constresponse=`Search results for: ${query}`;res.send(response);});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constxss=require('xss');app.get('/search',(req,res)=>{constquery=req.query.q;constsanitizedQuery=xss(query);constresponse=`Search results for: ${sanitizedQuery}`;res.send(response);});app.listen(3000,()=>{console.log('Server started on port 3000');});
SQL Injection
🐞 non-compliance
constexpress=require('express');constapp=express();constmysql=require('mysql');app.get('/users',(req,res)=>{constuserId=req.query.id;constquery=`SELECT * FROM users WHERE id = ${userId}`;// Execute the SQL query and return the resultsconstconnection=mysql.createConnection({host:'localhost',user:'root',password:'password',database:'mydb'});connection.query(query,(error,results)=>{if(error)throwerror;res.json(results);});});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constmysql=require('mysql');app.get('/users',(req,res)=>{constuserId=req.query.id;constquery='SELECT * FROM users WHERE id = ?';constconnection=mysql.createConnection({host:'localhost',user:'root',password:'password',database:'mydb'});connection.query(query,[userId],(error,results)=>{if(error)throwerror;res.json(results);});});app.listen(3000,()=>{console.log('Server started on port 3000');});
External Control of File Name or Path
🐞 non-compliance
constexpress=require('express');constapp=express();constfs=require('fs');app.get('/download',(req,res)=>{constfileName=req.query.file;constfilePath=`/path/to/files/${fileName}`;fs.readFile(filePath,(err,data)=>{if(err){res.status(404).send('File not found');}else{res.setHeader('Content-Disposition',`attachment; filename=${fileName}`);res.send(data);}});});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constfs=require('fs');constpath=require('path');app.get('/download',(req,res)=>{constfileName=req.query.file;constsanitizedFileName=path.basename(fileName);// Sanitize the file nameconstfilePath=path.join('/path/to/files',sanitizedFileName);fs.readFile(filePath,(err,data)=>{if(err){res.status(404).send('File not found');}else{res.setHeader('Content-Disposition',`attachment; filename=${sanitizedFileName}`);res.send(data);}});});app.listen(3000,()=>{console.log('Server started on port 3000');});
Generation of Error Message Containing Sensitive Information
🐞 non-compliance
constexpress=require('express');constapp=express();app.get('/user/:id',(req,res)=>{constuserId=req.params.id;constuser=getUserFromDatabase(userId);if(!user){thrownewError(`User ${userId} not found`);// Noncompliant: Error message contains sensitive information}res.send(user);});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();app.get('/user/:id',(req,res)=>{constuserId=req.params.id;constuser=getUserFromDatabase(userId);if(!user){res.status(404).send('User not found');// Compliant: Generic error message without sensitive informationreturn;}res.send(user);});app.listen(3000,()=>{console.log('Server started on port 3000');});
unprotected storage of credentials
🐞 non-compliance
constexpress=require('express');constapp=express();letdatabaseCredentials={username:'admin',password:'secretpassword'};app.post('/login',(req,res)=>{const{username,password}=req.body;if(username===databaseCredentials.username&&password===databaseCredentials.password){res.send('Login successful');}else{res.send('Invalid credentials');}});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();// These credentials should be stored securely, such as environment variables or a separate configuration file.constdatabaseCredentials={username:process.env.DB_USERNAME,password:process.env.DB_PASSWORD};app.post('/login',(req,res)=>{const{username,password}=req.body;if(username===databaseCredentials.username&&password===databaseCredentials.password){res.send('Login successful');}else{res.send('Invalid credentials');}});app.listen(3000,()=>{console.log('Server started on port 3000');});
Trust Boundary Violation
🐞 non-compliance
constexpress=require('express');constapp=express();app.post('/submitForm',(req,res)=>{constisAdmin=req.body.isAdmin;if(isAdmin){// Perform privileged operationgrantAdminAccess();}else{// Process user requestprocessUserRequest();}res.send('Form submitted successfully');});functiongrantAdminAccess(){// Code to grant admin access// ...}functionprocessUserRequest(){// Code to process user request// ...}app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();app.post('/submitForm',(req,res)=>{constisAdmin=Boolean(req.body.isAdmin);if(isAdmin){// Verify user authentication and authorization before granting admin accessauthenticateAndAuthorizeUser(req).then(()=>{grantAdminAccess();res.send('Admin access granted');}).catch(()=>{res.status(403).send('Access denied');});}else{// Process user requestprocessUserRequest();res.send('Form submitted successfully');}});functiongrantAdminAccess(){// Code to grant admin access// ...}functionprocessUserRequest(){// Code to process user request// ...}functionauthenticateAndAuthorizeUser(req){// Perform user authentication and authorization// ...// Return a promise that resolves if the user is authenticated and authorized, or rejects otherwise}app.listen(3000,()=>{console.log('Server started on port 3000');});
Insufficiently Protected Credentials
🐞 non-compliance
constexpress=require('express');constapp=express();app.post('/login',(req,res)=>{constusername=req.body.username;constpassword=req.body.password;// Store the credentials in plain textstoreCredentials(username,password);// Perform authenticationconstisAuthenticated=authenticate(username,password);if(isAuthenticated){res.send('Login successful');}else{res.send('Login failed');}});functionstoreCredentials(username,password){// Code to store credentials (noncompliant)// ...}functionauthenticate(username,password){// Code to authenticate user// ...}app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constbcrypt=require('bcrypt');constapp=express();constsaltRounds=10;app.post('/login',async(req,res)=>{constusername=req.body.username;constpassword=req.body.password;// Hash the passwordconsthashedPassword=awaithashPassword(password);// Store the hashed passwordstoreCredentials(username,hashedPassword);// Perform authenticationconstisAuthenticated=awaitauthenticate(username,password);if(isAuthenticated){res.send('Login successful');}else{res.send('Login failed');}});asyncfunctionhashPassword(password){// Hash the password using bcryptconstsalt=awaitbcrypt.genSalt(saltRounds);consthashedPassword=awaitbcrypt.hash(password,salt);returnhashedPassword;}functionstoreCredentials(username,hashedPassword){// Code to store hashed credentials// ...}asyncfunctionauthenticate(username,password){// Retrieve hashed password from storageconststoredHashedPassword=awaitgetHashedPassword(username);// Compare the provided password with the stored hashed passwordconstisAuthenticated=awaitbcrypt.compare(password,storedHashedPassword);returnisAuthenticated;}asyncfunctiongetHashedPassword(username){// Code to retrieve hashed password from storage// ...}app.listen(3000,()=>{console.log('Server started on port 3000');});
Restriction of XML External Entity Reference
🐞 non-compliance
constexpress=require('express');constapp=express();constbodyParser=require('body-parser');constxml2js=require('xml2js');app.use(bodyParser.text({type:'text/xml'}));app.post('/parse-xml',(req,res)=>{constxmlData=req.body;// Parse the XML dataxml2js.parseString(xmlData,(err,result)=>{if(err){res.status(400).send('Invalid XML data');}else{// Process the XML data// ...res.send('XML data processed successfully');}});});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constbodyParser=require('body-parser');constxml2js=require('xml2js');app.use(bodyParser.text({type:'text/xml'}));app.post('/parse-xml',(req,res)=>{constxmlData=req.body;// Configure the XML parser to disable external entity referencesconstparser=newxml2js.Parser({explicitCharkey:true,explicitRoot:false,explicitArray:false,ignoreAttrs:true,mergeAttrs:false,xmlns:false,allowDtd:false,allowXmlExternalEntities:false,// Disable external entity references});// Parse the XML dataparser.parseString(xmlData,(err,result)=>{if(err){res.status(400).send('Invalid XML data');}else{// Process the XML data// ...res.send('XML data processed successfully');}});});app.listen(3000,()=>{console.log('Server started on port 3000');});
Vulnerable and Outdated Components
🐞 non-compliance
constexpress=require('express');constapp=express();constbodyParser=require('body-parser');constmongo=require('mongo');app.use(bodyParser.json());app.post('/user',(req,res)=>{constuser=req.body;mongo.connect('mongodb://localhost:27017',(err,client)=>{if(err){res.status(500).send('Internal Server Error');}else{constdb=client.db('myapp');db.collection('users').insertOne(user,(err,result)=>{if(err){res.status(500).send('Internal Server Error');}else{res.status(200).send('User created successfully');}});}});});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constbodyParser=require('body-parser');constMongoClient=require('mongodb').MongoClient;app.use(bodyParser.json());app.post('/user',(req,res)=>{constuser=req.body;MongoClient.connect('mongodb://localhost:27017',{useUnifiedTopology:true},(err,client)=>{if(err){console.error(err);res.status(500).send('Database connection error');}else{constdb=client.db('myapp');db.collection('users').insertOne(user,(err,result)=>{if(err){console.error(err);res.status(500).send('User creation error');}else{res.status(200).send('User created successfully');}client.close();// Close the database connection});}});});app.listen(3000,()=>{console.log('Server started on port 3000');});
Improper Validation of Certificate with Host Mismatch
consthttps=require('https');consttls=require('tls');constoptions={hostname:'example.com',port:443,path:'/',method:'GET',checkServerIdentity:(host,cert)=>{consterr=tls.checkServerIdentity(host,cert);if(err){throwerr;// Terminate the connection on certificate mismatch}},};constreq=https.request(options,(res)=>{res.on('data',(data)=>{console.log(data.toString());});});req.end();
Improper Authentication
🐞 non-compliance
constexpress=require('express');constapp=express();app.post('/login',(req,res)=>{constusername=req.body.username;constpassword=req.body.password;if(username==='admin'&&password==='admin123'){// Successful authenticationres.send('Login successful!');}else{// Failed authenticationres.send('Invalid username or password!');}});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constbcrypt=require('bcrypt');// Mock user dataconstusers=[{username:'admin',password:'$2b$10$rZrVJnI1.Y9OyK6ZrLqmguXHBXYTNcIQ00CJQc8XU1gYRGmdxcqzK',// Hashed password: "admin123"},];app.use(express.json());app.post('/login',(req,res)=>{constusername=req.body.username;constpassword=req.body.password;constuser=users.find((user)=>user.username===username);if(!user){// User not foundreturnres.status(401).send('Invalid username or password!');}bcrypt.compare(password,user.password,(err,result)=>{if(err){// Error during password comparisonreturnres.status(500).send('Internal Server Error');}if(result){// Successful authenticationres.send('Login successful!');}else{// Failed authenticationres.status(401).send('Invalid username or password!');}});});app.listen(3000,()=>{console.log('Server started on port 3000');});
Session Fixation
🐞 non-compliance
constexpress=require('express');constsession=require('express-session');constapp=express();app.use(session({secret:'insecuresecret',resave:false,saveUninitialized:true,}));app.get('/login',(req,res)=>{// Generate a new session ID and store it in the session cookiereq.session.regenerate(()=>{req.session.userId='admin';res.send('Logged in!');});});app.get('/profile',(req,res)=>{// Accessing the profile without authenticationconstuserId=req.session.userId;if(userId){res.send(`Welcome, ${userId}!`);}else{res.send('Please log in!');}});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constsession=require('express-session');constcrypto=require('crypto');constapp=express();app.use(session({secret:'securesecret',resave:false,saveUninitialized:true,genid:()=>{// Generate a unique session IDreturncrypto.randomBytes(16).toString('hex');},}));app.get('/login',(req,res)=>{// Regenerate session ID to prevent session fixationreq.session.regenerate(()=>{req.session.userId='admin';res.send('Logged in!');});});app.get('/profile',(req,res)=>{// Accessing the profile without authenticationconstuserId=req.session.userId;if(userId){res.send(`Welcome, ${userId}!`);}else{res.send('Please log in!');}});app.listen(3000,()=>{console.log('Server started on port 3000');});
Inclusion of Functionality from Untrusted Control
🐞 non-compliance
constexpress=require('express');constapp=express();app.get('/dynamic',(req,res)=>{constfunctionName=req.query.function;// Execute the specified function from untrusted user inputeval(functionName);});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();app.get('/dynamic',(req,res)=>{constfunctionName=req.query.function;// Validate the function name against a whitelistif(isFunctionAllowed(functionName)){// Call the allowed function from a predefined setconstresult=callAllowedFunction(functionName);res.send(result);}else{res.status(400).send('Invalid function');}});app.listen(3000,()=>{console.log('Server started on port 3000');});functionisFunctionAllowed(functionName){// Check if the function name is in the allowed setconstallowedFunctions=['function1','function2','function3'];returnallowedFunctions.includes(functionName);}functioncallAllowedFunction(functionName){// Implement the logic for each allowed functionif(functionName==='function1'){return'Function 1 called';}elseif(functionName==='function2'){return'Function 2 called';}elseif(functionName==='function3'){return'Function 3 called';}}
Download of Code Without Integrity Check
🐞 non-compliance
constexpress=require('express');constapp=express();app.get('/download',(req,res)=>{constfileName=req.query.filename;// Download the file without integrity checkres.download(fileName);});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constfs=require('fs');constcrypto=require('crypto');app.get('/download',(req,res)=>{constfileName=req.query.filename;// Read the file contentsfs.readFile(fileName,(err,data)=>{if(err){res.status(404).send('File not found');return;}// Calculate the file's hashconstfileHash=crypto.createHash('sha256').update(data).digest('hex');// Perform integrity checkif(isFileIntegrityValid(fileHash)){// Download the fileres.download(fileName);}else{res.status(403).send('Integrity check failed');}});});app.listen(3000,()=>{console.log('Server started on port 3000');});functionisFileIntegrityValid(fileHash){// Compare the calculated hash with a trusted hashconsttrustedHash='...';// Replace with the trusted hashreturnfileHash===trustedHash;}
Deserialization of Untrusted Data
🐞 non-compliance
constexpress=require('express');constapp=express();constbodyParser=require('body-parser');constdeserialize=require('deserialize');// Middleware to parse JSON dataapp.use(bodyParser.json());app.post('/user',(req,res)=>{constuserData=req.body;// Deserialize user data without validationconstuser=deserialize(userData);// Process user data// ...res.status(200).send('User data processed successfully');});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constbodyParser=require('body-parser');constvalidateUser=require('./validateUser');// Middleware to parse JSON dataapp.use(bodyParser.json());app.post('/user',(req,res)=>{constuserData=req.body;// Validate user dataconstvalidationResult=validateUser(userData);if(validationResult.isValid){// Sanitize user dataconstsanitizedData=sanitizeUserData(validationResult.data);// Deserialize user dataconstuser=deserialize(sanitizedData);// Process user data// ...res.status(200).send('User data processed successfully');}else{res.status(400).send('Invalid user data');}});app.listen(3000,()=>{console.log('Server started on port 3000');});
Insufficient Logging
🐞 non-compliance
constexpress=require('express');constapp=express();app.get('/user/:id',(req,res)=>{constuserId=req.params.id;// Fetch user from the databaseconstuser=db.getUser(userId);// Return user detailsres.status(200).json(user);});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constlogger=require('winston');// Configure loggerlogger.configure({transports:[newlogger.transports.Console(),newlogger.transports.File({filename:'app.log'})]});app.get('/user/:id',(req,res)=>{constuserId=req.params.id;// Log the user retrieval eventlogger.info(`User retrieval requested for id: ${userId}`);// Fetch user from the databaseconstuser=db.getUser(userId);if(user){// Log successful user retrievallogger.info(`User retrieved successfully: ${user.name}`);// Return user detailsres.status(200).json(user);}else{// Log unsuccessful user retrievallogger.warn(`User not found for id: ${userId}`);// Return appropriate error responseres.status(404).json({error:'User not found'});}});app.listen(3000,()=>{console.log('Server started on port 3000');});
Improper Output Neutralization for Logs
🐞 non-compliance
constexpress=require('express');constapp=express();constfs=require('fs');app.get('/user/:id',(req,res)=>{constuserId=req.params.id;// Log the user retrieval eventconstlogMessage=`User retrieval requested for id: ${userId}`;fs.appendFile('app.log',logMessage,(err)=>{if(err){console.error('Error writing to log file:',err);}});// Fetch user from the databaseconstuser=db.getUser(userId);// Return user detailsres.status(200).json(user);});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();constfs=require('fs');const{sanitizeLogMessage}=require('./utils');app.get('/user/:id',(req,res)=>{constuserId=req.params.id;// Log the user retrieval eventconstlogMessage=`User retrieval requested for id: ${sanitizeLogMessage(userId)}`;fs.appendFile('app.log',logMessage,(err)=>{if(err){console.error('Error writing to log file:',err);}});// Fetch user from the databaseconstuser=db.getUser(userId);// Return user detailsres.status(200).json(user);});app.listen(3000,()=>{console.log('Server started on port 3000');});
Omission of Security-relevant Information
🐞 non-compliance
constexpress=require('express');constapp=express();app.post('/login',(req,res)=>{constusername=req.body.username;constpassword=req.body.password;// Perform login logicif(loggedIn){res.status(200).send('Login successful');}else{res.status(401).send('Invalid credentials');}});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();app.post('/login',(req,res)=>{constusername=req.body.username;constpassword=req.body.password;// Perform login logicif(loggedIn){res.status(200).send('Login successful');}else{console.error(`Login failed for username: ${username}`);res.status(401).send('Invalid username or password');}});app.listen(3000,()=>{console.log('Server started on port 3000');});
Sensitive Information into Log File
🐞 non-compliance
constexpress=require('express');constapp=express();app.get('/user/:id',(req,res)=>{constuserId=req.params.id;// Fetch user information from the databaseconstuser=User.findById(userId);// Log user informationconsole.log(`User information: ${user}`);res.status(200).json(user);});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constapp=express();app.get('/user/:id',(req,res)=>{constuserId=req.params.id;// Fetch user information from the databaseconstuser=User.findById(userId);// Log a generic message instead of sensitive informationconsole.log(`User requested: ${userId}`);res.status(200).json(user);});app.listen(3000,()=>{console.log('Server started on port 3000');});
Server-Side Request Forgery (SSRF)
🐞 non-compliance
constexpress=require('express');constaxios=require('axios');constapp=express();app.get('/fetch',(req,res)=>{consturl=req.query.url;// Make a request to the provided URLaxios.get(url).then(response=>{res.status(200).json(response.data);}).catch(error=>{res.status(500).json({error:'An error occurred while fetching the URL'});});});app.listen(3000,()=>{console.log('Server started on port 3000');});
✅ compliance
constexpress=require('express');constaxios=require('axios');const{URL}=require('url');constapp=express();app.get('/fetch',(req,res)=>{consturl=req.query.url;// Validate the URL to ensure it is not an internal resourceconstparsedUrl=newURL(url);if(parsedUrl.hostname!=='example.com'){returnres.status(400).json({error:'Invalid URL'});}// Make a request to the provided URLaxios.get(url).then(response=>{res.status(200).json(response.data);}).catch(error=>{res.status(500).json({error:'An error occurred while fetching the URL'});});});app.listen(3000,()=>{console.log('Server started on port 3000');});