Refactor React route handling to improve security and clarity; add module docstring, normalize path to prevent directory traversal, and ensure static folder is configured.

This commit is contained in:
voldemort 2025-07-23 01:45:05 +07:00
parent 8940d57b25
commit a2a12b4c49

View File

@ -1,10 +1,13 @@
import sys """Module to handle the React routes."""
import os import os
from flask import Blueprint, send_from_directory, request, render_template import sys
from flask import Blueprint, send_from_directory, render_template
from configs import index_tags from configs import index_tags
if getattr(sys, "frozen", False): # Running as a bundled app if getattr(sys, "frozen", False): # Running as a bundled app
base_path = sys._MEIPASS base_path = getattr(sys, "_MEIPASS", os.path.abspath("."))
else: # Running in a normal Python environment else: # Running in a normal Python environment
base_path = os.path.abspath(".") base_path = os.path.abspath(".")
@ -23,12 +26,23 @@ react_bp = Blueprint(
@react_bp.route("/<path:path>", methods=["GET"]) @react_bp.route("/<path:path>", methods=["GET"])
@react_bp.route("/<path>", methods=["GET"]) @react_bp.route("/<path>", methods=["GET"])
def index(path=""): def index(path=""):
if request.method == "GET": """Handle the index route."""
file_path = os.path.join(react_bp.static_folder, path) # Ensure static_folder is not None
if path != "" and os.path.exists(file_path): if react_bp.static_folder is None:
return send_from_directory(react_bp.static_folder, path) raise ValueError("Static folder is not configured for the blueprint")
elif path.lower() in ["", "cache", "api", "testplayer", "account"]:
data = index_tags.tags.get(path.lower(), index_tags.tags["index"]) # Normalize the path to prevent directory traversal
safe_path = os.path.normpath(path)
file_path = os.path.join(react_bp.static_folder, safe_path)
if path and os.path.exists(file_path):
return send_from_directory(react_bp.static_folder, safe_path)
# Only allow certain paths to render index.html with tags
allowed_paths = ["", "cache", "api", "testplayer", "account"]
if safe_path.lower() in allowed_paths:
data = index_tags.tags.get(safe_path.lower(), index_tags.tags.get("index", {}))
return render_template("index.html", data=data) return render_template("index.html", data=data)
else:
# Fallback: serve index.html for all other routes (SPA)
return send_from_directory(react_bp.static_folder, "index.html") return send_from_directory(react_bp.static_folder, "index.html")