File size: 7,487 Bytes
42bba47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Cloudflare Tunnel Setup for Chase
Creates secure external access to E-FIRE-1 from anywhere
"""

import subprocess
import json
import os
import sys
from pathlib import Path
import asyncio
import aiohttp

class CloudflareTunnelManager:
    """Manages Cloudflare tunnel for external access"""
    
    def __init__(self):
        self.config_dir = Path.home() / ".cloudflared"
        self.config_dir.mkdir(exist_ok=True)
        self.tunnel_name = "e-fire-1-chase"
        self.config_file = self.config_dir / f"{self.tunnel_name}.yml"
        
    async def install_cloudflared(self):
        """Install cloudflared if not present"""
        try:
            result = subprocess.run(["cloudflared", "--version"], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                print("βœ… cloudflared already installed")
                return True
        except FileNotFoundError:
            pass
            
        print("πŸ“¦ Installing cloudflared...")
        
        # Auto-install based on platform
        if sys.platform == "linux":
            install_cmd = [
                "wget", "-q", 
                "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64",
                "-O", "/usr/local/bin/cloudflared"
            ]
            chmod_cmd = ["chmod", "+x", "/usr/local/bin/cloudflared"]
            
            subprocess.run(install_cmd, check=True)
            subprocess.run(chmod_cmd, check=True)
            
        elif sys.platform == "darwin":
            install_cmd = ["brew", "install", "cloudflare/cloudflare/cloudflared"]
            subprocess.run(install_cmd, check=True)
            
        elif sys.platform == "win32":
            install_cmd = [
                "powershell", "-Command",
                "Invoke-WebRequest -Uri 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe' -OutFile 'cloudflared.exe'"
            ]
            subprocess.run(install_cmd, check=True)
            
        print("βœ… cloudflared installed successfully")
        return True
    
    def create_tunnel_config(self, local_port=8080):
        """Create Cloudflare tunnel configuration"""
        
        config = {
            "tunnel": self.tunnel_name,
            "credentials-file": str(self.config_dir / f"{self.tunnel_name}.json"),
            "ingress": [
                {
                    "hostname": f"{self.tunnel_name}.trycloudflare.com",
                    "service": f"http://localhost:{local_port}"
                },
                {
                    "service": "http_status:404"
                }
            ]
        }
        
        # Write configuration
        with open(self.config_file, 'w') as f:
            yaml_content = f"""
tunnel: {self.tunnel_name}
credentials-file: {self.config_dir}/{self.tunnel_name}.json

ingress:
  - hostname: {self.tunnel_name}.trycloudflare.com
    service: http://localhost:{local_port}
  - service: http_status:404
"""
            f.write(yaml_content.strip())
            
        print(f"βœ… Tunnel config created: {self.config_file}")
        return str(self.config_file)
    
    async def create_tunnel(self):
        """Create Cloudflare tunnel"""
        
        # Create tunnel
        cmd = ["cloudflared", "tunnel", "create", self.tunnel_name]
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode != 0:
            print(f"❌ Failed to create tunnel: {result.stderr}")
            return None
            
        # Get tunnel ID
        cmd = ["cloudflared", "tunnel", "list", "--output", "json"]
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            tunnels = json.loads(result.stdout)
            for tunnel in tunnels:
                if tunnel.get("name") == self.tunnel_name:
                    tunnel_id = tunnel.get("id")
                    print(f"βœ… Tunnel created: {tunnel_id}")
                    return tunnel_id
                    
        return None
    
    def start_tunnel(self, local_port=8080):
        """Start the tunnel"""
        config_path = self.create_tunnel_config(local_port)
        
        # Start tunnel
        cmd = [
            "cloudflared", "tunnel", "--config", config_path, "run"
        ]
        
        print("πŸš€ Starting Cloudflare tunnel...")
        print(f"πŸ”— External URL: https://{self.tunnel_name}.trycloudflare.com")
        
        # Start in background
        process = subprocess.Popen(cmd)
        return process
    
    def quick_tunnel(self, local_port=8080):
        """Quick tunnel without persistent setup"""
        cmd = [
            "cloudflared", "tunnel", "--url", f"http://localhost:{local_port}"
        ]
        
        print("πŸš€ Starting quick Cloudflare tunnel...")
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                                 stderr=subprocess.PIPE, text=True)
        
        # Parse output to get URL
        for line in iter(process.stdout.readline, ''):
            if "trycloudflare.com" in line:
                url = line.strip().split()[-1]
                print(f"πŸ”— Quick tunnel URL: {url}")
                return process, url
                
        return process, None
    
    def create_service_file(self):
        """Create systemd service for persistent tunnel"""
        
        service_content = f"""[Unit]
Description=Cloudflare Tunnel for E-FIRE-1
After=network.target

[Service]
Type=simple
User=chase
ExecStart=/usr/local/bin/cloudflared tunnel --config {self.config_file} run
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
"""
        
        service_path = Path("/etc/systemd/system/e-fire-1-tunnel.service")
        
        try:
            with open(service_path, 'w') as f:
                f.write(service_content)
                
            subprocess.run(["sudo", "systemctl", "daemon-reload"], check=True)
            subprocess.run(["sudo", "systemctl", "enable", "e-fire-1-tunnel"], check=True)
            
            print("βœ… Systemd service created")
            return True
        except PermissionError:
            print("⚠️  Run with sudo to create systemd service")
            return False

async def main():
    """Main setup function"""
    
    print("🌐 Cloudflare Tunnel Setup for Chase")
    print("=" * 50)
    
    manager = CloudflareTunnelManager()
    
    # Install cloudflared
    await manager.install_cloudflared()
    
    # Quick tunnel for immediate access
    print("\nπŸš€ Starting quick tunnel...")
    process, url = manager.quick_tunnel(8080)
    
    if url:
        print(f"πŸ”— Mobile access URL: {url}")
        print("πŸ“± Use this URL on your phone/laptop from anywhere!")
        
        # Create QR code
        try:
            import qrcode
            qr = qrcode.QRCode(version=1, box_size=10, border=5)
            qr.add_data(url)
            qr.make(fit=True)
            qr.print_ascii()
            print(f"πŸ“± Scan QR code or visit: {url}")
        except ImportError:
            print("pip install qrcode to enable QR code generation")
    
    print("\nπŸ’ Elizabeth is now accessible from anywhere!")
    print("🎯 Use your phone to monitor earnings toward $50/day")

if __name__ == "__main__":
    asyncio.run(main())