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/main.py ADDED
@@ -0,0 +1,1366 @@
1
+ """Hookstride CLI: project-scoped Control API management.
2
+
3
+ Commands use Control API tokens. This module never persists a token.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextlib
9
+ import getpass
10
+ import json
11
+ import os
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ import unicodedata
16
+ import uuid
17
+ import warnings
18
+ from pathlib import Path
19
+ from typing import Any
20
+ from urllib.parse import urlsplit
21
+
22
+ import httpx
23
+ import typer
24
+ from rich.cells import cell_len
25
+ from rich.console import Console
26
+ from rich.markup import escape
27
+ from rich.panel import Panel
28
+ from rich.text import Text
29
+
30
+ from . import __version__
31
+
32
+ VERSION = __version__
33
+ ORIGINS = {
34
+ "dev": "https://api-dev.hookstride.com",
35
+ "production": "https://api.hookstride.com",
36
+ }
37
+ app = typer.Typer(
38
+ help="Manage webhook delivery, projects and destinations with Hookstride.",
39
+ add_completion=False,
40
+ no_args_is_help=False,
41
+ pretty_exceptions_show_locals=False,
42
+ )
43
+ auth_app = typer.Typer(help="Check Control API authentication.")
44
+ projects_app = typer.Typer(help="List, create, update and select workspace projects.")
45
+ destinations_app = typer.Typer(help="List, create and update webhook destinations.")
46
+ events_app = typer.Typer(help="Send webhook events and inspect delivery history.")
47
+ billing_app = typer.Typer(help="View project billing and payment history.")
48
+ incoming_app = typer.Typer(help="View incoming webhook configuration where available.")
49
+ keys_app = typer.Typer(help="View project API key metadata.")
50
+ config_app = typer.Typer(help="Inspect local CLI configuration.")
51
+ actions_app = typer.Typer(help="Preview and confirm actions available to your account.")
52
+ app.add_typer(auth_app, name="auth")
53
+ app.add_typer(projects_app, name="projects")
54
+ app.add_typer(destinations_app, name="destinations")
55
+ app.add_typer(events_app, name="events")
56
+ app.add_typer(billing_app, name="billing")
57
+ app.add_typer(incoming_app, name="incoming")
58
+ app.add_typer(keys_app, name="keys")
59
+ app.add_typer(config_app, name="config")
60
+ app.add_typer(actions_app, name="actions")
61
+
62
+
63
+ class CLIError(Exception):
64
+ """An error safe to display without leaking credentials."""
65
+
66
+
67
+ class Session:
68
+ def __init__(
69
+ self,
70
+ environment: str,
71
+ api_url: str | None,
72
+ project: str | None,
73
+ json_output: bool,
74
+ no_color: bool,
75
+ ) -> None:
76
+ if environment not in ORIGINS:
77
+ raise CLIError("Choose --env dev or --env production.")
78
+ self.environment = environment
79
+ self.origin = _origin(api_url or ORIGINS[environment])
80
+ self.project = _uuid(project) if project else None
81
+ self.json_output = json_output
82
+ self.console = Console(
83
+ stderr=False,
84
+ no_color=no_color or json_output,
85
+ force_terminal=False if json_output else None,
86
+ )
87
+
88
+
89
+ def _origin(value: str) -> str:
90
+ try:
91
+ parts = urlsplit(value)
92
+ # urlsplit accepts malformed ports unless the port property is accessed.
93
+ port = parts.port
94
+ hostname = parts.hostname
95
+ except ValueError:
96
+ raise CLIError(
97
+ "Invalid API origin. Specify a hostname and valid port."
98
+ ) from None
99
+ if (
100
+ not hostname
101
+ or port == 0
102
+ or parts.username
103
+ or parts.password
104
+ or parts.query
105
+ or parts.fragment
106
+ or parts.path not in ("", "/")
107
+ ):
108
+ raise CLIError("API URL must be an origin, without path, credentials or query.")
109
+ if parts.scheme != "https" and not (
110
+ parts.scheme == "http" and hostname in ("localhost", "127.0.0.1", "::1")
111
+ ):
112
+ raise CLIError("Use HTTPS for remote APIs; HTTP is allowed only on loopback.")
113
+ return value.rstrip("/")
114
+
115
+
116
+ def _uuid(value: str) -> str:
117
+ try:
118
+ return str(uuid.UUID(value))
119
+ except (ValueError, AttributeError) as exc:
120
+ raise CLIError("Expected a valid UUID.") from exc
121
+
122
+
123
+ def _config_file() -> Path:
124
+ configured = os.environ.get("HOOKSTRIDE_CONFIG_FILE")
125
+ return (
126
+ Path(configured).expanduser()
127
+ if configured
128
+ else (Path.home() / ".config" / "hookstride" / "settings.json")
129
+ )
130
+
131
+
132
+ def _read_config() -> dict[str, Any]:
133
+ path = _config_file()
134
+ try:
135
+ if not path.exists():
136
+ return {}
137
+ parsed = json.loads(path.read_text(encoding="utf-8"))
138
+ return parsed if isinstance(parsed, dict) else {}
139
+ except (OSError, ValueError) as exc:
140
+ raise CLIError("Cannot read Hookstride CLI settings.") from exc
141
+
142
+
143
+ def _save_project(env: str, project_id: str) -> None:
144
+ settings = _read_config()
145
+ profiles = settings.setdefault("projects", {})
146
+ if not isinstance(profiles, dict):
147
+ profiles = settings["projects"] = {}
148
+ profiles[env] = project_id
149
+ path = _config_file()
150
+ temporary = None
151
+ try:
152
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
153
+ # Replace atomically: don't truncate a working config if interrupted.
154
+ # The temporary file is owner-only, and never contains auth tokens.
155
+ fd, temporary = tempfile.mkstemp(prefix=".settings-", dir=path.parent)
156
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
157
+ os.fchmod(stream.fileno(), 0o600)
158
+ json.dump(settings, stream, indent=2, sort_keys=True)
159
+ stream.write("\n")
160
+ os.replace(temporary, path)
161
+ except OSError as exc:
162
+ raise CLIError("Cannot save Hookstride CLI settings.") from exc
163
+ finally:
164
+ if temporary is not None:
165
+ with contextlib.suppress(FileNotFoundError):
166
+ os.unlink(temporary)
167
+
168
+
169
+ def _session(ctx: typer.Context) -> Session:
170
+ return ctx.obj
171
+
172
+
173
+ def _project(ctx: typer.Context) -> str:
174
+ session = _session(ctx)
175
+ if session.project:
176
+ return session.project
177
+ saved = _read_config().get("projects", {})
178
+ selected = saved.get(session.environment) if isinstance(saved, dict) else None
179
+ if not selected:
180
+ raise CLIError(
181
+ "Select a project with 'hookstride projects use UUID' or --project UUID."
182
+ )
183
+ return _uuid(selected)
184
+
185
+
186
+ def _token() -> str:
187
+ token = os.environ.get("HOOKSTRIDE_CONTROL_TOKEN", "").strip()
188
+ if not token.startswith("whrctl_"):
189
+ raise CLIError(
190
+ "Control token missing. Set HOOKSTRIDE_CONTROL_TOKEN to an MFA-verified "
191
+ "management token from the Hookstride dashboard."
192
+ )
193
+ return token
194
+
195
+
196
+ def _request(
197
+ session: Session,
198
+ path: str,
199
+ *,
200
+ authenticate: bool = True,
201
+ params: dict[str, Any] | None = None,
202
+ method: str = "GET",
203
+ json_body: dict[str, Any] | None = None,
204
+ auth_token: str | None = None,
205
+ ) -> Any:
206
+ if method not in {"GET", "POST", "PATCH"}:
207
+ raise CLIError("Unsupported API request method.")
208
+ headers = {"Accept": "application/json"}
209
+ if authenticate:
210
+ headers["Authorization"] = "Bearer " + (auth_token if auth_token is not None else _token())
211
+ try:
212
+ with httpx.Client(
213
+ base_url=session.origin,
214
+ headers=headers,
215
+ timeout=15,
216
+ follow_redirects=False,
217
+ ) as client:
218
+ if method == "GET":
219
+ response = client.get(path, params=params)
220
+ else:
221
+ response = client.request(method, path, json=json_body)
222
+ except (httpx.HTTPError, httpx.InvalidURL, ImportError, ValueError):
223
+ # Never print provider errors: transport exceptions may include headers.
224
+ raise CLIError(
225
+ "Unable to reach the Hookstride API. Check the URL and connection."
226
+ ) from None
227
+ if response.status_code == 401:
228
+ if auth_token is not None:
229
+ raise CLIError("Delivery API key rejected. Check that the project's delivery key is valid.")
230
+ raise CLIError(
231
+ "Authentication rejected. Check that your control token is valid."
232
+ )
233
+ if response.status_code == 403:
234
+ raise CLIError("Access denied for this account or project (HTTP 403).")
235
+ if response.status_code == 404:
236
+ raise CLIError("Resource not found or not enabled for this project (HTTP 404).")
237
+ if not 200 <= response.status_code < 300:
238
+ raise CLIError(f"API request failed (HTTP {response.status_code}).")
239
+ try:
240
+ return response.json()
241
+ except ValueError as exc:
242
+ raise CLIError("API returned a non-JSON response.") from exc
243
+
244
+
245
+ def _print(ctx: typer.Context, data: Any) -> None:
246
+ session = _session(ctx)
247
+ if session.json_output:
248
+ # ASCII escapes prevent C1/bidi controls from reaching the terminal
249
+ # while retaining all original JSON values for scripts.
250
+ typer.echo(json.dumps(data, indent=2, ensure_ascii=True))
251
+ else:
252
+ session.console.print_json(data=data)
253
+
254
+
255
+ def _safe_terminal_text(value: Any) -> str:
256
+ """Display untrusted values without executable terminal or bidi controls.
257
+
258
+ Rich escaping handles markup, but not ESC/C1/OSC/CSI control sequences.
259
+ Make control/format characters visible as literal Unicode escapes before
260
+ any response field reaches a console renderer. Keep API/JSON values intact.
261
+ """
262
+ safe = []
263
+ for char in str(value):
264
+ number = ord(char)
265
+ if unicodedata.category(char) in {"Cc", "Cf", "Cs", "Zl", "Zp"}:
266
+ if number <= 0xFF:
267
+ safe.append(f"\\x{number:02x}")
268
+ elif number <= 0xFFFF:
269
+ safe.append(f"\\u{number:04x}")
270
+ else:
271
+ safe.append(f"\\U{number:08x}")
272
+ else:
273
+ safe.append(char)
274
+ return "".join(safe)
275
+
276
+
277
+ def _plain(value: Any) -> Text:
278
+ return Text("—" if value is None or value == "" else _safe_terminal_text(value))
279
+
280
+
281
+ def _escaped(value: Any) -> str:
282
+ """Render API-controlled values literally inside Rich markup templates."""
283
+ return escape(str(_plain(value)))
284
+
285
+
286
+ def _colored_status(value: Any) -> Text:
287
+ label = _safe_terminal_text(value or "unknown")
288
+ style = {
289
+ "active": "green",
290
+ "delivered": "green",
291
+ "succeeded": "green",
292
+ "success": "green",
293
+ "failed": "red",
294
+ "revoked": "red",
295
+ "abandoned": "yellow",
296
+ "pending": "yellow",
297
+ "delivering": "cyan",
298
+ }.get(label.lower(), "white")
299
+ return Text(label.upper(), style=style)
300
+
301
+
302
+ def _table(
303
+ ctx: typer.Context,
304
+ title: str,
305
+ columns: list[str],
306
+ rows: list[list[Any]],
307
+ *,
308
+ status_column: int | None = None,
309
+ ) -> None:
310
+ """Render Metasploit-style columns without borders or wrapped identifiers."""
311
+ session = _session(ctx)
312
+ if not rows:
313
+ session.console.print(f"[dim]No {title.lower()} found.[/dim]")
314
+ return
315
+
316
+ styled_rows = [
317
+ [
318
+ _colored_status(value) if i == status_column else _plain(value)
319
+ for i, value in enumerate(values)
320
+ ]
321
+ for values in rows
322
+ ]
323
+ widths = [
324
+ max(cell_len(header), *(row[i].cell_len for row in styled_rows))
325
+ for i, header in enumerate(columns)
326
+ ]
327
+ gap = 2
328
+ available = max(20, session.console.width - 1)
329
+
330
+ # Keep names, dates, plans and statuses readable. On narrow terminals,
331
+ # trim identifiers/references first instead of wrapping them across lines.
332
+ priority = [
333
+ (
334
+ 100
335
+ if ("id" in header.lower() or "reference" in header.lower())
336
+ else 50 if header.lower() in {"url", "error"} else 0
337
+ )
338
+ for header in columns
339
+ ]
340
+ minimums = [
341
+ min(width, 8 if priority[i] == 100 else 4) for i, width in enumerate(widths)
342
+ ]
343
+ while sum(widths) + gap * (len(widths) - 1) > available:
344
+ candidates = [i for i in range(len(widths)) if widths[i] > minimums[i]]
345
+ if not candidates:
346
+ break
347
+ index = max(candidates, key=lambda i: (priority[i], widths[i] - minimums[i]))
348
+ widths[index] -= 1
349
+
350
+ session.console.print(title, highlight=False)
351
+ session.console.print("=" * cell_len(title), highlight=False)
352
+
353
+ def row_text(values: list[Text]) -> Text:
354
+ result = Text()
355
+ for i, value in enumerate(values):
356
+ if i:
357
+ result.append(" " * gap)
358
+ rendered = value.copy()
359
+ rendered.truncate(widths[i], overflow="ellipsis")
360
+ result.append(rendered)
361
+ if i < len(values) - 1:
362
+ result.append(" " * max(0, widths[i] - rendered.cell_len))
363
+ return result
364
+
365
+ session.console.print(row_text([Text(col) for col in columns]), highlight=False)
366
+ session.console.print(
367
+ row_text([Text("-" * size) for size in widths]), highlight=False
368
+ )
369
+ for values in styled_rows:
370
+ session.console.print(row_text(values), highlight=False)
371
+
372
+
373
+ def _date(value: Any) -> str:
374
+ return str(value or "—")[:19].replace("T", " ")
375
+
376
+
377
+ def _entries(data: Any, label: str) -> list[dict[str, Any]]:
378
+ items = data.get("results") if isinstance(data, dict) else data
379
+ if not isinstance(items, list):
380
+ raise CLIError(f"Unexpected API response for {label}.")
381
+ return [entry for entry in items if isinstance(entry, dict)]
382
+
383
+
384
+ def _print_or_table(
385
+ ctx: typer.Context,
386
+ data: Any,
387
+ title: str,
388
+ columns: list[str],
389
+ rows: list[list[Any]],
390
+ *,
391
+ status_column: int | None = None,
392
+ ) -> None:
393
+ if _session(ctx).json_output:
394
+ _print(ctx, data)
395
+ else:
396
+ _table(ctx, title, columns, rows, status_column=status_column)
397
+
398
+
399
+ @app.command("console")
400
+ def console_entry(ctx: typer.Context) -> None:
401
+ """Open the interactive Hookstride console."""
402
+ from .console import run_console
403
+
404
+ run_console(_session(ctx))
405
+
406
+
407
+ @app.callback(invoke_without_command=True)
408
+ def root(
409
+ ctx: typer.Context,
410
+ env: str = typer.Option("production", "--env", help="production (default) or dev."),
411
+ api_url: str | None = typer.Option(
412
+ None, "--api-url", help="Override the API origin."
413
+ ),
414
+ project: str | None = typer.Option(
415
+ None, "--project", help="Project UUID override."
416
+ ),
417
+ json_output: bool = typer.Option(
418
+ False, "--json", help="Machine-readable JSON, no styling."
419
+ ),
420
+ no_color: bool = typer.Option(False, "--no-color", help="Disable ANSI colors."),
421
+ version: bool = typer.Option(
422
+ False, "--version", is_eager=True, help="Show CLI version."
423
+ ),
424
+ ) -> None:
425
+ if version:
426
+ typer.echo(f"hookstride {VERSION}")
427
+ raise typer.Exit()
428
+ try:
429
+ ctx.obj = Session(env, api_url, project, json_output, no_color)
430
+ except CLIError as exc:
431
+ typer.echo(f"Error: {exc}", err=True)
432
+ raise typer.Exit(2) from exc
433
+ if ctx.invoked_subcommand is None:
434
+ _session(ctx).console.print(
435
+ Panel.fit(
436
+ "[bold cyan]HOOKSTRIDE[/bold cyan] [dim]CLI[/dim]\n"
437
+ "[green]●[/green] Webhook delivery, from your terminal\n\n"
438
+ "Start with [bold]hookstride auth status[/bold] or "
439
+ "[bold]hookstride projects list[/bold].\n"
440
+ "Run [bold]hookstride --help[/bold] for all commands.",
441
+ border_style="cyan",
442
+ )
443
+ )
444
+
445
+
446
+ @app.command("status")
447
+ def status(ctx: typer.Context, pipeline: bool = typer.Option(False, "--pipeline", help="Also check delivery-worker readiness.")) -> None:
448
+ """Check API readiness; add --pipeline for delivery-worker readiness."""
449
+ session = _session(ctx)
450
+ try:
451
+ paths = {"health": "/health/", "ready": "/ready/"}
452
+ if pipeline:
453
+ paths["pipeline"] = "/status/"
454
+ checks = {label: _request(session, path, authenticate=False) for label, path in paths.items()}
455
+ health = checks["health"]
456
+ readiness = checks["ready"]
457
+ online = (
458
+ isinstance(health, dict)
459
+ and health.get("status") in {"ok", "healthy"}
460
+ and isinstance(readiness, dict)
461
+ and readiness.get("status") == "ready"
462
+ and (not pipeline or isinstance(checks.get("pipeline"), dict)
463
+ and checks["pipeline"].get("status") == "operational")
464
+ and (
465
+ not isinstance(readiness.get("checks"), dict)
466
+ or all(value is True for value in readiness["checks"].values())
467
+ )
468
+ )
469
+ except CLIError:
470
+ if session.json_output:
471
+ raise
472
+ online = False
473
+ if session.json_output:
474
+ _print(ctx, checks)
475
+ if not online:
476
+ raise typer.Exit(code=1)
477
+ return
478
+ color = "green" if online else "red"
479
+ label = "Online" if online else "Offline"
480
+ session.console.print(
481
+ Panel.fit(
482
+ f"[{color}]● {label}[/{color}]", title="Hookstride", border_style=color
483
+ )
484
+ )
485
+ if not online:
486
+ raise typer.Exit(code=1)
487
+
488
+
489
+ @auth_app.command("status")
490
+ def auth_status(ctx: typer.Context) -> None:
491
+ """Verify your Control API token without printing it."""
492
+ data = _request(_session(ctx), "/control/v1/me/")
493
+ if _session(ctx).json_output:
494
+ # Authentication status never needs to dump membership/user PII.
495
+ _print(ctx, {"authenticated": True, "email": data.get("user", {}).get("email")})
496
+ return
497
+ user = data.get("user", {})
498
+ _session(ctx).console.print(
499
+ Panel.fit(
500
+ f"[green]✓ Authenticated[/green]\n"
501
+ f"Account: {_escaped(user.get('email'))}\n"
502
+ f"Workspace memberships: {len(data.get('memberships', []))}",
503
+ title="Control API",
504
+ border_style="green",
505
+ )
506
+ )
507
+
508
+
509
+ def _ordered_projects(data: Any) -> list[dict[str, Any]]:
510
+ """The same deterministic order is used for display and numbered selection."""
511
+ return sorted(
512
+ _entries(data, "projects"),
513
+ key=lambda p: (
514
+ str(p.get("name") or "").casefold(),
515
+ str(p.get("account_name") or "").casefold(),
516
+ str(p.get("id") or ""),
517
+ ),
518
+ )
519
+
520
+
521
+ def _resolve_project_choice(session: Session, value: str) -> str:
522
+ """Accept a full UUID or a current, 1-based position from the project list."""
523
+ if value.isascii() and value.isdecimal():
524
+ items = _ordered_projects(_request(session, "/control/v1/projects/"))
525
+ number = int(value)
526
+ if number < 1 or number > len(items):
527
+ raise CLIError(
528
+ f"Project number must be between 1 and {len(items)}. "
529
+ "Run 'projects list' to check available projects."
530
+ )
531
+ return _uuid(str(items[number - 1].get("id") or ""))
532
+ return _uuid(value)
533
+
534
+
535
+ @projects_app.command("list")
536
+ def projects_list(ctx: typer.Context) -> None:
537
+ """List projects accessible to the signed-in account."""
538
+ data = _request(_session(ctx), "/control/v1/projects/")
539
+ items = _ordered_projects(data)
540
+ _print_or_table(
541
+ ctx,
542
+ data,
543
+ "Projects",
544
+ ["#", "Name", "Workspace", "Role", "Plan", "Project ID"],
545
+ [
546
+ [
547
+ index,
548
+ p.get("name"),
549
+ p.get("account_name"),
550
+ p.get("role"),
551
+ (p.get("subscription") or {}).get("plan_code"),
552
+ p.get("id"),
553
+ ]
554
+ for index, p in enumerate(items, start=1)
555
+ ],
556
+ )
557
+
558
+
559
+ @projects_app.command("use")
560
+ def projects_use(
561
+ ctx: typer.Context, project_id: str = typer.Argument(..., help="Project number from 'projects list' or full UUID.")
562
+ ) -> None:
563
+ """Choose a default project for this environment (only saves its UUID)."""
564
+ session = _session(ctx)
565
+ project_id = _resolve_project_choice(session, project_id)
566
+ data = _request(session, f"/control/v1/projects/{project_id}/")
567
+ _save_project(session.environment, project_id)
568
+ if session.json_output:
569
+ _print(ctx, {"selected_project": project_id, "name": data.get("name")})
570
+ else:
571
+ session.console.print(
572
+ f"[green]✓[/green] Using [bold]{_escaped(data.get('name'))}[/bold] "
573
+ f"({project_id}) in {session.environment}."
574
+ )
575
+
576
+
577
+ @destinations_app.command("list")
578
+ def destinations_list(ctx: typer.Context, page: int = typer.Option(1, min=1)) -> None:
579
+ """List the selected project's outgoing destinations."""
580
+ project = _project(ctx)
581
+ data = _request(
582
+ _session(ctx),
583
+ f"/control/v1/projects/{project}/destinations/",
584
+ params={"page": page},
585
+ )
586
+ items = _entries(data, "destinations")
587
+ _print_or_table(
588
+ ctx,
589
+ data,
590
+ "Destinations",
591
+ ["Name", "URL", "Active", "Destination ID"],
592
+ [
593
+ [
594
+ x.get("name"),
595
+ x.get("url"),
596
+ "yes" if x.get("is_active") else "no",
597
+ x.get("id"),
598
+ ]
599
+ for x in items
600
+ ],
601
+ )
602
+
603
+
604
+ def _name(value: str, label: str) -> str:
605
+ value = value.strip()
606
+ if not value or len(value) > 120:
607
+ raise CLIError(f"{label} must be between 1 and 120 characters.")
608
+ return value
609
+
610
+
611
+ def _webhook_url(value: str) -> str:
612
+ """Basic local validation; the server also enforces public-URL SSRF policy."""
613
+ if len(value) > 500:
614
+ raise CLIError("Destination URL must not exceed 500 characters.")
615
+ try:
616
+ url = urlsplit(value)
617
+ port = url.port
618
+ hostname = url.hostname
619
+ except ValueError:
620
+ raise CLIError("Invalid destination HTTPS URL.") from None
621
+ if (
622
+ url.scheme != "https"
623
+ or not hostname
624
+ or port == 0
625
+ or url.username
626
+ or url.password
627
+ or url.fragment
628
+ or any(ch.isspace() for ch in value)
629
+ ):
630
+ raise CLIError("Destination must have a valid public HTTPS URL without credentials or fragment.")
631
+ return value
632
+
633
+
634
+ def _result(ctx: typer.Context, title: str, data: Any, *, secret: str | None = None) -> None:
635
+ if not isinstance(data, dict):
636
+ raise CLIError("Unexpected API response.")
637
+ if _session(ctx).json_output:
638
+ _print(ctx, data)
639
+ return
640
+ session = _session(ctx)
641
+ session.console.print(f"[green]✓[/green] {title}")
642
+ for key in ("id", "name", "slug", "url", "is_active", "account_name"):
643
+ if key in data:
644
+ session.console.print(f" {key.replace('_', ' ').title()}: {_escaped(data[key])}")
645
+ if secret is not None:
646
+ # Shown once and never saved to the CLI config or command history.
647
+ session.console.print("[yellow]Signing secret (save this now; it cannot be retrieved later):[/yellow]")
648
+ session.console.print(_plain(secret), highlight=False)
649
+
650
+
651
+ @projects_app.command("create")
652
+ def projects_create(
653
+ ctx: typer.Context,
654
+ name: str = typer.Option(..., "--name", help="New project name."),
655
+ account: str = typer.Option(..., "--account", help="Workspace account UUID from projects list."),
656
+ slug: str | None = typer.Option(None, "--slug", help="Optional project slug."),
657
+ ) -> None:
658
+ """Create a project in a workspace where you are an admin or owner."""
659
+ payload = {"account_id": _uuid(account), "name": _name(name, "Project name")}
660
+ if slug is not None:
661
+ if not slug.strip():
662
+ raise CLIError("Project slug cannot be blank.")
663
+ payload["slug"] = slug.strip()
664
+ data = _request(_session(ctx), "/control/v1/projects/", method="POST", json_body=payload)
665
+ _result(ctx, "Project created", data)
666
+
667
+
668
+ @projects_app.command("update")
669
+ def projects_update(
670
+ ctx: typer.Context,
671
+ project_id: str = typer.Argument(..., help="Project UUID."),
672
+ name: str | None = typer.Option(None, "--name", help="New project name."),
673
+ slug: str | None = typer.Option(None, "--slug", help="New project slug."),
674
+ ) -> None:
675
+ """Rename a project or update its slug (admin/owner only)."""
676
+ changes: dict[str, Any] = {}
677
+ if name is not None:
678
+ changes["name"] = _name(name, "Project name")
679
+ if slug is not None:
680
+ if not slug.strip():
681
+ raise CLIError("Project slug cannot be blank.")
682
+ changes["slug"] = slug.strip()
683
+ if not changes:
684
+ raise CLIError("Specify --name and/or --slug.")
685
+ project_id = _uuid(project_id)
686
+ data = _request(
687
+ _session(ctx), f"/control/v1/projects/{project_id}/",
688
+ method="PATCH", json_body=changes,
689
+ )
690
+ _result(ctx, "Project updated", data)
691
+
692
+
693
+ @destinations_app.command("create")
694
+ def destinations_create(
695
+ ctx: typer.Context,
696
+ name: str = typer.Option(..., "--name", help="Destination name."),
697
+ url: str = typer.Option(..., "--url", help="Public HTTPS webhook receiver."),
698
+ ) -> None:
699
+ """Create a destination and display its signing secret exactly once."""
700
+ project = _project(ctx)
701
+ data = _request(
702
+ _session(ctx), f"/control/v1/projects/{project}/destinations/",
703
+ method="POST", json_body={"name": _name(name, "Destination name"), "url": _webhook_url(url)},
704
+ )
705
+ if not isinstance(data, dict) or not isinstance(data.get("destination"), dict):
706
+ raise CLIError("Unexpected destination creation response.")
707
+ secret = data.get("signing_secret")
708
+ if not isinstance(secret, str) or not secret:
709
+ raise CLIError("Destination created but the signing secret was not returned. Rotate it in the dashboard.")
710
+ if _session(ctx).json_output:
711
+ _print(ctx, data)
712
+ else:
713
+ _result(ctx, "Destination created", data["destination"], secret=secret)
714
+
715
+
716
+ @destinations_app.command("update")
717
+ def destinations_update(
718
+ ctx: typer.Context,
719
+ destination_id: str = typer.Argument(..., help="Destination UUID."),
720
+ name: str | None = typer.Option(None, "--name", help="New destination name."),
721
+ url: str | None = typer.Option(None, "--url", help="New public HTTPS receiver."),
722
+ pause: bool = typer.Option(False, "--pause", help="Pause delivery to this destination."),
723
+ resume: bool = typer.Option(False, "--resume", help="Resume delivery to this destination."),
724
+ ) -> None:
725
+ """Update a destination in the selected project (developer role or above)."""
726
+ if pause and resume:
727
+ raise CLIError("Choose --pause or --resume, not both.")
728
+ changes: dict[str, Any] = {}
729
+ if name is not None:
730
+ changes["name"] = _name(name, "Destination name")
731
+ if url is not None:
732
+ changes["url"] = _webhook_url(url)
733
+ if pause or resume:
734
+ changes["is_active"] = bool(resume)
735
+ if not changes:
736
+ raise CLIError("Specify --name, --url, --pause, or --resume.")
737
+ destination_id = _uuid(destination_id)
738
+ project = _project(ctx)
739
+ data = _request(
740
+ _session(ctx),
741
+ f"/control/v1/projects/{project}/destinations/{destination_id}/",
742
+ method="PATCH", json_body=changes,
743
+ )
744
+ _result(ctx, "Destination updated", data)
745
+
746
+
747
+ @keys_app.command("list")
748
+ def keys_list(ctx: typer.Context) -> None:
749
+ """List API key metadata; the server never returns the raw secret."""
750
+ project = _project(ctx)
751
+ data = _request(_session(ctx), f"/control/v1/projects/{project}/api-keys/")
752
+ items = _entries(data, "API keys")
753
+ _print_or_table(
754
+ ctx,
755
+ data,
756
+ "API keys",
757
+ ["Name", "Masked key", "Enabled", "Expires", "Key ID"],
758
+ [
759
+ [
760
+ key.get("name"),
761
+ key.get("masked_key"),
762
+ "yes" if key.get("is_active") else "no",
763
+ _date(key.get("expires_at")),
764
+ key.get("id"),
765
+ ]
766
+ for key in items
767
+ ],
768
+ )
769
+
770
+
771
+ @events_app.command("list")
772
+ def events_list(
773
+ ctx: typer.Context,
774
+ page: int = typer.Option(1, min=1),
775
+ status_filter: str | None = typer.Option(
776
+ None, "--status", help="delivered, failed, pending..."
777
+ ),
778
+ origin: str | None = typer.Option(
779
+ None, "--origin", help="api, incoming or replay."
780
+ ),
781
+ search: str | None = typer.Option(
782
+ None, "--search", help="Event ID, type or destination."
783
+ ),
784
+ ) -> None:
785
+ """List recent delivery activity with optional filters."""
786
+ project = _project(ctx)
787
+ params: dict[str, Any] = {"page": page}
788
+ if status_filter:
789
+ params["status"] = status_filter
790
+ if origin:
791
+ params["origin"] = origin
792
+ if search:
793
+ params["q"] = search
794
+ data = _request(
795
+ _session(ctx), f"/control/v1/projects/{project}/events/", params=params
796
+ )
797
+ items = _entries(data, "events")
798
+ _print_or_table(
799
+ ctx,
800
+ data,
801
+ "Activity",
802
+ ["Created", "Event", "Destination", "Status", "Attempts", "Event ID"],
803
+ [
804
+ [
805
+ _date(x.get("created_at")),
806
+ x.get("event_type"),
807
+ x.get("destination_name"),
808
+ x.get("status"),
809
+ x.get("attempt_count"),
810
+ x.get("id"),
811
+ ]
812
+ for x in items
813
+ ],
814
+ status_column=3,
815
+ )
816
+
817
+
818
+ @events_app.command("export")
819
+ def events_export(
820
+ ctx: typer.Context,
821
+ status_filter: str | None = typer.Option(None, "--status"),
822
+ origin: str | None = typer.Option(None, "--origin"),
823
+ event_type: str | None = typer.Option(None, "--type"),
824
+ ) -> None:
825
+ """Export up to 200 matching events and redacted attempts as JSON."""
826
+ project = _project(ctx)
827
+ params = {"export_type": "json"}
828
+ if status_filter:
829
+ params["status"] = status_filter
830
+ if origin:
831
+ params["origin"] = origin
832
+ if event_type:
833
+ params["event_type"] = event_type
834
+ data = _request(_session(ctx), f"/control/v1/projects/{project}/events/export/", params=params)
835
+ if not isinstance(data, dict) or not isinstance(data.get("results"), list):
836
+ raise CLIError("The API did not return a JSON event export.")
837
+ if data.get("truncated"):
838
+ typer.echo("Export truncated at the server limit. Narrow the filters for a complete export.", err=True)
839
+ _print(ctx, data)
840
+
841
+
842
+ @events_app.command("show")
843
+ def events_show(ctx: typer.Context, event_id: str = typer.Argument(...)) -> None:
844
+ """Inspect an event and its delivery attempts (redacted by the API)."""
845
+ project = _project(ctx)
846
+ data = _request(
847
+ _session(ctx), f"/control/v1/projects/{project}/events/{_uuid(event_id)}/"
848
+ )
849
+ if _session(ctx).json_output:
850
+ _print(ctx, data)
851
+ return
852
+ session = _session(ctx)
853
+ session.console.print(
854
+ Panel.fit(
855
+ f"[bold]{_escaped(data.get('event_type'))}[/bold]\n"
856
+ f"Status: {_escaped(str(_colored_status(data.get('status'))))}\n"
857
+ f"Destination: {_escaped(data.get('destination_name'))}\n"
858
+ f"Event ID: {_escaped(data.get('id'))}",
859
+ title="Delivery",
860
+ border_style="cyan",
861
+ )
862
+ )
863
+ _table(
864
+ ctx,
865
+ "Delivery attempts",
866
+ ["Attempt", "HTTP", "Duration (ms)", "Time", "Error"],
867
+ [
868
+ [
869
+ x.get("attempt_number"),
870
+ x.get("status_code"),
871
+ x.get("duration_ms"),
872
+ _date(x.get("created_at")),
873
+ x.get("error"),
874
+ ]
875
+ for x in data.get("attempts", [])
876
+ ],
877
+ )
878
+
879
+
880
+ def _delivery_key(session: Session) -> str:
881
+ """Read a project-scoped delivery key without saving or echoing it."""
882
+ env_name = f"HOOKSTRIDE_{session.environment.upper()}_API_KEY"
883
+ token = os.environ.get(env_name, "").strip()
884
+ if not token:
885
+ try:
886
+ # Never fall back to visibly echoed input on a noninteractive terminal.
887
+ with warnings.catch_warnings():
888
+ warnings.simplefilter("error", getpass.GetPassWarning)
889
+ token = getpass.getpass("Project delivery API key (hidden): ").strip()
890
+ except (getpass.GetPassWarning, KeyboardInterrupt, EOFError):
891
+ raise CLIError(
892
+ f"Cannot read a hidden delivery key. Set {env_name} in your shell instead."
893
+ ) from None
894
+ if (
895
+ not token.startswith("whrk_")
896
+ or not 16 <= len(token) <= 512
897
+ or any(ch.isspace() for ch in token)
898
+ ):
899
+ raise CLIError("Expected a valid project delivery API key (whrk_...).")
900
+ return token
901
+
902
+
903
+ @events_app.command("send")
904
+ def events_send(
905
+ ctx: typer.Context,
906
+ destination_id: str = typer.Argument(..., help="Existing destination UUID."),
907
+ event_type: str = typer.Option("webhook.test", "--type", help="Event type."),
908
+ payload_file: Path | None = typer.Option(
909
+ None, "--payload-file", help="Optional JSON object file, never passed on the command line."
910
+ ),
911
+ wait: bool = typer.Option(False, "--wait", help="Wait for delivered or failed status."),
912
+ timeout: int = typer.Option(120, "--timeout", min=5, max=600, help="Maximum wait in seconds."),
913
+ ) -> None:
914
+ """Send one real event through Hookstride using a project delivery API key."""
915
+ _project(ctx) # Explicit project selection prevents accidental context-free writes.
916
+ destination_id = _uuid(destination_id)
917
+ event_type = event_type.strip()
918
+ if not event_type or len(event_type) > 160 or any(ord(ch) < 33 or ord(ch) > 126 for ch in event_type):
919
+ raise CLIError("Event type must contain 1–160 visible ASCII characters without spaces.")
920
+ payload: dict[str, Any] = {"message": "Hookstride CLI delivery test", "source": "cli"}
921
+ if payload_file is not None:
922
+ try:
923
+ if payload_file.stat().st_size > 65536:
924
+ raise CLIError("Payload file exceeds the 64 KB CLI limit.")
925
+ value = json.loads(payload_file.read_text(encoding="utf-8"))
926
+ except (OSError, UnicodeError, ValueError):
927
+ raise CLIError("Cannot read payload file as JSON.") from None
928
+ if not isinstance(value, dict):
929
+ raise CLIError("Payload file must contain a JSON object.")
930
+ payload = value
931
+ session = _session(ctx)
932
+ token = _delivery_key(session)
933
+ data = _request(
934
+ session,
935
+ "/api/v1/events/",
936
+ method="POST",
937
+ json_body={"endpoint": destination_id, "event_type": event_type, "payload": payload},
938
+ auth_token=token,
939
+ )
940
+ if not isinstance(data, dict) or not isinstance(data.get("id"), str):
941
+ raise CLIError("Unexpected event creation response.")
942
+ event_id = _uuid(data["id"])
943
+ if not session.json_output:
944
+ session.console.print(f"[green]✓[/green] Event accepted: {_escaped(event_id)}")
945
+ if wait:
946
+ deadline = time.monotonic() + timeout
947
+ previous = None
948
+ while True:
949
+ data = _request(session, f"/api/v1/events/{event_id}/", auth_token=token)
950
+ if not isinstance(data, dict):
951
+ raise CLIError("Unexpected event status response.")
952
+ status = data.get("status")
953
+ if not session.json_output and status != previous:
954
+ session.console.print(" Status:", _colored_status(status))
955
+ previous = status
956
+ if status in {"delivered", "failed"}:
957
+ break
958
+ if time.monotonic() >= deadline:
959
+ if session.json_output:
960
+ _print(ctx, {"id": event_id, "status": status, "timed_out": True})
961
+ raise CLIError(f"Delivery is still {status or 'pending'} for event {event_id}; inspect it with 'events show'.")
962
+ time.sleep(min(2, max(0, deadline - time.monotonic())))
963
+ if session.json_output:
964
+ _print(ctx, {"id": event_id, "status": data.get("status"), "attempt_count": data.get("attempt_count")})
965
+ elif data.get("status") == "delivered":
966
+ session.console.print(f"[green]✓[/green] Delivered: {_escaped(event_id)}")
967
+ elif data.get("status") == "failed":
968
+ safe_error = _safe_terminal_text(data.get("last_error") or "Unknown delivery failure.")
969
+ session.console.print(" Error:", Text(safe_error))
970
+ for attempt in data.get("attempts", []):
971
+ session.console.print(
972
+ f" Attempt {_escaped(attempt.get('attempt_number', '?'))}: "
973
+ f"HTTP {_escaped(attempt.get('status_code') or 'no response')}"
974
+ )
975
+ if data.get("status") == "failed":
976
+ raise CLIError(f"Event {event_id} failed. Inspect 'events show {event_id}'.")
977
+
978
+
979
+ @billing_app.command("status")
980
+ def billing_status(ctx: typer.Context) -> None:
981
+ """Show the selected project's plan and Flex credit balance."""
982
+ project = _project(ctx)
983
+ data = _request(_session(ctx), f"/control/v1/projects/{project}/billing/")
984
+ if _session(ctx).json_output:
985
+ _print(ctx, data)
986
+ return
987
+ plan = data.get("subscription") or {}
988
+ _session(ctx).console.print(
989
+ Panel.fit(
990
+ f"Plan: [bold]{_escaped(plan.get('plan_code'))}[/bold]\n"
991
+ f"Status: {_escaped(str(_colored_status(plan.get('status'))))}\n"
992
+ f"Flex credits: {_escaped(plan.get('flex_credits'))}\n"
993
+ f"Current period ends: {_escaped(_date(plan.get('current_period_end')))}\n"
994
+ f"Payment attempts: {len(data.get('records', []))}",
995
+ title="Project Billing",
996
+ border_style="cyan",
997
+ )
998
+ )
999
+
1000
+
1001
+ @billing_app.command("history")
1002
+ def billing_history(ctx: typer.Context) -> None:
1003
+ """View project payment history and payment statuses."""
1004
+ project = _project(ctx)
1005
+ data = _request(_session(ctx), f"/control/v1/projects/{project}/billing/")
1006
+ records = data.get("records", [])
1007
+ _print_or_table(
1008
+ ctx,
1009
+ records,
1010
+ "Payment history",
1011
+ ["Date", "Plan", "Amount", "Status", "Reference"],
1012
+ [
1013
+ [
1014
+ _date(r.get("created_at")),
1015
+ r.get("plan_code"),
1016
+ f"{r.get('currency', '')} {int(r.get('amount_minor', 0)) / 100:.2f}",
1017
+ r.get("status"),
1018
+ r.get("reference"),
1019
+ ]
1020
+ for r in records
1021
+ ],
1022
+ status_column=3,
1023
+ )
1024
+
1025
+
1026
+ @incoming_app.command("sources")
1027
+ def incoming_sources(ctx: typer.Context) -> None:
1028
+ """List incoming sources where the feature is available."""
1029
+ project = _project(ctx)
1030
+ data = _request(_session(ctx), f"/control/v1/projects/{project}/incoming/sources/")
1031
+ items = data.get("sources", [])
1032
+ _print_or_table(
1033
+ ctx,
1034
+ data,
1035
+ "Incoming sources",
1036
+ ["Name", "Provider", "Routing", "Active", "Source ID"],
1037
+ [
1038
+ [
1039
+ s.get("name"),
1040
+ s.get("provider"),
1041
+ s.get("routing"),
1042
+ "yes" if s.get("is_active") else "no",
1043
+ s.get("id"),
1044
+ ]
1045
+ for s in items
1046
+ ],
1047
+ )
1048
+
1049
+
1050
+ @incoming_app.command("routes")
1051
+ def incoming_routes(ctx: typer.Context) -> None:
1052
+ """List incoming event-routing rules for the selected project."""
1053
+ project = _project(ctx)
1054
+ data = _request(_session(ctx), f"/control/v1/projects/{project}/incoming/routes/")
1055
+ routes = data.get("routes", [])
1056
+ _print_or_table(
1057
+ ctx,
1058
+ data,
1059
+ "Incoming routes",
1060
+ ["Source", "Destination", "Pattern", "Active", "Route ID"],
1061
+ [
1062
+ [
1063
+ route.get("source"),
1064
+ route.get("endpoint"),
1065
+ route.get("event_pattern"),
1066
+ "yes" if route.get("is_active") else "no",
1067
+ route.get("id"),
1068
+ ]
1069
+ for route in routes
1070
+ ],
1071
+ )
1072
+
1073
+
1074
+ @incoming_app.command("bindings")
1075
+ def incoming_bindings(ctx: typer.Context) -> None:
1076
+ """List existing reference-to-destination bindings."""
1077
+ project = _project(ctx)
1078
+ data = _request(_session(ctx), f"/control/v1/projects/{project}/incoming/bindings/")
1079
+ bindings = data.get("bindings", [])
1080
+ _print_or_table(
1081
+ ctx,
1082
+ data,
1083
+ "Incoming bindings",
1084
+ ["Reference", "Source", "Destination", "Binding ID"],
1085
+ [
1086
+ [
1087
+ item.get("reference"),
1088
+ item.get("source"),
1089
+ item.get("endpoint"),
1090
+ item.get("id"),
1091
+ ]
1092
+ for item in bindings
1093
+ ],
1094
+ )
1095
+
1096
+
1097
+ @incoming_app.command("registration-keys")
1098
+ def incoming_registration_keys(ctx: typer.Context) -> None:
1099
+ """List masked incoming registration keys (never raw credentials)."""
1100
+ project = _project(ctx)
1101
+ data = _request(
1102
+ _session(ctx), f"/control/v1/projects/{project}/incoming/registration-keys/"
1103
+ )
1104
+ keys = data.get("keys", [])
1105
+ _print_or_table(
1106
+ ctx,
1107
+ data,
1108
+ "Registration keys",
1109
+ ["Name", "Masked key", "Active", "Expiry", "Key ID"],
1110
+ [
1111
+ [
1112
+ item.get("name"),
1113
+ item.get("masked_key"),
1114
+ "yes" if item.get("is_active") else "no",
1115
+ _date(item.get("expires_at")),
1116
+ item.get("id"),
1117
+ ]
1118
+ for item in keys
1119
+ ],
1120
+ )
1121
+
1122
+
1123
+ @app.command("stats")
1124
+ def delivery_stats(ctx: typer.Context) -> None:
1125
+ """Show delivery success/failure totals for the selected project."""
1126
+ project = _project(ctx)
1127
+ data = _request(_session(ctx), f"/control/v1/projects/{project}/delivery-stats/")
1128
+ if _session(ctx).json_output:
1129
+ _print(ctx, data)
1130
+ return
1131
+ counts = data.get("events", {})
1132
+ _table(
1133
+ ctx,
1134
+ "Delivery overview",
1135
+ ["Total", "Delivered", "Failed", "Pending", "Delivered / all"],
1136
+ [
1137
+ [
1138
+ counts.get("total"),
1139
+ counts.get("delivered"),
1140
+ counts.get("failed"),
1141
+ counts.get("pending"),
1142
+ f"{counts.get('success_rate', 0)}%",
1143
+ ]
1144
+ ],
1145
+ )
1146
+ _session(ctx).console.print(
1147
+ "Delivered / all includes pending events. Use 'metrics' for completed "
1148
+ "delivery success and current queue health."
1149
+ )
1150
+
1151
+
1152
+ @app.command("metrics")
1153
+ def delivery_metrics(
1154
+ ctx: typer.Context,
1155
+ days: int = typer.Option(7, "--days", help="Rolling UTC window: 1, 7 or 30 days."),
1156
+ ) -> None:
1157
+ """Inspect current queue health and delivery results; not service uptime."""
1158
+ if days not in {1, 7, 30}:
1159
+ raise CLIError("Choose --days 1, 7 or 30.")
1160
+ session = _session(ctx)
1161
+ project = _project(ctx)
1162
+ data = _request(
1163
+ session, f"/control/v1/projects/{project}/delivery-metrics/",
1164
+ params={"days": days},
1165
+ )
1166
+ if session.json_output:
1167
+ _print(ctx, data)
1168
+ return
1169
+ events = data.get("events", {})
1170
+ queue = data.get("queue", {})
1171
+ rate = events.get("terminal_success_rate")
1172
+ _table(ctx, f"Delivery results · last {days} days (UTC)",
1173
+ ["Delivered", "Failed", "Waiting", "Recovered", "Completed success"],
1174
+ [[events.get("delivered"), events.get("failed"), events.get("pending"),
1175
+ events.get("recovered_after_retry"), "—" if rate is None else f"{rate}%"]])
1176
+ wait = queue.get("oldest_due_wait_seconds")
1177
+ _table(ctx, "Current queue · all accepted dates",
1178
+ ["Ready", "Scheduled", "In progress", "Longest ready wait"],
1179
+ [[queue.get("due_pending"), queue.get("scheduled_pending"),
1180
+ queue.get("delivering"), "—" if wait is None else f"{wait}s"]])
1181
+ if queue.get("expired_leases", 0):
1182
+ session.console.print("Interrupted deliveries are awaiting recovery. Contact Support if delays persist.")
1183
+ if queue.get("blocked_credentials", 0):
1184
+ session.console.print("Some deliveries are paused because destination credentials are unavailable. Contact Hookstride Support.")
1185
+ session.console.print(
1186
+ "Completed success excludes waiting events. Queue counts include all dates. "
1187
+ "These results are not service uptime or billing usage."
1188
+ )
1189
+
1190
+
1191
+ def _action_payload(path: Path) -> dict[str, Any]:
1192
+ try:
1193
+ with path.open("rb") as source:
1194
+ raw = source.read(10001)
1195
+ if len(raw) > 10000:
1196
+ raise ValueError("large")
1197
+ def reject_constant(_value):
1198
+ raise ValueError("Non-finite JSON number")
1199
+ data = json.loads(raw, parse_constant=reject_constant)
1200
+ if not isinstance(data, dict):
1201
+ raise ValueError("object")
1202
+ return data
1203
+ except (OSError, ValueError, UnicodeError):
1204
+ raise CLIError("Use an accessible UTF-8 JSON object file no larger than 10 KB.") from None
1205
+
1206
+
1207
+ def _action_body(ctx: typer.Context, action: str, path: Path) -> dict[str, Any]:
1208
+ return {
1209
+ "project_id": None if action == "project.create" else _project(ctx),
1210
+ "action": action, "payload": _action_payload(path),
1211
+ }
1212
+
1213
+
1214
+ @actions_app.command("list")
1215
+ def actions_list(ctx: typer.Context) -> None:
1216
+ """List actions currently permitted for the selected project and user role."""
1217
+ data = _request(_session(ctx), "/control/v1/support/project-actions/",
1218
+ params={"project_id": _project(ctx)})
1219
+ actions = data.get("available_actions")
1220
+ if not isinstance(actions, list):
1221
+ raise CLIError("Confirmed actions are not available for this project.")
1222
+ _print_or_table(ctx, {"actions": actions}, "Permitted actions", ["Action"], [[a] for a in actions])
1223
+
1224
+
1225
+ @actions_app.command("context")
1226
+ def actions_context(ctx: typer.Context) -> None:
1227
+ """Inspect authorized IDs, current settings, usage and masked metadata for action inputs."""
1228
+ data = _request(_session(ctx), "/control/v1/support/project-actions/",
1229
+ params={"project_id": _project(ctx)})
1230
+ _print(ctx, data)
1231
+
1232
+
1233
+ @actions_app.command("workspaces")
1234
+ def actions_workspaces(ctx: typer.Context) -> None:
1235
+ """List workspaces where the user may create a project, including the first."""
1236
+ data = _request(_session(ctx), "/control/v1/support/workspaces/")
1237
+ _print_or_table(ctx, data, "Project creation workspaces", ["ID", "Name", "Role"],
1238
+ [[w.get("id"), w.get("name"), w.get("role")] for w in data.get("workspaces", [])])
1239
+
1240
+
1241
+ @actions_app.command("preview")
1242
+ def actions_preview(ctx: typer.Context, action: str = typer.Argument(...),
1243
+ input_file: Path = typer.Option(..., "--input-file")) -> None:
1244
+ """Read a typed JSON payload and preview an action without performing it."""
1245
+ body = _action_body(ctx, action, input_file)
1246
+ data = _request(_session(ctx), "/control/v1/support/project-actions/preview/",
1247
+ method="POST", json_body=body)
1248
+ _print_or_table(ctx, data, "Review action · no change performed", ["Field", "Value"],
1249
+ [[key, json.dumps(value, ensure_ascii=False)] for key, value in data.get("preview", {}).items()])
1250
+
1251
+
1252
+ @actions_app.command("apply")
1253
+ def actions_apply(ctx: typer.Context, action: str = typer.Argument(...),
1254
+ input_file: Path = typer.Option(..., "--input-file"),
1255
+ confirm: bool = typer.Option(False, "--confirm", help="Explicitly approve the displayed action without a prompt.")) -> None:
1256
+ """Preview, then explicitly confirm one permitted action using a one-use approval."""
1257
+ session = _session(ctx)
1258
+ body = _action_body(ctx, action, input_file)
1259
+ reviewed = _request(session, "/control/v1/support/project-actions/preview/",
1260
+ method="POST", json_body=body)
1261
+ if not isinstance(reviewed.get("approval_id"), str) or not isinstance(reviewed.get("preview"), dict):
1262
+ raise CLIError("Could not retrieve a valid action preview. Try again.")
1263
+ # JSON scripts require explicit --confirm; never hide a prompt in stdout.
1264
+ if session.json_output and not confirm:
1265
+ raise CLIError("JSON action execution requires explicit --confirm. Use 'actions preview' first.")
1266
+ if not session.json_output:
1267
+ _table(ctx, "Review before confirming", ["Field", "Value"],
1268
+ [[key, json.dumps(value, ensure_ascii=False)] for key, value in reviewed["preview"].items()])
1269
+ if not confirm and not typer.confirm("Apply this action?", default=False):
1270
+ session.console.print("Cancelled. No action performed.")
1271
+ return
1272
+ result = _request(session, "/control/v1/support/project-actions/confirm/",
1273
+ method="POST", json_body={**body, "approval_id": reviewed["approval_id"]})
1274
+ if result.get("success") is not True:
1275
+ raise CLIError("The action was not confirmed as completed.")
1276
+ outcome = result.get("result", {})
1277
+ if session.json_output:
1278
+ _print(ctx, outcome)
1279
+ else:
1280
+ _result(ctx, "Event accepted for delivery" if action.startswith("event.") else "Action completed", outcome, secret=outcome.get("one_time_secret"))
1281
+
1282
+
1283
+ @config_app.command("show")
1284
+ def config_show(ctx: typer.Context) -> None:
1285
+ """View your active environment, project and authentication settings."""
1286
+ session = _session(ctx)
1287
+ saved = _read_config().get("projects", {})
1288
+ selected = session.project or (
1289
+ saved.get(session.environment) if isinstance(saved, dict) else None
1290
+ )
1291
+ data = {
1292
+ "environment": session.environment,
1293
+ "api_url": session.origin,
1294
+ "project": selected,
1295
+ "token_configured": bool(
1296
+ os.environ.get("HOOKSTRIDE_CONTROL_TOKEN", "").startswith("whrctl_")
1297
+ ),
1298
+ "token_source": (
1299
+ "environment"
1300
+ if os.environ.get("HOOKSTRIDE_CONTROL_TOKEN", "").startswith("whrctl_")
1301
+ else None
1302
+ ),
1303
+ }
1304
+ if session.json_output:
1305
+ _print(ctx, data)
1306
+ else:
1307
+ _table(
1308
+ ctx,
1309
+ "Configuration",
1310
+ ["Setting", "Value"],
1311
+ [[k, v] for k, v in data.items()],
1312
+ )
1313
+
1314
+
1315
+ @app.command("listen")
1316
+ def listen(
1317
+ ctx: typer.Context,
1318
+ port: int = typer.Argument(..., min=1, max=65535),
1319
+ path: str = typer.Option("/", "--path"),
1320
+ source: str | None = typer.Option(None, "--source", help="Incoming source UUID."),
1321
+ ttl: int = typer.Option(3600, "--ttl", min=60, max=3600, help="Session lifetime in seconds."),
1322
+ resume: str | None = typer.Option(None, "--resume", help="Resume an active session UUID."),
1323
+ ) -> None:
1324
+ """Forward verified incoming events locally (restricted preview)."""
1325
+ from .listen import ListenStopped, local_url, run_listener
1326
+
1327
+ session = _session(ctx)
1328
+ if session.json_output:
1329
+ raise CLIError("listen uses interactive status output; omit --json.")
1330
+ project = _project(ctx)
1331
+ token = _token()
1332
+ try:
1333
+ target = local_url(port, path)
1334
+ if not source:
1335
+ if not sys.stdin.isatty():
1336
+ raise CLIError("Choose an incoming source explicitly with --source UUID.")
1337
+ data = _request(session, f"/control/v1/projects/{project}/incoming/sources/")
1338
+ sources = data.get("sources", [])
1339
+ _table(ctx, "Select an incoming source", ["ID", "Name", "Provider"], [
1340
+ [item["id"], item["name"], item["provider"]]
1341
+ for item in sources if item.get("is_active")
1342
+ ])
1343
+ source = typer.prompt("Source UUID")
1344
+ source = _uuid(source)
1345
+ run_listener(origin=session.origin, token=token, project_id=project,
1346
+ source_id=source, target=target, ttl=ttl, resume=_uuid(resume) if resume else None,
1347
+ report=lambda message: session.console.print(_escaped(message)))
1348
+ except ListenStopped as exc:
1349
+ raise CLIError(str(exc)) from None
1350
+
1351
+
1352
+ def main() -> None:
1353
+ try:
1354
+ app()
1355
+ except CLIError as exc:
1356
+ # Error messages are intentionally generic. No auth tokens or response bodies.
1357
+ is_json = "--json" in sys.argv[1:]
1358
+ if is_json:
1359
+ typer.echo(json.dumps({"error": str(exc)}), err=True)
1360
+ else:
1361
+ Console(stderr=True).print(f"[red]✗[/red] {_escaped(exc)}")
1362
+ raise SystemExit(1) from exc
1363
+
1364
+
1365
+ if __name__ == "__main__":
1366
+ main()