-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
153 lines (126 loc) · 5.46 KB
/
Copy pathapp.py
File metadata and controls
153 lines (126 loc) · 5.46 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
"""
Flask API for the Model Forecast Viewer.
Slim entry point — all route logic lives in the routes/ package.
"""
import os
import re
import logging
from flask import Flask, send_from_directory, request, abort
from flask_cors import CORS
from flask_talisman import Talisman
import routes
FRONTEND_DIR = os.path.join(os.path.dirname(__file__), "frontend", "dist")
log = logging.getLogger(__name__)
def _running_in_managed_production():
return bool(
os.environ.get("K_SERVICE")
or os.environ.get("RENDER")
or os.environ.get("SPACE_ID")
or os.environ.get("APP_ENV") == "production"
or os.environ.get("FLASK_ENV") == "production"
)
# ─── Allowed origins ───────────────────────────────────────
ALLOWED_ORIGINS = [
"https://modelforecastpy.app",
"https://www.modelforecastpy.app",
"https://shianmike.github.io",
]
if not _running_in_managed_production():
ALLOWED_ORIGINS += [
"http://localhost:3000",
"http://localhost:3001",
"http://localhost:3002",
"http://localhost:5001",
"http://127.0.0.1:3000",
"http://127.0.0.1:3001",
"http://127.0.0.1:3002",
"http://127.0.0.1:5001",
]
app = Flask(__name__, static_folder=FRONTEND_DIR, static_url_path="")
# ─── CORS ──────────────────────────────────────────────────
CORS(app, resources={r"/api/*": {"origins": ALLOWED_ORIGINS}}, supports_credentials=False)
# ─── Runtime flags ─────────────────────────────────────────
_is_production = _running_in_managed_production()
_force_https = bool(os.environ.get("K_SERVICE"))
# ─── Security headers via Talisman ─────────────────────────
csp = {
"default-src": "'self'",
"script-src": "'self'",
"style-src": "'self' 'unsafe-inline' https://fonts.googleapis.com",
"font-src": "'self' https://fonts.gstatic.com data:",
"img-src": "'self' data: blob: https://*.basemaps.cartocdn.com https://*.tile.openstreetmap.org "
"https://server.arcgisonline.com https://tilecache.rainviewer.com",
"connect-src": "'self' https://api.open-meteo.com https://archive-api.open-meteo.com "
"https://ensemble-api.open-meteo.com https://api.rainviewer.com "
"https://*.basemaps.cartocdn.com https://*.tile.openstreetmap.org "
"https://server.arcgisonline.com https://tilecache.rainviewer.com "
"https://modelforecastpy.app https://www.modelforecastpy.app "
"https://*.hf.space https://*.onrender.com "
"https://*.run.app",
"media-src": "'self' blob:",
"frame-ancestors": "'none'",
"base-uri": "'self'",
"form-action": "'self'",
"object-src": "'none'",
}
Talisman(
app,
force_https=_force_https,
force_https_permanent=False,
strict_transport_security=True,
strict_transport_security_max_age=63072000,
strict_transport_security_include_subdomains=True,
strict_transport_security_preload=True,
content_security_policy=csp,
content_security_policy_nonce_in=["script-src"],
referrer_policy="strict-origin-when-cross-origin",
frame_options="DENY",
permissions_policy={
"geolocation": "()",
"camera": "()",
"microphone": "()",
"payment": "()",
},
session_cookie_secure=_is_production,
session_cookie_http_only=True,
session_cookie_samesite="Lax",
)
@app.after_request
def add_extra_security_headers(response):
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
response.headers["Cross-Origin-Resource-Policy"] = "same-origin"
if request.path.startswith("/api/"):
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
return response
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024
@app.before_request
def block_path_traversal():
if ".." in request.path or re.search(r"[<>\"';\x00]", request.path):
abort(400)
# Register all API blueprints
routes.register_all(app)
# ─── SPA catch-all ─────────────────────────────────────────
@app.route("/ModelForecast/", defaults={"path": ""})
@app.route("/ModelForecast/<path:path>")
def serve_spa_prefixed(path):
file_path = os.path.join(FRONTEND_DIR, path)
if path and os.path.isfile(file_path):
return send_from_directory(FRONTEND_DIR, path)
return send_from_directory(FRONTEND_DIR, "index.html")
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def serve_spa(path):
file_path = os.path.join(FRONTEND_DIR, path)
if path and os.path.isfile(file_path):
return send_from_directory(FRONTEND_DIR, path)
return send_from_directory(FRONTEND_DIR, "index.html")
if __name__ == "__main__":
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
log.info("Starting Model Forecast API on http://localhost:5001")
app.run(debug=True, port=5001)