sweatstack-cli 0.13.0__py3-none-any.whl → 0.15.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.
@@ -10,7 +10,12 @@ import httpx
10
10
 
11
11
  from sweatstack_cli.auth import Authenticator
12
12
  from sweatstack_cli.config import get_settings
13
- from sweatstack_cli.exceptions import APIError, AuthenticationError
13
+ from sweatstack_cli.exceptions import (
14
+ APIError,
15
+ AuthenticationError,
16
+ SecondFactorEnrollmentRequired,
17
+ SecondFactorRequired,
18
+ )
14
19
 
15
20
 
16
21
  class APIClient:
@@ -152,11 +157,16 @@ class APIClient:
152
157
  AuthenticationError: For 401 responses.
153
158
  APIError: For other error responses.
154
159
  """
160
+ # A step-up (RFC 9470) is a 401 too, but not an expired session: read the challenge first.
155
161
  if response.status_code == 401:
162
+ if "insufficient_user_authentication" in response.headers.get("WWW-Authenticate", ""):
163
+ raise SecondFactorRequired()
156
164
  raise AuthenticationError("Session expired. Run 'sweatstack login' again.")
157
165
 
158
166
  if response.status_code >= 400:
159
167
  detail, code = self._extract_error(response)
168
+ if code == "second_factor_enrollment_required":
169
+ raise SecondFactorEnrollmentRequired(detail)
160
170
  raise APIError(
161
171
  f"API error ({response.status_code}): {detail}",
162
172
  status_code=response.status_code,
@@ -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."""
@@ -154,6 +206,9 @@ class Authenticator:
154
206
  "code_challenge": pkce.challenge,
155
207
  "code_challenge_method": "S256",
156
208
  "state": pkce.state,
209
+ # SweatStack plan 084 D11: a user with a passkey confirms it in the browser here, and the
210
+ # CLI's tokens carry that confirmation. For anyone else it changes nothing.
211
+ "acr_values": "mfa",
157
212
  }
158
213
  return f"{self._settings.api_url}/oauth/authorize?{urlencode(params)}"
159
214
 
@@ -164,7 +219,7 @@ class Authenticator:
164
219
  code_verifier: str,
165
220
  ) -> TokenPair:
166
221
  """Exchange authorization code for tokens."""
167
- with httpx.Client(timeout=30.0) as client:
222
+ with self._oauth_client(timeout=30.0) as client:
168
223
  response = client.post(
169
224
  f"{self._settings.api_url}/api/v1/oauth/token",
170
225
  data={
@@ -191,7 +246,7 @@ class Authenticator:
191
246
 
192
247
  def _refresh_tokens(self, refresh_token: str) -> TokenPair:
193
248
  """Refresh expired access token using refresh token."""
194
- with httpx.Client(timeout=30.0) as client:
249
+ with self._oauth_client(timeout=30.0) as client:
195
250
  response = client.post(
196
251
  f"{self._settings.api_url}/api/v1/oauth/token",
197
252
  data={
@@ -207,10 +262,35 @@ class Authenticator:
207
262
  data = response.json()
208
263
  return TokenPair(
209
264
  access_token=data["access_token"],
210
- # Some OAuth servers return a new refresh token, some don't
211
- 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,
212
268
  )
213
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
+
214
294
 
215
295
  # Re-export commonly used types
216
296
  __all__ = ["AuthenticationError", "Authenticator", "FileTokenStorage", "TokenPair"]
@@ -2,10 +2,13 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from datetime import datetime
6
+
5
7
  import typer
6
8
 
7
9
  from sweatstack_cli.api import APIClient
8
10
  from sweatstack_cli.auth import Authenticator
11
+ from sweatstack_cli.auth.jwt import decode_jwt_payload
9
12
  from sweatstack_cli.console import console
10
13
  from sweatstack_cli.exceptions import APIError, AuthenticationError
11
14
  from sweatstack_cli.version_check import check_for_update
@@ -22,30 +25,22 @@ def _display_name(user: dict[str, object]) -> str:
22
25
 
23
26
 
24
27
  def login(
28
+ # Kept so scripts that pass it keep working.
25
29
  force: bool = typer.Option(
26
30
  False,
27
31
  "--force",
28
32
  "-f",
29
- help="Force re-authentication even if already logged in.",
33
+ hidden=True,
34
+ help="No longer needed: login always opens the browser.",
30
35
  ),
31
36
  ) -> None:
32
- """Authenticate with SweatStack via browser."""
33
- auth = Authenticator()
37
+ """Authenticate with SweatStack via browser.
34
38
 
35
- # Check if already logged in
36
- if not force:
37
- existing = auth.get_valid_tokens()
38
- if existing:
39
- try:
40
- client = APIClient(authenticator=auth)
41
- user = client.get("/api/v1/oauth/userinfo")
42
- console.print(
43
- f"Already logged in as [bold]{_display_name(user)}[/bold]. "
44
- f"Use [cyan]--force[/cyan] to re-authenticate."
45
- )
46
- return
47
- except AuthenticationError:
48
- pass # Token invalid, proceed with login
39
+ Always opens the browser, as ``gh auth login`` does: signing in again is how a
40
+ passkey confirmation reaches the CLI's tokens (SweatStack plan 084). Other
41
+ commands never open a browser on their own.
42
+ """
43
+ auth = Authenticator()
49
44
 
50
45
  with console.status("[bold]Opening browser for authentication...[/bold]"):
51
46
  try:
@@ -64,11 +59,29 @@ def login(
64
59
  raise typer.Exit(2)
65
60
 
66
61
 
62
+ def _confirmation(access_token: str) -> str:
63
+ """Whether the login that issued these tokens confirmed a passkey (SweatStack plan 084):
64
+ the ``amr`` and ``auth_time`` claims the browser's confirmation put on them. Which actions
65
+ need a confirmation, and how recent, is the server's to decide: a refusal says what to do."""
66
+ try:
67
+ claims = decode_jwt_payload(access_token)
68
+ except ValueError:
69
+ return "unknown"
70
+ if "mfa" in (claims.get("amr") or []) and isinstance(claims.get("auth_time"), int):
71
+ confirmed_at = datetime.fromtimestamp(claims["auth_time"]).astimezone()
72
+ return f"confirmed at login {confirmed_at:%Y-%m-%d %H:%M}"
73
+ return "not confirmed at login"
74
+
75
+
67
76
  def logout() -> None:
68
- """Remove stored credentials."""
69
- auth = Authenticator()
70
- auth.logout()
77
+ """End the sign-in on SweatStack and remove the stored credentials."""
78
+ failure = Authenticator().logout()
71
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
+ )
72
85
 
73
86
 
74
87
  def status() -> None:
@@ -86,11 +99,12 @@ def status() -> None:
86
99
  try:
87
100
  client = APIClient(authenticator=auth)
88
101
  user = client.get("/api/v1/oauth/userinfo")
89
- console.print(f" Name: {_display_name(user)}")
90
- console.print(f" Email: {user.get('email', 'unknown')}")
91
- console.print(f" ID: {user.get('sub', 'unknown')}")
102
+ console.print(f" Name: {_display_name(user)}")
103
+ console.print(f" Email: {user.get('email', 'unknown')}")
104
+ console.print(f" ID: {user.get('sub', 'unknown')}")
92
105
  except (AuthenticationError, APIError):
93
106
  pass # Silently skip user info on error
107
+ console.print(f" Passkey: {_confirmation(tokens.access_token)}")
94
108
 
95
109
  # Check version
96
110
  update_available, latest = check_for_update()
@@ -18,6 +18,27 @@ class AuthenticationError(CLIError):
18
18
  exit_code = 2
19
19
 
20
20
 
21
+ class SecondFactorRequired(AuthenticationError):
22
+ """The action needs a recent passkey confirmation (SweatStack plan 084).
23
+
24
+ The server answers RFC 9470's step-up challenge: a ``401`` whose ``WWW-Authenticate`` says
25
+ ``insufficient_user_authentication``. The browser confirms it at ``sweatstack login``; the CLI
26
+ never handles a passkey itself. Not an expired session, so it never says so."""
27
+
28
+ def __init__(self) -> None:
29
+ super().__init__(
30
+ "This needs your passkey. Run 'sweatstack login' to confirm in your browser, "
31
+ "then run this command again."
32
+ )
33
+
34
+
35
+ class SecondFactorEnrollmentRequired(AuthenticationError):
36
+ """The account has no passkey, and the action needs one (SweatStack plan 084)."""
37
+
38
+ def __init__(self, detail: str) -> None:
39
+ super().__init__(f"{detail} Then run 'sweatstack login' and this command again.")
40
+
41
+
21
42
  class APIError(CLIError):
22
43
  """API returned an error response.
23
44
 
sweatstack_cli/main.py CHANGED
@@ -27,7 +27,7 @@ app.add_typer(app_commands.app, name="app")
27
27
  # Register top-level auth commands for convenience
28
28
  # These are the most common operations, so we promote them to top level
29
29
  app.command(name="login", help="Authenticate with SweatStack via browser.")(auth.login)
30
- app.command(name="logout", help="Remove stored credentials.")(auth.logout)
30
+ app.command(name="logout", help="End the sign-in and remove stored credentials.")(auth.logout)
31
31
  app.command(name="status", help="Show authentication and version status.")(auth.status)
32
32
 
33
33
 
@@ -37,13 +37,17 @@
37
37
  border-radius: 4px; padding: 0.4rem 0.8rem; cursor: pointer;
38
38
  }
39
39
  .btn:hover { border-color: #bdbdbd; }
40
- .btn-red {
41
- background: var(--red); color: #fff; border: none; border-radius: 4px;
42
- padding: 0.6rem 1.2rem; font-size: 1rem; cursor: pointer;
40
+ .ss-signin {
41
+ display: inline-flex; align-items: center; gap: 0.5rem;
42
+ background: var(--red); color: #fff; font: inherit; font-weight: 600;
43
+ border: none; border-radius: 6px; padding: 0.75rem 1.5rem; cursor: pointer;
44
+ transition: filter 0.15s ease;
43
45
  }
44
- .btn-red:hover { filter: brightness(0.95); }
46
+ .ss-signin:hover { filter: brightness(0.93); }
47
+ .ss-signin:focus-visible { outline: 2px solid var(--red); outline-offset: 2px; }
45
48
 
46
- .intro { color: var(--muted); max-width: 36rem; margin: 0 0 1.75rem; }
49
+ .intro { color: var(--muted); max-width: 36rem; margin: 0 0 1rem; }
50
+ .signin-note { font-size: 0.85rem; color: var(--muted); margin: 0.6rem 0 0; }
47
51
 
48
52
  .picker { display: flex; align-items: center; gap: 0.6rem; margin: 0 0 1.25rem; }
49
53
  .picker label { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); }
@@ -73,17 +77,17 @@
73
77
  <div class="wrap">
74
78
  <header class="top">
75
79
  <h1>{{APP_TITLE}}</h1>
76
- <div>
77
- <button id="connect-btn" class="btn-red" onclick="startAuth()">Connect with SweatStack</button>
78
- <button id="logout-btn" class="btn hidden" onclick="logout()">Log out</button>
79
- </div>
80
+ <button type="button" id="signout-btn" class="btn hidden">Sign out</button>
80
81
  </header>
81
82
 
82
- <section id="login">
83
+ <section id="signin" class="hidden">
84
+ <p class="intro">Plot your latest activity and pick a metric to see it over time.</p>
83
85
  <p class="intro">
84
- This app connects to SweatStack to plot the latest activity from your account.
85
- Pick a metric to see it over time.
86
+ Sign in with SweatStack to bring your profile and workout history into this app.
87
+ No separate signup.
86
88
  </p>
89
+ <button type="button" id="signin-btn" class="ss-signin">Sign in with SweatStack</button>
90
+ <p class="signin-note">Use your Garmin, Wahoo or Intervals.icu account</p>
87
91
  </section>
88
92
 
89
93
  <div id="status" class="status hidden"></div>
@@ -118,8 +122,9 @@ const CLIENT_ID = '{{CLIENT_ID}}';
118
122
  const REDIRECT_URI = location.origin + location.pathname;
119
123
  const AUTH_URL = 'https://app.sweatstack.no/oauth/authorize';
120
124
  const TOKEN_URL = 'https://app.sweatstack.no/api/v1/oauth/token';
125
+ const REVOKE_URL = 'https://app.sweatstack.no/api/v1/oauth/revoke';
121
126
  const API_BASE = 'https://app.sweatstack.no/api/v1';
122
- const SCOPE = 'openid profile data:read';
127
+ const SCOPE = 'openid profile activities:read offline_access';
123
128
  const RED = '#EF2B2D';
124
129
 
125
130
  // Metrics worth plotting as a line over time, with display label, unit, and
@@ -151,84 +156,149 @@ function setStatus(msg, isError = false) {
151
156
  }
152
157
 
153
158
  /* ===================================================================
154
- Auth (OAuth2 PKCE)
155
- First-run safe: the Connect button starts an *interactive* authorize
156
- (no prompt=none), so a click always reaches a real login screen.
159
+ Auth: Sign in with SweatStack (OAuth2 PKCE, refresh tokens)
157
160
  =================================================================== */
161
+ // Thrown when the sign-in is gone. Show the sign-in button.
162
+ class SignedOut extends Error {
163
+ constructor(message = 'Please sign in again.') { super(message); }
164
+ }
165
+
158
166
  function b64url(bytes) {
159
- let s = '';
160
- for (const b of bytes) s += String.fromCharCode(b);
161
- return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
167
+ return btoa(String.fromCharCode(...bytes))
168
+ .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
162
169
  }
163
- async function pkce() {
164
- const verifier = b64url(crypto.getRandomValues(new Uint8Array(64)));
165
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
166
- return { verifier, challenge: b64url(new Uint8Array(digest)) };
170
+
171
+ function loadTokens() {
172
+ try { return JSON.parse(localStorage.getItem('ss_tokens')); } catch { return null; }
167
173
  }
168
- function getToken() {
169
- const t = localStorage.getItem('ss_token');
170
- const exp = +localStorage.getItem('ss_token_exp') || 0;
171
- return (t && Date.now() < exp - 30000) ? t : null;
174
+ function saveTokens(response) {
175
+ const tokens = {
176
+ access_token: response.access_token,
177
+ expires_at: Date.now() + response.expires_in * 1000,
178
+ refresh_token: response.refresh_token,
179
+ };
180
+ localStorage.setItem('ss_tokens', JSON.stringify(tokens));
181
+ return tokens;
172
182
  }
173
- function storeToken(j) {
174
- localStorage.setItem('ss_token', j.access_token);
175
- localStorage.setItem('ss_token_exp', String(Date.now() + (j.expires_in || 3600) * 1000));
183
+ function clearTokens() {
184
+ localStorage.removeItem('ss_tokens');
176
185
  }
177
- function clearToken() {
178
- localStorage.removeItem('ss_token');
179
- localStorage.removeItem('ss_token_exp');
186
+
187
+ async function tokenRequest(params) {
188
+ const response = await fetch(TOKEN_URL, {
189
+ method: 'POST',
190
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
191
+ body: new URLSearchParams({ client_id: CLIENT_ID, ...params }),
192
+ });
193
+ const body = await response.json().catch(() => ({}));
194
+ if (response.ok) return body;
195
+ if (body.error === 'invalid_grant') throw new SignedOut();
196
+ throw new Error(body.error_description || body.error || `token request failed (${response.status})`);
180
197
  }
181
- window.startAuth = async function () {
182
- const { verifier, challenge } = await pkce();
183
- const state = b64url(crypto.getRandomValues(new Uint8Array(16)));
184
- sessionStorage.setItem('ss_verifier', verifier);
185
- sessionStorage.setItem('ss_state', state);
186
- const p = new URLSearchParams({
187
- client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, response_type: 'code',
188
- scope: SCOPE, code_challenge: challenge, code_challenge_method: 'S256', state,
198
+
199
+ // One tab refreshes at a time, and every refresh can return a new refresh token.
200
+ // `stale` is the access token the caller can't use: expired, or answered with a 401.
201
+ function refreshTokens(stale) {
202
+ return navigator.locks.request('ss-token-refresh', async () => {
203
+ const tokens = loadTokens();
204
+ // Another tab may have refreshed while this one waited for the lock.
205
+ if (tokens && tokens.access_token !== stale && tokens.expires_at - Date.now() > 60000) return tokens;
206
+ if (!tokens?.refresh_token) { clearTokens(); throw new SignedOut(); }
207
+ try {
208
+ return saveTokens(await tokenRequest({ grant_type: 'refresh_token', refresh_token: tokens.refresh_token }));
209
+ } catch (e) {
210
+ if (e instanceof SignedOut) clearTokens();
211
+ throw e;
212
+ }
189
213
  });
190
- location.href = `${AUTH_URL}?${p}`;
191
- };
192
- window.logout = function () {
193
- clearToken();
194
- location.href = REDIRECT_URI;
195
- };
196
- async function handleCallback() {
197
- const q = new URLSearchParams(location.search);
198
- const code = q.get('code');
199
- if (!code) {
200
- if (q.get('error')) history.replaceState({}, '', location.pathname);
201
- return false;
214
+ }
215
+
216
+ async function accessToken() {
217
+ const tokens = loadTokens();
218
+ if (!tokens) throw new SignedOut();
219
+ if (tokens.expires_at - Date.now() > 60000) return tokens.access_token;
220
+ return (await refreshTokens(tokens.access_token)).access_token;
221
+ }
222
+
223
+ // Every API call goes through here: it refreshes and retries once on a 401.
224
+ async function api(path) {
225
+ let token = await accessToken();
226
+ let response = await fetch(API_BASE + path, { headers: { Authorization: `Bearer ${token}` } });
227
+ if (response.status === 401) {
228
+ token = (await refreshTokens(token)).access_token;
229
+ response = await fetch(API_BASE + path, { headers: { Authorization: `Bearer ${token}` } });
202
230
  }
203
- const ok = q.get('state') && q.get('state') === sessionStorage.getItem('ss_state');
204
- const verifier = sessionStorage.getItem('ss_verifier');
205
- history.replaceState({}, '', location.pathname);
206
- if (!ok || !verifier) return false;
207
- const body = new URLSearchParams({
208
- grant_type: 'authorization_code', code, redirect_uri: REDIRECT_URI,
209
- client_id: CLIENT_ID, code_verifier: verifier,
210
- });
211
- const r = await fetch(TOKEN_URL, {
212
- method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body,
213
- });
214
- if (!r.ok) return false;
215
- storeToken(await r.json());
216
- return true;
231
+ if (response.status === 401) { clearTokens(); throw new SignedOut(); }
232
+ if (!response.ok) throw new Error(`request failed (${response.status})`);
233
+ return response;
217
234
  }
218
- async function apiGet(path) {
219
- const token = getToken();
220
- if (!token) { showLoggedOut(); throw new Error('unauthenticated'); }
221
- const r = await fetch(API_BASE + path, { headers: { Authorization: `Bearer ${token}` } });
222
- if (r.status === 401) {
223
- clearToken();
224
- showLoggedOut('Your session expired. Please reconnect.');
225
- throw new Error('unauthenticated');
235
+
236
+ async function startAuth() {
237
+ const verifier = b64url(crypto.getRandomValues(new Uint8Array(32)));
238
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
239
+ const state = b64url(crypto.getRandomValues(new Uint8Array(16)));
240
+ sessionStorage.setItem('ss_pkce', JSON.stringify({ verifier, state }));
241
+ location.assign(`${AUTH_URL}?${new URLSearchParams({
242
+ response_type: 'code', client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, scope: SCOPE,
243
+ state, code_challenge: b64url(new Uint8Array(digest)), code_challenge_method: 'S256',
244
+ })}`);
245
+ }
246
+
247
+ function signOut() {
248
+ // End the sign-in on SweatStack too, so its refresh token stops working. Best effort.
249
+ const tokens = loadTokens();
250
+ if (tokens?.refresh_token) {
251
+ fetch(REVOKE_URL, {
252
+ method: 'POST', keepalive: true,
253
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
254
+ body: new URLSearchParams({ client_id: CLIENT_ID, token: tokens.refresh_token }),
255
+ }).catch(() => {});
226
256
  }
227
- if (!r.ok) throw new Error(`request failed (${r.status})`);
228
- return r;
257
+ clearTokens();
258
+ document.cookie = 'ss_known=; path=/; max-age=0';
259
+ showSignIn();
229
260
  }
230
- const apiJSON = async path => (await apiGet(path)).json();
231
- const apiBuffer = async path => (await apiGet(path)).arrayBuffer();
261
+
262
+ // The page-load order. Never redirect from a callback, or a cancelled sign-in loops.
263
+ async function boot() {
264
+ const params = new URLSearchParams(location.search);
265
+ if (params.has('code') || params.has('error')) {
266
+ history.replaceState(null, '', location.pathname);
267
+ const pkce = JSON.parse(sessionStorage.getItem('ss_pkce'));
268
+ sessionStorage.removeItem('ss_pkce');
269
+ const error = params.get('error');
270
+ if (error) {
271
+ return showSignIn(params.get('error_description')
272
+ || (error === 'access_denied' ? 'Sign-in was cancelled.' : `Sign-in failed (${error}).`));
273
+ }
274
+ if (!pkce || params.get('state') !== pkce.state) {
275
+ return showSignIn('Sign-in could not be verified. Please try again.');
276
+ }
277
+ try {
278
+ saveTokens(await tokenRequest({
279
+ grant_type: 'authorization_code', code: params.get('code'), code_verifier: pkce.verifier,
280
+ }));
281
+ } catch (e) {
282
+ return showSignIn(e instanceof SignedOut ? 'Sign-in expired. Please try again.' : `Sign-in failed: ${e.message}`);
283
+ }
284
+ document.cookie = 'ss_known=1; path=/; max-age=2147483647; SameSite=Lax';
285
+ return showApp();
286
+ }
287
+ if (loadTokens()) {
288
+ try {
289
+ await accessToken();
290
+ return showApp();
291
+ } catch (e) {
292
+ // A network error keeps the tokens, so a reload tries again.
293
+ if (!(e instanceof SignedOut)) return showSignIn(`Could not reach SweatStack: ${e.message}`);
294
+ }
295
+ }
296
+ if (document.cookie.split('; ').includes('ss_known=1')) return startAuth();
297
+ showSignIn();
298
+ }
299
+
300
+ const apiJSON = async path => (await api(path)).json();
301
+ const apiBuffer = async path => (await api(path)).arrayBuffer();
232
302
 
233
303
  /* ===================================================================
234
304
  DuckDB-WASM parquet parsing (lazy, single shared instance)
@@ -280,7 +350,7 @@ const plottableOf = a => (a && a.metrics ? a.metrics.filter(m => PLOTTABLE.inclu
280
350
  // There is no activity picker, so fall back to the most recent one that does.
281
351
  async function findActivity() {
282
352
  const latest = await apiJSON('/activities/latest').catch(e => {
283
- if (e.message === 'unauthenticated') throw e;
353
+ if (e instanceof SignedOut) throw e;
284
354
  return null; // no activities yet → 404; fall through to the list
285
355
  });
286
356
  if (plottableOf(latest).length) return latest;
@@ -347,7 +417,7 @@ async function drawMetric(id, metric) {
347
417
  try {
348
418
  series = await getSeries(id, metric);
349
419
  } catch (e) {
350
- if (e.message !== 'unauthenticated') setStatus(`Could not load data: ${e.message}`, true);
420
+ showError(e, 'Could not load data');
351
421
  return;
352
422
  }
353
423
  setStatus('');
@@ -380,17 +450,20 @@ async function drawMetric(id, metric) {
380
450
  /* ===================================================================
381
451
  Views + boot
382
452
  =================================================================== */
383
- function showLoggedOut(note) {
384
- el('connect-btn').classList.remove('hidden');
385
- el('logout-btn').classList.add('hidden');
453
+ function showSignIn(note) {
454
+ el('signout-btn').classList.add('hidden');
386
455
  el('app').classList.add('hidden');
387
- el('login').classList.remove('hidden');
388
- if (note) setStatus(note, true); else setStatus('');
456
+ el('signin').classList.remove('hidden');
457
+ setStatus(note || '', Boolean(note));
458
+ }
459
+ function showApp() {
460
+ el('signin').classList.add('hidden');
461
+ el('signout-btn').classList.remove('hidden');
462
+ loadAndRender();
389
463
  }
390
- function showLoggedIn() {
391
- el('connect-btn').classList.add('hidden');
392
- el('logout-btn').classList.remove('hidden');
393
- el('login').classList.add('hidden');
464
+ function showError(e, what) {
465
+ if (e instanceof SignedOut) showSignIn(e.message);
466
+ else setStatus(`${what}: ${e.message}`, true);
394
467
  }
395
468
 
396
469
  async function loadAndRender() {
@@ -399,7 +472,7 @@ async function loadAndRender() {
399
472
  try {
400
473
  activity = await findActivity();
401
474
  } catch (e) {
402
- if (e.message !== 'unauthenticated') setStatus(`Could not load activities: ${e.message}`, true);
475
+ showError(e, 'Could not load activities');
403
476
  return;
404
477
  }
405
478
  if (!activity) {
@@ -434,16 +507,8 @@ window.addEventListener('resize', () => {
434
507
  }, 120);
435
508
  });
436
509
 
437
- async function boot() {
438
- await handleCallback();
439
- if (getToken()) {
440
- showLoggedIn();
441
- await loadAndRender();
442
- } else {
443
- showLoggedOut();
444
- }
445
- }
446
-
510
+ el('signin-btn').addEventListener('click', startAuth);
511
+ el('signout-btn').addEventListener('click', signOut);
447
512
  boot();
448
513
  </script>
449
514
  </body>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sweatstack-cli
3
- Version: 0.13.0
3
+ Version: 0.15.0
4
4
  Summary: Command-line interface for SweatStack — the sports data platform for developers
5
5
  Project-URL: Homepage, https://sweatstack.no
6
6
  Project-URL: Documentation, https://docs.sweatstack.no
@@ -26,6 +26,9 @@ Requires-Dist: mypy>=1.14; extra == 'dev'
26
26
  Requires-Dist: pytest-httpx>=0.35; extra == 'dev'
27
27
  Requires-Dist: pytest>=8.0; extra == 'dev'
28
28
  Requires-Dist: ruff>=0.9; extra == 'dev'
29
+ Provides-Extra: e2e
30
+ Requires-Dist: playwright>=1.50; extra == 'e2e'
31
+ Requires-Dist: pyarrow>=18.0; extra == 'e2e'
29
32
  Description-Content-Type: text/markdown
30
33
 
31
34
  # SweatStack CLI
@@ -83,7 +86,7 @@ sweatstack page deploy
83
86
  |---------|-------------|
84
87
  | `sweatstack login` | Authenticate via browser (OAuth2 PKCE) |
85
88
  | `sweatstack login --force` | Force re-authentication |
86
- | `sweatstack logout` | Remove stored credentials |
89
+ | `sweatstack logout` | End the sign-in on SweatStack and remove stored credentials |
87
90
  | `sweatstack status` | Show auth status, user info, and version |
88
91
  | `sweatstack --version` | Show version and check for updates |
89
92
 
@@ -1,27 +1,27 @@
1
1
  sweatstack_cli/__init__.py,sha256=FalqkgMa69vADPpNY76Cztq5oiLgzRNVlhaR4itdZ78,465
2
2
  sweatstack_cli/config.py,sha256=cD4OXnVAKVagYazyk9Cw-WWx62tJPqcjQt1cknYyymM,706
3
3
  sweatstack_cli/console.py,sha256=69KWAM7ksnYRTONMYTXGXN4LWRAQhRxcLXO0LcWGLqo,300
4
- sweatstack_cli/exceptions.py,sha256=VKV6KVhztfGRmj5jLKnqY0PEBD1qJGEg1ePuKY9rn_o,1334
4
+ sweatstack_cli/exceptions.py,sha256=Qzc1tbchk3Zhfin4Z08hQ1xpTK-dKqjkde2CXDpAY4s,2227
5
5
  sweatstack_cli/go_live.py,sha256=6-WjN9jyfLnbLXs0eAEX0NkwWeigf1A7BYVGG6W092w,1855
6
- sweatstack_cli/main.py,sha256=obcF1VGhwcE_pI1BwTJkY4J4BgIGac-y3yYGvY6ZOp8,2330
6
+ sweatstack_cli/main.py,sha256=D2Yd2pPY_Uf_rgCAy_ayxiQaNTV1t8BtyYxMl8lvMKU,2350
7
7
  sweatstack_cli/project.py,sha256=yUpkrEbPD2c0lu8IKw88aQrkFtksLHMjmgHlaqKVQUo,3660
8
8
  sweatstack_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
9
  sweatstack_cli/version_check.py,sha256=yZ_qVe7tUBowUDAmMki-wyf5pSxlNDsoWKgTcSfesBA,2015
10
10
  sweatstack_cli/api/__init__.py,sha256=l9s6BzF6Wx17K_ElRUX-8aAwwIIzqmGF1PQ3Mbc07mw,107
11
- sweatstack_cli/api/client.py,sha256=Ukpq_rVc2tW1cKlTBF_UfInHVcaHoPHF9pASNRAAcsQ,6632
12
- sweatstack_cli/auth/__init__.py,sha256=J5WTFjaogP5lPTorWcW3VTwok-9kI_NxFLtXBYWQCI4,6926
11
+ sweatstack_cli/api/client.py,sha256=bfNfLdbFqoWA47qdi4JrSCdTIASaP9zavTDAIvoxFAQ,7071
12
+ sweatstack_cli/auth/__init__.py,sha256=7oGPfkn3KswBM4Ffk6-uK1Ym8uL02h0eFPbZ9I50_Z8,10927
13
13
  sweatstack_cli/auth/callback_server.py,sha256=37aTX7smvmrn1azRzOPPDkuBwcunUt3KnNVZ5SCJRLM,6578
14
14
  sweatstack_cli/auth/jwt.py,sha256=Ja6ccFyRKtX5MPjFdHNavVYf8KTz0MYT86StbnF-cwg,1502
15
15
  sweatstack_cli/auth/pkce.py,sha256=sO_xUeN1UIvXKX0yEIGgMTIIzvfCOCUwlyNAveEd16k,1542
16
16
  sweatstack_cli/auth/tokens.py,sha256=kc8ytoO9PAyjLD6wUTIagVuP7_ia5ZjW5m_WjXIRIkA,4942
17
17
  sweatstack_cli/commands/__init__.py,sha256=YCO8wYVvdGeoEI0p_oUm8ANLneuET4SHsKDjitMjAgY,35
18
18
  sweatstack_cli/commands/app.py,sha256=90AwUm5RhagE5tZww77Fk9B0vpZFlC59OlylGXTxWC0,9055
19
- sweatstack_cli/commands/auth.py,sha256=kkSZoWFTUw9Mo30FA_bOJxduWC1nuvkl_m1qtrtSj4I,3905
19
+ sweatstack_cli/commands/auth.py,sha256=vmiYfkvrHIOyF0DTC6JI95dieu9uyaq6xvx9M9_grQE,4754
20
20
  sweatstack_cli/commands/page.py,sha256=G58KEsiCeq4hD0Z5ot2g9W6vBH6iZu-lCvdA1kzep-U,24612
21
21
  sweatstack_cli/services/__init__.py,sha256=pFrcjumdHNRU8aa3bxplq4jhCivH2YGGqkGG8yIMv20,337
22
22
  sweatstack_cli/services/applications.py,sha256=VToXlk48kn2-39eTdDf_hSJUdZqkJjCFoDaqf6DpdGA,4428
23
- sweatstack_cli/templates/page/index.html,sha256=vOnZnIstf252XLiQ6GBznVp5dSy5SqpSwRUfJT43bbQ,17374
24
- sweatstack_cli-0.13.0.dist-info/METADATA,sha256=D0md2zThfT3J3yDShj0E9bO93viZqYoT6gEoZH55YhI,5531
25
- sweatstack_cli-0.13.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
26
- sweatstack_cli-0.13.0.dist-info/entry_points.txt,sha256=rnH0EV1U9CQlmKQcJ7RmxGpNRTa9J-YdiIJZDYrAXb4,56
27
- sweatstack_cli-0.13.0.dist-info/RECORD,,
23
+ sweatstack_cli/templates/page/index.html,sha256=-PxqMi5eq4GbNGhjz4U9vD_oRReyngGPX2T0Rv1LL3M,20395
24
+ sweatstack_cli-0.15.0.dist-info/METADATA,sha256=yez50FaXk3UnGbQ5ZF6DVEX5ouVQuXTtGb4CswxKMo0,5678
25
+ sweatstack_cli-0.15.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
26
+ sweatstack_cli-0.15.0.dist-info/entry_points.txt,sha256=rnH0EV1U9CQlmKQcJ7RmxGpNRTa9J-YdiIJZDYrAXb4,56
27
+ sweatstack_cli-0.15.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.4
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any