Write instructions for develoeprs OR AI to build the APP described in the below PRD:

==================================

# LetScan Port Scanner - Product Requirements Document

## 1. Introduction

### 1.1 Purpose
This document outlines the requirements for rebuilding the LetScan Port Scanner, a web-based application that allows users to perform network port scans using various scanning techniques.

### 1.2 Scope
The LetScan Port Scanner is a Flask-based web application that integrates with Google OAuth for authentication and uses Nmap for port scanning functionality.

### 1.3 Definitions and Acronyms
- PRD: Product Requirements Document
- OAuth: Open Authorization
- Nmap: Network Mapper
- TCP: Transmission Control Protocol
- UDP: User Datagram Protocol
- SYN: Synchronize (TCP flag)

## 2. Product Overview

### 2.1 Product Description
LetScan Port Scanner is a web application that allows users to perform network port scans on specified targets. It provides a user-friendly interface for initiating scans and viewing results, with features such as different scan types, custom port selection, and optional OS detection.

### 2.2 Target Users
- Network administrators
- Security professionals
- IT enthusiasts

## 3. Features and Requirements

### 3.1 User Authentication
- Implement Google OAuth for user authentication
- Allow users to log in and log out
- Display user's email when logged in

### 3.2 Scanning Interface
- Provide options for scan type selection (TCP, UDP, SYN)
- Allow users to choose between common ports and custom port list
- Implement an input field for custom port lists
- Include an option for OS detection
- Require users to accept terms of service before scanning

### 3.3 Scanning Functionality
- Integrate Nmap for port scanning
- Support TCP, UDP, and SYN scan types
- Allow scanning of common ports or user-specified port lists
- Implement optional OS detection

### 3.4 Results Display
- Show real-time scanning progress
- Display scan results in a tabular format
- Provide different views: Raw Output, Scan Parameters, and Scan Summary
- Include information such as host, port, state, service name, protocol, and OS information (if available)

### 3.5 Error Handling
- Validate input for IP addresses and domain names
- Display appropriate error messages for invalid inputs or failed scans

## 4. Technical Requirements

### 4.1 Backend
- Use Flask as the web framework
- Implement SQLAlchemy for database management
- Integrate Flask-Dance for Google OAuth
- Use Flask-SocketIO for real-time communication

### 4.2 Frontend
- Implement a responsive design using HTML, CSS, and JavaScript
- Use client-side JavaScript for dynamic content updates and form handling

### 4.3 Security
- Implement secure session management
- Ensure proper handling of OAuth tokens
- Validate and sanitize all user inputs

### 4.4 Performance
- Optimize database queries for efficient user and OAuth token management
- Implement efficient real-time updates using WebSockets

## 5. User Interface

### 5.1 Home Page (index.html)
- Display logo and welcome message
- Show login button for unauthenticated users
- Display "Start Scanning" button for authenticated users
- Include sections explaining port scanning and how the app works

### 5.2 Scan Page (scan.html)
- Provide a form for scan configuration:
  - Scan type selection (TCP, UDP, SYN)
  - Port selection (Common or Custom)
  - Custom port input field
  - OS detection option
  - Terms of service checkbox
- Display user's email if logged in
- Show a logout button
- Implement a results section with tabs for different views

## 6. Data Models

### 6.1 User Model
- Fields: id, email

### 6.2 OAuth Model
- Fields: provider, provider_user_id, user_id, token

## 7. API Endpoints

### 7.1 Authentication
- `/login/google`: Google OAuth login
- `/logout`: User logout

### 7.2 Pages
- `/`: Home page
- `/scan`: Scan configuration and results page
- `/term-of-service`: Terms of Service page

### 7.3 WebSocket Events
- `start_scan`: Initiate a new scan
- `scan_progress`: Update scan progress
- `scan_complete`: Notify scan completion
- `scan_error`: Report scan errors

## 8. Non-Functional Requirements

### 8.1 Security
- Implement proper authentication and authorization
- Secure handling of user data and scan results
- Protect against common web vulnerabilities (XSS, CSRF, etc.)

### 8.2 Performance
- Optimize scan execution and result processing
- Ensure responsive UI during scanning operations

### 8.3 Scalability
- Design the application to handle multiple concurrent users and scans

### 8.4 Compliance
- Ensure compliance with relevant data protection regulations
- Implement proper terms of service and user agreements

## 9. Future Considerations

### 9.1 Potential Enhancements
- Support for additional scan types
- Integration with other security tools
- Enhanced result analysis and reporting features
- User-specific scan history and saved configurations



## 10. Appendix

### 10.1 Technology Stack
[... This section remains the same ...]

### 10.2 File Structure
- `__init__.py`: Main application file
- `models.py`: Database models
- `oauth.py`: OAuth configuration
- `config.py`: Application configuration
- `cli.py`: Command-line interface commands
- Templates:
  - `index.html`: Home page
  - `scan.html`: Scan configuration and results page
  - `terms_of_service.html`: Terms of Service page

### 10.3 Directory Structure

```
letscan/
├── static/
│   ├── css/
│   ├── js/
│   └── img/
├── templates/
│   ├── index.html
│   ├── scan.html
│   └── terms_of_service.html
├── __init__.py
├── models.py
├── oauth.py
├── config.py
└── cli.py
```

This structure follows a typical Flask application layout:
- `static/`: Contains all static files (CSS, JavaScript, images)
- `templates/`: Houses all HTML templates
- Python files at the root level define the application's core functionality

### 10.4 Network Scan Implementation

The network scan is performed using the `nmap` library within a WebSocket event handler. Here's the example of core implementation of the scan functionality:

```python
@socketio.on('start_scan')
def handle_scan(data):
    target = data.get('target')
    scan_type = data.get('scan_type')
    ports = data.get('ports')
    osDetection = data.get('os_detection')

    nm = nmap.PortScanner()
    nmap_arguments = '-T4 '

    if osDetection == "on":
        nmap_arguments += '-sV '

    try:
        if ports == "common":
            if scan_type == 'tcp':
                nm.scan(target, arguments=nmap_arguments + '-sT')
            elif scan_type == 'udp':
                nm.scan(target, arguments=nmap_arguments + '-sU')
            elif scan_type == 'syn':
                nm.scan(target, arguments=nmap_arguments + '-sS')
        else:
            port_argument = ','.join(ports.split(','))
            if scan_type == 'tcp':
                nm.scan(target, arguments=nmap_arguments + f'-sT -p {port_argument}')
            elif scan_type == 'udp':
                nm.scan(target, arguments=nmap_arguments + f'-sU -p {port_argument}')
            elif scan_type == 'syn':
                nm.scan(target, arguments=nmap_arguments + f'-sS -p {port_argument}')

        if nm.all_hosts():
            for host in nm.all_hosts():
                host_info = {
                    'host': host,
                    'hostname': nm[host].hostname(),
                    'status': nm[host].state(),
                    'ports': [
                        {
                            'port': port,
                            'state': nm[host][proto][port]['state'],
                            'service': nm[host][proto][port]['name'],
                            'product': nm[host][proto][port].get('product', 'Unknown'),
                            'version': nm[host][proto][port].get('version', 'Unknown'),
                            'protocol': proto
                        } for proto in nm[host].all_protocols() for port in nm[host][proto]
                    ],
                    'os': nm[host].get('osclass', [])
                }
                socketio.emit('scan_progress', host_info)

            socketio.emit('scan_complete', {
                'message': 'Scan complete',
                'summary': {
                    'host': target,
                    'ports': host_info['ports'],
                    'raw_ports': ', '.join([str(port['port']) for port in host_info['ports']]),
                    'hosts': nm.all_hosts(),
                    'startTime': 'N/A',
                    'finishTime': 'N/A',
                    'duration': 'N/A',
                    'os': host_info['os']
                }
            })
        else:
            socketio.emit('scan_error', {'error': 'No hosts found. Please check the target.'})

    except Exception as e:
        error_message = str(e).replace('\n', ' ').strip()
        socketio.emit('scan_error', {'error': error_message})
```

Key points about the scan implementation:
- It uses WebSockets (`socketio`) for real-time communication.
- The scan type (TCP, UDP, SYN) and port selection (common or custom) are configurable.
- OS detection is optional and uses the `-sV` Nmap argument.
- Scan results are emitted in real-time as they are processed.
- Error handling is implemented to catch and report any issues during the scan.

This code should be carefully reviewed and potentially optimized when rebuilding the application, ensuring it meets security and performance requirements.



## 11. Appendix

### 11.1 Technology Stack
- Backend: Python, Flask
- Database: SQLAlchemy (ORM)
- Frontend: HTML, CSS, JavaScript
- Authentication: Google OAuth (Flask-Dance)
- Real-time Communication: Flask-SocketIO
- Network Scanning: Nmap

### 11.2 File Structure
- `__init__.py`: Main application file
- `models.py`: Database models
- `oauth.py`: OAuth configuration
- `config.py`: Application configuration
- `cli.py`: Command-line interface commands
- Templates:
  - `index.html`: Home page
  - `scan.html`: Scan configuration and results page
  - `terms_of_service.html`: Terms of Service page

This PRD provides a comprehensive overview of the LetScan Port Scanner application, detailing its features, technical requirements, and implementation guidelines. Developers can use this document as a reference for rebuilding the application while maintaining its core functionality and user experience.
======================