Cloudflare Tunnel Integration
Relevant source files
The following files were used as context for generating this wiki page:
The Cloudflare Tunnel integration provides a secure method for exposing the locally running Flask application to the public internet. This is achieved by creating a persistent, outbound-only connection to the Cloudflare network, which then proxies incoming public traffic to the local server. This functionality is critical for the project as it supplies a public HTTPS URL, which is a browser requirement for accessing the camera on mobile devices for features like QR code authentication and mobile-based attendance.
The integration eliminates the need for complex network configurations like port forwarding. The system provides multiple launch scripts (both Bash and Python) to automate the process of starting the Flask application and the Cloudflare Tunnel simultaneously.
Sources: README.md:12, INSTALLATION.md:204-207, app.py:1165-1178
System Architecture
The integration's architecture involves a launch script that orchestrates the startup of two key background processes: the Flask web server (app.py) and the cloudflared tunnel client. The cloudflared client establishes a secure tunnel to Cloudflare's edge, which in turn exposes a public, randomly generated trycloudflare.com URL. Any requests to this public URL are securely tunneled to the local Flask application running on http://localhost:5001.
Sources: start_cloudflare.sh:65-80, launcher_cloudflare.py:145-157, app.py:1186-1196
The following diagram illustrates the high-level data flow:
Launch Mechanisms
The project provides three different scripts to initiate the application with the Cloudflare Tunnel. All scripts perform the same core function but are implemented in different languages.
| Script | Language | Key Characteristics |
|---|---|---|
start_cloudflare.sh | Bash | Production-style script with detailed, colored console output. |
start_with_tunnel.sh | Bash | A slightly simpler Bash script with a different output format. |
launcher_cloudflare.py | Python | Manages Flask and cloudflared as subprocesses for more robust control. |
Sources: start_cloudflare.sh, start_with_tunnel.sh, launcher_cloudflare.py
Bash Scripts (start_cloudflare.sh & start_with_tunnel.sh)
Both Bash scripts follow a similar execution logic. They are designed for ease of use in a Linux/macOS environment.
- Check for
cloudflared: The script first verifies if thecloudflaredexecutable is available in the system's PATH. - Cleanup: It kills any previously running instances of the Flask app and
cloudflaredusingpkillto ensure a clean start. - Start Flask App: The
app.pyis executed in the background, with its output redirected to a log file (/tmp/kafebasabasi_flask.log). - Start Tunnel: The
cloudflaredclient is launched, pointing to the local Flask server. - Extract URL: The script monitors the
cloudflaredoutput stream, usinggrepto find and extract the public.trycloudflare.comURL. - Display Info: Once the URL is captured, it is printed to the console along with direct links to key pages like
/authand/admin/login. - Trap Signals: A
cleanupfunction is registered usingtrapto ensure that both the Flask andcloudflaredprocesses are terminated gracefully when the user pressesCTRL+C.
Sources: start_cloudflare.sh:20-25, 34-36, 65, 80-82, start_with_tunnel.sh:26-28, 38-40, 70-78
A key command used in the scripts is:
cloudflared tunnel --url http://localhost:5001
Sources: start_cloudflare.sh:80, start_with_tunnel.sh:38
Python Launcher (launcher_cloudflare.py)
The Python-based launcher provides a more structured and cross-platform compatible way to manage the processes.
- Process Management: It uses Python's
subprocess.Popento runapp.pyandcloudflaredas independent child processes. This allows for programmatic control over their execution. - URL Monitoring: A dedicated thread (
monitor_cloudflared) is started to read thestderrstream of thecloudflaredprocess. It uses a regular expression (re.search) to find and extract the tunnel URL. - Graceful Shutdown: It uses the
signalmodule to register acleanupfunction. WhenSIGINT(Ctrl+C) orSIGTERMis received, this function callsterminate()on both subprocess handles, ensuring they are properly shut down.
Sources: launcher_cloudflare.py:34-52, 83-107, 133-138, 152-157
Startup and Shutdown Flow
The startup and shutdown sequences are designed to be automated and resilient.
Startup Sequence
The following diagram shows the sequence of events when a launch script is executed.
Shutdown Process
All launch scripts implement a graceful shutdown mechanism. A cleanup function is registered to handle SIGINT (Ctrl+C), SIGTERM, and EXIT signals. This function is responsible for terminating both the Flask application process and the cloudflared tunnel process, preventing orphaned processes.
In the Bash scripts, this is achieved with pkill.
# From start_cloudflare.sh
cleanup() {
echo ""
echo -e "${YELLOW}🛑 Shutting down Kafebasabasi...${NC}"
pkill -f "cloudflared tunnel" 2>/dev/null
pkill -f "python3 app.py" 2>/dev/null
echo -e "${GREEN}✅ Cleanup complete. Goodbye!${NC}"
exit 0
}
trap cleanup SIGINT SIGTERM EXIT
Sources: start_cloudflare.sh:20-28
In the Python script, it is handled by terminating the Popen objects.
# From launcher_cloudflare.py
def cleanup(signum=None, frame=None):
"""Cleanup all processes on exit"""
print("\n\n🛑 Shutting down Kafebasabasi...")
if cloudflared_process:
cloudflared_process.terminate()
if flask_process:
flask_process.terminate()
sys.exit(0)
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
Sources: launcher_cloudflare.py:34-52
Configuration and Dependencies
The integration relies on a few key configurations and external dependencies.
cloudflaredExecutable: The primary dependency is thecloudflaredcommand-line tool, which must be installed and accessible in the system'sPATH. The launch scripts include checks to verify its presence before proceeding.- Target URL: The tunnel is hardcoded to point to
http://localhost:5001. This port is configured withinapp.pyas the default listening port for the Flask application. - Installation Instructions: The
INSTALLATION.mdfile provides guidance on how to install thecloudflaredtool on various operating systems (Linux, macOS, Windows).
Sources: start_cloudflare.sh:34-53, launcher_cloudflare.py:54-59, app.py:1186, INSTALLATION.md:209-222
Conclusion
The Cloudflare Tunnel integration is a vital component of the project's infrastructure, enabling seamless public access to the local development server. By providing a secure HTTPS endpoint automatically, it facilitates the development and testing of modern web features, particularly those involving cross-device interactions and browser-based camera access. The provision of automated launch scripts in both Bash and Python simplifies the developer workflow, making it easy to run the full application stack with a single command.
Sources: README.md:12, INSTALLATION.md:204-207