A fast, automated API to scan HTML and JavaScript code snippets for potential Cross-Site Scripting (XSS) vulnerabilities. Uses heuristic patterns to identify dangerous coding practices.
This is a security-hardened version that addresses critical vulnerabilities and implements industry best practices for web application security.
- Fast Scanning: Built with FastAPI for high-performance analysis
- Comprehensive Detection: Scans for multiple XSS patterns including:
innerHTMLassignmentsdocument.write()callseval()function usage- Script tag injections
- Inline event handlers
- JavaScript protocol usage
- RESTful API: Simple HTTP endpoints for easy integration
- Authentication: Secure API key-based authentication
- Cloud Deployment: Ready for Vercel serverless deployment
- Hardcoded Secret Key: Replaced with secure random key generation using
secrets.token_hex(32) - Authentication Bypass: Removed demo mode bypass, always validates against database
- Input Validation: Added comprehensive validation for code size and content
- Rate Limiting: Configurable rate limiting (default: 60 requests/minute) to prevent abuse
- Error Handling: Proper error responses without information leakage
- Input Sanitization: Code length limits and malicious pattern detection
- Secure Authentication: No fallback to insecure demo mode
- Comprehensive Logging: Security event monitoring and performance metrics
- Memory Management: Configurable limits to prevent memory exhaustion
- Python 3.8 or higher
- pip package manager
- MongoDB (for API key storage)
- Git
git clone https://github.com/DevToolsConglomerate/xss-scanner
cd xss-scanner-apipip install -r requirements.txtCreate a .env file in the root directory:
# MongoDB Configuration (optional - app runs in demo mode without it)
MONGODB_URI=mongodb://localhost:27017/your_database
# Stripe Configuration (for payments)
STRIPE_API_KEY=your_stripe_api_key
STRIPE_WEBHOOK_SECRET=your_webhook_secret
# API Configuration
API_HOST=0.0.0.0
API_PORT=8000
SECRET_KEY=your-secret-key-here
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:8000Note: The application runs in demo mode without MongoDB, accepting any API key for testing purposes.
- Start MongoDB service
- Create a database called
devtools_conglomerate - Create a collection called
api_keyswith documents like:
{
"key": "your-api-key-here",
"is_active": true,
"created_at": "2024-01-01T00:00:00Z"
}The application now serves both the API and the frontend from a single server:
# Install dependencies
pip install -r requirements.txt
# Start the server (serves API + frontend)
uvicorn main:app --reload --host 0.0.0.0 --port 8000- Frontend:
http://localhost:8000/index.html - API:
http://localhost:8000/scan - API Documentation:
http://localhost:8000/docs - Health Check:
http://localhost:8000/
- Landing page with demo scanner
- User signup/login with API key generation
- Full XSS scanning interface
- RESTful API for integrations
If MongoDB is not configured, the application runs in demo mode:
- Accepts any API key for scanning
- Stores user data in localStorage (browser-based)
- No database required for testing
http://localhost:8000
All API requests require an API key in the header:
X-API-Key: your_api_key_here
- GET
/ - Description: Check if the API is running
- Response:
{
"message": "XSS Scanner API is operational",
"status": "success"
}- POST
/scan - Description: Scan HTML/JavaScript code for XSS vulnerabilities
- Headers:
Content-Type: application/json X-API-Key: your_api_key - Request Body:
{
"code": "your HTML or JavaScript code here"
}- Response:
{
"status": "success",
"vulnerabilities_found": 2,
"vulnerabilities": [
{
"line": 5,
"vulnerability_type": "innerHTML_assignment",
"snippet": "element.innerHTML = userInput",
"confidence": "medium"
},
{
"line": 10,
"vulnerability_type": "eval_function_call",
"snippet": "eval(userInput)",
"confidence": "medium"
}
],
"message": "Scan completed. Found 2 potential vulnerabilities."
}- POST
/stripe-webhook - Description: Handle Stripe payment webhooks
- Headers:
Content-Type: application/json Stripe-Signature: webhook_signature
- Connect Repository: Link your GitHub repository to Vercel
- Configure Build Settings:
- Build Command:
./build.sh - Output Directory:
. - Install Command:
pip install -r requirements.txt
- Build Command:
- Environment Variables: Add your environment variables in Vercel dashboard
- Deploy: Push to main branch or deploy manually
# Install dependencies
pip install -r requirements.txt
# Set environment variables
export MONGODB_URI="your_mongodb_uri"
export STRIPE_API_KEY="your_stripe_key"
# Run with production server
uvicorn main:app --host 0.0.0.0 --port 8000import requests
# API endpoint
url = "http://localhost:8000/scan"
# Headers
headers = {
"Content-Type": "application/json",
"X-API-Key": "your_api_key_here"
}
# Code to scan
payload = {
"code": """
<div id="content"></div>
<script>
var userInput = getQueryParam('input');
document.getElementById('content').innerHTML = userInput;
eval(userInput);
</script>
"""
}
# Make request
response = requests.post(url, json=payload, headers=headers)
result = response.json()
print(f"Vulnerabilities found: {result['vulnerabilities_found']}")
for vuln in result['vulnerabilities']:
print(f"Line {vuln['line']}: {vuln['vulnerability_type']} - {vuln['snippet']}")curl -X POST "http://localhost:8000/scan" \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key_here" \
-d '{
"code": "<script>eval(location.hash.slice(1))</script>"
}'const scanCode = async (code) => {
const response = await fetch('http://localhost:8000/scan', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your_api_key_here'
},
body: JSON.stringify({ code })
});
const result = await response.json();
console.log('Scan result:', result);
};
// Example usage
scanCode('<div innerHTML=userInput></div>');xss-scanner/
βββ main.py # Main FastAPI application
βββ config.py # Application configuration
βββ models.py # Pydantic data models
βββ utils.py # XSS scanner utilities
βββ api/
β βββ vercel_bootstrap.py # Vercel deployment bootstrap
βββ index.html # Landing page
βββ login.html # Login page
βββ signup.html # Signup page
βββ scan.html # Scanner interface
βββ requirements.txt # Python dependencies
βββ build.sh # Vercel build script
βββ deploy_secure.sh # Secure deployment script
βββ security_test.py # Security testing utilities
βββ test_scanner.py # Comprehensive test suite
βββ TODO.md # Development task tracking
βββ README.md # This file
βββ .env # Environment variables (create this)
- Uses type hints for better code clarity
- Comprehensive error handling
- Modular function design
- Detailed documentation strings
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
If you encounter any issues or have questions:
- Check the Issues page
- Review the API documentation at
/docs - Create a new issue with detailed information
- Initial release
- Basic XSS scanning functionality
- FastAPI implementation
- Vercel deployment support
- API key authentication