unleashed-podcasts-cli 0.4.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.
unleashed/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Command-line interface for the UnleashedPodcasts.com private v1 API."""
2
+
3
+ __version__ = "0.4.0"
unleashed/auth.py ADDED
@@ -0,0 +1,209 @@
1
+ """`unleashed login`: fetch a personal access token by approving the CLI in a browser.
2
+
3
+ The handshake is a loopback authorization, the same shape as OAuth's PKCE flow:
4
+
5
+ 1. The CLI invents a secret verifier and a state value, and listens on 127.0.0.1.
6
+ 2. It opens <site>/cli/authorize with the SHA-256 of the verifier, the state, the
7
+ listener's address, a device name, and the abilities it wants.
8
+ 3. The user signs in if needed and presses Approve. The site mints the token, parks it
9
+ behind a one-use code, and redirects the browser to the listener with that code.
10
+ 4. The CLI posts the code and the plain verifier to /apiv1/cli/token and gets the
11
+ token back.
12
+
13
+ The token itself never passes through the browser, and a stolen code is useless
14
+ without the verifier, which never leaves this process.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import secrets
21
+ import time
22
+ from collections.abc import Sequence
23
+ from dataclasses import dataclass, field
24
+ from http.server import BaseHTTPRequestHandler, HTTPServer
25
+ from typing import Any
26
+ from urllib.parse import parse_qs, urlencode, urlsplit
27
+
28
+ import httpx
29
+
30
+ from unleashed.errors import ApiError, AuthError, UnleashedError, error_for_status
31
+
32
+ DEFAULT_API_URL = "https://unleashedpodcasts.com/apiv1"
33
+
34
+ #: Every ability the site grants. The server rejects a request naming anything else.
35
+ ABILITIES = (
36
+ "episodes:read",
37
+ "episodes:write",
38
+ "leads:read",
39
+ "leads:write",
40
+ "tasks:read",
41
+ "tasks:write",
42
+ )
43
+
44
+ #: How long to wait for the browser. The server's code lives two minutes after approval,
45
+ #: but signing in first can take a while.
46
+ DEFAULT_WAIT_SECONDS = 300.0
47
+
48
+ CALLBACK_PATH = "/callback"
49
+ LOOPBACK_HOST = "127.0.0.1"
50
+ API_SUFFIX = "/apiv1"
51
+
52
+ _DONE_PAGE = (
53
+ b"<!doctype html><html><head><meta charset=utf-8><title>Unleashed CLI</title></head>"
54
+ b"<body style='font-family:system-ui;margin:4rem auto;max-width:32rem'>"
55
+ b"<h1>You can close this tab</h1><p>Return to your terminal.</p></body></html>"
56
+ )
57
+
58
+
59
+ class LoginError(UnleashedError):
60
+ """The browser handshake did not produce a code."""
61
+
62
+ exit_code = AuthError.exit_code
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Handshake:
67
+ """The secrets for one login attempt. Neither is ever written to disk."""
68
+
69
+ verifier: str = field(default_factory=lambda: secrets.token_urlsafe(48))
70
+ state: str = field(default_factory=lambda: secrets.token_urlsafe(24))
71
+
72
+ def __repr__(self) -> str:
73
+ return "Handshake(***redacted***)"
74
+
75
+ @property
76
+ def verifier_hash(self) -> str:
77
+ return hashlib.sha256(self.verifier.encode()).hexdigest()
78
+
79
+
80
+ def site_url(api_url: str) -> str:
81
+ """The web app's root, where /cli/authorize lives, derived from the API URL."""
82
+ url = api_url.rstrip("/")
83
+ if url.endswith(API_SUFFIX):
84
+ return url[: -len(API_SUFFIX)]
85
+ parts = urlsplit(url)
86
+ return f"{parts.scheme}://{parts.netloc}"
87
+
88
+
89
+ def authorize_url(
90
+ api_url: str,
91
+ handshake: Handshake,
92
+ redirect_uri: str,
93
+ device_name: str,
94
+ abilities: Sequence[str],
95
+ ) -> str:
96
+ query: list[tuple[str, str]] = [
97
+ ("state", handshake.state),
98
+ ("verifier_hash", handshake.verifier_hash),
99
+ ("redirect_uri", redirect_uri),
100
+ ("device_name", device_name),
101
+ ]
102
+ query.extend(("abilities[]", ability) for ability in abilities)
103
+ return f"{site_url(api_url)}/cli/authorize?{urlencode(query)}"
104
+
105
+
106
+ class _CallbackHandler(BaseHTTPRequestHandler):
107
+ server: _CallbackServer
108
+
109
+ def do_GET(self) -> None:
110
+ parts = urlsplit(self.path)
111
+ if parts.path != CALLBACK_PATH:
112
+ self.send_error(404)
113
+ return
114
+ self.server.result = {key: values[0] for key, values in parse_qs(parts.query).items()}
115
+ self.send_response(200)
116
+ self.send_header("Content-Type", "text/html; charset=utf-8")
117
+ self.send_header("Content-Length", str(len(_DONE_PAGE)))
118
+ self.end_headers()
119
+ self.wfile.write(_DONE_PAGE)
120
+
121
+ def log_message(self, format: str, *args: Any) -> None:
122
+ """Silence the default access log: the query string carries the code."""
123
+
124
+
125
+ class _CallbackServer(HTTPServer):
126
+ result: dict[str, str] | None = None
127
+
128
+
129
+ class LoopbackListener:
130
+ """A one-shot HTTP listener on 127.0.0.1, on a port the OS picks.
131
+
132
+ Bound to the loopback address only, so nothing off this machine can deliver a code.
133
+ """
134
+
135
+ def __init__(self) -> None:
136
+ self._server = _CallbackServer((LOOPBACK_HOST, 0), _CallbackHandler)
137
+
138
+ @property
139
+ def redirect_uri(self) -> str:
140
+ port = self._server.server_address[1]
141
+ return f"http://{LOOPBACK_HOST}:{port}{CALLBACK_PATH}"
142
+
143
+ def wait(self, timeout: float) -> dict[str, str]:
144
+ """Serve requests until the callback arrives or the timeout passes."""
145
+ deadline = time.monotonic() + timeout
146
+ while self._server.result is None:
147
+ remaining = deadline - time.monotonic()
148
+ if remaining <= 0:
149
+ raise LoginError(
150
+ f"Gave up waiting for the browser after {int(timeout)} seconds. "
151
+ "Run: unleashed login"
152
+ )
153
+ self._server.timeout = min(remaining, 1.0)
154
+ self._server.handle_request()
155
+ return self._server.result
156
+
157
+ def close(self) -> None:
158
+ self._server.server_close()
159
+
160
+ def __enter__(self) -> LoopbackListener:
161
+ return self
162
+
163
+ def __exit__(self, *_exc: object) -> None:
164
+ self.close()
165
+
166
+
167
+ def code_from(result: dict[str, str], handshake: Handshake) -> str:
168
+ """Check the redirect belongs to this attempt and pull the code out of it."""
169
+ if not secrets.compare_digest(result.get("state", ""), handshake.state):
170
+ raise LoginError("The browser answered for a different login attempt. Nothing was saved.")
171
+ if result.get("error") == "access_denied":
172
+ raise LoginError("Access was denied in the browser. Nothing was saved.")
173
+ if "error" in result:
174
+ raise LoginError(f"The browser returned an error: {result['error']}")
175
+ code = result.get("code", "")
176
+ if not code:
177
+ raise LoginError("The browser returned no authorization code.")
178
+ return code
179
+
180
+
181
+ def exchange(api_url: str, code: str, verifier: str, *, timeout: float = 30.0) -> str:
182
+ """Trade the one-use code and the verifier for the token."""
183
+ try:
184
+ response = httpx.post(
185
+ f"{api_url.rstrip('/')}/cli/token",
186
+ json={"code": code, "verifier": verifier},
187
+ headers={"Accept": "application/json", "Content-Type": "application/json"},
188
+ timeout=timeout,
189
+ )
190
+ except httpx.HTTPError as exc:
191
+ raise ApiError(0, message=f"Could not reach the API: {exc}") from exc
192
+
193
+ payload = _safe_json(response)
194
+ if response.status_code == 400:
195
+ raise AuthError(400, payload)
196
+ if response.status_code >= 400:
197
+ raise error_for_status(response.status_code, payload)
198
+
199
+ token = payload.get("token") if isinstance(payload, dict) else None
200
+ if not isinstance(token, str) or not token.strip():
201
+ raise ApiError(response.status_code, message="The API answered without a token.")
202
+ return token.strip()
203
+
204
+
205
+ def _safe_json(response: httpx.Response) -> Any:
206
+ try:
207
+ return response.json()
208
+ except ValueError:
209
+ return None
unleashed/cli.py ADDED
@@ -0,0 +1,211 @@
1
+ """Entry point. Wires manifests into commands and maps errors onto exit codes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import socket
7
+ import sys
8
+ import webbrowser
9
+ from collections.abc import Mapping, Sequence
10
+ from pathlib import Path
11
+
12
+ import click
13
+
14
+ from unleashed import __version__, auth
15
+ from unleashed.client import Client
16
+ from unleashed.config import (
17
+ DEFAULT_PROFILE,
18
+ PROFILE_VAR,
19
+ URL_VAR,
20
+ config_path_in,
21
+ home_config_path,
22
+ load_config,
23
+ read_existing,
24
+ write_config,
25
+ )
26
+ from unleashed.errors import ExitCode, UnleashedError, UsageError
27
+ from unleashed.generator import build_group
28
+ from unleashed.output import OutputFormat, default_output, render
29
+ from unleashed.reporting import handle_errors, report
30
+ from unleashed.resources import SHIPPED
31
+
32
+
33
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
34
+ @click.version_option(__version__, "--version")
35
+ @click.option(
36
+ "--profile",
37
+ default=None,
38
+ help=f"Config profile to use. Defaults to {PROFILE_VAR} or '{DEFAULT_PROFILE}'.",
39
+ )
40
+ @click.pass_context
41
+ def cli(ctx: click.Context, profile: str | None) -> None:
42
+ """Command-line interface for the UnleashedPodcasts.com v1 API."""
43
+ ctx.ensure_object(dict)
44
+ ctx.obj.setdefault("env", os.environ)
45
+ ctx.obj["profile"] = profile
46
+
47
+
48
+ @cli.command()
49
+ @click.option("--local", "local", is_flag=True, help="Write ./.unleashed/config instead of ~/.")
50
+ @click.option("--profile", "profile", default=None, help="Profile to write.")
51
+ @click.pass_context
52
+ @handle_errors
53
+ def configure(ctx: click.Context, local: bool, profile: str | None) -> None:
54
+ """Write credentials to a config file.
55
+
56
+ Values are stored per profile. A local config overrides the home one key by key,
57
+ so a project directory can swap the token and inherit everything else.
58
+ """
59
+ profile = _profile_for(ctx, profile)
60
+ path = _config_path(local)
61
+ existing = read_existing(path, profile)
62
+
63
+ url = click.prompt("API URL", default=existing.get("api_url", ""), show_default=True).strip()
64
+ if not url:
65
+ raise UsageError("An API URL is required.")
66
+ token = click.prompt(
67
+ "API token",
68
+ default=existing.get("api_token", ""),
69
+ show_default=False,
70
+ hide_input=True,
71
+ ).strip()
72
+ if not token:
73
+ raise UsageError("An API token is required.")
74
+
75
+ write_config(path, profile, url, token)
76
+ click.echo(f"Wrote profile '{profile}' to {path}")
77
+
78
+
79
+ @cli.command()
80
+ @click.option("--local", "local", is_flag=True, help="Write ./.unleashed/config instead of ~/.")
81
+ @click.option("--profile", "profile", default=None, help="Profile to write.")
82
+ @click.option(
83
+ "--api-url",
84
+ default=None,
85
+ help=f"API to log in to. Defaults to the profile's, then {URL_VAR}, then production.",
86
+ )
87
+ @click.option(
88
+ "--device-name",
89
+ default=None,
90
+ help="Name shown in the web app's token list. Defaults to this machine's hostname.",
91
+ )
92
+ @click.option(
93
+ "--ability",
94
+ "abilities",
95
+ multiple=True,
96
+ type=click.Choice(auth.ABILITIES),
97
+ help="Ability to request. Repeat for several. Defaults to all of them.",
98
+ )
99
+ @click.option(
100
+ "--no-browser",
101
+ is_flag=True,
102
+ default=False,
103
+ help="Print the approval URL instead of opening a browser.",
104
+ )
105
+ @click.pass_context
106
+ @handle_errors
107
+ def login(
108
+ ctx: click.Context,
109
+ local: bool,
110
+ profile: str | None,
111
+ api_url: str | None,
112
+ device_name: str | None,
113
+ abilities: tuple[str, ...],
114
+ no_browser: bool,
115
+ ) -> None:
116
+ """Approve this machine in a browser and save the token it is issued.
117
+
118
+ The token is written to the selected profile exactly as `configure` would write it.
119
+ It never passes through the browser: the browser carries a one-use code that only
120
+ this process can redeem.
121
+ """
122
+ profile = _profile_for(ctx, profile)
123
+ path = _config_path(local)
124
+ existing = read_existing(path, profile)
125
+ url = (
126
+ api_url
127
+ or existing.get("api_url")
128
+ or ctx.obj["env"].get(URL_VAR, "").strip()
129
+ or auth.DEFAULT_API_URL
130
+ ).rstrip("/")
131
+ device = (device_name or socket.gethostname()).strip()
132
+ if not device:
133
+ raise UsageError("A device name is required. Pass --device-name.")
134
+
135
+ handshake = auth.Handshake()
136
+ with auth.LoopbackListener() as listener:
137
+ approve_url = auth.authorize_url(
138
+ url, handshake, listener.redirect_uri, device, abilities or auth.ABILITIES
139
+ )
140
+ opened = False if no_browser else webbrowser.open(approve_url)
141
+ if opened:
142
+ click.echo("Opened a browser to approve this login. If it did not, visit:", err=True)
143
+ else:
144
+ click.echo("Open this URL in a browser to approve this login:", err=True)
145
+ click.echo(f"\n {approve_url}\n", err=True)
146
+ click.echo("Waiting for approval...", err=True)
147
+ result = listener.wait(auth.DEFAULT_WAIT_SECONDS)
148
+
149
+ token = auth.exchange(url, auth.code_from(result, handshake), handshake.verifier)
150
+ write_config(path, profile, url, token)
151
+ click.echo(f"Logged in. Wrote profile '{profile}' to {path}")
152
+
153
+
154
+ @cli.command()
155
+ @click.option(
156
+ "--output",
157
+ "-o",
158
+ type=click.Choice([f.value for f in OutputFormat]),
159
+ default=None,
160
+ help="Output format. Defaults to table on a terminal, json when piped.",
161
+ )
162
+ @click.option("--query", default=None, help="JMESPath expression applied to the result.")
163
+ @click.pass_context
164
+ @handle_errors
165
+ def whoami(ctx: click.Context, output: str | None, query: str | None) -> None:
166
+ """Show the user and abilities behind the configured token."""
167
+ config = load_config(ctx.obj["env"], profile=ctx.obj.get("profile"))
168
+ for warning in config.warnings:
169
+ click.echo(f"Warning: {warning}", err=True)
170
+ chosen = OutputFormat(output) if output else default_output(sys.stdout.isatty())
171
+ click.echo(render(Client(config).request("GET", "/whoami"), chosen, query))
172
+
173
+
174
+ def _profile_for(ctx: click.Context, profile: str | None) -> str:
175
+ """A subcommand's --profile, then the global one, then the environment."""
176
+ return profile or ctx.obj.get("profile") or ctx.obj["env"].get(PROFILE_VAR) or DEFAULT_PROFILE
177
+
178
+
179
+ def _config_path(local: bool) -> Path:
180
+ return config_path_in(Path.cwd()) if local else home_config_path()
181
+
182
+
183
+ for _resource in SHIPPED:
184
+ cli.add_command(build_group(_resource))
185
+
186
+
187
+ def main(argv: Sequence[str] | None = None, env: Mapping[str, str] | None = None) -> int:
188
+ """Run the CLI and return an exit code instead of raising."""
189
+ obj = {"env": dict(env) if env is not None else os.environ}
190
+ try:
191
+ # standalone_mode=False makes Click return an exit code rather than calling
192
+ # sys.exit, so a command that exited deliberately keeps its code.
193
+ result = cli.main(
194
+ args=list(argv) if argv is not None else None,
195
+ obj=obj,
196
+ standalone_mode=False,
197
+ )
198
+ except UnleashedError as error:
199
+ report(error)
200
+ return int(error.exit_code)
201
+ except click.ClickException as error:
202
+ error.show()
203
+ return int(ExitCode.USAGE)
204
+ except click.exceptions.Abort:
205
+ click.echo("Aborted.", err=True)
206
+ return int(ExitCode.ERROR)
207
+ return result if isinstance(result, int) else int(ExitCode.SUCCESS)
208
+
209
+
210
+ if __name__ == "__main__": # pragma: no cover
211
+ sys.exit(main())
unleashed/client.py ADDED
@@ -0,0 +1,169 @@
1
+ """HTTP client for the v1 API.
2
+
3
+ Knows about status codes and retries. Knows nothing about any particular resource.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+ from unleashed.config import Config
16
+ from unleashed.errors import ApiError, RateLimitError, error_for_status
17
+
18
+ DEFAULT_MAX_RETRIES = 3
19
+ DEFAULT_MAX_BACKOFF = 30.0
20
+ DEFAULT_TIMEOUT = 30.0
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class DescribedRequest:
25
+ """What a request would look like. Used by --dry-run, never sent."""
26
+
27
+ method: str
28
+ url: str
29
+ headers: dict[str, str]
30
+ body: dict[str, Any] | list[dict[str, Any]] | None
31
+
32
+
33
+ class Client:
34
+ def __init__(
35
+ self,
36
+ config: Config,
37
+ *,
38
+ max_retries: int = DEFAULT_MAX_RETRIES,
39
+ max_backoff: float = DEFAULT_MAX_BACKOFF,
40
+ sleep: Callable[[float], None] = time.sleep,
41
+ timeout: float = DEFAULT_TIMEOUT,
42
+ ) -> None:
43
+ self.config = config
44
+ self.max_retries = max_retries
45
+ self.max_backoff = max_backoff
46
+ self._sleep = sleep
47
+ self._timeout = timeout
48
+
49
+ def url_for(self, path: str) -> str:
50
+ return f"{self.config.base_url}/{path.lstrip('/')}"
51
+
52
+ def describe(
53
+ self, method: str, path: str, body: dict[str, Any] | list[dict[str, Any]] | None = None
54
+ ) -> DescribedRequest:
55
+ return DescribedRequest(
56
+ method=method.upper(),
57
+ url=self.url_for(path),
58
+ headers=self.config.headers(redact=True),
59
+ body=body,
60
+ )
61
+
62
+ def request(
63
+ self,
64
+ method: str,
65
+ path: str,
66
+ *,
67
+ json: dict[str, Any] | list[dict[str, Any]] | None = None,
68
+ params: dict[str, Any] | None = None,
69
+ unwrap: bool = True,
70
+ ) -> Any:
71
+ """Send a request, retrying only on 429, and unwrap the `data` envelope."""
72
+ response = self._send_with_retries(method, path, json=json, params=params)
73
+
74
+ if response.status_code >= 400:
75
+ raise error_for_status(response.status_code, _safe_json(response))
76
+
77
+ if response.status_code == 204 or not response.content:
78
+ return None
79
+
80
+ payload = _safe_json(response)
81
+ if unwrap and isinstance(payload, dict) and "data" in payload:
82
+ return payload["data"]
83
+ return payload
84
+
85
+ def create(self, resource: str, body: dict[str, Any] | list[dict[str, Any]]) -> Any:
86
+ return self.request("POST", f"/{resource}", json=body)
87
+
88
+ def index(
89
+ self,
90
+ resource: str,
91
+ params: dict[str, Any],
92
+ *,
93
+ paginate: bool = True,
94
+ max_items: int | None = None,
95
+ ) -> list[Any]:
96
+ """Walk the index, following `meta.last_page` until the caller has enough.
97
+
98
+ `resource` is a path relative to the base URL, so a nested collection such as
99
+ `episodes/<uuid>/transcript/utterances` pages the same way a top-level one does.
100
+
101
+ Auto-pagination is the default so a caller never mistakes page one for the
102
+ whole answer. `--no-paginate` and `--max-items` are the ways to spend less.
103
+ """
104
+ records: list[Any] = []
105
+ page = 1
106
+ while True:
107
+ payload = self.request(
108
+ "GET", f"/{resource}", params={**params, "page": page}, unwrap=False
109
+ )
110
+ batch = payload.get("data", []) if isinstance(payload, dict) else (payload or [])
111
+ records.extend(batch)
112
+
113
+ if max_items is not None and len(records) >= max_items:
114
+ return records[:max_items]
115
+ if not paginate or not batch:
116
+ return records
117
+
118
+ meta = payload.get("meta") or {} if isinstance(payload, dict) else {}
119
+ last_page = meta.get("last_page")
120
+ if last_page is None or page >= last_page:
121
+ return records
122
+ page += 1
123
+
124
+ def _send_with_retries(
125
+ self,
126
+ method: str,
127
+ path: str,
128
+ *,
129
+ json: dict[str, Any] | list[dict[str, Any]] | None,
130
+ params: dict[str, Any] | None,
131
+ ) -> httpx.Response:
132
+ attempt = 0
133
+ while True:
134
+ try:
135
+ response = httpx.request(
136
+ method,
137
+ self.url_for(path),
138
+ headers=self.config.headers(),
139
+ json=json,
140
+ params=params,
141
+ timeout=self._timeout,
142
+ )
143
+ except httpx.HTTPError as exc:
144
+ raise ApiError(0, message=f"Could not reach the API: {exc}") from exc
145
+
146
+ if response.status_code != 429:
147
+ return response
148
+
149
+ if attempt >= self.max_retries:
150
+ raise RateLimitError(429, _safe_json(response))
151
+
152
+ self._sleep(self._backoff_for(response, attempt))
153
+ attempt += 1
154
+
155
+ def _backoff_for(self, response: httpx.Response, attempt: int) -> float:
156
+ """Honour Retry-After, but cap it — a hostile header must not hang the CLI."""
157
+ header = response.headers.get("Retry-After")
158
+ try:
159
+ wait = float(header) if header is not None else 2.0**attempt
160
+ except ValueError:
161
+ wait = 2.0**attempt
162
+ return min(max(wait, 0.0), self.max_backoff)
163
+
164
+
165
+ def _safe_json(response: httpx.Response) -> Any:
166
+ try:
167
+ return response.json()
168
+ except ValueError:
169
+ return None