sweatstack-cli 0.14.0__py3-none-any.whl → 0.16.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.
@@ -13,6 +13,7 @@ from sweatstack_cli.auth.callback_server import CallbackServer
13
13
  from sweatstack_cli.auth.pkce import PKCEChallenge, generate_pkce
14
14
  from sweatstack_cli.auth.tokens import FileTokenStorage, TokenPair
15
15
  from sweatstack_cli.config import get_settings
16
+ from sweatstack_cli.console import stderr_console
16
17
  from sweatstack_cli.exceptions import AuthenticationError
17
18
 
18
19
  if TYPE_CHECKING:
@@ -24,6 +25,15 @@ CLIENT_ID = "5382f68b0d254378"
24
25
  # Default OAuth2 scopes (offline_access required for refresh tokens)
25
26
  SCOPES = "offline_access data:read data:write profile"
26
27
 
28
+ # Said once per command when the refresh token from the environment was replaced by a new one,
29
+ # which the CLI can keep only for that command.
30
+ ROTATION_LOST_WARNING = (
31
+ "[yellow]Warning:[/yellow] SweatStack replaced the refresh token from "
32
+ "SWEATSTACK_REFRESH_TOKEN. This command used the new one, but the variable still holds the "
33
+ "old one, which SweatStack will stop accepting. To stay signed in on this machine, unset "
34
+ "SWEATSTACK_API_KEY and SWEATSTACK_REFRESH_TOKEN and run 'sweatstack login'."
35
+ )
36
+
27
37
 
28
38
  class Authenticator:
29
39
  """
@@ -57,6 +67,10 @@ class Authenticator:
57
67
  self._client_id = client_id
58
68
  self._scopes = scopes
59
69
  self._settings = get_settings()
70
+ # The environment's tokens once this command refreshed them. Never written to the
71
+ # tokens file: that holds the sign-in of `sweatstack login`, shared with the Python SDK.
72
+ self._renewed_environment_tokens: TokenPair | None = None
73
+ self._warned_rotation_lost = False
60
74
 
61
75
  def login(self, force: bool = False) -> TokenPair:
62
76
  """
@@ -110,39 +124,77 @@ class Authenticator:
110
124
  Checks token expiry with a 30-second margin to avoid
111
125
  edge cases where token expires during a request.
112
126
 
127
+ Every refresh returns a new refresh token, and the old one stops working. Tokens from
128
+ the tokens file are saved back to it. Tokens from the environment are kept for the
129
+ rest of this command only, with a warning, because the variables cannot be updated.
130
+
113
131
  Returns:
114
132
  Valid TokenPair, or None if not authenticated or refresh fails.
115
133
  """
116
- tokens = self._load_tokens()
134
+ tokens, from_environment = self._load_tokens()
117
135
  if tokens is None:
118
136
  return None
119
137
 
120
138
  if tokens.is_expired(margin_seconds=30):
121
139
  try:
122
- tokens = self._refresh_tokens(tokens.refresh_token)
123
- self._storage.save(tokens)
140
+ renewed = self._refresh_tokens(tokens.refresh_token)
124
141
  except AuthenticationError:
125
142
  return None
143
+ if from_environment:
144
+ self._renewed_environment_tokens = renewed
145
+ if renewed.refresh_token != tokens.refresh_token:
146
+ self._warn_rotation_lost()
147
+ else:
148
+ self._storage.save(renewed)
149
+ tokens = renewed
126
150
 
127
151
  return tokens
128
152
 
129
- def logout(self) -> None:
130
- """Remove stored credentials."""
131
- self._storage.delete()
153
+ def logout(self) -> str | None:
154
+ """
155
+ End the sign-in of ``sweatstack login`` and remove the tokens file.
156
+
157
+ The refresh token is revoked on SweatStack first, so it stops working everywhere, also
158
+ for a copy of the file. The file is removed whether or not that succeeds.
159
+
160
+ Returns:
161
+ Why SweatStack did not end the sign-in, or None when it did or nothing was stored.
162
+ """
163
+ tokens = self._storage.load()
164
+ try:
165
+ return None if tokens is None else self._revoke(tokens.refresh_token)
166
+ finally:
167
+ self._storage.delete()
132
168
 
133
- def _load_tokens(self) -> TokenPair | None:
169
+ def _load_tokens(self) -> tuple[TokenPair | None, bool]:
134
170
  """
135
- Load tokens from environment or persistent storage.
171
+ The tokens to use, and whether they come from the environment.
136
172
 
137
- Environment variables take precedence for CI/CD use cases.
173
+ ``SWEATSTACK_API_KEY`` and ``SWEATSTACK_REFRESH_TOKEN`` together take precedence over
174
+ the tokens file, for CI. Either one alone is ignored: an API key cannot act for the CLI.
138
175
  """
176
+ if self._renewed_environment_tokens is not None:
177
+ return self._renewed_environment_tokens, True
178
+
139
179
  access = os.environ.get("SWEATSTACK_API_KEY")
140
180
  refresh = os.environ.get("SWEATSTACK_REFRESH_TOKEN")
141
181
 
142
182
  if access and refresh:
143
- return TokenPair(access_token=access, refresh_token=refresh)
183
+ return TokenPair(access_token=access, refresh_token=refresh), True
184
+
185
+ return self._storage.load(), False
186
+
187
+ def _oauth_client(self, timeout: float) -> httpx.Client:
188
+ """A client for the OAuth endpoints, named as the API client names itself."""
189
+ return httpx.Client(
190
+ timeout=timeout,
191
+ headers={"User-Agent": f"sweatstack-cli/{self._settings.version}"},
192
+ )
144
193
 
145
- return self._storage.load()
194
+ def _warn_rotation_lost(self) -> None:
195
+ if not self._warned_rotation_lost:
196
+ self._warned_rotation_lost = True
197
+ stderr_console.print(ROTATION_LOST_WARNING)
146
198
 
147
199
  def _build_auth_url(self, redirect_uri: str, pkce: PKCEChallenge) -> str:
148
200
  """Construct OAuth2 authorization URL with PKCE challenge."""
@@ -167,7 +219,7 @@ class Authenticator:
167
219
  code_verifier: str,
168
220
  ) -> TokenPair:
169
221
  """Exchange authorization code for tokens."""
170
- with httpx.Client(timeout=30.0) as client:
222
+ with self._oauth_client(timeout=30.0) as client:
171
223
  response = client.post(
172
224
  f"{self._settings.api_url}/api/v1/oauth/token",
173
225
  data={
@@ -194,7 +246,7 @@ class Authenticator:
194
246
 
195
247
  def _refresh_tokens(self, refresh_token: str) -> TokenPair:
196
248
  """Refresh expired access token using refresh token."""
197
- with httpx.Client(timeout=30.0) as client:
249
+ with self._oauth_client(timeout=30.0) as client:
198
250
  response = client.post(
199
251
  f"{self._settings.api_url}/api/v1/oauth/token",
200
252
  data={
@@ -210,10 +262,35 @@ class Authenticator:
210
262
  data = response.json()
211
263
  return TokenPair(
212
264
  access_token=data["access_token"],
213
- # Some OAuth servers return a new refresh token, some don't
214
- refresh_token=data.get("refresh_token", refresh_token),
265
+ # SweatStack returns a new refresh token with every refresh (it rotates them); an
266
+ # older server returned none, and the presented one stays good then.
267
+ refresh_token=data.get("refresh_token") or refresh_token,
215
268
  )
216
269
 
270
+ def _revoke(self, refresh_token: str) -> str | None:
271
+ """Revoke a refresh token (RFC 7009). Returns why it failed, or None."""
272
+ try:
273
+ with self._oauth_client(timeout=10.0) as client:
274
+ response = client.post(
275
+ f"{self._settings.api_url}/api/v1/oauth/revoke",
276
+ data={
277
+ "token": refresh_token,
278
+ "token_type_hint": "refresh_token",
279
+ "client_id": self._client_id,
280
+ },
281
+ )
282
+ except httpx.HTTPError:
283
+ return "SweatStack could not be reached"
284
+
285
+ if response.status_code == 200:
286
+ return None
287
+ try:
288
+ body = response.json()
289
+ reason = body.get("error_description") or body.get("error")
290
+ except Exception:
291
+ reason = None
292
+ return f"SweatStack answered {response.status_code}" + (f": {reason}" if reason else "")
293
+
217
294
 
218
295
  # Re-export commonly used types
219
296
  __all__ = ["AuthenticationError", "Authenticator", "FileTokenStorage", "TokenPair"]
@@ -74,10 +74,14 @@ def _confirmation(access_token: str) -> str:
74
74
 
75
75
 
76
76
  def logout() -> None:
77
- """Remove stored credentials."""
78
- auth = Authenticator()
79
- auth.logout()
77
+ """End the sign-in on SweatStack and remove the stored credentials."""
78
+ failure = Authenticator().logout()
80
79
  console.print("[green]✓[/green] Logged out")
80
+ if failure:
81
+ console.print(
82
+ f"[yellow]![/yellow] The sign-in could not be ended on SweatStack ({failure}). "
83
+ "The removed refresh token keeps working until it goes a year unused."
84
+ )
81
85
 
82
86
 
83
87
  def status() -> None:
@@ -0,0 +1,153 @@
1
+ """Tool commands: serve a tool locally under the SweatStack Tools policy, and check it.
2
+
3
+ `tool create`, `deploy`, `publish` and `rollback` follow when the SweatStack app's tool API exists.
4
+ See plans/developer-kit/cli.md in sweatstack-tools.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import socket
10
+ from pathlib import Path
11
+
12
+ import typer
13
+
14
+ from sweatstack_cli.console import console
15
+ from sweatstack_cli.tools.check import REMOVED_KINDS, Finding, check_folder
16
+ from sweatstack_cli.tools.policy import Policy, load_policy
17
+ from sweatstack_cli.tools.server import make_server
18
+
19
+ DOCS_DEPENDENCIES = "https://docs.sweatstack.no/learn/tools/dependencies/"
20
+
21
+ app = typer.Typer(
22
+ name="tool",
23
+ help="Build tools for SweatStack Tools: serve and check them locally.",
24
+ no_args_is_help=True,
25
+ )
26
+
27
+
28
+ def _directory(directory: Path) -> Path:
29
+ if not directory.is_dir():
30
+ console.print(f"[red]Error:[/red] '{directory}' is not a directory.")
31
+ raise typer.Exit(1)
32
+ return directory.resolve()
33
+
34
+
35
+ def _policy() -> Policy:
36
+ policy = load_policy()
37
+ if policy.source == "cached":
38
+ console.print(
39
+ "[yellow]sweatstack.tools is unreachable: using the policy from the last run.[/yellow]"
40
+ )
41
+ elif policy.source == "built-in":
42
+ console.print(
43
+ "[yellow]sweatstack.tools is unreachable: using the policy this CLI shipped with.[/yellow]"
44
+ )
45
+ return policy
46
+
47
+
48
+ def _free_port(start: int, attempts: int = 100) -> int:
49
+ for port in range(start, start + attempts):
50
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
51
+ try:
52
+ probe.bind(("localhost", port))
53
+ return port
54
+ except OSError:
55
+ continue
56
+ console.print(f"[red]Error:[/red] No free port from {start} to {start + attempts - 1}.")
57
+ raise typer.Exit(1)
58
+
59
+
60
+ @app.command()
61
+ def serve(
62
+ directory: Path = typer.Argument(Path("."), help="The tool's folder."),
63
+ port: int | None = typer.Option(
64
+ None, "--port", "-p", help="Port to serve on. The first free one from 8000 by default."
65
+ ),
66
+ slug: str = typer.Option("local", "--slug", help="The tool's slug, for its report link."),
67
+ ) -> None:
68
+ """Serve a tool locally, with the same network policy as SweatStack Tools."""
69
+ root = _directory(directory)
70
+ policy = _policy()
71
+ chosen = port if port is not None else _free_port(8000)
72
+ try:
73
+ server = make_server(root, policy, slug=slug, port=chosen)
74
+ except OSError as error:
75
+ console.print(f"[red]Error:[/red] Cannot serve on port {chosen}: {error.strerror}.")
76
+ raise typer.Exit(1)
77
+ console.print(
78
+ "Serving with the SweatStack Tools network policy: requests to other hosts are blocked, "
79
+ "as they will be when deployed. Blocked requests show in the browser console."
80
+ )
81
+ console.print(f" [cyan]http://localhost:{chosen}[/cyan] ({root})")
82
+ try:
83
+ server.serve_forever()
84
+ except KeyboardInterrupt:
85
+ pass
86
+ finally:
87
+ server.server_close()
88
+
89
+
90
+ def say(text: str = "", *, highlight: bool = True) -> None:
91
+ """Print one line without wrapping."""
92
+ console.print(text, soft_wrap=True, highlight=highlight)
93
+
94
+
95
+ def print_findings(findings: list[Finding], directory: Path) -> None:
96
+ """The check's report, written for a person and for an agent: what, where, and the fix.
97
+
98
+ Lines never wrap, so each finding stays on one line with its whole URL, at any terminal width.
99
+ """
100
+ blocked = [f for f in findings if f.kind not in REMOVED_KINDS]
101
+ removed = [f for f in findings if f.kind in REMOVED_KINDS]
102
+ if blocked:
103
+ files = len({f.file for f in blocked})
104
+ say(
105
+ f"[red]✗[/red] {len(blocked)} load{'s' if len(blocked) != 1 else ''} in {files} "
106
+ f"file{'s' if files != 1 else ''} would be blocked on SweatStack Tools"
107
+ )
108
+ say()
109
+ width = max(len(f"{f.file}:{f.line}") for f in blocked)
110
+ kind_width = max(len(f.kind) for f in blocked)
111
+ for f in blocked:
112
+ say(
113
+ f" {f'{f.file}:{f.line}':<{width}} {f.kind:<{kind_width}} {f.url}",
114
+ highlight=False,
115
+ )
116
+ say()
117
+ say(" Tools can load only their own files and the SweatStack API.")
118
+ say(
119
+ " Download these files into your tool (for example into vendor/) and use relative paths."
120
+ )
121
+ say(f" How, including DuckDB and Pyodide: {DOCS_DEPENDENCIES}")
122
+ if removed:
123
+ if blocked:
124
+ say()
125
+ say(
126
+ f"[yellow]![/yellow] {len(removed)} element{'s' if len(removed) != 1 else ''} SweatStack Tools removes, so they do nothing there:"
127
+ )
128
+ say()
129
+ width = max(len(f"{f.file}:{f.line}") for f in removed)
130
+ for f in removed:
131
+ say(f" {f'{f.file}:{f.line}':<{width}} {f.kind} {f.url}", highlight=False)
132
+ say()
133
+ say(
134
+ " Speculation rules, preconnect and DNS prefetch are not available in SweatStack Tools."
135
+ )
136
+ if not findings:
137
+ say(f"[green]✓[/green] Nothing in {directory} loads from another site.")
138
+
139
+
140
+ @app.command()
141
+ def check(
142
+ directory: Path = typer.Argument(Path("."), help="The tool's folder."),
143
+ ) -> None:
144
+ """Check a tool for files it would load from other sites, which SweatStack Tools blocks.
145
+
146
+ Exits with 1 when anything would be blocked, so an agent's loop treats it as a failure to fix.
147
+ """
148
+ root = _directory(directory)
149
+ policy = _policy()
150
+ findings = check_folder(root, policy.load_origins())
151
+ print_findings(findings, directory)
152
+ if any(f.kind not in REMOVED_KINDS for f in findings):
153
+ raise typer.Exit(1)
sweatstack_cli/config.py CHANGED
@@ -7,6 +7,7 @@ from dataclasses import dataclass
7
7
  from functools import cache
8
8
 
9
9
  DEFAULT_API_URL = "https://app.sweatstack.no"
10
+ DEFAULT_TOOLS_URL = "https://sweatstack.tools"
10
11
 
11
12
 
12
13
  @dataclass(frozen=True, slots=True)
@@ -14,6 +15,7 @@ class Settings:
14
15
  """Immutable application settings."""
15
16
 
16
17
  api_url: str
18
+ tools_url: str
17
19
  version: str
18
20
 
19
21
 
@@ -28,5 +30,6 @@ def get_settings() -> Settings:
28
30
 
29
31
  return Settings(
30
32
  api_url=os.environ.get("SWEATSTACK_URL", DEFAULT_API_URL).rstrip("/"),
33
+ tools_url=os.environ.get("SWEATSTACK_TOOLS_URL", DEFAULT_TOOLS_URL).rstrip("/"),
31
34
  version=__version__,
32
35
  )
sweatstack_cli/main.py CHANGED
@@ -6,7 +6,7 @@ import typer
6
6
 
7
7
  from sweatstack_cli import __version__
8
8
  from sweatstack_cli.commands import app as app_commands
9
- from sweatstack_cli.commands import auth, page
9
+ from sweatstack_cli.commands import auth, page, tool
10
10
  from sweatstack_cli.console import console
11
11
  from sweatstack_cli.exceptions import CLIError
12
12
  from sweatstack_cli.version_check import get_update_message
@@ -23,11 +23,12 @@ app = typer.Typer(
23
23
  # Register command groups
24
24
  app.add_typer(page.app, name="page")
25
25
  app.add_typer(app_commands.app, name="app")
26
+ app.add_typer(tool.app, name="tool")
26
27
 
27
28
  # Register top-level auth commands for convenience
28
29
  # These are the most common operations, so we promote them to top level
29
30
  app.command(name="login", help="Authenticate with SweatStack via browser.")(auth.login)
30
- app.command(name="logout", help="Remove stored credentials.")(auth.logout)
31
+ app.command(name="logout", help="End the sign-in and remove stored credentials.")(auth.logout)
31
32
  app.command(name="status", help="Show authentication and version status.")(auth.status)
32
33
 
33
34