hookstride-cli 1.0.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.
- hookstride_cli/__init__.py +3 -0
- hookstride_cli/console.py +514 -0
- hookstride_cli/listen.py +227 -0
- hookstride_cli/main.py +1366 -0
- hookstride_cli-1.0.0.dist-info/METADATA +215 -0
- hookstride_cli-1.0.0.dist-info/RECORD +8 -0
- hookstride_cli-1.0.0.dist-info/WHEEL +4 -0
- hookstride_cli-1.0.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
"""Interactive Hookstride console with allowlisted project and destination writes.
|
|
2
|
+
|
|
3
|
+
The console never executes shell commands, retains tokens only in memory,
|
|
4
|
+
and stores no command history on disk.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import getpass
|
|
11
|
+
import os
|
|
12
|
+
import shlex
|
|
13
|
+
import uuid
|
|
14
|
+
import warnings
|
|
15
|
+
from collections.abc import Iterator
|
|
16
|
+
|
|
17
|
+
import click
|
|
18
|
+
from prompt_toolkit import PromptSession
|
|
19
|
+
from prompt_toolkit.completion import WordCompleter
|
|
20
|
+
from prompt_toolkit.formatted_text import FormattedText
|
|
21
|
+
from prompt_toolkit.history import InMemoryHistory
|
|
22
|
+
from typer.main import get_command
|
|
23
|
+
|
|
24
|
+
from . import main as cli
|
|
25
|
+
|
|
26
|
+
# Only these typed commands may execute through the console.
|
|
27
|
+
# Write actions are intentionally allowlisted, never automatically unlocked.
|
|
28
|
+
ALLOWED_COMMANDS: dict[str, set[str]] = {
|
|
29
|
+
"auth": {"status"},
|
|
30
|
+
"actions": {"list", "context", "workspaces", "preview", "apply"},
|
|
31
|
+
"projects": {"list", "use", "create", "update"},
|
|
32
|
+
"destinations": {"list", "create", "update"},
|
|
33
|
+
"keys": {"list"},
|
|
34
|
+
"events": {"list", "show", "send", "export"},
|
|
35
|
+
"billing": {"status", "history"},
|
|
36
|
+
"incoming": {"sources", "routes", "bindings", "registration-keys"},
|
|
37
|
+
"config": {"show"},
|
|
38
|
+
}
|
|
39
|
+
ROOT_COMMANDS = {"status", "stats", "metrics", "listen"}
|
|
40
|
+
|
|
41
|
+
# Aliases that feel like a familiar operator console.
|
|
42
|
+
SHOW_TARGETS: dict[str, tuple[str, ...] | None] = {
|
|
43
|
+
"options": None,
|
|
44
|
+
"projects": ("projects", "list"),
|
|
45
|
+
"destinations": ("destinations", "list"),
|
|
46
|
+
"keys": ("keys", "list"),
|
|
47
|
+
"events": ("events", "list"),
|
|
48
|
+
"billing": ("billing", "status"),
|
|
49
|
+
"payments": ("billing", "history"),
|
|
50
|
+
"sources": ("incoming", "sources"),
|
|
51
|
+
"routes": ("incoming", "routes"),
|
|
52
|
+
"bindings": ("incoming", "bindings"),
|
|
53
|
+
"registration-keys": ("incoming", "registration-keys"),
|
|
54
|
+
"stats": ("stats",),
|
|
55
|
+
"metrics": ("metrics",),
|
|
56
|
+
"status": ("status",),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
SAFE_HISTORY_COMMANDS = frozenset(
|
|
60
|
+
[
|
|
61
|
+
"help", "?", "clear", "exit", "quit", "back", "status", "stats", "metrics",
|
|
62
|
+
"history", "auth login", "auth logout", "auth status",
|
|
63
|
+
"projects list", "destinations list", "keys list", "billing status",
|
|
64
|
+
"billing history", "events list", "incoming sources",
|
|
65
|
+
"incoming routes", "incoming bindings", "incoming registration-keys",
|
|
66
|
+
"config show", "actions list", "actions context", "actions workspaces",
|
|
67
|
+
*(f"show {name}" for name in SHOW_TARGETS),
|
|
68
|
+
"set env dev", "set env production",
|
|
69
|
+
]
|
|
70
|
+
)
|
|
71
|
+
COMMAND_COMPLETIONS = sorted(
|
|
72
|
+
{
|
|
73
|
+
*SAFE_HISTORY_COMMANDS,
|
|
74
|
+
"actions preview ", "actions apply ", "metrics --days ", "listen ", "use ", "projects use ", "events show ", "events send ", "events list --status ",
|
|
75
|
+
"events list --origin ", "events list --page ", "set project ",
|
|
76
|
+
"projects create --name ", "projects update ",
|
|
77
|
+
"destinations create --name ", "destinations update ",
|
|
78
|
+
"set env ", "json ", "show ", "auth ",
|
|
79
|
+
}
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _project_uuid(value: str) -> str:
|
|
84
|
+
try:
|
|
85
|
+
return str(uuid.UUID(value))
|
|
86
|
+
except (ValueError, AttributeError):
|
|
87
|
+
raise cli.CLIError("Expected a valid project UUID.") from None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _is_project_uuid(value: str) -> bool:
|
|
91
|
+
try:
|
|
92
|
+
_project_uuid(value)
|
|
93
|
+
return True
|
|
94
|
+
except cli.CLIError:
|
|
95
|
+
return False
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _saved_project(environment: str) -> str | None:
|
|
99
|
+
settings = cli._read_config().get("projects", {})
|
|
100
|
+
value = settings.get(environment) if isinstance(settings, dict) else None
|
|
101
|
+
if not value:
|
|
102
|
+
return None
|
|
103
|
+
# An old/corrupt settings file should not crash the console.
|
|
104
|
+
try:
|
|
105
|
+
return _project_uuid(value)
|
|
106
|
+
except cli.CLIError:
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _history_safe(line: str) -> bool:
|
|
111
|
+
"""Only retain recognized non-sensitive commands in process memory."""
|
|
112
|
+
if len(line) > 180 or any(ord(ch) < 32 or ord(ch) > 126 for ch in line):
|
|
113
|
+
return False
|
|
114
|
+
line = line.strip()
|
|
115
|
+
if line in SAFE_HISTORY_COMMANDS:
|
|
116
|
+
return True
|
|
117
|
+
tokens = line.split()
|
|
118
|
+
if len(tokens) == 2 and tokens[0] == "use":
|
|
119
|
+
return (tokens[1].isascii() and tokens[1].isdecimal()
|
|
120
|
+
and len(tokens[1]) <= 6) or _is_project_uuid(tokens[1])
|
|
121
|
+
if len(tokens) == 3 and tokens[:2] in (
|
|
122
|
+
["projects", "use"], ["set", "project"], ["events", "show"],
|
|
123
|
+
):
|
|
124
|
+
return ((tokens[:2] != ["events", "show"]
|
|
125
|
+
and tokens[2].isascii() and tokens[2].isdecimal()
|
|
126
|
+
and len(tokens[2]) <= 6)
|
|
127
|
+
or _is_project_uuid(tokens[2]))
|
|
128
|
+
return False
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class SafeMemoryHistory(InMemoryHistory):
|
|
132
|
+
"""Only safe, non-sensitive recognized commands enter arrow-key history."""
|
|
133
|
+
|
|
134
|
+
def append_string(self, string: str) -> None:
|
|
135
|
+
if _history_safe(string):
|
|
136
|
+
super().append_string(string)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _missing_send_destination(args: list[str]) -> bool:
|
|
141
|
+
"""Check the required send argument before Typer can exit the console."""
|
|
142
|
+
# We deliberately inspect only known options. Unknown options remain
|
|
143
|
+
# Click's responsibility, without interpreting their values as a key.
|
|
144
|
+
index = 2
|
|
145
|
+
valued = {"--type", "--payload-file", "--timeout"}
|
|
146
|
+
while index < len(args):
|
|
147
|
+
token = args[index]
|
|
148
|
+
if token in {"--help", "-h"}:
|
|
149
|
+
return False
|
|
150
|
+
if token in valued:
|
|
151
|
+
index += 2
|
|
152
|
+
continue
|
|
153
|
+
if token in {"--wait", "--no-wait"} or token.startswith("--"):
|
|
154
|
+
index += 1
|
|
155
|
+
continue
|
|
156
|
+
return False # A positional destination argument was supplied.
|
|
157
|
+
return True
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class HookstrideConsole:
|
|
161
|
+
def __init__(self, session: cli.Session) -> None:
|
|
162
|
+
self.session = session
|
|
163
|
+
self.start_environment = session.environment
|
|
164
|
+
self.origins = dict(cli.ORIGINS)
|
|
165
|
+
self.origins[session.environment] = session.origin
|
|
166
|
+
self.project = session.project or _saved_project(session.environment)
|
|
167
|
+
self.session.project = self.project
|
|
168
|
+
self.tokens: dict[str, str] = {} # volatile; never persisted or printed
|
|
169
|
+
self.logged_out: set[str] = set()
|
|
170
|
+
self.history = SafeMemoryHistory()
|
|
171
|
+
self.click_command = get_command(cli.app)
|
|
172
|
+
self.completer = WordCompleter(
|
|
173
|
+
COMMAND_COMPLETIONS, ignore_case=True, sentence=True,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
@property
|
|
177
|
+
def environment(self) -> str:
|
|
178
|
+
return self.session.environment
|
|
179
|
+
|
|
180
|
+
def _current_token(self) -> str | None:
|
|
181
|
+
env = self.environment
|
|
182
|
+
if env in self.logged_out:
|
|
183
|
+
return None
|
|
184
|
+
if token := self.tokens.get(env):
|
|
185
|
+
return token
|
|
186
|
+
if token := os.getenv(f"HOOKSTRIDE_{env.upper()}_CONTROL_TOKEN"):
|
|
187
|
+
return token if token.startswith("whrctl_") else None
|
|
188
|
+
# The legacy generic token is bound ONLY to the initial environment.
|
|
189
|
+
# Do not forward a development token to production on "set env".
|
|
190
|
+
if env == self.start_environment:
|
|
191
|
+
token = os.getenv("HOOKSTRIDE_CONTROL_TOKEN", "")
|
|
192
|
+
return token if token.startswith("whrctl_") else None
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
@contextlib.contextmanager
|
|
196
|
+
def _token_scope(self) -> Iterator[None]:
|
|
197
|
+
"""Temporarily expose just the selected environment's token to the CLI."""
|
|
198
|
+
previous = os.environ.get("HOOKSTRIDE_CONTROL_TOKEN")
|
|
199
|
+
current = self._current_token()
|
|
200
|
+
if current:
|
|
201
|
+
os.environ["HOOKSTRIDE_CONTROL_TOKEN"] = current
|
|
202
|
+
else:
|
|
203
|
+
os.environ.pop("HOOKSTRIDE_CONTROL_TOKEN", None)
|
|
204
|
+
try:
|
|
205
|
+
yield
|
|
206
|
+
finally:
|
|
207
|
+
if previous is None:
|
|
208
|
+
os.environ.pop("HOOKSTRIDE_CONTROL_TOKEN", None)
|
|
209
|
+
else:
|
|
210
|
+
os.environ["HOOKSTRIDE_CONTROL_TOKEN"] = previous
|
|
211
|
+
|
|
212
|
+
def _write(self, message: str) -> None:
|
|
213
|
+
# Message is trusted markup. Never interpolate raw API fields.
|
|
214
|
+
self.session.console.print(message)
|
|
215
|
+
|
|
216
|
+
def _error(self, message: str) -> None:
|
|
217
|
+
self._write(f"[red]✗[/red] {cli._escaped(message)}")
|
|
218
|
+
|
|
219
|
+
def _show_help(self) -> None:
|
|
220
|
+
self._write(
|
|
221
|
+
"\n"
|
|
222
|
+
"[bold]help[/bold] Show console help\n"
|
|
223
|
+
"[bold]show options[/bold] Display environment, project and authentication\n"
|
|
224
|
+
"[bold]show projects[/bold] List accessible projects\n"
|
|
225
|
+
"[bold]projects create --name N --account UUID[/bold] Create a project\n"
|
|
226
|
+
"[bold]projects update UUID --name N[/bold] Rename a project\n"
|
|
227
|
+
"[bold]use 1[/bold] Select by number from 'show projects'\n"
|
|
228
|
+
"[bold]use UUID[/bold] Or select by full project ID\n"
|
|
229
|
+
"[bold]back[/bold] Leave the active project context\n"
|
|
230
|
+
"[bold]set env dev[/bold] Switch to development API\n"
|
|
231
|
+
"[bold]set env production[/bold] Switch to production API\n"
|
|
232
|
+
"[bold]auth login[/bold] Enter a Control API token securely\n"
|
|
233
|
+
"[bold]auth logout[/bold] Clear the current environment's session token\n"
|
|
234
|
+
"[bold]auth status[/bold] Validate current token\n"
|
|
235
|
+
"[bold]show destinations[/bold] List webhook destinations\n"
|
|
236
|
+
"[bold]destinations create --name N --url HTTPS_URL[/bold] Add receiver\n"
|
|
237
|
+
"[bold]destinations update UUID --pause[/bold] Pause a receiver\n"
|
|
238
|
+
"[bold]show events[/bold] View recent events\n"
|
|
239
|
+
"[bold]events list --status failed[/bold] Filter delivery history\n"
|
|
240
|
+
"[bold]events show UUID[/bold] Inspect a delivery and attempts\n"
|
|
241
|
+
"[bold]events send DEST_UUID --wait[/bold] Send one signed delivery test\n"
|
|
242
|
+
"[bold]metrics --days 7[/bold] Inspect queue health and delivery results\n"
|
|
243
|
+
"[bold]actions list[/bold] List available actions\n"
|
|
244
|
+
"[bold]actions context[/bold] View action inputs and current settings\n"
|
|
245
|
+
"[bold]actions preview ACTION --input-file FILE[/bold] Preview an action\n"
|
|
246
|
+
"[bold]actions apply ACTION --input-file FILE[/bold] Confirm an action\n"
|
|
247
|
+
"[bold]events export[/bold] Export redacted event records\n"
|
|
248
|
+
"[bold]status --pipeline[/bold] Check API and delivery readiness\n"
|
|
249
|
+
"[bold]show billing[/bold] View plan and credits\n"
|
|
250
|
+
"[bold]show payments[/bold] View payment history\n"
|
|
251
|
+
"[bold]listen 8000 --path /webhooks --source UUID[/bold] Local forwarding (restricted preview)\n"
|
|
252
|
+
"[bold]show sources[/bold] Inspect incoming sources\n"
|
|
253
|
+
"[bold]show keys[/bold] List masked keys\n"
|
|
254
|
+
"[bold]json projects list[/bold] Print the complete JSON response\n"
|
|
255
|
+
"[bold]history[/bold] View session command history\n"
|
|
256
|
+
"[bold]clear[/bold] Clear screen\n"
|
|
257
|
+
"[bold]exit[/bold] Close this console\n\n"
|
|
258
|
+
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def _show_options(self) -> None:
|
|
262
|
+
project = self.project or "none"
|
|
263
|
+
rows = [
|
|
264
|
+
["Environment", self.environment],
|
|
265
|
+
["API", self.session.origin],
|
|
266
|
+
["Project", project],
|
|
267
|
+
["Authenticated token", "configured" if self._current_token() else "missing"],
|
|
268
|
+
]
|
|
269
|
+
cli._table(_FakeContext(self.session), "Session options", ["Setting", "Value"], rows)
|
|
270
|
+
|
|
271
|
+
def _history(self) -> None:
|
|
272
|
+
commands = list(self.history.get_strings())
|
|
273
|
+
if not commands:
|
|
274
|
+
self._write("[dim]No safe commands in history.[/dim]")
|
|
275
|
+
return
|
|
276
|
+
for i, command in enumerate(reversed(commands[-20:]), 1):
|
|
277
|
+
self._write(f"[dim]{i:>3}[/dim] {cli._escaped(command)}")
|
|
278
|
+
|
|
279
|
+
def _set_environment(self, target: str) -> None:
|
|
280
|
+
if target not in cli.ORIGINS:
|
|
281
|
+
raise cli.CLIError("Use 'set env dev' or 'set env production'.")
|
|
282
|
+
self.session.environment = target
|
|
283
|
+
self.session.origin = self.origins[target]
|
|
284
|
+
self.project = _saved_project(target)
|
|
285
|
+
self.session.project = self.project
|
|
286
|
+
self._write(
|
|
287
|
+
f"[green]✓[/green] Environment: [bold]{target}[/bold] "
|
|
288
|
+
f"({_env_hint(self._current_token())})"
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
def _login(self) -> None:
|
|
292
|
+
# getpass does not echo, and is not part of the PromptSession history.
|
|
293
|
+
try:
|
|
294
|
+
# getpass normally degrades to VISIBLE input on unsupported terminals.
|
|
295
|
+
# Treat that warning as an exception before it can read a credential.
|
|
296
|
+
with warnings.catch_warnings():
|
|
297
|
+
warnings.simplefilter("error", getpass.GetPassWarning)
|
|
298
|
+
token = getpass.getpass("Control token (hidden): ").strip()
|
|
299
|
+
except getpass.GetPassWarning:
|
|
300
|
+
raise cli.CLIError(
|
|
301
|
+
"Cannot hide token input on this terminal. Authentication cancelled."
|
|
302
|
+
) from None
|
|
303
|
+
except (KeyboardInterrupt, EOFError):
|
|
304
|
+
raise cli.CLIError("Authentication cancelled.") from None
|
|
305
|
+
if (
|
|
306
|
+
not token.startswith("whrctl_")
|
|
307
|
+
or not 16 <= len(token) <= 512
|
|
308
|
+
or any(ch.isspace() for ch in token)
|
|
309
|
+
):
|
|
310
|
+
raise cli.CLIError("Expected a valid Control API management token.")
|
|
311
|
+
previous = self.tokens.get(self.environment)
|
|
312
|
+
logged_out = self.environment in self.logged_out
|
|
313
|
+
self.tokens[self.environment] = token
|
|
314
|
+
self.logged_out.discard(self.environment)
|
|
315
|
+
try:
|
|
316
|
+
with self._token_scope():
|
|
317
|
+
info = cli._request(self.session, "/control/v1/me/")
|
|
318
|
+
except (cli.CLIError, ValueError, TypeError):
|
|
319
|
+
if previous is None:
|
|
320
|
+
self.tokens.pop(self.environment, None)
|
|
321
|
+
else:
|
|
322
|
+
self.tokens[self.environment] = previous
|
|
323
|
+
if logged_out:
|
|
324
|
+
self.logged_out.add(self.environment)
|
|
325
|
+
raise cli.CLIError("Token verification failed for this environment.") from None
|
|
326
|
+
account = (info.get("user") or {}).get("email") if isinstance(info, dict) else None
|
|
327
|
+
if account:
|
|
328
|
+
self._write(f"[green]✓[/green] Authenticated as {cli._escaped(account)}")
|
|
329
|
+
else:
|
|
330
|
+
self._write("[green]✓[/green] Management token verified.")
|
|
331
|
+
|
|
332
|
+
def _logout(self) -> None:
|
|
333
|
+
self.tokens.pop(self.environment, None)
|
|
334
|
+
self.logged_out.add(self.environment)
|
|
335
|
+
self._write("[green]✓[/green] Signed out for this console environment.")
|
|
336
|
+
|
|
337
|
+
def _execute_cli(self, args: list[str], *, json_output: bool = False) -> None:
|
|
338
|
+
"""Invoke explicitly allowed Click/Typer commands, never a shell."""
|
|
339
|
+
if not _allowed_cli(args):
|
|
340
|
+
raise cli.CLIError("Unknown or unavailable command. Type 'help'.")
|
|
341
|
+
group = args[0]
|
|
342
|
+
action = args[1] if len(args) > 1 else None
|
|
343
|
+
if _requires_project(group, action) and not self.project:
|
|
344
|
+
raise cli.CLIError("No project selected. Run 'show projects' then 'use 1' or 'use UUID'.")
|
|
345
|
+
if _requires_token(group, action) and not self._current_token():
|
|
346
|
+
raise cli.CLIError("No management token for this environment. Run 'auth login'.")
|
|
347
|
+
if args[:2] == ["events", "show"] and len(args) == 2:
|
|
348
|
+
raise cli.CLIError("Usage: events show EVENT_UUID.")
|
|
349
|
+
if args[:2] == ["events", "send"] and _missing_send_destination(args):
|
|
350
|
+
raise cli.CLIError("Usage: events send DESTINATION_UUID [--wait].")
|
|
351
|
+
options = ["--env", self.environment, "--api-url", self.session.origin]
|
|
352
|
+
if self.project:
|
|
353
|
+
options += ["--project", self.project]
|
|
354
|
+
if json_output:
|
|
355
|
+
options.append("--json")
|
|
356
|
+
try:
|
|
357
|
+
with self._token_scope():
|
|
358
|
+
self.click_command.main(
|
|
359
|
+
args=[*options, *args],
|
|
360
|
+
prog_name="hookstride",
|
|
361
|
+
standalone_mode=False,
|
|
362
|
+
)
|
|
363
|
+
except click.exceptions.Exit as exc:
|
|
364
|
+
# The nested CLI must never terminate the interactive console.
|
|
365
|
+
if exc.exit_code == 0:
|
|
366
|
+
return
|
|
367
|
+
# 'status' already displayed a red Offline panel.
|
|
368
|
+
if group == "status" and not json_output and exc.exit_code == 1:
|
|
369
|
+
return
|
|
370
|
+
raise cli.CLIError("Invalid command arguments. Type 'help'.") from None
|
|
371
|
+
except SystemExit as exc:
|
|
372
|
+
# Some Typer/Click error paths raise SystemExit instead of Exit.
|
|
373
|
+
# Do not let them unwind run() and clear in-memory authentication.
|
|
374
|
+
if exc.code in (0, None):
|
|
375
|
+
return
|
|
376
|
+
raise cli.CLIError("Invalid command arguments. Type 'help'.") from None
|
|
377
|
+
except (click.ClickException, click.Abort):
|
|
378
|
+
# Click errors can quote user-provided arguments; don't echo them.
|
|
379
|
+
raise cli.CLIError("Invalid command arguments. Type 'help'.") from None
|
|
380
|
+
if args[:2] == ["projects", "use"]:
|
|
381
|
+
# The CLI resolves numeric choices against the authorized project
|
|
382
|
+
# list, validates the project, and persists its *UUID* only.
|
|
383
|
+
self.project = _saved_project(self.environment)
|
|
384
|
+
self.session.project = self.project
|
|
385
|
+
|
|
386
|
+
def execute_line(self, line: str) -> bool:
|
|
387
|
+
"""Run one input line. False means exit; all other outcomes continue."""
|
|
388
|
+
line = line.strip()
|
|
389
|
+
if not line:
|
|
390
|
+
return True
|
|
391
|
+
try:
|
|
392
|
+
parts = shlex.split(line, posix=True)
|
|
393
|
+
if not parts:
|
|
394
|
+
return True
|
|
395
|
+
command = parts[0].lower()
|
|
396
|
+
if command in {"exit", "quit"} and len(parts) == 1:
|
|
397
|
+
return False
|
|
398
|
+
if command in {"help", "?"} and len(parts) == 1:
|
|
399
|
+
self._show_help()
|
|
400
|
+
elif command == "clear" and len(parts) == 1:
|
|
401
|
+
self.session.console.clear()
|
|
402
|
+
elif command == "history" and len(parts) == 1:
|
|
403
|
+
self._history()
|
|
404
|
+
elif command == "back" and len(parts) == 1:
|
|
405
|
+
self.project = None
|
|
406
|
+
self.session.project = None
|
|
407
|
+
self._write("[dim]Project context cleared. Run 'show projects' then 'use 1' or 'use UUID'.[/dim]")
|
|
408
|
+
elif command == "set" and len(parts) == 3 and parts[1].lower() == "env":
|
|
409
|
+
self._set_environment(parts[2].lower())
|
|
410
|
+
elif command == "set" and len(parts) == 3 and parts[1].lower() == "project":
|
|
411
|
+
self._execute_cli(["projects", "use", parts[2]])
|
|
412
|
+
elif command == "use" and len(parts) == 2:
|
|
413
|
+
self._execute_cli(["projects", "use", parts[1]])
|
|
414
|
+
elif command == "auth" and len(parts) == 2 and parts[1] == "login":
|
|
415
|
+
self._login()
|
|
416
|
+
elif command == "auth" and len(parts) == 2 and parts[1] == "logout":
|
|
417
|
+
self._logout()
|
|
418
|
+
elif command == "show" and len(parts) == 2:
|
|
419
|
+
target = SHOW_TARGETS.get(parts[1].lower(), ())
|
|
420
|
+
if target is None:
|
|
421
|
+
self._show_options()
|
|
422
|
+
elif target:
|
|
423
|
+
self._execute_cli(list(target))
|
|
424
|
+
else:
|
|
425
|
+
raise cli.CLIError("Unknown display target. Type 'help'.")
|
|
426
|
+
elif command == "json" and len(parts) > 1:
|
|
427
|
+
self._execute_cli(parts[1:], json_output=True)
|
|
428
|
+
else:
|
|
429
|
+
self._execute_cli(parts)
|
|
430
|
+
except ValueError:
|
|
431
|
+
self._error("Invalid command syntax. Type 'help'.")
|
|
432
|
+
except cli.CLIError as exc:
|
|
433
|
+
self._error(str(exc))
|
|
434
|
+
except (click.ClickException, click.Abort, click.exceptions.Exit):
|
|
435
|
+
self._error("Invalid command arguments. Type 'help'.")
|
|
436
|
+
return True
|
|
437
|
+
|
|
438
|
+
def run(self) -> None:
|
|
439
|
+
self._write(
|
|
440
|
+
f"\n[bold cyan]HOOKSTRIDE[/bold cyan] [dim]CONSOLE v{cli.VERSION}[/dim]\n"
|
|
441
|
+
"[dim]Type 'help' for commands, 'auth login' for a token, "
|
|
442
|
+
"or 'exit' to quit.[/dim]\n"
|
|
443
|
+
)
|
|
444
|
+
terminal = PromptSession(
|
|
445
|
+
history=self.history,
|
|
446
|
+
completer=self.completer,
|
|
447
|
+
complete_while_typing=False,
|
|
448
|
+
)
|
|
449
|
+
try:
|
|
450
|
+
while True:
|
|
451
|
+
tag = self.environment
|
|
452
|
+
if self.project:
|
|
453
|
+
tag += ":" + self.project[:8]
|
|
454
|
+
prompt = FormattedText(
|
|
455
|
+
[("ansicyan bold", "hookstride"),
|
|
456
|
+
("", " ["), ("ansigreen", tag), ("", "] > ")]
|
|
457
|
+
)
|
|
458
|
+
try:
|
|
459
|
+
line = terminal.prompt(prompt)
|
|
460
|
+
except KeyboardInterrupt:
|
|
461
|
+
self._write("[dim]Interrupted; type 'exit' to quit.[/dim]")
|
|
462
|
+
continue
|
|
463
|
+
except EOFError:
|
|
464
|
+
break
|
|
465
|
+
if not self.execute_line(line):
|
|
466
|
+
break
|
|
467
|
+
finally:
|
|
468
|
+
self.tokens.clear()
|
|
469
|
+
self.logged_out.clear()
|
|
470
|
+
self._write("[dim]Console closed.[/dim]")
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
class _FakeContext:
|
|
474
|
+
def __init__(self, obj: cli.Session) -> None:
|
|
475
|
+
self.obj = obj
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _env_hint(token: str | None) -> str:
|
|
479
|
+
return "token configured" if token else "run 'auth login' to authenticate"
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _allowed_cli(parts: list[str]) -> bool:
|
|
483
|
+
if not parts:
|
|
484
|
+
return False
|
|
485
|
+
if parts[0] in {"listen", "metrics", "status"}:
|
|
486
|
+
return True
|
|
487
|
+
if parts[0] in ROOT_COMMANDS:
|
|
488
|
+
return len(parts) == 1
|
|
489
|
+
return (
|
|
490
|
+
len(parts) >= 2
|
|
491
|
+
and parts[0] in ALLOWED_COMMANDS
|
|
492
|
+
and parts[1] in ALLOWED_COMMANDS[parts[0]]
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _requires_project(group: str, action: str | None) -> bool:
|
|
497
|
+
return group in {
|
|
498
|
+
"destinations", "keys", "events", "billing", "incoming", "listen",
|
|
499
|
+
} or group in {"stats", "metrics"}
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _requires_token(group: str, action: str | None) -> bool:
|
|
503
|
+
return (group != "status" and not (group == "config" and action == "show")
|
|
504
|
+
and not (group == "events" and action == "send"))
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def run_console(session: cli.Session) -> None:
|
|
508
|
+
if session.json_output:
|
|
509
|
+
raise cli.CLIError("Interactive console does not support --json; use 'json COMMAND' inside it.")
|
|
510
|
+
if not os.isatty(0):
|
|
511
|
+
raise cli.CLIError(
|
|
512
|
+
"Interactive console requires a terminal. Use direct Hookstride CLI commands in scripts."
|
|
513
|
+
)
|
|
514
|
+
HookstrideConsole(session).run()
|