-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
233 lines (178 loc) · 6.51 KB
/
Copy pathapp.py
File metadata and controls
233 lines (178 loc) · 6.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""
CellSeeU Flask Application
Main entry point for the web dashboard. Implements security best practices
including HTTPS enforcement, security headers, input validation, and rate limiting.
Run with: flask run --host=0.0.0.0 --port=5000
Or: python app.py
"""
import os
from flask import Flask, render_template, jsonify, request
from flask_cors import CORS
from flask_talisman import Talisman
from dotenv import load_dotenv
from datetime import datetime, timezone
# Import API blueprint
from src.dashboard.routes import api as api_blueprint
# Load environment variables from .env file
load_dotenv()
# Initialize Flask app
app = Flask(__name__)
# Load configuration from environment
app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET_KEY', 'dev-secret-change-in-production')
app.config['ENV'] = os.getenv('FLASK_ENV', 'development')
app.config['DEBUG'] = os.getenv('FLASK_DEBUG', 'False').lower() == 'true'
# CORS configuration - Allow API access from mobile app
# In production, restrict this to specific origins
CORS(app, resources={
r"/api/*": {
"origins": os.getenv('ALLOWED_ORIGINS', '*').split(',')
}
})
# Security headers with Talisman
# Disabled in development for easier testing, enabled in production
if app.config['ENV'] == 'production':
# Enforce HTTPS and set Content Security Policy
# CSP allows maps from external services while blocking inline scripts
Talisman(app,
force_https=True,
strict_transport_security=True,
strict_transport_security_max_age=31536000, # 1 year
content_security_policy={
'default-src': ["'self'"],
'script-src': ["'self'", 'unpkg.com', 'cdn.jsdelivr.net'], # For Leaflet.js
'style-src': ["'self'", "'unsafe-inline'", 'unpkg.com', 'cdn.jsdelivr.net'],
'img-src': ["'self'", 'data:', '*.tile.openstreetmap.org', '*.basemaps.cartocdn.com'],
'connect-src': ["'self'", 'api.opencellid.org'],
'font-src': ["'self'", 'data:'],
},
content_security_policy_nonce_in=['script-src']
)
# Register API blueprint
app.register_blueprint(api_blueprint)
@app.after_request
def set_security_headers(response):
"""
Add security headers to all responses.
Implements OWASP security best practices:
- X-Content-Type-Options: Prevent MIME-type sniffing
- X-Frame-Options: Prevent clickjacking
- X-XSS-Protection: Enable browser XSS filter
- Strict-Transport-Security: Enforce HTTPS (production only)
Args:
response: Flask response object
Returns:
Modified response with security headers
"""
# Prevent MIME-type sniffing
response.headers['X-Content-Type-Options'] = 'nosniff'
# Prevent clickjacking - don't allow framing
response.headers['X-Frame-Options'] = 'DENY'
# Enable XSS protection (legacy but still useful)
response.headers['X-XSS-Protection'] = '1; mode=block'
# HSTS header - only in production with HTTPS
if app.config['ENV'] == 'production':
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains; preload'
# Referrer policy - don't leak URLs
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
# Permissions policy - disable unnecessary features
response.headers['Permissions-Policy'] = 'geolocation=(self), camera=(), microphone=(), payment=()'
return response
@app.route('/')
def index():
"""
Main dashboard page.
Mobile-first responsive dashboard showing detected cell towers,
device location, and interactive map visualization.
Returns:
Rendered dashboard HTML template
"""
return render_template('dashboard.html')
@app.route('/map')
def map_view():
"""
Full-screen interactive map view.
Displays all detected towers with color-coded markers based on
signal strength and tower type (terrestrial vs satellite).
Returns:
Rendered map HTML template
"""
return render_template('map.html')
@app.route('/wifi')
def wifi_view():
"""
WiFi network detection view.
Displays all detected WiFi networks with signal strength,
security type, and tracking awareness information.
Returns:
Rendered WiFi HTML template
"""
return render_template('wifi.html')
@app.route('/wifi3d')
def wifi3d_view():
"""
WiFi 3D visualization view.
Interactive 3D sphere showing WiFi networks in 3D space around
your device, with signal strength determining distance and
compass heading determining horizontal angle.
Returns:
Rendered WiFi 3D HTML template
"""
return render_template('wifi3d.html')
@app.route('/health')
def health_check():
"""
Health check endpoint for monitoring.
Returns basic app status and version information.
Used by monitoring tools to verify the app is running.
Returns:
JSON with status and version
"""
return jsonify({
'status': 'healthy',
'version': '0.1.0',
'timestamp': datetime.now(timezone.utc).isoformat()
})
@app.errorhandler(404)
def not_found(error):
"""
Handle 404 Not Found errors.
Returns user-friendly JSON response instead of exposing
server details in error pages.
Returns:
JSON error message with 404 status
"""
return jsonify({
'error': 'Resource not found',
'status': 404
}), 404
@app.errorhandler(500)
def internal_error(error):
"""
Handle 500 Internal Server errors.
Logs the actual error server-side but returns generic
message to user to avoid leaking implementation details.
Args:
error: The exception that caused the 500 error
Returns:
JSON error message with 500 status
"""
# TODO: Log error to proper logging system
app.logger.error(f'Internal error: {error}')
return jsonify({
'error': 'Internal server error',
'status': 500
}), 500
if __name__ == '__main__':
# Development server
# In production, use proper WSGI server like gunicorn
port = int(os.getenv('PORT', 5000))
debug = os.getenv('FLASK_DEBUG', 'False').lower() == 'true'
print(f"CellSeeU starting on port {port}")
print(f"Dashboard: http://localhost:{port}")
print(f"Map view: http://localhost:{port}/map")
print(f"Security headers: {'ENABLED' if app.config['ENV'] == 'production' else 'DEVELOPMENT MODE'}")
app.run(
host='0.0.0.0',
port=port,
debug=debug
)