proxyrack 0.1.1__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.
proxyrack/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """Proxyrack API wrapper and CLI client."""
2
+
3
+ from proxyrack.account import AccountClient
4
+ from proxyrack.errors import ApiError, ProxyrackError
5
+ from proxyrack.proxy_control import ProxyControlClient
6
+
7
+ __version__ = "0.1.1"
8
+
9
+ __all__ = [
10
+ "AccountClient",
11
+ "ApiError",
12
+ "ProxyControlClient",
13
+ "ProxyrackError",
14
+ "__version__",
15
+ ]
proxyrack/account.py ADDED
@@ -0,0 +1,92 @@
1
+ """Client for the Account API at app.proxyrack.com (sub-users and shared access)."""
2
+
3
+ from typing import Any
4
+
5
+ import httpx2
6
+
7
+ from proxyrack.base import BaseClient
8
+
9
+ ACCOUNT_BASE = "https://app.proxyrack.com"
10
+
11
+
12
+ class AccountClient(BaseClient):
13
+ def __init__(
14
+ self,
15
+ username: str,
16
+ api_key: str,
17
+ *,
18
+ base_url: str = ACCOUNT_BASE,
19
+ timeout: float = 30.0,
20
+ verbose: bool = False,
21
+ ):
22
+ self._account_username = username
23
+ self._api_key = api_key
24
+ self._base_url = base_url.rstrip("/")
25
+ super().__init__(timeout=timeout, verbose=verbose)
26
+
27
+ def _build_client(self) -> httpx2.Client:
28
+ return httpx2.Client(
29
+ headers={
30
+ "X-AUTH-USERNAME": self._account_username,
31
+ "X-AUTH-API-KEY": self._api_key,
32
+ }
33
+ )
34
+
35
+ def _url(self, path: str) -> str:
36
+ return f"{self._base_url}{path}"
37
+
38
+ def list_sub_users(self) -> Any:
39
+ return self._request("GET", self._url("/api/u/sub-users"))
40
+
41
+ def create_sub_user(self, *, email: str, first_name: str, last_name: str, password: str) -> Any:
42
+ return self._request(
43
+ "POST",
44
+ self._url("/api/u/sub-users"),
45
+ json={
46
+ "email": email,
47
+ "first_name": first_name,
48
+ "last_name": last_name,
49
+ "password": password,
50
+ },
51
+ )
52
+
53
+ def update_sub_user(
54
+ self,
55
+ username: str,
56
+ *,
57
+ email: str | None = None,
58
+ first_name: str | None = None,
59
+ last_name: str | None = None,
60
+ password: str | None = None,
61
+ ) -> Any:
62
+ payload = {
63
+ key: value
64
+ for key, value in (
65
+ ("email", email),
66
+ ("first_name", first_name),
67
+ ("last_name", last_name),
68
+ ("password", password),
69
+ )
70
+ if value is not None
71
+ }
72
+ return self._request("PATCH", self._url(f"/api/u/sub-users/{username}"), json=payload)
73
+
74
+ def delete_sub_user(self, username: str) -> Any:
75
+ return self._request("DELETE", self._url(f"/api/u/sub-users/{username}"))
76
+
77
+ def add_shared_access(
78
+ self, username: str, *, service_id: str, units: int, speed: int | None = None
79
+ ) -> Any:
80
+ payload: dict[str, Any] = {"service_id": service_id, "units": units}
81
+ if speed is not None:
82
+ payload["speed"] = speed
83
+ return self._request(
84
+ "POST", self._url(f"/api/u/sub-users/{username}/access/add"), json=payload
85
+ )
86
+
87
+ def remove_shared_access(self, username: str, *, service_id: str) -> Any:
88
+ return self._request(
89
+ "POST",
90
+ self._url(f"/api/u/sub-users/{username}/access/delete"),
91
+ json={"service_id": service_id},
92
+ )
proxyrack/base.py ADDED
@@ -0,0 +1,69 @@
1
+ import json
2
+ from typing import Any, Self
3
+
4
+ import httpx2
5
+
6
+ from proxyrack.errors import ApiError
7
+
8
+ _DETAIL_KEYS = ("message", "error", "detail", "msg")
9
+
10
+
11
+ class BaseClient:
12
+ """Shared HTTP plumbing for both API surfaces."""
13
+
14
+ def __init__(self, timeout: float = 30.0, verbose: bool = False):
15
+ self._timeout = timeout
16
+ self._verbose = verbose
17
+ self._client = self._build_client()
18
+
19
+ def _build_client(self) -> httpx2.Client:
20
+ raise NotImplementedError
21
+
22
+ def close(self) -> None:
23
+ self._client.close()
24
+
25
+ def __enter__(self) -> Self:
26
+ return self
27
+
28
+ def __exit__(self, *exc_info: object) -> None:
29
+ self.close()
30
+
31
+ def _log(self, method: str, url: str) -> None:
32
+ if not self._verbose:
33
+ return
34
+ from rich.console import Console
35
+
36
+ Console(stderr=True).print(f"[dim]-> {method} {url}[/dim]")
37
+
38
+ def _request(self, method: str, url: str, **kwargs: Any) -> Any:
39
+ self._log(method, url)
40
+ response = self._client.request(method, url, timeout=self._timeout, **kwargs)
41
+ return self._handle_response(response)
42
+
43
+ def _handle_response(self, response: httpx2.Response) -> Any:
44
+ if response.status_code >= 400:
45
+ raise _api_error(response)
46
+ if "json" in response.headers.get("content-type", ""):
47
+ return response.json()
48
+ text = response.text.strip()
49
+ try:
50
+ return json.loads(text)
51
+ except ValueError:
52
+ return text
53
+
54
+
55
+ def _api_error(response: httpx2.Response) -> ApiError:
56
+ detail: str | None = None
57
+ try:
58
+ body = response.json()
59
+ except ValueError:
60
+ body = None
61
+ if isinstance(body, dict):
62
+ for key in _DETAIL_KEYS:
63
+ value = body.get(key)
64
+ if value:
65
+ detail = str(value)
66
+ break
67
+ if detail is None:
68
+ detail = (response.text or "").strip()[:200] or response.reason_phrase
69
+ return ApiError(response.status_code, detail, retry_after=response.headers.get("Retry-After"))
@@ -0,0 +1,3 @@
1
+ from proxyrack.cli.main import app, main
2
+
3
+ __all__ = ["app", "main"]
@@ -0,0 +1,22 @@
1
+ """Process-wide CLI state set by the root callback."""
2
+
3
+ _verbose = False
4
+ _profile_name: str | None = None
5
+
6
+
7
+ def set_verbose(value: bool) -> None:
8
+ global _verbose
9
+ _verbose = value
10
+
11
+
12
+ def is_verbose() -> bool:
13
+ return _verbose
14
+
15
+
16
+ def set_profile_name(value: str | None) -> None:
17
+ global _profile_name
18
+ _profile_name = value
19
+
20
+
21
+ def get_profile_name() -> str | None:
22
+ return _profile_name
@@ -0,0 +1,85 @@
1
+ """Shared Typer option annotations, client factories and reply parsing."""
2
+
3
+ from typing import Annotated, Any
4
+
5
+ import typer
6
+ from pydantic import BaseModel, ValidationError
7
+
8
+ from proxyrack.account import AccountClient
9
+ from proxyrack.cli._context import get_profile_name, is_verbose
10
+ from proxyrack.config import (
11
+ Profile,
12
+ Settings,
13
+ load_settings,
14
+ resolve_credentials,
15
+ resolve_network,
16
+ resolve_profile,
17
+ )
18
+ from proxyrack.errors import ProxyrackError
19
+ from proxyrack.proxy_control import ProxyControlClient
20
+
21
+ NetworkOption = Annotated[
22
+ str | None,
23
+ typer.Option("--network", help="Proxy network key (see `proxyrack networks list`)"),
24
+ ]
25
+ JsonOption = Annotated[bool, typer.Option("--json", help="Output raw API JSON")]
26
+
27
+
28
+ def _unexpected_reply() -> ProxyrackError:
29
+ return ProxyrackError("unexpected API reply; run with --json to see the raw response")
30
+
31
+
32
+ def parse_api_model(model: type[BaseModel], raw: object) -> Any:
33
+ """Validate an API reply, or fail cleanly instead of a pydantic traceback."""
34
+ try:
35
+ return model.model_validate(raw)
36
+ except ValidationError:
37
+ raise _unexpected_reply() from None
38
+
39
+
40
+ def parse_api_shape(raw: object, shape: type) -> Any:
41
+ """Require a list or dict reply shape, or fail cleanly instead of a traceback."""
42
+ if not isinstance(raw, shape):
43
+ raise _unexpected_reply()
44
+ return raw
45
+
46
+
47
+ def parse_api_list(model: type[BaseModel], raw: object) -> list[Any]:
48
+ """Validate a list reply item by item, or fail cleanly instead of a traceback."""
49
+ return [parse_api_model(model, item) for item in parse_api_shape(raw, list)]
50
+
51
+
52
+ def current_profile(settings: Settings) -> Profile | None:
53
+ return resolve_profile(get_profile_name(), settings)
54
+
55
+
56
+ def make_proxy_control_client(
57
+ network: str | None, port: int | None = None, session: str | None = None
58
+ ) -> ProxyControlClient:
59
+ settings = load_settings()
60
+ profile = current_profile(settings)
61
+ host, base_port = resolve_network(network, profile)
62
+ resolved_username, resolved_api_key = resolve_credentials(profile)
63
+ username = resolved_username
64
+ if session is not None:
65
+ username = f"{username};session={session}"
66
+ return ProxyControlClient(
67
+ username,
68
+ resolved_api_key,
69
+ host,
70
+ port if port is not None else base_port,
71
+ timeout=settings.timeout,
72
+ verbose=is_verbose(),
73
+ )
74
+
75
+
76
+ def make_account_client() -> AccountClient:
77
+ settings = load_settings()
78
+ profile = current_profile(settings)
79
+ resolved_username, resolved_api_key = resolve_credentials(profile)
80
+ return AccountClient(
81
+ resolved_username,
82
+ resolved_api_key,
83
+ timeout=settings.timeout,
84
+ verbose=is_verbose(),
85
+ )
@@ -0,0 +1,88 @@
1
+ import typer
2
+
3
+ from proxyrack.cli._context import get_profile_name
4
+ from proxyrack.cli.output import mask_secret, print_raw, print_table
5
+ from proxyrack.config import (
6
+ SETTING_KEYS,
7
+ config_path,
8
+ load_settings,
9
+ resolve_profile,
10
+ save_settings,
11
+ )
12
+ from proxyrack.errors import ProxyrackError
13
+
14
+ app = typer.Typer(help="Manage global CLI settings", no_args_is_help=True)
15
+
16
+
17
+ def _unknown_setting(key: str) -> ProxyrackError:
18
+ return ProxyrackError(
19
+ f"unknown setting {key!r}; valid keys: {', '.join(SETTING_KEYS)}. "
20
+ "Credentials live in profiles: `proxyrack profile add NAME`."
21
+ )
22
+
23
+
24
+ @app.command("set")
25
+ def set_cmd(
26
+ key: str = typer.Argument(help=f"One of: {', '.join(SETTING_KEYS)}"),
27
+ value: str = typer.Argument(help="Value to store"),
28
+ ) -> None:
29
+ """Set a global setting (e.g. timeout)."""
30
+ field = SETTING_KEYS.get(key)
31
+ if field is None:
32
+ raise _unknown_setting(key)
33
+ try:
34
+ parsed = float(value)
35
+ except ValueError:
36
+ raise ProxyrackError(f"invalid timeout {value!r}; expected seconds") from None
37
+ if parsed <= 0:
38
+ raise ProxyrackError("timeout must be positive")
39
+ settings = load_settings()
40
+ setattr(settings, field, parsed)
41
+ path = save_settings(settings)
42
+ print_raw(f"saved {key} to {path}")
43
+
44
+
45
+ @app.command("get")
46
+ def get_cmd(key: str = typer.Argument(help=f"One of: {', '.join(SETTING_KEYS)}")) -> None:
47
+ """Get a global setting."""
48
+ field = SETTING_KEYS.get(key)
49
+ if field is None:
50
+ raise _unknown_setting(key)
51
+ settings = load_settings()
52
+ print_raw(str(getattr(settings, field)))
53
+
54
+
55
+ @app.command("show")
56
+ def show_cmd() -> None:
57
+ """Show the effective configuration."""
58
+ settings = load_settings()
59
+ profile = resolve_profile(get_profile_name(), settings)
60
+ rows: list[tuple[str, object]] = [
61
+ ("timeout", settings.timeout),
62
+ ("default_profile", settings.default_profile),
63
+ ]
64
+ if profile is not None:
65
+ rows += [
66
+ ("profile", profile.name),
67
+ ("profile.username", profile.username),
68
+ ("profile.api-key", mask_secret(profile.api_key) if profile.api_key else None),
69
+ ("profile.default-network", profile.default_network),
70
+ ]
71
+ print_table(
72
+ "Configuration",
73
+ [("Key", lambda row: row[0]), ("Value", lambda row: _display(row))],
74
+ rows,
75
+ )
76
+
77
+
78
+ @app.command("path")
79
+ def path_cmd() -> None:
80
+ """Show the config file path."""
81
+ print_raw(str(config_path()))
82
+
83
+
84
+ def _display(row: tuple[str, object]) -> str:
85
+ _, value = row
86
+ if value is None:
87
+ return "(not set)"
88
+ return str(value)
@@ -0,0 +1,35 @@
1
+ import typer
2
+
3
+ from proxyrack.cli._options import (
4
+ JsonOption,
5
+ NetworkOption,
6
+ make_proxy_control_client,
7
+ parse_api_list,
8
+ )
9
+ from proxyrack.cli.output import print_json, print_table
10
+ from proxyrack.models import ActiveConnection
11
+
12
+ app = typer.Typer(help="Active connections (Proxy-Control API)", no_args_is_help=True)
13
+
14
+
15
+ @app.command("list")
16
+ def list_cmd(
17
+ network: NetworkOption = None,
18
+ json_output: JsonOption = False,
19
+ ) -> None:
20
+ """List active proxy connections."""
21
+ with make_proxy_control_client(network) as client:
22
+ raw = client.list_active_connections()
23
+ if json_output:
24
+ print_json(raw)
25
+ return
26
+ connections = parse_api_list(ActiveConnection, raw)
27
+ print_table(
28
+ "Active connections",
29
+ [
30
+ ("Created", lambda c: c.create_time),
31
+ ("Source", lambda c: c.source_addr),
32
+ ("Destination", lambda c: c.dest_addr),
33
+ ],
34
+ connections,
35
+ )
proxyrack/cli/geo.py ADDED
@@ -0,0 +1,103 @@
1
+ from typing import Annotated
2
+
3
+ import typer
4
+
5
+ from proxyrack.cli._options import (
6
+ JsonOption,
7
+ NetworkOption,
8
+ make_proxy_control_client,
9
+ parse_api_shape,
10
+ )
11
+ from proxyrack.cli.output import print_json, print_raw, print_table
12
+
13
+ app = typer.Typer(
14
+ help="Geo-targeting inventory: countries, cities, ISPs and IP counts (Proxy-Control API)",
15
+ no_args_is_help=True,
16
+ )
17
+
18
+ CountsOption = Annotated[
19
+ bool,
20
+ typer.Option("--counts", help="Include the number of available IPs per item"),
21
+ ]
22
+
23
+
24
+ def _print_string_list(items) -> None:
25
+ print_raw("\n".join(str(item) for item in items))
26
+
27
+
28
+ def _print_counts(items) -> None:
29
+ rows = [(name or "—", values.get("proxyCount")) for name, values in items.items()]
30
+ print_table(
31
+ "Available IPs",
32
+ [("Name", lambda row: row[0]), ("IPs", lambda row: row[1])],
33
+ rows,
34
+ )
35
+
36
+
37
+ def _print_geo(raw, counts: bool) -> None:
38
+ if counts:
39
+ _print_counts(parse_api_shape(raw, dict))
40
+ else:
41
+ _print_string_list(parse_api_shape(raw, list))
42
+
43
+
44
+ @app.command("countries")
45
+ def countries_cmd(
46
+ counts: CountsOption = False,
47
+ network: NetworkOption = None,
48
+ json_output: JsonOption = False,
49
+ ) -> None:
50
+ """List country codes available for geo-targeting."""
51
+ with make_proxy_control_client(network) as client:
52
+ raw = client.list_countries(include_count=counts)
53
+ if json_output:
54
+ print_json(raw)
55
+ return
56
+ _print_geo(raw, counts)
57
+
58
+
59
+ @app.command("cities")
60
+ def cities_cmd(
61
+ country: str = typer.Argument(help="Country code, e.g. US"),
62
+ counts: CountsOption = False,
63
+ network: NetworkOption = None,
64
+ json_output: JsonOption = False,
65
+ ) -> None:
66
+ """List cities available in a country for geo-targeting."""
67
+ with make_proxy_control_client(network) as client:
68
+ raw = client.list_country_cities(country, include_count=counts)
69
+ if json_output:
70
+ print_json(raw)
71
+ return
72
+ _print_geo(raw, counts)
73
+
74
+
75
+ @app.command("isps")
76
+ def isps_cmd(
77
+ country: str = typer.Argument(help="Country code, e.g. US"),
78
+ counts: CountsOption = False,
79
+ network: NetworkOption = None,
80
+ json_output: JsonOption = False,
81
+ ) -> None:
82
+ """List ISPs available in a country for geo-targeting."""
83
+ with make_proxy_control_client(network) as client:
84
+ raw = client.list_country_isps(country, include_count=counts)
85
+ if json_output:
86
+ print_json(raw)
87
+ return
88
+ _print_geo(raw, counts)
89
+
90
+
91
+ @app.command("count")
92
+ def count_cmd(
93
+ country: str = typer.Argument(help="Country code, e.g. US"),
94
+ network: NetworkOption = None,
95
+ json_output: JsonOption = False,
96
+ ) -> None:
97
+ """Show the number of available IPs in a country."""
98
+ with make_proxy_control_client(network) as client:
99
+ value = client.country_ip_count(country)
100
+ if json_output:
101
+ print_json(value)
102
+ return
103
+ print_raw(value)
proxyrack/cli/main.py ADDED
@@ -0,0 +1,93 @@
1
+ from typing import Annotated
2
+
3
+ import typer
4
+
5
+ from proxyrack.cli import (
6
+ config as config_commands,
7
+ )
8
+ from proxyrack.cli import (
9
+ connections as connections_commands,
10
+ )
11
+ from proxyrack.cli import (
12
+ geo as geo_commands,
13
+ )
14
+ from proxyrack.cli import (
15
+ networks as networks_commands,
16
+ )
17
+ from proxyrack.cli import (
18
+ passwords as passwords_commands,
19
+ )
20
+ from proxyrack.cli import (
21
+ profile as profile_commands,
22
+ )
23
+ from proxyrack.cli import (
24
+ proxy_url,
25
+ )
26
+ from proxyrack.cli import (
27
+ sessions as sessions_commands,
28
+ )
29
+ from proxyrack.cli import (
30
+ subusers as subusers_commands,
31
+ )
32
+ from proxyrack.cli import (
33
+ usage as usage_commands,
34
+ )
35
+ from proxyrack.cli import (
36
+ whitelist as whitelist_commands,
37
+ )
38
+ from proxyrack.cli._context import set_profile_name, set_verbose
39
+ from proxyrack.cli.output import err_console
40
+ from proxyrack.errors import ProxyrackError
41
+
42
+ app = typer.Typer(
43
+ no_args_is_help=True,
44
+ add_completion=False,
45
+ help="CLI for the Proxyrack proxy service.",
46
+ )
47
+
48
+
49
+ @app.callback()
50
+ def root(
51
+ verbose: Annotated[
52
+ bool,
53
+ typer.Option(
54
+ "--verbose",
55
+ help="Log outgoing requests (method and URL, without credentials)",
56
+ ),
57
+ ] = False,
58
+ profile: Annotated[
59
+ str | None,
60
+ typer.Option(
61
+ "--profile",
62
+ help="Saved credential profile to use (see `proxyrack profile list`)",
63
+ ),
64
+ ] = None,
65
+ ) -> None:
66
+ set_verbose(verbose)
67
+ set_profile_name(profile)
68
+
69
+
70
+ # Proxy-Control API
71
+ app.add_typer(sessions_commands.app, name="sessions")
72
+ app.add_typer(connections_commands.app, name="connections")
73
+ app.add_typer(geo_commands.app, name="geo")
74
+ app.add_typer(usage_commands.app, name="usage")
75
+ app.add_typer(passwords_commands.app, name="passwords")
76
+ app.add_typer(whitelist_commands.app, name="whitelist")
77
+ # Account API
78
+ app.add_typer(subusers_commands.app, name="sub-users")
79
+ # Local registry and setup
80
+ app.add_typer(networks_commands.app, name="networks")
81
+ app.add_typer(profile_commands.app, name="profile")
82
+ app.add_typer(config_commands.app, name="config")
83
+ app.command(name="proxy-url", help="Compose a ready-to-use proxy URL (local only)")(
84
+ proxy_url.proxy_url
85
+ )
86
+
87
+
88
+ def main() -> None:
89
+ try:
90
+ app()
91
+ except ProxyrackError as error:
92
+ err_console.print(f"[red]error:[/red] {error}")
93
+ raise SystemExit(1) from None