raytunnel 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- raytunnel/__init__.py +80 -0
- raytunnel/cli.py +69 -0
- raytunnel/client.py +333 -0
- raytunnel/py.typed +0 -0
- raytunnel/server.py +499 -0
- raytunnel-0.1.0.dist-info/METADATA +357 -0
- raytunnel-0.1.0.dist-info/RECORD +9 -0
- raytunnel-0.1.0.dist-info/WHEEL +4 -0
- raytunnel-0.1.0.dist-info/entry_points.txt +2 -0
raytunnel/__init__.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import threading
|
|
3
|
+
from typing import Optional
|
|
4
|
+
from raytunnel.client import run_client
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
allocated_info = {}
|
|
8
|
+
# Event that is set once allocated_info has been populated by the client.
|
|
9
|
+
# Call allocated_event.wait(timeout=N) in the caller to block until the
|
|
10
|
+
# tunnel is established rather than busy-polling.
|
|
11
|
+
allocated_event = threading.Event()
|
|
12
|
+
|
|
13
|
+
def _run_async_loop(loop, server, token, http_port, ssh, subdomain, ssl):
|
|
14
|
+
asyncio.set_event_loop(loop)
|
|
15
|
+
try:
|
|
16
|
+
loop.run_until_complete(
|
|
17
|
+
run_client(
|
|
18
|
+
server=server,
|
|
19
|
+
token=token,
|
|
20
|
+
http_port=http_port,
|
|
21
|
+
ssh=ssh,
|
|
22
|
+
subdomain=subdomain,
|
|
23
|
+
ssl=ssl
|
|
24
|
+
)
|
|
25
|
+
)
|
|
26
|
+
except Exception as e:
|
|
27
|
+
print(f"Raytunnel background worker encountered an error: {e}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TunnelHandle:
|
|
31
|
+
"""Handle to manage a background tunnel worker."""
|
|
32
|
+
def __init__(self, thread: threading.Thread, loop: asyncio.AbstractEventLoop):
|
|
33
|
+
self.thread = thread
|
|
34
|
+
self.loop = loop
|
|
35
|
+
|
|
36
|
+
def stop(self):
|
|
37
|
+
"""Stops the background tunnel."""
|
|
38
|
+
if self.loop.is_running():
|
|
39
|
+
self.loop.call_soon_threadsafe(self.loop.stop)
|
|
40
|
+
self.thread.join()
|
|
41
|
+
print("Raytunnel background worker stopped.")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def start(
|
|
45
|
+
server: str,
|
|
46
|
+
token: str,
|
|
47
|
+
http_port: int,
|
|
48
|
+
ssh: bool = True,
|
|
49
|
+
subdomain: Optional[str] = None,
|
|
50
|
+
ssl: bool = True,
|
|
51
|
+
background: bool = False
|
|
52
|
+
) -> Optional[TunnelHandle]:
|
|
53
|
+
"""
|
|
54
|
+
Starts the raytunnel client.
|
|
55
|
+
|
|
56
|
+
If background=True, starts it in a separate thread and returns a TunnelHandle
|
|
57
|
+
so it doesn't block the caller (ideal for notebooks).
|
|
58
|
+
Otherwise, blocks the caller and runs in the main thread.
|
|
59
|
+
"""
|
|
60
|
+
if background:
|
|
61
|
+
loop = asyncio.new_event_loop()
|
|
62
|
+
thread = threading.Thread(
|
|
63
|
+
target=_run_async_loop,
|
|
64
|
+
args=(loop, server, token, http_port, ssh, subdomain, ssl),
|
|
65
|
+
daemon=True
|
|
66
|
+
)
|
|
67
|
+
thread.start()
|
|
68
|
+
return TunnelHandle(thread, loop)
|
|
69
|
+
else:
|
|
70
|
+
asyncio.run(
|
|
71
|
+
run_client(
|
|
72
|
+
server=server,
|
|
73
|
+
token=token,
|
|
74
|
+
http_port=http_port,
|
|
75
|
+
ssh=ssh,
|
|
76
|
+
subdomain=subdomain,
|
|
77
|
+
ssl=ssl
|
|
78
|
+
)
|
|
79
|
+
)
|
|
80
|
+
return None
|
raytunnel/cli.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import sys
|
|
3
|
+
import click
|
|
4
|
+
import logging
|
|
5
|
+
from raytunnel.client import run_client
|
|
6
|
+
from raytunnel.server import run_server
|
|
7
|
+
|
|
8
|
+
# Set up logging level based on input
|
|
9
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
|
|
10
|
+
|
|
11
|
+
@click.group()
|
|
12
|
+
def main():
|
|
13
|
+
"""Raytunnel: A lightweight reverse tunnel and SSH forwarding tool."""
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
@main.command()
|
|
17
|
+
@click.option("--server", "-s", required=True, help="Domain/IP of the raytunnel server (e.g. s.yourdomain.com)")
|
|
18
|
+
@click.option("--token", "-t", required=True, envvar="RAYTUNNEL_TOKEN", help="Authentication token for the server")
|
|
19
|
+
@click.option("--port", "-p", default=8000, type=int, help="Local HTTP port to forward (e.g. your web app port)")
|
|
20
|
+
@click.option("--ssh/--no-ssh", default=True, help="Enable SSH forward terminal (launches user-space sshd)")
|
|
21
|
+
@click.option("--subdomain", "-d", default=None, help="Desired custom subdomain prefix (e.g. 'my-app')")
|
|
22
|
+
@click.option("--ssl/--no-ssl", default=True, help="Use WebSocket Secure (wss://) connection")
|
|
23
|
+
def client(server, token, port, ssh, subdomain, ssl):
|
|
24
|
+
"""Start the tunnel client forwarding local HTTP and SSH to the server."""
|
|
25
|
+
try:
|
|
26
|
+
asyncio.run(
|
|
27
|
+
run_client(
|
|
28
|
+
server=server,
|
|
29
|
+
token=token,
|
|
30
|
+
http_port=port,
|
|
31
|
+
ssh=ssh,
|
|
32
|
+
subdomain=subdomain,
|
|
33
|
+
ssl=ssl
|
|
34
|
+
)
|
|
35
|
+
)
|
|
36
|
+
except KeyboardInterrupt:
|
|
37
|
+
click.echo("\nTunnel stopped by user.")
|
|
38
|
+
sys.exit(0)
|
|
39
|
+
except Exception as e:
|
|
40
|
+
click.echo(f"Client error: {e}", err=True)
|
|
41
|
+
sys.exit(1)
|
|
42
|
+
|
|
43
|
+
@main.command()
|
|
44
|
+
@click.option("--host", default="0.0.0.0", help="API and WebSockets bind address")
|
|
45
|
+
@click.option("--port", default=8001, type=int, help="API and WebSockets bind port (control port)")
|
|
46
|
+
@click.option("--tcp-port", default=8000, type=int, help="TCP HTTP Host-routing entrypoint port")
|
|
47
|
+
@click.option("--token", "-t", required=True, envvar="RAYTUNNEL_TOKEN", help="Token clients must provide to connect")
|
|
48
|
+
@click.option("--domain", "-d", default="s.yourdomain.com", help="Main domain of the server for routing")
|
|
49
|
+
def server(host, port, tcp_port, token, domain):
|
|
50
|
+
"""Start the raytunnel server."""
|
|
51
|
+
try:
|
|
52
|
+
asyncio.run(
|
|
53
|
+
run_server(
|
|
54
|
+
host=host,
|
|
55
|
+
api_port=port,
|
|
56
|
+
tcp_port=tcp_port,
|
|
57
|
+
token=token,
|
|
58
|
+
domain=domain
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
except KeyboardInterrupt:
|
|
62
|
+
click.echo("\nServer stopped by user.")
|
|
63
|
+
sys.exit(0)
|
|
64
|
+
except Exception as e:
|
|
65
|
+
click.echo(f"Server error: {e}", err=True)
|
|
66
|
+
sys.exit(1)
|
|
67
|
+
|
|
68
|
+
if __name__ == "__main__":
|
|
69
|
+
main()
|
raytunnel/client.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
import tempfile
|
|
5
|
+
import subprocess
|
|
6
|
+
import shutil
|
|
7
|
+
import logging
|
|
8
|
+
import urllib.parse
|
|
9
|
+
from typing import Optional
|
|
10
|
+
import websockets
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
|
|
13
|
+
console = Console()
|
|
14
|
+
logger = logging.getLogger("raytunnel.client")
|
|
15
|
+
|
|
16
|
+
def setup_ssh_daemon() -> int:
|
|
17
|
+
"""
|
|
18
|
+
Sets up and starts a local SSH daemon (sshd) in user-space if not already running.
|
|
19
|
+
Returns the port the SSH daemon is listening on.
|
|
20
|
+
"""
|
|
21
|
+
# 1. Check if sshd is installed
|
|
22
|
+
sshd_path = shutil.which("sshd") or "/usr/sbin/sshd"
|
|
23
|
+
if not os.path.exists(sshd_path):
|
|
24
|
+
console.print("[yellow]WARNING: sshd not found. Attempting to install openssh-server...[/yellow]")
|
|
25
|
+
try:
|
|
26
|
+
subprocess.run(["apt-get", "update", "-qq"], check=True)
|
|
27
|
+
subprocess.run(["apt-get", "install", "-y", "-qq", "openssh-server"], check=True)
|
|
28
|
+
sshd_path = shutil.which("sshd") or "/usr/sbin/sshd"
|
|
29
|
+
except Exception as e:
|
|
30
|
+
console.print(f"[red]Failed to install openssh-server: {e}. SSH function might not work.[/red]")
|
|
31
|
+
return -1
|
|
32
|
+
|
|
33
|
+
# 2. Check if we have key pair and add to authorized_keys
|
|
34
|
+
ssh_dir = os.path.expanduser("~/.ssh")
|
|
35
|
+
os.makedirs(ssh_dir, mode=0o700, exist_ok=True)
|
|
36
|
+
authorized_keys_path = os.path.join(ssh_dir, "authorized_keys")
|
|
37
|
+
|
|
38
|
+
# Generate a temporary keypair for raytunnel if it doesn't exist
|
|
39
|
+
key_path = os.path.expanduser("~/.ssh/raytunnel_id_ed25519")
|
|
40
|
+
if not os.path.exists(key_path):
|
|
41
|
+
console.print("[cyan]Generating temporary SSH keypair for client terminal access...[/cyan]")
|
|
42
|
+
try:
|
|
43
|
+
subprocess.run([
|
|
44
|
+
"ssh-keygen", "-t", "ed25519", "-f", key_path, "-N", "", "-q"
|
|
45
|
+
], check=True)
|
|
46
|
+
# Ensure correct permissions
|
|
47
|
+
os.chmod(key_path, 0o600)
|
|
48
|
+
except Exception as e:
|
|
49
|
+
console.print(f"[red]Failed to generate SSH keypair: {e}[/red]")
|
|
50
|
+
return -1
|
|
51
|
+
|
|
52
|
+
# Read the public key
|
|
53
|
+
pub_key_path = key_path + ".pub"
|
|
54
|
+
with open(pub_key_path, "r") as f:
|
|
55
|
+
pub_key = f.read().strip()
|
|
56
|
+
|
|
57
|
+
# Add public key to authorized_keys if not present
|
|
58
|
+
existing_keys = ""
|
|
59
|
+
if os.path.exists(authorized_keys_path):
|
|
60
|
+
with open(authorized_keys_path, "r") as f:
|
|
61
|
+
existing_keys = f.read()
|
|
62
|
+
|
|
63
|
+
if pub_key not in existing_keys:
|
|
64
|
+
with open(authorized_keys_path, "a") as f:
|
|
65
|
+
f.write(f"\n{pub_key}\n")
|
|
66
|
+
os.chmod(authorized_keys_path, 0o600)
|
|
67
|
+
|
|
68
|
+
# 3. Create host keys and user-space sshd config
|
|
69
|
+
temp_dir = tempfile.gettempdir()
|
|
70
|
+
host_key_path = os.path.join(temp_dir, "raytunnel_ssh_host_ed25519_key")
|
|
71
|
+
if not os.path.exists(host_key_path):
|
|
72
|
+
try:
|
|
73
|
+
subprocess.run([
|
|
74
|
+
"ssh-keygen", "-t", "ed25519", "-f", host_key_path, "-N", "", "-q"
|
|
75
|
+
], check=True)
|
|
76
|
+
os.chmod(host_key_path, 0o600)
|
|
77
|
+
except Exception as e:
|
|
78
|
+
console.print(f"[red]Failed to generate host key: {e}[/red]")
|
|
79
|
+
return -1
|
|
80
|
+
|
|
81
|
+
# Use a custom port (e.g. 2222) to avoid requiring root privileges
|
|
82
|
+
sshd_port = 2222
|
|
83
|
+
sshd_config_content = f"""
|
|
84
|
+
Port {sshd_port}
|
|
85
|
+
HostKey {host_key_path}
|
|
86
|
+
AuthorizedKeysFile {authorized_keys_path}
|
|
87
|
+
ChallengeResponseAuthentication no
|
|
88
|
+
PasswordAuthentication no
|
|
89
|
+
UsePAM no
|
|
90
|
+
PidFile {os.path.join(temp_dir, "raytunnel_sshd.pid")}
|
|
91
|
+
Subsystem sftp /usr/lib/openssh/sftp-server
|
|
92
|
+
StrictModes no
|
|
93
|
+
"""
|
|
94
|
+
sshd_config_path = os.path.join(temp_dir, "raytunnel_sshd_config")
|
|
95
|
+
with open(sshd_config_path, "w") as f:
|
|
96
|
+
f.write(sshd_config_content)
|
|
97
|
+
|
|
98
|
+
# 4. Start the sshd daemon
|
|
99
|
+
try:
|
|
100
|
+
# sshd requires /run/sshd to exist on many systems, otherwise it fails to start
|
|
101
|
+
os.makedirs("/run/sshd", exist_ok=True)
|
|
102
|
+
except Exception as e:
|
|
103
|
+
console.print(f"[yellow]Warning: could not create /run/sshd: {e}[/yellow]")
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
# Check if already running by trying to read PID
|
|
107
|
+
pid_file = os.path.join(temp_dir, "raytunnel_sshd.pid")
|
|
108
|
+
if os.path.exists(pid_file):
|
|
109
|
+
with open(pid_file, "r") as f:
|
|
110
|
+
pid = int(f.read().strip())
|
|
111
|
+
# Check if process actually exists
|
|
112
|
+
try:
|
|
113
|
+
os.kill(pid, 0)
|
|
114
|
+
console.print(f"[green]SSH daemon already running on port {sshd_port} (PID {pid})[/green]")
|
|
115
|
+
return sshd_port
|
|
116
|
+
except OSError:
|
|
117
|
+
# PID is stale, remove pid file
|
|
118
|
+
os.remove(pid_file)
|
|
119
|
+
except Exception:
|
|
120
|
+
pass
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
# Start sshd process and redirect output to a log file for diagnostics
|
|
124
|
+
sshd_log_path = os.path.join(temp_dir, "raytunnel_sshd.log")
|
|
125
|
+
log_file = open(sshd_log_path, "w")
|
|
126
|
+
proc = subprocess.Popen(
|
|
127
|
+
[sshd_path, "-f", sshd_config_path, "-D"],
|
|
128
|
+
stdout=log_file,
|
|
129
|
+
stderr=log_file
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# Give it a short moment to check if it crashed on startup
|
|
133
|
+
import time
|
|
134
|
+
time.sleep(0.8)
|
|
135
|
+
if proc.poll() is not None:
|
|
136
|
+
log_file.close()
|
|
137
|
+
try:
|
|
138
|
+
with open(sshd_log_path, "r") as lf:
|
|
139
|
+
log_content = lf.read().strip()
|
|
140
|
+
except Exception:
|
|
141
|
+
log_content = ""
|
|
142
|
+
console.print(f"[red]SSH daemon exited immediately with code {proc.poll()}[/red]")
|
|
143
|
+
if log_content:
|
|
144
|
+
console.print(f"[red]sshd error log:\n{log_content}[/red]")
|
|
145
|
+
return -1
|
|
146
|
+
|
|
147
|
+
console.print(f"[green]SSH daemon started successfully on port {sshd_port}[/green]")
|
|
148
|
+
return sshd_port
|
|
149
|
+
except Exception as e:
|
|
150
|
+
console.print(f"[red]Failed to start SSH daemon: {e}[/red]")
|
|
151
|
+
return -1
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
async def pipe_streams(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, ws: websockets.WebSocketClientProtocol):
|
|
155
|
+
"""Pipes data bidirectionally between a local TCP connection and a remote WebSocket."""
|
|
156
|
+
async def tcp_to_ws():
|
|
157
|
+
try:
|
|
158
|
+
while True:
|
|
159
|
+
data = await reader.read(4096)
|
|
160
|
+
if not data:
|
|
161
|
+
break
|
|
162
|
+
await ws.send(data)
|
|
163
|
+
except Exception as e:
|
|
164
|
+
logger.debug(f"TCP to WS error: {e}")
|
|
165
|
+
|
|
166
|
+
async def ws_to_tcp():
|
|
167
|
+
try:
|
|
168
|
+
async for message in ws:
|
|
169
|
+
if isinstance(message, str):
|
|
170
|
+
message = message.encode('utf-8')
|
|
171
|
+
writer.write(message)
|
|
172
|
+
await writer.drain()
|
|
173
|
+
except Exception as e:
|
|
174
|
+
logger.debug(f"WS to TCP error: {e}")
|
|
175
|
+
|
|
176
|
+
t1 = asyncio.create_task(tcp_to_ws())
|
|
177
|
+
t2 = asyncio.create_task(ws_to_tcp())
|
|
178
|
+
try:
|
|
179
|
+
done, pending = await asyncio.wait([t1, t2], return_when=asyncio.FIRST_COMPLETED)
|
|
180
|
+
if t1 not in done:
|
|
181
|
+
# t2 (remote→local) finished first (e.g. finished receiving request body).
|
|
182
|
+
# Wait for t1 (local→remote) so the response can flow back fully.
|
|
183
|
+
await t1
|
|
184
|
+
finally:
|
|
185
|
+
t1.cancel()
|
|
186
|
+
t2.cancel()
|
|
187
|
+
writer.close()
|
|
188
|
+
try:
|
|
189
|
+
await writer.wait_closed()
|
|
190
|
+
except Exception:
|
|
191
|
+
pass
|
|
192
|
+
try:
|
|
193
|
+
await ws.close()
|
|
194
|
+
except Exception:
|
|
195
|
+
pass
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
async def handle_channel(server_url: str, channel_id: str, local_port: int, ssl: bool):
|
|
199
|
+
"""Handles an individual tunnel channel by forwarding to the local TCP port."""
|
|
200
|
+
ws_scheme = "wss" if ssl else "ws"
|
|
201
|
+
parsed = urllib.parse.urlparse(server_url)
|
|
202
|
+
# The actual network location of the server (e.g. s.ray.ac:8001 or s.ray.ac)
|
|
203
|
+
netloc = parsed.netloc or parsed.path
|
|
204
|
+
if ":" not in netloc and not ssl:
|
|
205
|
+
# Default ws port if not specified
|
|
206
|
+
netloc = f"{netloc}:8001"
|
|
207
|
+
|
|
208
|
+
data_url = f"{ws_scheme}://{netloc}/ws/data?channel_id={channel_id}"
|
|
209
|
+
|
|
210
|
+
reader, writer = None, None
|
|
211
|
+
ws = None
|
|
212
|
+
try:
|
|
213
|
+
# Connect to local port
|
|
214
|
+
reader, writer = await asyncio.open_connection("127.0.0.1", local_port)
|
|
215
|
+
# Connect to server's data WebSocket
|
|
216
|
+
ws = await websockets.connect(data_url, open_timeout=30, ping_interval=None)
|
|
217
|
+
# Pipe them
|
|
218
|
+
await pipe_streams(reader, writer, ws)
|
|
219
|
+
except Exception as e:
|
|
220
|
+
logger.error(f"Error handling channel {channel_id} (port {local_port}): {e}")
|
|
221
|
+
if writer:
|
|
222
|
+
writer.close()
|
|
223
|
+
if ws:
|
|
224
|
+
await ws.close()
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
async def run_client(
|
|
228
|
+
server: str,
|
|
229
|
+
token: str,
|
|
230
|
+
http_port: int,
|
|
231
|
+
ssh: bool = True,
|
|
232
|
+
subdomain: Optional[str] = None,
|
|
233
|
+
ssl: bool = True
|
|
234
|
+
):
|
|
235
|
+
"""
|
|
236
|
+
Main client loop. Connects to server control channel and listens for incoming connections.
|
|
237
|
+
"""
|
|
238
|
+
ws_scheme = "wss" if ssl else "ws"
|
|
239
|
+
# Ensure server doesn't contain scheme
|
|
240
|
+
server_clean = server
|
|
241
|
+
if "://" in server:
|
|
242
|
+
server_clean = server.split("://")[1]
|
|
243
|
+
|
|
244
|
+
# Connect to the backend control port (typically 8001 for WS API, unless specified)
|
|
245
|
+
control_netloc = server_clean
|
|
246
|
+
if ":" not in control_netloc and not ssl:
|
|
247
|
+
control_netloc = f"{control_netloc}:8001"
|
|
248
|
+
|
|
249
|
+
params = {"token": token}
|
|
250
|
+
if subdomain:
|
|
251
|
+
params["subdomain"] = subdomain
|
|
252
|
+
|
|
253
|
+
query_str = urllib.parse.urlencode(params)
|
|
254
|
+
control_url = f"{ws_scheme}://{control_netloc}/ws/control?{query_str}"
|
|
255
|
+
|
|
256
|
+
# Setup SSH daemon if requested
|
|
257
|
+
ssh_local_port = -1
|
|
258
|
+
if ssh:
|
|
259
|
+
ssh_local_port = setup_ssh_daemon()
|
|
260
|
+
|
|
261
|
+
console.print(f"[cyan]Connecting to tunnel server at {control_url}...[/cyan]")
|
|
262
|
+
|
|
263
|
+
while True:
|
|
264
|
+
try:
|
|
265
|
+
async with websockets.connect(control_url, open_timeout=30) as ws:
|
|
266
|
+
# Expect welcome message
|
|
267
|
+
import json
|
|
268
|
+
welcome_msg = await ws.recv()
|
|
269
|
+
config = json.loads(welcome_msg)
|
|
270
|
+
|
|
271
|
+
if config.get("status") == "error":
|
|
272
|
+
console.print(f"[red]Server error: {config.get('message')}[/red]")
|
|
273
|
+
return
|
|
274
|
+
|
|
275
|
+
allocated_subdomain = config.get("subdomain")
|
|
276
|
+
allocated_ssh_port = config.get("ssh_port")
|
|
277
|
+
server_host = server_clean.split(":")[0]
|
|
278
|
+
public_http_url = f"https://{allocated_subdomain}.{server_host}" if ssl else f"http://{allocated_subdomain}.{server_host}"
|
|
279
|
+
|
|
280
|
+
console.print("\n" + "="*60)
|
|
281
|
+
console.print(f"[green]✔ Raytunnel Established Successfully![/green]")
|
|
282
|
+
console.print(f" [bold]HTTP Web App URL:[/bold] [underline]{public_http_url}[/underline]")
|
|
283
|
+
if ssh and allocated_ssh_port:
|
|
284
|
+
key_path = os.path.expanduser("~/.ssh/raytunnel_id_ed25519")
|
|
285
|
+
try:
|
|
286
|
+
with open(key_path, "r") as kf:
|
|
287
|
+
private_key_content = kf.read().strip()
|
|
288
|
+
except Exception as e:
|
|
289
|
+
private_key_content = f"Error reading key: {e}"
|
|
290
|
+
# console.print(f" [bold]SSH Command:[/bold] ssh -i ~/.ssh/raytunnel_id_ed25519 -p {allocated_ssh_port} root@{server_clean.split(':')[0]}")
|
|
291
|
+
# console.print(f" [bold]SSH Port:[/bold] {allocated_ssh_port}")
|
|
292
|
+
# console.print(f" [bold]SSH Private Key (Copy & save to ~/.ssh/raytunnel_id_ed25519 on your PC):[/bold]")
|
|
293
|
+
# console.print(f"\n{private_key_content}\n")
|
|
294
|
+
else:
|
|
295
|
+
private_key_content = ""
|
|
296
|
+
import raytunnel
|
|
297
|
+
raytunnel.allocated_info = {
|
|
298
|
+
"subdomain": allocated_subdomain,
|
|
299
|
+
"ssh_port": allocated_ssh_port,
|
|
300
|
+
"server": server_clean.split(":")[0],
|
|
301
|
+
"key": private_key_content
|
|
302
|
+
}
|
|
303
|
+
raytunnel.allocated_event.set()
|
|
304
|
+
console.print("="*60 + "\n")
|
|
305
|
+
|
|
306
|
+
# Listen for control messages
|
|
307
|
+
async for message in ws:
|
|
308
|
+
event = json.loads(message)
|
|
309
|
+
action = event.get("action")
|
|
310
|
+
if action == "open_channel":
|
|
311
|
+
channel_id = event.get("channel_id")
|
|
312
|
+
channel_type = event.get("type")
|
|
313
|
+
|
|
314
|
+
target_port = http_port if channel_type == "http" else ssh_local_port
|
|
315
|
+
if target_port <= 0:
|
|
316
|
+
logger.error(f"Cannot open channel for type '{channel_type}' as port is invalid.")
|
|
317
|
+
continue
|
|
318
|
+
|
|
319
|
+
# Spawn task to handle the connection
|
|
320
|
+
asyncio.create_task(
|
|
321
|
+
handle_channel(
|
|
322
|
+
server_url=control_url,
|
|
323
|
+
channel_id=channel_id,
|
|
324
|
+
local_port=target_port,
|
|
325
|
+
ssl=ssl
|
|
326
|
+
)
|
|
327
|
+
)
|
|
328
|
+
except (websockets.exceptions.ConnectionClosed, OSError) as e:
|
|
329
|
+
console.print(f"[yellow]Connection lost ({e}). Reconnecting in 5 seconds...[/yellow]")
|
|
330
|
+
await asyncio.sleep(5)
|
|
331
|
+
except Exception as e:
|
|
332
|
+
console.print(f"[red]Unexpected client error: {e}[/red]")
|
|
333
|
+
await asyncio.sleep(5)
|
raytunnel/py.typed
ADDED
|
File without changes
|
raytunnel/server.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
import uuid
|
|
4
|
+
import re
|
|
5
|
+
import json
|
|
6
|
+
from typing import Dict, Any, Optional
|
|
7
|
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, status
|
|
8
|
+
from fastapi.responses import HTMLResponse
|
|
9
|
+
import uvicorn
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger("raytunnel.server")
|
|
12
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s")
|
|
13
|
+
|
|
14
|
+
# In-memory storage for active tunnels
|
|
15
|
+
# Structure:
|
|
16
|
+
# {
|
|
17
|
+
# "subdomain": {
|
|
18
|
+
# "control_ws": WebSocket,
|
|
19
|
+
# "ssh_port": int,
|
|
20
|
+
# "ssh_server": asyncio.Server,
|
|
21
|
+
# "pending_channels": {
|
|
22
|
+
# "channel_id": asyncio.Future (resolves to WebSocket)
|
|
23
|
+
# }
|
|
24
|
+
# }
|
|
25
|
+
# }
|
|
26
|
+
active_tunnels: Dict[str, Dict[str, Any]] = {}
|
|
27
|
+
used_ssh_ports = set()
|
|
28
|
+
|
|
29
|
+
# Config
|
|
30
|
+
SSH_PORT_START = 2200
|
|
31
|
+
SSH_PORT_END = 2300
|
|
32
|
+
TOKEN = "secret-tunnel-token" # User can override via CLI/env
|
|
33
|
+
DOMAIN = "s.yourdomain.com" # Main domain of the server
|
|
34
|
+
|
|
35
|
+
app = FastAPI(title="Raytunnel Server")
|
|
36
|
+
|
|
37
|
+
def get_subdomain_from_host(host: str) -> Optional[str]:
|
|
38
|
+
"""Extracts subdomain label from the Host header."""
|
|
39
|
+
host_clean = host.split(":")[0].strip().lower()
|
|
40
|
+
|
|
41
|
+
# Check if host matches base domains
|
|
42
|
+
root_domain = DOMAIN.lower()
|
|
43
|
+
if root_domain.startswith("s."):
|
|
44
|
+
root_domain = root_domain[2:] # Strip 's.' prefix to get root domain
|
|
45
|
+
|
|
46
|
+
base_domains = (DOMAIN.lower(), root_domain, "localhost", "127.0.0.1")
|
|
47
|
+
if host_clean in base_domains:
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
# Check if host matches <subdomain>.s.yourdomain.com or <subdomain>.yourdomain.com
|
|
51
|
+
for suffix in (f".{DOMAIN.lower()}", f".{root_domain}"):
|
|
52
|
+
if host_clean.endswith(suffix):
|
|
53
|
+
sub = host_clean[:-len(suffix)]
|
|
54
|
+
if "." not in sub: # single level subdomain
|
|
55
|
+
return sub
|
|
56
|
+
# If multi-level, take the leftmost part
|
|
57
|
+
return sub.split(".")[0]
|
|
58
|
+
|
|
59
|
+
# Fallback: take the first part of the hostname
|
|
60
|
+
parts = host_clean.split(".")
|
|
61
|
+
if len(parts) > 1:
|
|
62
|
+
return parts[0]
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def allocate_ssh_port() -> int:
|
|
67
|
+
"""Finds an available TCP port in the configured SSH port range."""
|
|
68
|
+
for port in range(SSH_PORT_START, SSH_PORT_END):
|
|
69
|
+
if port in used_ssh_ports:
|
|
70
|
+
continue
|
|
71
|
+
# Verify port is actually free by trying to listen on it
|
|
72
|
+
try:
|
|
73
|
+
server = await asyncio.start_server(lambda r, w: w.close(), "0.0.0.0", port)
|
|
74
|
+
server.close()
|
|
75
|
+
await server.wait_closed()
|
|
76
|
+
used_ssh_ports.add(port)
|
|
77
|
+
return port
|
|
78
|
+
except OSError:
|
|
79
|
+
continue
|
|
80
|
+
raise RuntimeError("No available SSH ports in the configured range.")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def pipe_websocket_tcp(ws: WebSocket, tcp_reader: asyncio.StreamReader, tcp_writer: asyncio.StreamWriter, initial_data: bytes = b""):
|
|
84
|
+
"""Pipes bytes bidirectionally between a data WebSocket and a TCP socket."""
|
|
85
|
+
async def tcp_to_ws():
|
|
86
|
+
try:
|
|
87
|
+
if initial_data:
|
|
88
|
+
# If there's any data we already read from TCP, send it first
|
|
89
|
+
await ws.send_bytes(initial_data)
|
|
90
|
+
while True:
|
|
91
|
+
data = await tcp_reader.read(4096)
|
|
92
|
+
if not data:
|
|
93
|
+
break
|
|
94
|
+
await ws.send_bytes(data)
|
|
95
|
+
except Exception as e:
|
|
96
|
+
logger.debug(f"TCP to WS forward error: {e}")
|
|
97
|
+
|
|
98
|
+
async def ws_to_tcp():
|
|
99
|
+
try:
|
|
100
|
+
while True:
|
|
101
|
+
# Receive binary messages
|
|
102
|
+
message = await ws.receive_bytes()
|
|
103
|
+
if not message:
|
|
104
|
+
break
|
|
105
|
+
tcp_writer.write(message)
|
|
106
|
+
await tcp_writer.drain()
|
|
107
|
+
except WebSocketDisconnect:
|
|
108
|
+
pass
|
|
109
|
+
except Exception as e:
|
|
110
|
+
logger.debug(f"WS to TCP forward error: {e}")
|
|
111
|
+
|
|
112
|
+
t1 = asyncio.create_task(tcp_to_ws())
|
|
113
|
+
t2 = asyncio.create_task(ws_to_tcp())
|
|
114
|
+
try:
|
|
115
|
+
done, pending = await asyncio.wait([t1, t2], return_when=asyncio.FIRST_COMPLETED)
|
|
116
|
+
if t2 not in done:
|
|
117
|
+
# Client finished sending request (t1 done), wait for remote response (t2)
|
|
118
|
+
await t2
|
|
119
|
+
finally:
|
|
120
|
+
t1.cancel()
|
|
121
|
+
t2.cancel()
|
|
122
|
+
tcp_writer.close()
|
|
123
|
+
try:
|
|
124
|
+
await tcp_writer.wait_closed()
|
|
125
|
+
except Exception:
|
|
126
|
+
pass
|
|
127
|
+
try:
|
|
128
|
+
await ws.close()
|
|
129
|
+
except Exception:
|
|
130
|
+
pass
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@app.get("/")
|
|
134
|
+
def read_root():
|
|
135
|
+
# Return HTML dashboard showing active tunnels
|
|
136
|
+
tunnels_html = ""
|
|
137
|
+
for sub, info in active_tunnels.items():
|
|
138
|
+
tunnels_html += f"<li><strong>{sub}.{DOMAIN}</strong> -> SSH Port: {info['ssh_port']}</li>"
|
|
139
|
+
if not tunnels_html:
|
|
140
|
+
tunnels_html = "<li>No active tunnels.</li>"
|
|
141
|
+
|
|
142
|
+
html = f"""
|
|
143
|
+
<html>
|
|
144
|
+
<head>
|
|
145
|
+
<title>Raytunnel Server Dashboard</title>
|
|
146
|
+
<style>
|
|
147
|
+
body {{ font-family: sans-serif; margin: 40px; background-color: #f7f9fa; color: #333; }}
|
|
148
|
+
h1 {{ color: #1a73e8; }}
|
|
149
|
+
ul {{ background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); list-style-type: none; }}
|
|
150
|
+
li {{ padding: 10px 0; border-bottom: 1px solid #eee; }}
|
|
151
|
+
li:last-child {{ border-bottom: none; }}
|
|
152
|
+
</style>
|
|
153
|
+
</head>
|
|
154
|
+
<body>
|
|
155
|
+
<h1>Raytunnel Dashboard</h1>
|
|
156
|
+
<p>Active tunnels:</p>
|
|
157
|
+
<ul>{tunnels_html}</ul>
|
|
158
|
+
</body>
|
|
159
|
+
</html>
|
|
160
|
+
"""
|
|
161
|
+
return HTMLResponse(content=html)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@app.websocket("/ws/control")
|
|
165
|
+
async def ws_control(websocket: WebSocket, token: str, subdomain: Optional[str] = None):
|
|
166
|
+
"""
|
|
167
|
+
Control channel for the tunnel client. Authenticates the client, allocates
|
|
168
|
+
resources, and keeps the channel alive.
|
|
169
|
+
"""
|
|
170
|
+
if token != TOKEN:
|
|
171
|
+
await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="Invalid token")
|
|
172
|
+
return
|
|
173
|
+
|
|
174
|
+
await websocket.accept()
|
|
175
|
+
|
|
176
|
+
# Generate or validate subdomain
|
|
177
|
+
if not subdomain:
|
|
178
|
+
subdomain = f"client-{uuid.uuid4().hex[:6]}"
|
|
179
|
+
else:
|
|
180
|
+
# Sanitize subdomain
|
|
181
|
+
subdomain = re.sub(r"[^a-zA-Z0-9-]", "", subdomain).lower()
|
|
182
|
+
if not subdomain:
|
|
183
|
+
subdomain = f"client-{uuid.uuid4().hex[:6]}"
|
|
184
|
+
|
|
185
|
+
# Handle collisions: evict old session if it exists to prevent subdomain drift on reconnect
|
|
186
|
+
if subdomain in active_tunnels:
|
|
187
|
+
logger.info(f"Subdomain '{subdomain}' is already active. Evicting stale session.")
|
|
188
|
+
old_info = active_tunnels.pop(subdomain, None)
|
|
189
|
+
if old_info:
|
|
190
|
+
# Cancel all pending channel futures so their coroutines can exit cleanly
|
|
191
|
+
for ch in old_info.get("pending_channels", {}).values():
|
|
192
|
+
fut = ch.get("close_fut")
|
|
193
|
+
if fut and not fut.done():
|
|
194
|
+
fut.cancel()
|
|
195
|
+
try:
|
|
196
|
+
ch["tcp_writer"].close()
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
try:
|
|
200
|
+
await old_info["control_ws"].close(code=status.WS_1001_GOING_AWAY, reason="Evicted by newer session")
|
|
201
|
+
except Exception:
|
|
202
|
+
pass
|
|
203
|
+
try:
|
|
204
|
+
old_info["ssh_server"].close()
|
|
205
|
+
await old_info["ssh_server"].wait_closed()
|
|
206
|
+
except Exception:
|
|
207
|
+
pass
|
|
208
|
+
used_ssh_ports.discard(old_info["ssh_port"])
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
# Allocate SSH Port
|
|
212
|
+
ssh_port = await allocate_ssh_port()
|
|
213
|
+
except Exception as e:
|
|
214
|
+
logger.error(f"Failed to allocate SSH port: {e}")
|
|
215
|
+
await websocket.send_json({"status": "error", "message": "No port available on server"})
|
|
216
|
+
await websocket.close()
|
|
217
|
+
return
|
|
218
|
+
|
|
219
|
+
# Create dynamic SSH TCP Server
|
|
220
|
+
async def handle_ssh_conn(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
|
|
221
|
+
channel_id = str(uuid.uuid4())
|
|
222
|
+
logger.info(f"New SSH connection on port {ssh_port}. Registering channel {channel_id}")
|
|
223
|
+
|
|
224
|
+
loop = asyncio.get_running_loop()
|
|
225
|
+
close_fut = loop.create_future()
|
|
226
|
+
connected_fut = loop.create_future()
|
|
227
|
+
active_tunnels[subdomain]["pending_channels"][channel_id] = {
|
|
228
|
+
"tcp_reader": reader,
|
|
229
|
+
"tcp_writer": writer,
|
|
230
|
+
"initial_data": b"",
|
|
231
|
+
"close_fut": close_fut,
|
|
232
|
+
"connected_fut": connected_fut
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
try:
|
|
236
|
+
# Signal client to open SSH channel — guard against closed/evicted WS
|
|
237
|
+
info = active_tunnels.get(subdomain)
|
|
238
|
+
if not info or info.get("session_id") != session_id:
|
|
239
|
+
logger.debug(f"Session {session_id} for '{subdomain}' already evicted; dropping SSH channel")
|
|
240
|
+
writer.close()
|
|
241
|
+
return
|
|
242
|
+
await websocket.send_json({
|
|
243
|
+
"action": "open_channel",
|
|
244
|
+
"channel_id": channel_id,
|
|
245
|
+
"type": "ssh"
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
# Wait for client to connect to ws/data (handshake) within 60 seconds
|
|
249
|
+
try:
|
|
250
|
+
await asyncio.wait_for(connected_fut, timeout=60.0)
|
|
251
|
+
except asyncio.TimeoutError:
|
|
252
|
+
logger.warning(f"SSH handshake timed out for channel {channel_id}")
|
|
253
|
+
writer.close()
|
|
254
|
+
return
|
|
255
|
+
|
|
256
|
+
# Once connected, wait indefinitely for the SSH connection to close
|
|
257
|
+
try:
|
|
258
|
+
await close_fut
|
|
259
|
+
except asyncio.CancelledError:
|
|
260
|
+
pass
|
|
261
|
+
except Exception as err:
|
|
262
|
+
logger.error(f"Error handling SSH connection: {err}")
|
|
263
|
+
writer.close()
|
|
264
|
+
try:
|
|
265
|
+
await writer.wait_closed()
|
|
266
|
+
except Exception:
|
|
267
|
+
pass
|
|
268
|
+
finally:
|
|
269
|
+
active_tunnels[subdomain]["pending_channels"].pop(channel_id, None)
|
|
270
|
+
|
|
271
|
+
try:
|
|
272
|
+
ssh_server = await asyncio.start_server(handle_ssh_conn, "0.0.0.0", ssh_port)
|
|
273
|
+
except Exception as e:
|
|
274
|
+
logger.error(f"Failed to start SSH server on port {ssh_port}: {e}")
|
|
275
|
+
used_ssh_ports.discard(ssh_port)
|
|
276
|
+
await websocket.send_json({"status": "error", "message": "Failed to open SSH port on server"})
|
|
277
|
+
await websocket.close()
|
|
278
|
+
return
|
|
279
|
+
|
|
280
|
+
session_id = uuid.uuid4().hex
|
|
281
|
+
|
|
282
|
+
# Register tunnel
|
|
283
|
+
active_tunnels[subdomain] = {
|
|
284
|
+
"session_id": session_id,
|
|
285
|
+
"control_ws": websocket,
|
|
286
|
+
"ssh_port": ssh_port,
|
|
287
|
+
"ssh_server": ssh_server,
|
|
288
|
+
"pending_channels": {}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
logger.info(f"Registered tunnel '{subdomain}' forwarding SSH on port {ssh_port}")
|
|
292
|
+
|
|
293
|
+
# Send welcome / configuration details to client
|
|
294
|
+
await websocket.send_json({
|
|
295
|
+
"status": "success",
|
|
296
|
+
"subdomain": subdomain,
|
|
297
|
+
"ssh_port": ssh_port
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
# Wait for client disconnect or ping failures
|
|
301
|
+
try:
|
|
302
|
+
while True:
|
|
303
|
+
# Simple keep-alive ping loop — guard: only ping while this session is still registered
|
|
304
|
+
await asyncio.sleep(30)
|
|
305
|
+
info = active_tunnels.get(subdomain)
|
|
306
|
+
if not info or info.get("session_id") != session_id:
|
|
307
|
+
# This session has been evicted; exit the loop silently
|
|
308
|
+
break
|
|
309
|
+
try:
|
|
310
|
+
await websocket.send_json({"action": "ping"})
|
|
311
|
+
except Exception:
|
|
312
|
+
# WS already closed (evicted or disconnected)
|
|
313
|
+
break
|
|
314
|
+
except WebSocketDisconnect:
|
|
315
|
+
logger.info(f"Client '{subdomain}' disconnected.")
|
|
316
|
+
except Exception as e:
|
|
317
|
+
logger.error(f"Error on control websocket for '{subdomain}': {e}")
|
|
318
|
+
finally:
|
|
319
|
+
# Cleanup allocated resources only if it belongs to this session
|
|
320
|
+
info = active_tunnels.get(subdomain)
|
|
321
|
+
if info and info.get("session_id") == session_id:
|
|
322
|
+
active_tunnels.pop(subdomain, None)
|
|
323
|
+
info["ssh_server"].close()
|
|
324
|
+
await info["ssh_server"].wait_closed()
|
|
325
|
+
used_ssh_ports.discard(info["ssh_port"])
|
|
326
|
+
logger.info(f"Cleaned up tunnel '{subdomain}' and released port {info['ssh_port']}.")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@app.websocket("/ws/data")
|
|
330
|
+
async def ws_data(websocket: WebSocket, channel_id: str):
|
|
331
|
+
"""
|
|
332
|
+
Pipes raw data to/from the local app.
|
|
333
|
+
When a client receives an `open_channel` request, it connects here to hook
|
|
334
|
+
up the data pipeline.
|
|
335
|
+
"""
|
|
336
|
+
await websocket.accept()
|
|
337
|
+
|
|
338
|
+
# Find the corresponding channel info
|
|
339
|
+
channel_info = None
|
|
340
|
+
for sub, tunnel in active_tunnels.items():
|
|
341
|
+
if channel_id in tunnel["pending_channels"]:
|
|
342
|
+
channel_info = tunnel["pending_channels"].pop(channel_id)
|
|
343
|
+
break
|
|
344
|
+
|
|
345
|
+
if not channel_info:
|
|
346
|
+
logger.warning(f"Data channel connection received for unknown/expired channel_id: {channel_id}")
|
|
347
|
+
await websocket.close(code=status.WS_1008_POLICY_VIOLATION, reason="Unknown channel_id")
|
|
348
|
+
return
|
|
349
|
+
|
|
350
|
+
tcp_reader = channel_info["tcp_reader"]
|
|
351
|
+
tcp_writer = channel_info["tcp_writer"]
|
|
352
|
+
initial_data = channel_info["initial_data"]
|
|
353
|
+
close_fut = channel_info["close_fut"]
|
|
354
|
+
connected_fut = channel_info.get("connected_fut")
|
|
355
|
+
|
|
356
|
+
if connected_fut and not connected_fut.done():
|
|
357
|
+
connected_fut.set_result(True)
|
|
358
|
+
|
|
359
|
+
try:
|
|
360
|
+
await pipe_websocket_tcp(websocket, tcp_reader, tcp_writer, initial_data)
|
|
361
|
+
finally:
|
|
362
|
+
if not close_fut.done():
|
|
363
|
+
close_fut.set_result(True)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
# --- TCP Host-Based Proxy Server (Port 8000) ---
|
|
367
|
+
async def start_http_routing_server(tcp_port: int):
|
|
368
|
+
"""
|
|
369
|
+
Starts a raw TCP server that inspects the HTTP Host header of incoming connections
|
|
370
|
+
and routes them to the correct client tunnel.
|
|
371
|
+
"""
|
|
372
|
+
async def handle_http_conn(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
|
|
373
|
+
peer = writer.get_extra_info("peername")
|
|
374
|
+
try:
|
|
375
|
+
# Read first chunk of data containing HTTP request headers
|
|
376
|
+
initial_data = await reader.read(4096)
|
|
377
|
+
if not initial_data:
|
|
378
|
+
writer.close()
|
|
379
|
+
return
|
|
380
|
+
|
|
381
|
+
# Log first line of HTTP request for debugging
|
|
382
|
+
request_line = initial_data.split(b"\r\n")[0].decode("utf-8", errors="ignore")
|
|
383
|
+
logger.info(f"[HTTP-ROUTER] New connection from {peer}: {request_line}")
|
|
384
|
+
|
|
385
|
+
# Find the Host header
|
|
386
|
+
host_match = re.search(b'(?i)host:\\s*([a-zA-Z0-9.-]+)', initial_data)
|
|
387
|
+
if not host_match:
|
|
388
|
+
logger.warning(f"[HTTP-ROUTER] No Host header from {peer}")
|
|
389
|
+
# No host header, reject
|
|
390
|
+
writer.write(b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\nNo Host Header")
|
|
391
|
+
await writer.drain()
|
|
392
|
+
writer.close()
|
|
393
|
+
return
|
|
394
|
+
|
|
395
|
+
host = host_match.group(1).decode("utf-8", errors="ignore")
|
|
396
|
+
subdomain = get_subdomain_from_host(host)
|
|
397
|
+
logger.info(f"[HTTP-ROUTER] host={host} subdomain={subdomain} active_tunnels={list(active_tunnels.keys())}")
|
|
398
|
+
|
|
399
|
+
if not subdomain or subdomain not in active_tunnels:
|
|
400
|
+
# Subdomain not registered or inactive
|
|
401
|
+
logger.warning(f"[HTTP-ROUTER] 502 — subdomain '{subdomain}' not in active_tunnels")
|
|
402
|
+
html_resp = f"""HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n
|
|
403
|
+
<html>
|
|
404
|
+
<head><title>502 Tunnel Not Found</title></head>
|
|
405
|
+
<body style="font-family: sans-serif; text-align: center; padding-top: 100px;">
|
|
406
|
+
<h1 style="color: #e51c23;">502 Tunnel Offline</h1>
|
|
407
|
+
<p>The tunnel subdomain <strong>{subdomain or host}</strong> is offline or not registered.</p>
|
|
408
|
+
</body>
|
|
409
|
+
</html>"""
|
|
410
|
+
writer.write(html_resp.encode("utf-8"))
|
|
411
|
+
await writer.drain()
|
|
412
|
+
writer.close()
|
|
413
|
+
return
|
|
414
|
+
|
|
415
|
+
# Subdomain is active. Route it!
|
|
416
|
+
tunnel = active_tunnels[subdomain]
|
|
417
|
+
channel_id = str(uuid.uuid4())
|
|
418
|
+
loop = asyncio.get_running_loop()
|
|
419
|
+
close_fut = loop.create_future()
|
|
420
|
+
connected_fut = loop.create_future()
|
|
421
|
+
|
|
422
|
+
tunnel["pending_channels"][channel_id] = {
|
|
423
|
+
"tcp_reader": reader,
|
|
424
|
+
"tcp_writer": writer,
|
|
425
|
+
"initial_data": initial_data,
|
|
426
|
+
"close_fut": close_fut,
|
|
427
|
+
"connected_fut": connected_fut
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
logger.info(f"[HTTP-ROUTER] Channel {channel_id[:8]} created for '{subdomain}' — notifying client")
|
|
431
|
+
|
|
432
|
+
# Notify the client to open an HTTP tunnel channel
|
|
433
|
+
# Guard: the control_ws may have just been closed (eviction race)
|
|
434
|
+
try:
|
|
435
|
+
await tunnel["control_ws"].send_json({
|
|
436
|
+
"action": "open_channel",
|
|
437
|
+
"channel_id": channel_id,
|
|
438
|
+
"type": "http"
|
|
439
|
+
})
|
|
440
|
+
except Exception as send_err:
|
|
441
|
+
# Control WS closed before we could notify — clean up and bail
|
|
442
|
+
tunnel["pending_channels"].pop(channel_id, None)
|
|
443
|
+
if not close_fut.done():
|
|
444
|
+
close_fut.cancel()
|
|
445
|
+
logger.warning(f"[HTTP-ROUTER] control_ws send FAILED for '{subdomain}' ch={channel_id[:8]}: {send_err}")
|
|
446
|
+
writer.write(b"HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\nTunnel disconnected")
|
|
447
|
+
try:
|
|
448
|
+
await writer.drain()
|
|
449
|
+
except Exception:
|
|
450
|
+
pass
|
|
451
|
+
writer.close()
|
|
452
|
+
return
|
|
453
|
+
|
|
454
|
+
# Wait for data ws connection (handshake) within 60 seconds
|
|
455
|
+
logger.info(f"[HTTP-ROUTER] Waiting for client WS handshake ch={channel_id[:8]}")
|
|
456
|
+
try:
|
|
457
|
+
await asyncio.wait_for(connected_fut, timeout=60.0)
|
|
458
|
+
logger.info(f"[HTTP-ROUTER] Handshake OK ch={channel_id[:8]} — piping data")
|
|
459
|
+
except asyncio.TimeoutError:
|
|
460
|
+
logger.warning(f"[HTTP-ROUTER] Handshake TIMEOUT (60s) for ch={channel_id[:8]}")
|
|
461
|
+
tunnel["pending_channels"].pop(channel_id, None)
|
|
462
|
+
writer.close()
|
|
463
|
+
return
|
|
464
|
+
|
|
465
|
+
# Wait indefinitely for completion of piping
|
|
466
|
+
try:
|
|
467
|
+
await close_fut
|
|
468
|
+
logger.info(f"[HTTP-ROUTER] Pipe complete ch={channel_id[:8]}")
|
|
469
|
+
except (asyncio.CancelledError, Exception) as e:
|
|
470
|
+
logger.debug(f"[HTTP-ROUTER] Pipe ended ch={channel_id[:8]}: {e}")
|
|
471
|
+
|
|
472
|
+
except Exception as e:
|
|
473
|
+
logger.error(f"[HTTP-ROUTER] Unhandled error from {peer}: {e}")
|
|
474
|
+
writer.close()
|
|
475
|
+
|
|
476
|
+
server = await asyncio.start_server(handle_http_conn, "0.0.0.0", tcp_port)
|
|
477
|
+
logger.info(f"HTTP Routing TCP Server listening on 0.0.0.0:{tcp_port}")
|
|
478
|
+
return server
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
async def run_server(host: str, api_port: int, tcp_port: int, token: str, domain: str = "s.yourdomain.com"):
|
|
482
|
+
"""Runs the main server combining FastAPI and the TCP Host Router."""
|
|
483
|
+
global TOKEN, DOMAIN
|
|
484
|
+
TOKEN = token
|
|
485
|
+
DOMAIN = domain
|
|
486
|
+
|
|
487
|
+
# Start dynamic HTTP router
|
|
488
|
+
http_router = await start_http_routing_server(tcp_port)
|
|
489
|
+
|
|
490
|
+
# Start FastAPI API & WS server
|
|
491
|
+
config = uvicorn.Config(app, host=host, port=api_port, log_level="info", ws_ping_interval=None)
|
|
492
|
+
server = uvicorn.Server(config)
|
|
493
|
+
|
|
494
|
+
try:
|
|
495
|
+
await server.serve()
|
|
496
|
+
finally:
|
|
497
|
+
http_router.close()
|
|
498
|
+
await http_router.wait_closed()
|
|
499
|
+
logger.info("Server stopped.")
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: raytunnel
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A lightweight, secure reverse tunnel and SSH forwarding tool — Ngrok/Gradio alternative for Homelab.
|
|
5
|
+
Project-URL: Homepage, https://github.com/mrtruongleo/raytunnel
|
|
6
|
+
Project-URL: Repository, https://github.com/mrtruongleo/raytunnel
|
|
7
|
+
Project-URL: Issues, https://github.com/mrtruongleo/raytunnel/issues
|
|
8
|
+
Author-email: mrtruongleo <66201727+mrtruongleo@users.noreply.github.com>
|
|
9
|
+
License: MIT
|
|
10
|
+
Keywords: homelab,kaggle,ngrok,reverse-proxy,ssh,tunnel,websocket
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Internet :: Proxy Servers
|
|
20
|
+
Classifier: Topic :: System :: Networking
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Requires-Dist: click>=8.0.0
|
|
23
|
+
Requires-Dist: fastapi>=0.100.0
|
|
24
|
+
Requires-Dist: rich>=13.0.0
|
|
25
|
+
Requires-Dist: uvicorn>=0.22.0
|
|
26
|
+
Requires-Dist: websockets>=11.0.0
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# Raytunnel 🚀
|
|
30
|
+
|
|
31
|
+
Raytunnel là một giải pháp reverse tunnel (HTTP và SSH forwarding) siêu nhẹ, bảo mật và được thiết kế tối giản nhằm thay thế cho Gradio/Ngrok. Thích hợp nhất cho việc tương tác giữa máy cá nhân và các remote instance (Kaggle, Colab, Cloud Server) kết nối trực tiếp về hệ thống Homelab.
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## 🌟 Tính năng nổi bật
|
|
36
|
+
|
|
37
|
+
- **Tối giản & Tự chủ**: Hoạt động hoàn toàn trong user-space, không cần cấu hình tài khoản Unix hay SSH keys phức tạp trên Host OS của server.
|
|
38
|
+
- **Tự động cấu hình SSH Daemon**: Client tự phát hiện, cấu hình và khởi chạy SSH Daemon (`sshd`) ở cổng 2222, tạo cặp khóa SSH động giúp bạn SSH trực tiếp vào remote instance (ví dụ: Kaggle) cực kỳ tiện lợi.
|
|
39
|
+
- **Dynamic HTTP Host Routing**: Tự động phân tích trường `Host` trong HTTP request để điều hướng tới đúng client đăng ký (ví dụ: `my-worker.s.yourdomain.com`).
|
|
40
|
+
- **Thân thiện với Notebook**: Có sẵn API bất đồng bộ chạy ngầm (`background=True`) để bạn gọi trực tiếp trong cell của Jupyter/Kaggle notebook mà không làm nghẽn luồng xử lý chính.
|
|
41
|
+
- **Bảo mật tuyệt đối**:
|
|
42
|
+
- Xác thực kết nối điều khiển bằng Token bí mật.
|
|
43
|
+
- SSH daemon được cấu hình chỉ nhận khóa public key, cấm đăng nhập bằng mật khẩu (`PasswordAuthentication no`).
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## 📐 Kiến trúc hoạt động
|
|
48
|
+
|
|
49
|
+
```mermaid
|
|
50
|
+
sequenceDiagram
|
|
51
|
+
participant Client as Kaggle / Remote Worker
|
|
52
|
+
participant Server as Raytunnel Server (s.yourdomain.com)
|
|
53
|
+
participant Proxy as Reverse Proxy (Traefik / NPM)
|
|
54
|
+
participant User as Terminal / Trình duyệt
|
|
55
|
+
|
|
56
|
+
Client->>Server: Kết nối wss://s.yourdomain.com/ws/control + Auth Token
|
|
57
|
+
Server-->>Client: Trả về Subdomain: client-abc, SSH Port: 2200
|
|
58
|
+
|
|
59
|
+
Note over User,Client: Chuyển tiếp HTTP Web App
|
|
60
|
+
User->>Proxy: Truy cập https://client-abc.s.yourdomain.com
|
|
61
|
+
Proxy->>Server: Forward HTTP → cổng 8000 (TCP router)
|
|
62
|
+
Server->>Client: Yêu cầu mở kênh HTTP
|
|
63
|
+
Client->>Server: Kết nối wss://s.yourdomain.com/ws/data?channel_id=xxx
|
|
64
|
+
Client->>Client: Forward tới web app local (cổng 8000)
|
|
65
|
+
Server-->>Client: Chuyển tiếp dữ liệu hai chiều (TCP <-> WS)
|
|
66
|
+
|
|
67
|
+
Note over User,Client: Kết nối SSH Terminal
|
|
68
|
+
User->>Server: Chạy ssh -p 2200 user@s.yourdomain.com
|
|
69
|
+
Server->>Client: Yêu cầu mở kênh SSH
|
|
70
|
+
Client->>Server: Kết nối wss://s.yourdomain.com/ws/data?channel_id=yyy
|
|
71
|
+
Client->>Client: Forward tới SSH Daemon nội bộ (cổng 2222)
|
|
72
|
+
Server-->>Client: Chuyển tiếp luồng terminal hai chiều
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Phân vai các cổng
|
|
76
|
+
|
|
77
|
+
| Cổng | Mục đích |
|
|
78
|
+
|------|----------|
|
|
79
|
+
| `8001` | FastAPI API + WebSocket control (`/ws/control`, `/ws/data`) + Dashboard |
|
|
80
|
+
| `8000` | TCP raw proxy — đọc Host header và route HTTP traffic đến đúng client |
|
|
81
|
+
| `2200-2300` | Dải cổng SSH động được server cấp phát cho từng tunnel |
|
|
82
|
+
|
|
83
|
+
> [!IMPORTANT]
|
|
84
|
+
> Reverse proxy cần **2 route riêng biệt**: `s.yourdomain.com` → cổng **8001** (control WebSocket + Dashboard), `*.s.yourdomain.com` → cổng **8000** (HTTP tunnel traffic). Nếu route tất cả về 8000, client sẽ gặp lỗi `HTTP 404` khi kết nối WebSocket control.
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## 📦 Cấu trúc dự án
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
raytunnel/
|
|
92
|
+
├── src/ # Source code Python
|
|
93
|
+
├── Dockerfile # Docker image definition
|
|
94
|
+
├── compose.yaml # Docker Compose config
|
|
95
|
+
├── example-env # Template file biến môi trường
|
|
96
|
+
├── raytunnel-server.service # Systemd service file
|
|
97
|
+
├── pyproject.toml
|
|
98
|
+
└── README.md
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 🛠 Hướng dẫn Cấu hình & Triển khai
|
|
104
|
+
|
|
105
|
+
### 1. Triển khai Server (Trên Proxmox Container / VPS)
|
|
106
|
+
|
|
107
|
+
Bạn có ba cách để chạy server:
|
|
108
|
+
|
|
109
|
+
#### Cách A: Chạy trực tiếp qua Systemd Service (Khuyên dùng)
|
|
110
|
+
|
|
111
|
+
1. Cài đặt package `raytunnel` trên container:
|
|
112
|
+
```bash
|
|
113
|
+
pip install git+https://github.com/mrtruongleo/raytunnel.git
|
|
114
|
+
```
|
|
115
|
+
2. Copy file `raytunnel-server.service` vào `/etc/systemd/system/`:
|
|
116
|
+
```bash
|
|
117
|
+
cp raytunnel-server.service /etc/systemd/system/
|
|
118
|
+
```
|
|
119
|
+
3. Chỉnh sửa dòng `ExecStart` trong file service — thêm token và domain thực:
|
|
120
|
+
```ini
|
|
121
|
+
ExecStart=/usr/local/bin/raytunnel server --host 0.0.0.0 --port 8001 --tcp-port 8000 --token your_very_strong_token --domain s.yourdomain.com
|
|
122
|
+
```
|
|
123
|
+
4. Kích hoạt và chạy dịch vụ:
|
|
124
|
+
```bash
|
|
125
|
+
sudo systemctl daemon-reload
|
|
126
|
+
sudo systemctl enable --now raytunnel-server
|
|
127
|
+
sudo systemctl status raytunnel-server
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
#### Cách B: Chạy qua Docker Compose
|
|
131
|
+
|
|
132
|
+
1. Copy file cấu hình môi trường:
|
|
133
|
+
```bash
|
|
134
|
+
cp example-env .env
|
|
135
|
+
```
|
|
136
|
+
2. Chỉnh sửa `.env` với token và domain thực của bạn:
|
|
137
|
+
```env
|
|
138
|
+
RAYTUNNEL_TOKEN=your_very_strong_token
|
|
139
|
+
DOMAIN=s.yourdomain.com
|
|
140
|
+
```
|
|
141
|
+
3. Build và chạy từ thư mục gốc của project:
|
|
142
|
+
```bash
|
|
143
|
+
docker compose up -d --build
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Verify sau khi start:
|
|
147
|
+
```bash
|
|
148
|
+
docker logs raytunnel-server --tail 20
|
|
149
|
+
curl http://localhost:8001 # → Dashboard hiện "No active tunnels"
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
> [!WARNING]
|
|
153
|
+
> **Không dùng shell variable** `${RAYTUNNEL_TOKEN:-default}` trong compose.yaml nếu bạn không set env trước khi chạy — sẽ dùng giá trị `default` thay vì token thực. Luôn dùng file `.env` hoặc hardcode trực tiếp.
|
|
154
|
+
|
|
155
|
+
#### Cách C: Chạy qua Docker CLI trực tiếp
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
docker build -t raytunnel-server .
|
|
159
|
+
docker run -d --name raytunnel \
|
|
160
|
+
-p 8000:8000 -p 8001:8001 -p 2200-2300:2200-2300 \
|
|
161
|
+
-e RAYTUNNEL_TOKEN="your_very_strong_token" \
|
|
162
|
+
-e DOMAIN="s.yourdomain.com" \
|
|
163
|
+
raytunnel-server
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
### 2. Cấu hình DNS & Reverse Proxy
|
|
169
|
+
|
|
170
|
+
#### 2.1 DNS trên Cloudflare
|
|
171
|
+
|
|
172
|
+
Tạo 2 bản ghi CNAME (hoặc A) trỏ về IP public của homelab:
|
|
173
|
+
|
|
174
|
+
| Type | Name | Target | Proxy |
|
|
175
|
+
|------|------|--------|-------|
|
|
176
|
+
| `CNAME` | `s` | `ip.yourdomain.com` | Proxied ☁️ |
|
|
177
|
+
| `CNAME` | `*.s` | `ip.yourdomain.com` | **DNS only** 🔘 |
|
|
178
|
+
|
|
179
|
+
> [!WARNING]
|
|
180
|
+
> Cloudflare **Free plan không hỗ trợ Proxied wildcard** — bắt buộc để `*.s` là **DNS only** (grey cloud). Verify bằng: `dig rvc.s.yourdomain.com @1.1.1.1 +short`
|
|
181
|
+
|
|
182
|
+
#### 2.2 Port Forwarding trên Router
|
|
183
|
+
|
|
184
|
+
| External Port | Internal IP | Internal Port | Protocol |
|
|
185
|
+
|--------------|-------------|---------------|----------|
|
|
186
|
+
| `443` | IP của reverse proxy | `443` | TCP |
|
|
187
|
+
| `2200-2300` | IP của raytunnel server | `2200-2300` | TCP |
|
|
188
|
+
|
|
189
|
+
> [!NOTE]
|
|
190
|
+
> Cổng `2200-2300` chỉ thực sự listen sau khi có client kết nối. `Connection refused` trên cổng này là bình thường khi chưa có tunnel nào hoạt động.
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
#### 2.3 Cấu hình Traefik (Nếu bạn dùng Traefik)
|
|
195
|
+
|
|
196
|
+
Thêm service raytunnel vào Traefik bằng cách tạo một file config động trong thư mục dynamic config của Traefik (ví dụ: `./external/raytunnel.yaml`):
|
|
197
|
+
|
|
198
|
+
```yaml
|
|
199
|
+
http:
|
|
200
|
+
routers:
|
|
201
|
+
# Control plane: WebSocket /ws/control + Dashboard — cổng 8001 (FastAPI)
|
|
202
|
+
raytunnel-control:
|
|
203
|
+
rule: "Host(`s.yourdomain.com`)"
|
|
204
|
+
entryPoints:
|
|
205
|
+
- websecure
|
|
206
|
+
service: raytunnel-api
|
|
207
|
+
tls:
|
|
208
|
+
certResolver: production
|
|
209
|
+
|
|
210
|
+
# Tunnel traffic: worker.s.yourdomain.com — cổng 8000 (TCP router)
|
|
211
|
+
raytunnel-tunnel:
|
|
212
|
+
rule: "HostRegexp(`{subdomain:[a-z0-9-]+}.s.yourdomain.com`)"
|
|
213
|
+
entryPoints:
|
|
214
|
+
- websecure
|
|
215
|
+
service: raytunnel-tcp
|
|
216
|
+
tls:
|
|
217
|
+
certResolver: production
|
|
218
|
+
|
|
219
|
+
services:
|
|
220
|
+
raytunnel-api:
|
|
221
|
+
loadBalancer:
|
|
222
|
+
servers:
|
|
223
|
+
- url: "http://<IP_RAYTUNNEL_SERVER>:8001" # Control/WS API
|
|
224
|
+
|
|
225
|
+
raytunnel-tcp:
|
|
226
|
+
loadBalancer:
|
|
227
|
+
servers:
|
|
228
|
+
- url: "http://<IP_RAYTUNNEL_SERVER>:8000" # HTTP tunnel routing
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
> [!NOTE]
|
|
232
|
+
> Thay `<IP_RAYTUNNEL_SERVER>` bằng IP thực của container/VPS đang chạy raytunnel server. Đảm bảo thư mục dynamic config của Traefik đang được watch (thường cấu hình qua `providers.file.directory` trong `traefik.yaml`).
|
|
233
|
+
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
#### 2.4 Cấu hình Nginx Proxy Manager (Nếu bạn dùng NPM)
|
|
237
|
+
|
|
238
|
+
Nginx Proxy Manager cần **2 Proxy Host** riêng biệt. Cả hai đều cần bật **SSL với Let's Encrypt**.
|
|
239
|
+
|
|
240
|
+
##### Proxy Host 1 — Control Plane (`s.yourdomain.com`)
|
|
241
|
+
|
|
242
|
+
Vào **Proxy Hosts → Add Proxy Host**, điền như sau:
|
|
243
|
+
|
|
244
|
+
| Trường | Giá trị |
|
|
245
|
+
|--------|---------|
|
|
246
|
+
| Domain Names | `s.yourdomain.com` |
|
|
247
|
+
| Scheme | `http` |
|
|
248
|
+
| Forward Hostname/IP | `<IP_RAYTUNNEL_SERVER>` |
|
|
249
|
+
| Forward Port | `8001` |
|
|
250
|
+
| Websockets Support | ✅ Bật |
|
|
251
|
+
| Block Common Exploits | ✅ Bật |
|
|
252
|
+
|
|
253
|
+
Tab **SSL**: Chọn **Request a new SSL Certificate**, bật **Force SSL** và **HTTP/2 Support**.
|
|
254
|
+
|
|
255
|
+
##### Proxy Host 2 — Tunnel Traffic (`*.s.yourdomain.com`)
|
|
256
|
+
|
|
257
|
+
Vào **Proxy Hosts → Add Proxy Host**, điền như sau:
|
|
258
|
+
|
|
259
|
+
| Trường | Giá trị |
|
|
260
|
+
|--------|---------|
|
|
261
|
+
| Domain Names | `*.s.yourdomain.com` |
|
|
262
|
+
| Scheme | `http` |
|
|
263
|
+
| Forward Hostname/IP | `<IP_RAYTUNNEL_SERVER>` |
|
|
264
|
+
| Forward Port | `8000` |
|
|
265
|
+
| Websockets Support | ✅ Bật |
|
|
266
|
+
| Block Common Exploits | ✅ Bật |
|
|
267
|
+
|
|
268
|
+
Tab **SSL**: Chọn **Request a new SSL Certificate** — NPM sẽ issue wildcard cert qua DNS Challenge.
|
|
269
|
+
|
|
270
|
+
> [!IMPORTANT]
|
|
271
|
+
> **Wildcard SSL (`*.s.yourdomain.com`) bắt buộc phải dùng DNS Challenge** (HTTP Challenge không hỗ trợ wildcard). Trong NPM, tab SSL → chọn DNS Challenge provider (ví dụ Cloudflare) → nhập API Token Cloudflare có quyền `Zone:DNS:Edit`.
|
|
272
|
+
|
|
273
|
+
> [!WARNING]
|
|
274
|
+
> NPM không thực hiện routing theo subdomain ở tầng ứng dụng — toàn bộ `*.s.yourdomain.com` được forward thẳng về cổng `8000` của raytunnel server, và **raytunnel server tự xử lý routing** dựa vào `Host` header. Đây là hành vi đúng và mong muốn.
|
|
275
|
+
|
|
276
|
+
Tab **Advanced** của Proxy Host 2, thêm custom Nginx config để đảm bảo `Host` header được truyền đúng:
|
|
277
|
+
|
|
278
|
+
```nginx
|
|
279
|
+
proxy_set_header Host $host;
|
|
280
|
+
proxy_set_header X-Real-IP $remote_addr;
|
|
281
|
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
282
|
+
proxy_set_header X-Forwarded-Proto $scheme;
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
---
|
|
286
|
+
|
|
287
|
+
### 3. Cài đặt & Sử dụng Client (Trên Kaggle / Colab / Máy trạm)
|
|
288
|
+
|
|
289
|
+
```bash
|
|
290
|
+
# Cài đặt qua pip từ Git (môi trường remote)
|
|
291
|
+
pip install git+https://github.com/mrtruongleo/raytunnel.git
|
|
292
|
+
|
|
293
|
+
# Hoặc cài đặt ở chế độ editable (phát triển local)
|
|
294
|
+
uv pip install -e /path/to/raytunnel
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
#### Cách A: Sử dụng Command Line (CLI)
|
|
298
|
+
|
|
299
|
+
```bash
|
|
300
|
+
raytunnel client --server s.yourdomain.com --token your_very_strong_token --port 8000 --ssh --subdomain my-kaggle-job
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
#### Cách B: Chạy Programmatic trong Python / Jupyter Notebook
|
|
304
|
+
|
|
305
|
+
> [!WARNING]
|
|
306
|
+
> **Kaggle không hỗ trợ background process qua `!command &`** — sẽ gặp lỗi `OSError: Background processes not supported`. Phải dùng `subprocess.Popen`.
|
|
307
|
+
|
|
308
|
+
```python
|
|
309
|
+
import subprocess, time
|
|
310
|
+
|
|
311
|
+
proc = subprocess.Popen(
|
|
312
|
+
[
|
|
313
|
+
"raytunnel", "client",
|
|
314
|
+
"--server", "s.yourdomain.com",
|
|
315
|
+
"--token", "your_very_strong_token",
|
|
316
|
+
"--port", "8000", # Cổng local của Web App (RVC, Gradio, v.v.)
|
|
317
|
+
"--ssh", # Bật SSH Terminal
|
|
318
|
+
"--subdomain", "my-worker" # Subdomain mong muốn
|
|
319
|
+
],
|
|
320
|
+
stdout=open("raytunnel.log", "w"),
|
|
321
|
+
stderr=subprocess.STDOUT
|
|
322
|
+
)
|
|
323
|
+
print(f"Raytunnel PID: {proc.pid}")
|
|
324
|
+
|
|
325
|
+
# Chờ kết nối thiết lập
|
|
326
|
+
time.sleep(8)
|
|
327
|
+
with open("raytunnel.log") as f:
|
|
328
|
+
print(f.read())
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
Kết quả mong đợi trong log:
|
|
332
|
+
```
|
|
333
|
+
✔ Raytunnel Established Successfully!
|
|
334
|
+
HTTP Web App URL: https://my-worker.s.yourdomain.com
|
|
335
|
+
SSH Command: ssh -i ~/.ssh/raytunnel_id_ed25519 -p 2200 root@s.yourdomain.com
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
Dừng tunnel:
|
|
339
|
+
```python
|
|
340
|
+
proc.terminate()
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
---
|
|
344
|
+
|
|
345
|
+
## 🔒 Cơ chế Bảo mật của SSH
|
|
346
|
+
|
|
347
|
+
Khi bạn khởi chạy client với tùy chọn `--ssh`:
|
|
348
|
+
1. Client kiểm tra và tự động cài đặt `openssh-server` nếu môi trường chưa có.
|
|
349
|
+
2. Sinh một cặp khóa SSH tạm thời: Private key `~/.ssh/raytunnel_id_ed25519` và Public key được tự động thêm vào `~/.ssh/authorized_keys`.
|
|
350
|
+
3. Khởi chạy `sshd` ở cổng 2222 trong phạm vi user-space.
|
|
351
|
+
4. Server cấp phát một cổng SSH ngẫu nhiên trong dải `2200-2300` chuyển tiếp về client.
|
|
352
|
+
5. Để kết nối SSH vào Kaggle từ máy cá nhân:
|
|
353
|
+
```bash
|
|
354
|
+
# Copy private key từ Kaggle về máy, sau đó:
|
|
355
|
+
ssh -i raytunnel_id_ed25519 -p 2200 root@s.yourdomain.com
|
|
356
|
+
```
|
|
357
|
+
Server cấm đăng nhập bằng mật khẩu và chỉ nhận đúng khóa đã đăng ký — đảm bảo không ai brute-force được.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
raytunnel/__init__.py,sha256=d4RUb3ojogrUsrLDn71YA4t87XtJ4g8EYI39Rc7OyxQ,2352
|
|
2
|
+
raytunnel/cli.py,sha256=nVcaA9fl8xF5Q7iAPGiDavCDVUb7FkRZQjjtL4xBLws,2713
|
|
3
|
+
raytunnel/client.py,sha256=qVlnBYVW867lqkhdr4exxbntxMrenTTk6-bHAYR86Hc,13165
|
|
4
|
+
raytunnel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
raytunnel/server.py,sha256=2bANMMb8m2L4OILLhY1fpPXAsiEjNFQGk7YPeUGn3jg,19370
|
|
6
|
+
raytunnel-0.1.0.dist-info/METADATA,sha256=swrAC8_h-r7XcjO95BGJkIRtQyr8heypYdxl2b53xV8,13907
|
|
7
|
+
raytunnel-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
8
|
+
raytunnel-0.1.0.dist-info/entry_points.txt,sha256=4ocV7JFttYEg9jYBknCFttgtrNPl2ozKcs_LiJJ_Id4,49
|
|
9
|
+
raytunnel-0.1.0.dist-info/RECORD,,
|