sub2api 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sub2api
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Python client for the user-facing API of Sub2API instances
5
5
  Author: Eight Labs
6
6
  License-Expression: MIT
@@ -29,7 +29,7 @@ Description-Content-Type: text/markdown
29
29
 
30
30
  # sub2api
31
31
 
32
- `sub2api` is a Python client for the shared user-facing panel API exposed by Sub2API instances. One client object represents one user's in-memory dashboard session. Requests use `curl_cffi` with Chrome browser impersonation by default.
32
+ `sub2api` is a Python client for the shared user-facing panel API exposed by Sub2API instances. One client object represents one user's dashboard session. Requests use `curl_cffi` with Chrome browser impersonation by default.
33
33
 
34
34
  The library targets operations present on standard Sub2API deployments: account balance, optional payment deposits, payment orders, platform quotas, usage history and statistics, API keys, groups, subscriptions, announcements, and redemption.
35
35
 
@@ -43,7 +43,7 @@ Python 3.10 or newer is required.
43
43
 
44
44
  ## Authenticate with an existing session
45
45
 
46
- The dashboard's access token is different from an `sk-...` gateway API key. Browser deployments normally store the panel tokens under `auth_token` and `refresh_token` in local storage.
46
+ The client authenticates with a dashboard access token. If your integration owns the session and its renewal, you can also supply its refresh token.
47
47
 
48
48
  ```python
49
49
  import os
@@ -60,9 +60,9 @@ print(client.me().email)
60
60
  print(client.balance().balance)
61
61
  ```
62
62
 
63
- Pass either the instance origin or its full `/api/v1` URL. Tokens are retained only in memory. If a refresh token is supplied, the client rotates the token pair after an authenticated `401`. Supplying `expires_at` as a Unix timestamp also enables proactive refresh.
63
+ Pass either the instance origin or its full `/api/v1` URL. By default, the client keeps its tokens in memory and attempts renewal after an authenticated `401` if it has a refresh token. Supplying `expires_at` as a Unix timestamp also enables proactive renewal within 30 seconds of expiry.
64
64
 
65
- The default browser fingerprint is Chrome. Choose another `curl_cffi` fingerprint or configure proxies by supplying your own `curl_cffi.requests.Session`:
65
+ The default browser fingerprint is Chrome. You can choose another `curl_cffi` fingerprint or configure proxies with your own `curl_cffi.requests.Session`.
66
66
 
67
67
  ```python
68
68
  from curl_cffi import requests
@@ -71,6 +71,33 @@ session = requests.Session(impersonate="safari")
71
71
  client = Sub2API("https://sub2api.example.com", session=session)
72
72
  ```
73
73
 
74
+ ### Use a browser-managed session
75
+
76
+ If the dashboard owns renewal, pass its access token with `externally_managed=True`. The client surfaces the original `401`. When the dashboard supplies a new token, call `set_access_token()` on the existing client. You can pass `expires_at` with either call to retain the dashboard's expiry timestamp.
77
+
78
+ ```python
79
+ client = Sub2API(
80
+ "https://sub2api.example.com",
81
+ access_token=dashboard_access_token,
82
+ externally_managed=True,
83
+ )
84
+ client.set_access_token(updated_dashboard_access_token)
85
+ ```
86
+
87
+ ### Persist and share a library-managed session
88
+
89
+ Pass a `token_store` that implements `TokenStore`. The client uses the stored `SessionTokens` when present and can initialize an empty store from the constructor credentials. Keep one store per user session and instance. Each write must persist `access_token`, `refresh_token`, `expires_at`, and `token_type` together.
90
+
91
+ - `load()` returns the current snapshot, or `None` for an uninitialized store.
92
+ - `save(tokens)` atomically replaces the snapshot after a successful login, including 2FA.
93
+ - `compare_and_set(expected, tokens)` atomically replaces the snapshot only if it matches `expected`. Return `False` when another writer has changed it. An empty `SessionTokens()` snapshot represents a cleared session.
94
+
95
+ When multiple clients share the session, pass the same `refresh_lock` to each client along with the shared store. A `threading.Lock()` works for threads in one process. Workers in separate processes need a lock that coordinates across those processes and supports `with`. Clients reload the stored pair under that lock and save a rotation before releasing it or retrying the original request.
96
+
97
+ If the rotation write raises, the client surfaces the store exception and keeps the new pair in `client.tokens`. Call `client.save_tokens()` to retry the conditional write without another refresh request. A newer login in the store takes precedence over a pending rotation.
98
+
99
+ Rate limits, transport errors, and server errors during renewal leave credentials intact. HTTP errors expose `retry_after` in seconds when the server supplies a valid `Retry-After` header. After a transport failure the client checks the store for a replacement pair, and surfaces `TransportError` if it finds none. `SessionExpiredError`, `SessionRevokedError`, and `SessionBindingError` are subclasses of `AuthenticationError` that carry the server's reason or code.
100
+
74
101
  ## Log in with email and password
75
102
 
76
103
  ```python
@@ -1,6 +1,6 @@
1
1
  # sub2api
2
2
 
3
- `sub2api` is a Python client for the shared user-facing panel API exposed by Sub2API instances. One client object represents one user's in-memory dashboard session. Requests use `curl_cffi` with Chrome browser impersonation by default.
3
+ `sub2api` is a Python client for the shared user-facing panel API exposed by Sub2API instances. One client object represents one user's dashboard session. Requests use `curl_cffi` with Chrome browser impersonation by default.
4
4
 
5
5
  The library targets operations present on standard Sub2API deployments: account balance, optional payment deposits, payment orders, platform quotas, usage history and statistics, API keys, groups, subscriptions, announcements, and redemption.
6
6
 
@@ -14,7 +14,7 @@ Python 3.10 or newer is required.
14
14
 
15
15
  ## Authenticate with an existing session
16
16
 
17
- The dashboard's access token is different from an `sk-...` gateway API key. Browser deployments normally store the panel tokens under `auth_token` and `refresh_token` in local storage.
17
+ The client authenticates with a dashboard access token. If your integration owns the session and its renewal, you can also supply its refresh token.
18
18
 
19
19
  ```python
20
20
  import os
@@ -31,9 +31,9 @@ print(client.me().email)
31
31
  print(client.balance().balance)
32
32
  ```
33
33
 
34
- Pass either the instance origin or its full `/api/v1` URL. Tokens are retained only in memory. If a refresh token is supplied, the client rotates the token pair after an authenticated `401`. Supplying `expires_at` as a Unix timestamp also enables proactive refresh.
34
+ Pass either the instance origin or its full `/api/v1` URL. By default, the client keeps its tokens in memory and attempts renewal after an authenticated `401` if it has a refresh token. Supplying `expires_at` as a Unix timestamp also enables proactive renewal within 30 seconds of expiry.
35
35
 
36
- The default browser fingerprint is Chrome. Choose another `curl_cffi` fingerprint or configure proxies by supplying your own `curl_cffi.requests.Session`:
36
+ The default browser fingerprint is Chrome. You can choose another `curl_cffi` fingerprint or configure proxies with your own `curl_cffi.requests.Session`.
37
37
 
38
38
  ```python
39
39
  from curl_cffi import requests
@@ -42,6 +42,33 @@ session = requests.Session(impersonate="safari")
42
42
  client = Sub2API("https://sub2api.example.com", session=session)
43
43
  ```
44
44
 
45
+ ### Use a browser-managed session
46
+
47
+ If the dashboard owns renewal, pass its access token with `externally_managed=True`. The client surfaces the original `401`. When the dashboard supplies a new token, call `set_access_token()` on the existing client. You can pass `expires_at` with either call to retain the dashboard's expiry timestamp.
48
+
49
+ ```python
50
+ client = Sub2API(
51
+ "https://sub2api.example.com",
52
+ access_token=dashboard_access_token,
53
+ externally_managed=True,
54
+ )
55
+ client.set_access_token(updated_dashboard_access_token)
56
+ ```
57
+
58
+ ### Persist and share a library-managed session
59
+
60
+ Pass a `token_store` that implements `TokenStore`. The client uses the stored `SessionTokens` when present and can initialize an empty store from the constructor credentials. Keep one store per user session and instance. Each write must persist `access_token`, `refresh_token`, `expires_at`, and `token_type` together.
61
+
62
+ - `load()` returns the current snapshot, or `None` for an uninitialized store.
63
+ - `save(tokens)` atomically replaces the snapshot after a successful login, including 2FA.
64
+ - `compare_and_set(expected, tokens)` atomically replaces the snapshot only if it matches `expected`. Return `False` when another writer has changed it. An empty `SessionTokens()` snapshot represents a cleared session.
65
+
66
+ When multiple clients share the session, pass the same `refresh_lock` to each client along with the shared store. A `threading.Lock()` works for threads in one process. Workers in separate processes need a lock that coordinates across those processes and supports `with`. Clients reload the stored pair under that lock and save a rotation before releasing it or retrying the original request.
67
+
68
+ If the rotation write raises, the client surfaces the store exception and keeps the new pair in `client.tokens`. Call `client.save_tokens()` to retry the conditional write without another refresh request. A newer login in the store takes precedence over a pending rotation.
69
+
70
+ Rate limits, transport errors, and server errors during renewal leave credentials intact. HTTP errors expose `retry_after` in seconds when the server supplies a valid `Retry-After` header. After a transport failure the client checks the store for a replacement pair, and surfaces `TransportError` if it finds none. `SessionExpiredError`, `SessionRevokedError`, and `SessionBindingError` are subclasses of `AuthenticationError` that carry the server's reason or code.
71
+
45
72
  ## Log in with email and password
46
73
 
47
74
  ```python
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "sub2api"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Python client for the user-facing API of Sub2API instances"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -8,6 +8,9 @@ from ._exceptions import (
8
8
  PermissionDeniedError,
9
9
  ProtocolError,
10
10
  RateLimitError,
11
+ SessionBindingError,
12
+ SessionExpiredError,
13
+ SessionRevokedError,
11
14
  Sub2APIError,
12
15
  TransportError,
13
16
  TwoFactorRequired,
@@ -35,6 +38,7 @@ from ._models import (
35
38
  UsageRecord,
36
39
  User,
37
40
  )
41
+ from ._token_store import TokenStore
38
42
 
39
43
  __all__ = [
40
44
  "APIError",
@@ -60,11 +64,15 @@ __all__ = [
60
64
  "RateLimitError",
61
65
  "Redemption",
62
66
  "Resource",
67
+ "SessionBindingError",
68
+ "SessionExpiredError",
69
+ "SessionRevokedError",
63
70
  "SessionTokens",
64
71
  "Sub2API",
65
72
  "Sub2APIError",
66
73
  "Subscription",
67
74
  "SubscriptionPlan",
75
+ "TokenStore",
68
76
  "TransportError",
69
77
  "TwoFactorRequired",
70
78
  "UsageRecord",
@@ -72,4 +80,4 @@ __all__ = [
72
80
  "ValidationError",
73
81
  ]
74
82
 
75
- __version__ = "0.2.0"
83
+ __version__ = "0.3.0"
@@ -1,9 +1,12 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import math
3
4
  import threading
4
5
  import time
5
6
  from collections.abc import Mapping
6
- from datetime import date, datetime
7
+ from contextlib import AbstractContextManager
8
+ from datetime import date, datetime, timezone
9
+ from email.utils import parsedate_to_datetime
7
10
  from typing import Any, cast
8
11
  from urllib.parse import unquote, urlsplit, urlunsplit
9
12
 
@@ -18,6 +21,9 @@ from ._exceptions import (
18
21
  PermissionDeniedError,
19
22
  ProtocolError,
20
23
  RateLimitError,
24
+ SessionBindingError,
25
+ SessionExpiredError,
26
+ SessionRevokedError,
21
27
  TransportError,
22
28
  TwoFactorRequired,
23
29
  ValidationError,
@@ -33,6 +39,7 @@ from ._resources import (
33
39
  SubscriptionsResource,
34
40
  UsageResource,
35
41
  )
42
+ from ._token_store import TokenStore
36
43
 
37
44
  _ERROR_TYPES: dict[int, type[APIError]] = {
38
45
  400: ValidationError,
@@ -43,6 +50,18 @@ _ERROR_TYPES: dict[int, type[APIError]] = {
43
50
  422: ValidationError,
44
51
  429: RateLimitError,
45
52
  }
53
+ _SESSION_ERROR_TYPES: dict[str, type[AuthenticationError]] = {
54
+ "ACCESS_TOKEN_EXPIRED": SessionExpiredError,
55
+ "REFRESH_TOKEN_EXPIRED": SessionExpiredError,
56
+ "TOKEN_EXPIRED": SessionExpiredError,
57
+ "REFRESH_TOKEN_REVOKED": SessionRevokedError,
58
+ "SESSION_REVOKED": SessionRevokedError,
59
+ "TOKEN_REVOKED": SessionRevokedError,
60
+ "SESSION_BINDING_MISMATCH": SessionBindingError,
61
+ }
62
+ _REFRESH_REJECTION_REASONS = frozenset(
63
+ {"INVALID_TOKEN", "REFRESH_TOKEN_INVALID", "REFRESH_TOKEN_REUSED", "USER_NOT_ACTIVE"}
64
+ )
46
65
  _LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
47
66
 
48
67
 
@@ -114,9 +133,24 @@ def _retry_after(response: Any) -> float | None:
114
133
  if value is None:
115
134
  return None
116
135
  try:
117
- return max(0.0, float(value))
136
+ delay = float(value)
118
137
  except ValueError:
119
- return None
138
+ try:
139
+ retry_at = parsedate_to_datetime(value)
140
+ except (ValueError, OverflowError):
141
+ return None
142
+ if retry_at.tzinfo is None:
143
+ retry_at = retry_at.replace(tzinfo=timezone.utc)
144
+ delay = (retry_at - datetime.now(timezone.utc)).total_seconds()
145
+ return max(0.0, delay) if math.isfinite(delay) else None
146
+
147
+
148
+ def _refresh_rejected(error: APIError) -> bool:
149
+ return isinstance(error, AuthenticationError) or (
150
+ 400 <= error.status_code < 500
151
+ and error.status_code != 429
152
+ and (error.reason in _REFRESH_REJECTION_REASONS or error.code in _REFRESH_REJECTION_REASONS)
153
+ )
120
154
 
121
155
 
122
156
  class Sub2API:
@@ -135,12 +169,30 @@ class Sub2API:
135
169
  allow_insecure: bool = False,
136
170
  impersonate: str | None = "chrome",
137
171
  session: Any | None = None,
172
+ externally_managed: bool = False,
173
+ token_store: TokenStore | None = None,
174
+ refresh_lock: AbstractContextManager[Any] | None = None,
138
175
  ) -> None:
139
176
  self.base_url = _api_base_url(base_url, allow_insecure)
140
177
  self.timezone = timezone
141
178
  self.language = language
142
- self._tokens = SessionTokens(access_token, refresh_token, expires_at)
143
- self._refresh_lock = threading.RLock()
179
+ if externally_managed and token_store is not None:
180
+ raise ConfigurationError("token_store is only available for library-managed sessions")
181
+ self._externally_managed = externally_managed
182
+ self._token_store = token_store
183
+ self._tokens = SessionTokens(
184
+ access_token, None if externally_managed else refresh_token, expires_at
185
+ )
186
+ if token_store is not None:
187
+ stored = token_store.load()
188
+ if stored is None and (access_token or refresh_token):
189
+ if not token_store.compare_and_set(None, self._tokens):
190
+ self._tokens = token_store.load() or SessionTokens()
191
+ elif stored is not None:
192
+ self._tokens = stored
193
+ self._refresh_lock = threading.Lock() if refresh_lock is None else refresh_lock
194
+ self._auth_lock = threading.Lock()
195
+ self._pending_save: SessionTokens | None = None
144
196
  self._pending_2fa_token: str | None = None
145
197
  self.timeout = timeout
146
198
  self.impersonate = impersonate
@@ -170,6 +222,15 @@ class Sub2API:
170
222
  def is_authenticated(self) -> bool:
171
223
  return self._tokens.authenticated
172
224
 
225
+ def set_access_token(self, access_token: str, *, expires_at: float | None = None) -> None:
226
+ """Replace the access token for an externally managed session."""
227
+ if not self._externally_managed:
228
+ raise ConfigurationError("set_access_token requires externally_managed=True")
229
+ if not isinstance(access_token, str) or not access_token.strip():
230
+ raise ValueError("access_token must be a non-empty string")
231
+ with self._auth_lock:
232
+ self._tokens = SessionTokens(access_token=access_token, expires_at=expires_at)
233
+
173
234
  def login(
174
235
  self,
175
236
  email: str,
@@ -226,53 +287,45 @@ class Sub2API:
226
287
  return user
227
288
 
228
289
  def refresh(self) -> SessionTokens:
229
- with self._refresh_lock:
230
- refresh_token = self._tokens.refresh_token
231
- if not refresh_token:
232
- raise AuthenticationError(
233
- "No refresh token is available",
234
- status_code=401,
235
- code="NO_REFRESH_TOKEN",
236
- )
237
- try:
238
- data = self._request(
239
- "POST",
240
- "auth/refresh",
241
- json={"refresh_token": refresh_token},
242
- authenticated=False,
243
- allow_refresh=False,
244
- )
245
- auth = self._auth_mapping(data, "token refresh")
246
- access_token = auth.get("access_token")
247
- rotated_token = auth.get("refresh_token")
248
- if not isinstance(access_token, str) or not access_token:
249
- raise ProtocolError("token refresh did not return an access token")
250
- if not isinstance(rotated_token, str) or not rotated_token:
251
- raise ProtocolError("token refresh did not return a refresh token")
252
- self._tokens = self._tokens_from_auth(auth)
253
- return self._tokens
254
- except APIError as error:
255
- if 400 <= error.status_code < 500:
256
- self.clear_auth()
257
- raise
290
+ """Renew the session or adopt a pair another worker has already saved."""
291
+ if self._externally_managed:
292
+ raise ConfigurationError("session renewal is externally managed")
293
+ tokens = self._renew(self._tokens)
294
+ if tokens is None:
295
+ raise AuthenticationError(
296
+ "No refresh token is available", status_code=401, code="NO_REFRESH_TOKEN"
297
+ )
298
+ return tokens
299
+
300
+ def save_tokens(self) -> SessionTokens:
301
+ """Retry a pending rotation save and return the latest session snapshot."""
302
+ with self._refresh_lock, self._auth_lock:
303
+ self._save_rotation()
304
+ return self._tokens
258
305
 
259
306
  def logout(self) -> None:
260
- refresh_token = self._tokens.refresh_token
261
- try:
262
- if refresh_token:
263
- self._request(
264
- "POST",
265
- "auth/logout",
266
- json={"refresh_token": refresh_token},
267
- authenticated=False,
268
- allow_refresh=False,
269
- )
270
- finally:
271
- self.clear_auth()
307
+ with self._refresh_lock:
308
+ with self._auth_lock:
309
+ if self._tokens.access_token or self._tokens.refresh_token:
310
+ self._reload_tokens()
311
+ tokens = self._tokens
312
+ try:
313
+ if tokens.refresh_token:
314
+ self._request(
315
+ "POST",
316
+ "auth/logout",
317
+ json={"refresh_token": tokens.refresh_token},
318
+ authenticated=False,
319
+ allow_refresh=False,
320
+ )
321
+ finally:
322
+ with self._auth_lock:
323
+ if self._tokens is tokens:
324
+ self._clear_tokens()
272
325
 
273
326
  def clear_auth(self) -> None:
274
- self._tokens = SessionTokens()
275
- self._pending_2fa_token = None
327
+ with self._auth_lock:
328
+ self._clear_tokens()
276
329
 
277
330
  def me(self) -> User:
278
331
  return self.account.profile()
@@ -354,32 +407,41 @@ class Sub2API:
354
407
  allow_refresh: bool,
355
408
  ) -> Any:
356
409
  normalized_method = method.upper()
357
- if authenticated and allow_refresh:
358
- self._refresh_if_expiring()
359
- failed_token = self._tokens.access_token
410
+ can_refresh = authenticated and allow_refresh and not self._externally_managed
411
+ tokens = self._tokens if authenticated else None
412
+ if can_refresh and tokens is not None:
413
+ if tokens.needs_refresh() or self._pending_save is not None:
414
+ self._renew(tokens, only_if_expiring=True)
415
+ tokens = self._tokens
360
416
  response = self._send(
361
417
  normalized_method,
362
418
  path,
363
419
  params=params,
364
420
  json=json,
365
421
  headers=headers,
366
- authenticated=authenticated,
422
+ tokens=tokens,
423
+ )
424
+ try:
425
+ return self._decode(response)
426
+ except AuthenticationError as error:
427
+ if (
428
+ not can_refresh
429
+ or tokens is None
430
+ or error.status_code != 401
431
+ or isinstance(error, (SessionRevokedError, SessionBindingError))
432
+ ):
433
+ raise
434
+ replacement = self._renew(tokens)
435
+ if replacement is None:
436
+ raise
437
+ response = self._send(
438
+ normalized_method,
439
+ path,
440
+ params=params,
441
+ json=json,
442
+ headers=headers,
443
+ tokens=replacement,
367
444
  )
368
- if (
369
- response.status_code == 401
370
- and authenticated
371
- and allow_refresh
372
- and self._tokens.refresh_token
373
- ):
374
- self._refresh_after_unauthorized(failed_token)
375
- response = self._send(
376
- normalized_method,
377
- path,
378
- params=params,
379
- json=json,
380
- headers=headers,
381
- authenticated=authenticated,
382
- )
383
445
  return self._decode(response)
384
446
 
385
447
  def _send(
@@ -390,19 +452,17 @@ class Sub2API:
390
452
  params: Mapping[str, Any] | None,
391
453
  json: Any,
392
454
  headers: Mapping[str, str] | None,
393
- authenticated: bool,
455
+ tokens: SessionTokens | None,
394
456
  ) -> Any:
395
457
  relative_path = _request_path(path)
396
458
  request_headers = {
397
459
  "Accept": "application/json",
398
460
  "Accept-Language": self.language,
399
- "User-Agent": "sub2api-python/0.2.0",
461
+ "User-Agent": "sub2api-python/0.3.0",
400
462
  "X-User-UI-Request": "1",
401
463
  }
402
- if authenticated and self._tokens.access_token:
403
- request_headers["Authorization"] = (
404
- f"{self._tokens.token_type} {self._tokens.access_token}"
405
- )
464
+ if tokens is not None and tokens.access_token:
465
+ request_headers["Authorization"] = f"{tokens.token_type} {tokens.access_token}"
406
466
  if headers:
407
467
  request_headers.update(headers)
408
468
  try:
@@ -426,6 +486,8 @@ class Sub2API:
426
486
  try:
427
487
  payload = response.json()
428
488
  except ValueError as error:
489
+ if response.status_code in (401, 429) or response.status_code >= 500:
490
+ self._raise_api_error(response, {})
429
491
  if not _success(response):
430
492
  raise ProtocolError(
431
493
  f"Sub2API returned non-JSON HTTP {response.status_code}"
@@ -455,6 +517,11 @@ class Sub2API:
455
517
  if _success(response) and isinstance(code, int) and 400 <= code <= 599:
456
518
  status_code = code
457
519
  error_type = _ERROR_TYPES.get(status_code, APIError)
520
+ if 400 <= status_code < 500 and status_code != 429:
521
+ for identifier in (reason, code):
522
+ if isinstance(identifier, str) and identifier in _SESSION_ERROR_TYPES:
523
+ error_type = _SESSION_ERROR_TYPES[identifier]
524
+ break
458
525
  raise error_type(
459
526
  str(message),
460
527
  status_code=status_code,
@@ -464,16 +531,79 @@ class Sub2API:
464
531
  retry_after=_retry_after(response),
465
532
  )
466
533
 
467
- def _refresh_if_expiring(self) -> None:
468
- with self._refresh_lock:
469
- if self._tokens.needs_refresh():
470
- self.refresh()
471
-
472
- def _refresh_after_unauthorized(self, failed_token: str | None) -> None:
534
+ def _renew(
535
+ self, observed: SessionTokens, *, only_if_expiring: bool = False
536
+ ) -> SessionTokens | None:
473
537
  with self._refresh_lock:
474
- if self._tokens.access_token and self._tokens.access_token != failed_token:
475
- return
476
- self.refresh()
538
+ with self._auth_lock:
539
+ had_pending_save = self._pending_save is not None
540
+ if had_pending_save:
541
+ self._save_rotation()
542
+ else:
543
+ self._reload_tokens()
544
+ current = self._tokens
545
+ if current.authenticated and (current != observed or had_pending_save):
546
+ return current
547
+ if not current.refresh_token or (only_if_expiring and not current.needs_refresh()):
548
+ return None
549
+ try:
550
+ rotated = self._request_rotation(current.refresh_token)
551
+ except (APIError, TransportError) as error:
552
+ rejected = isinstance(error, APIError) and _refresh_rejected(error)
553
+ if rejected or isinstance(error, TransportError):
554
+ with self._auth_lock:
555
+ self._reload_tokens()
556
+ if self._tokens is not current and self._tokens.authenticated:
557
+ return self._tokens
558
+ if rejected and self._tokens is current:
559
+ self._clear_tokens()
560
+ raise
561
+ with self._auth_lock:
562
+ if self._tokens is current:
563
+ if self._token_store is not None:
564
+ self._pending_save = current
565
+ self._tokens = rotated
566
+ self._save_rotation()
567
+ return self._tokens if self._tokens.authenticated else None
568
+
569
+ def _request_rotation(self, refresh_token: str) -> SessionTokens:
570
+ data = self._request(
571
+ "POST",
572
+ "auth/refresh",
573
+ json={"refresh_token": refresh_token},
574
+ authenticated=False,
575
+ allow_refresh=False,
576
+ )
577
+ auth = self._auth_mapping(data, "token refresh")
578
+ access_token = auth.get("access_token")
579
+ rotated_token = auth.get("refresh_token")
580
+ if not isinstance(access_token, str) or not access_token.strip():
581
+ raise ProtocolError("token refresh did not return an access token")
582
+ if not isinstance(rotated_token, str) or not rotated_token.strip():
583
+ raise ProtocolError("token refresh did not return a refresh token")
584
+ return self._tokens_from_auth(auth)
585
+
586
+ def _reload_tokens(self) -> None:
587
+ if self._token_store is not None and self._pending_save is None:
588
+ stored = self._token_store.load() or SessionTokens()
589
+ if stored != self._tokens:
590
+ self._tokens = stored
591
+
592
+ def _save_rotation(self) -> None:
593
+ store, previous = self._token_store, self._pending_save
594
+ if store is not None and previous is not None:
595
+ if not store.compare_and_set(previous, self._tokens):
596
+ self._tokens = store.load() or SessionTokens()
597
+ self._pending_save = None
598
+
599
+ def _clear_tokens(self) -> None:
600
+ store, current, previous = self._token_store, self._tokens, self._pending_save
601
+ empty = SessionTokens()
602
+ self._tokens = empty
603
+ self._pending_save = None
604
+ self._pending_2fa_token = None
605
+ if store is not None and not store.compare_and_set(current, empty) and previous is not None:
606
+ store.compare_and_set(previous, empty)
477
607
 
478
608
  def _auth_mapping(self, data: Any, operation: str) -> Mapping[str, Any]:
479
609
  if not isinstance(data, Mapping):
@@ -487,19 +617,31 @@ class Sub2API:
487
617
  user_data = auth.get("user")
488
618
  if not isinstance(user_data, Mapping):
489
619
  raise ProtocolError("login did not return a user profile")
490
- self._tokens = self._tokens_from_auth(auth)
620
+ tokens = self._tokens_from_auth(auth)
621
+ with self._auth_lock:
622
+ if self._token_store is not None:
623
+ self._token_store.save(tokens)
624
+ self._tokens = tokens
625
+ self._pending_save = None
491
626
  return User(user_data)
492
627
 
493
628
  def _tokens_from_auth(self, auth: Mapping[str, Any]) -> SessionTokens:
494
629
  expires_in = auth.get("expires_in")
495
630
  expires_at = None
496
- if isinstance(expires_in, (int, float)) and not isinstance(expires_in, bool):
631
+ if (
632
+ isinstance(expires_in, (int, float))
633
+ and not isinstance(expires_in, bool)
634
+ and math.isfinite(expires_in)
635
+ ):
497
636
  expires_at = time.time() + max(0.0, float(expires_in))
498
637
  token_type = auth.get("token_type")
638
+ refresh_token = auth.get("refresh_token")
499
639
  return SessionTokens(
500
640
  access_token=str(auth["access_token"]),
501
641
  refresh_token=(
502
- str(auth["refresh_token"]) if auth.get("refresh_token") not in (None, "") else None
642
+ str(refresh_token)
643
+ if not self._externally_managed and refresh_token not in (None, "")
644
+ else None
503
645
  ),
504
646
  expires_at=expires_at,
505
647
  token_type=str(token_type) if token_type else "Bearer",
@@ -50,6 +50,18 @@ class AuthenticationError(APIError):
50
50
  """Raised when login or session authentication fails."""
51
51
 
52
52
 
53
+ class SessionExpiredError(AuthenticationError):
54
+ """Raised when the instance reports that a session token expired."""
55
+
56
+
57
+ class SessionRevokedError(AuthenticationError):
58
+ """Raised when the instance reports that a session was revoked."""
59
+
60
+
61
+ class SessionBindingError(AuthenticationError):
62
+ """Raised when the request no longer matches the session binding."""
63
+
64
+
53
65
  class PermissionDeniedError(APIError):
54
66
  """Raised when the user cannot perform an operation."""
55
67
 
@@ -199,7 +199,7 @@ class Balance:
199
199
 
200
200
  @dataclass(frozen=True)
201
201
  class SessionTokens:
202
- """The current in-memory dashboard session tokens."""
202
+ """A snapshot of the dashboard session tokens and their expiry."""
203
203
 
204
204
  access_token: str | None = field(default=None, repr=False)
205
205
  refresh_token: str | None = field(default=None, repr=False)
@@ -218,7 +218,7 @@ class SessionTokens:
218
218
 
219
219
  def needs_refresh(self, leeway: float = 30.0) -> bool:
220
220
  return (
221
- self.refresh_token is not None
221
+ bool(self.refresh_token)
222
222
  and self.expires_at is not None
223
223
  and self.expires_at <= time.time() + leeway
224
224
  )