1import asyncio
2import base64
3import json
4import os
5import sys
6
7import click
8from plain.cli import register_cli
9
10from .protocol import (
11 DEFAULT_EXEC_TIMEOUT,
12 DEFAULT_RELAY_HOST,
13 FILE_CHUNK_SIZE,
14 MAX_FILE_SIZE,
15 chunk_count,
16 make_exec,
17 make_file_pull,
18 make_file_push,
19)
20
21
22def _check_response(response: dict) -> None:
23 """Exit with an error message if the response indicates failure."""
24 error = response.get("error")
25 if error:
26 print(error, file=sys.stderr)
27 sys.exit(1)
28
29
30@register_cli("portal")
31@click.group()
32def cli() -> None:
33 """Remote Python shell and file transfer via encrypted tunnel."""
34
35
36@cli.command()
37@click.option(
38 "--read-only",
39 "read_only",
40 is_flag=True,
41 help="Enforce a read-only database connection.",
42)
43@click.option(
44 "--read-write",
45 "read_write",
46 is_flag=True,
47 help="Allow database writes (prompts for confirmation).",
48)
49@click.option(
50 "--timeout",
51 default=30,
52 type=int,
53 help="Idle timeout in minutes (0 to disable).",
54)
55@click.option(
56 "--relay-host",
57 envvar="PLAIN_PORTAL_RELAY_HOST",
58 default=DEFAULT_RELAY_HOST,
59 hidden=True,
60)
61@click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt.")
62def start(
63 read_only: bool, read_write: bool, timeout: int, relay_host: str, yes: bool
64) -> None:
65 """Start a portal session on the remote machine.
66
67 The database mode must be stated explicitly with --read-only or --read-write,
68 so the intent is visible in the command itself.
69 """
70 if read_only == read_write:
71 raise click.UsageError("Specify exactly one of --read-only or --read-write.")
72
73 if (
74 read_write
75 and not yes
76 and not click.confirm(
77 "This session allows writes to the production database. Continue?"
78 )
79 ):
80 return
81
82 from .remote import run_remote
83
84 asyncio.run(
85 run_remote(writable=read_write, timeout_minutes=timeout, relay_host=relay_host)
86 )
87
88
89@cli.command()
90@click.argument("code")
91@click.option(
92 "--relay-host",
93 envvar="PLAIN_PORTAL_RELAY_HOST",
94 default=DEFAULT_RELAY_HOST,
95 hidden=True,
96)
97def connect(code: str, relay_host: str) -> None:
98 """Connect to a remote portal session."""
99 from .local import connect as do_connect
100
101 asyncio.run(do_connect(code, relay_host=relay_host))
102
103
104@cli.command("exec")
105@click.argument("code")
106@click.option("--json", "json_output", is_flag=True, help="Output as JSON.")
107@click.option(
108 "--timeout",
109 default=DEFAULT_EXEC_TIMEOUT,
110 type=int,
111 help=f"Execution timeout in seconds (default: {DEFAULT_EXEC_TIMEOUT}).",
112)
113def exec_command(code: str, json_output: bool, timeout: int) -> None:
114 """Execute Python code on the remote machine."""
115 from .local import send_exec_streaming
116
117 request = make_exec(code, json_output=json_output, timeout=timeout)
118
119 # Collect streamed stdout for --json mode, print directly otherwise
120 stdout_parts: list[str] = []
121
122 def on_stdout(data: str) -> None:
123 if json_output:
124 stdout_parts.append(data)
125 else:
126 print(data, end="", flush=True)
127
128 response = asyncio.run(send_exec_streaming(request, on_stdout))
129 _check_response(response)
130
131 if json_output:
132 print(
133 json.dumps(
134 {
135 "stdout": "".join(stdout_parts),
136 "return_value": response.get("return_value"),
137 "error": response.get("error"),
138 }
139 )
140 )
141 else:
142 return_value = response.get("return_value")
143 if return_value is not None:
144 print(f"→ {return_value}")
145
146
147@cli.command()
148@click.argument("remote_path")
149@click.argument("local_path")
150def pull(remote_path: str, local_path: str) -> None:
151 """Pull a file from the remote machine."""
152 from .local import send_command
153
154 request = make_file_pull(remote_path)
155 response = asyncio.run(send_command(request))
156 _check_response(response)
157
158 if response.get("type") == "file_data":
159 data = base64.b64decode(response["data"])
160 with open(local_path, "wb") as f:
161 f.write(data)
162 print(f"Pulled {remote_path} → {local_path} ({len(data)} bytes)")
163 else:
164 print(f"Unexpected response: {response}", file=sys.stderr)
165 sys.exit(1)
166
167
168@cli.command()
169@click.argument("local_path")
170@click.argument("remote_path")
171def push(local_path: str, remote_path: str) -> None:
172 """Push a file to the remote machine."""
173 from .local import send_command
174
175 if not os.path.exists(local_path):
176 print(f"File not found: {local_path}", file=sys.stderr)
177 sys.exit(1)
178
179 file_size = os.path.getsize(local_path)
180 if file_size > MAX_FILE_SIZE:
181 print(
182 f"File too large: {file_size} bytes (max {MAX_FILE_SIZE})",
183 file=sys.stderr,
184 )
185 sys.exit(1)
186
187 async def _push_all() -> dict:
188 chunks = chunk_count(file_size)
189 response = {}
190 with open(local_path, "rb") as f: # noqa: ASYNC230 — dedicated transfer loop; the file IO is the work
191 for i in range(chunks):
192 data = f.read(FILE_CHUNK_SIZE)
193 request = make_file_push(
194 remote_path=remote_path, chunk=i, chunks=chunks, data=data
195 )
196 response = await send_command(request)
197 if response.get("error"):
198 return response
199 return response
200
201 response = asyncio.run(_push_all())
202 _check_response(response)
203
204 total_bytes = response.get("bytes", file_size)
205 print(f"Pushed {local_path} → {remote_path} ({total_bytes} bytes)")