orangecheck 2.5.2__tar.gz → 2.7.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.
Files changed (70) hide show
  1. {orangecheck-2.5.2 → orangecheck-2.7.0}/CHANGELOG.md +27 -0
  2. {orangecheck-2.5.2 → orangecheck-2.7.0}/PKG-INFO +18 -1
  3. {orangecheck-2.5.2 → orangecheck-2.7.0}/README.md +17 -0
  4. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/__init__.py +7 -1
  5. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/integrator.py +138 -6
  6. {orangecheck-2.5.2 → orangecheck-2.7.0}/pyproject.toml +1 -1
  7. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/test_integrator_vectors.py +100 -1
  8. {orangecheck-2.5.2 → orangecheck-2.7.0}/.gitignore +0 -0
  9. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/__main__.py +0 -0
  10. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/address.py +0 -0
  11. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/bond.py +0 -0
  12. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/canonical.py +0 -0
  13. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/client.py +0 -0
  14. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/errors.py +0 -0
  15. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/pledge/__init__.py +0 -0
  16. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/pledge/bond.py +0 -0
  17. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/pledge/canonical.py +0 -0
  18. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/pledge/delegation.py +0 -0
  19. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/pledge/envelopes.py +0 -0
  20. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/pledge/resolution.py +0 -0
  21. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/pledge/state.py +0 -0
  22. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/py.typed +0 -0
  23. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/top_level.py +0 -0
  24. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/types.py +0 -0
  25. {orangecheck-2.5.2 → orangecheck-2.7.0}/orangecheck/verify_sig.py +0 -0
  26. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/fixtures/bip137-parity.json +0 -0
  27. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/fixtures/bip322-js-6.1.8.json +0 -0
  28. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/fixtures/bip322-official-basic.json +0 -0
  29. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/fixtures/bip322-official-generated.json +0 -0
  30. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/pledge/__init__.py +0 -0
  31. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/pledge/test_authority.py +0 -0
  32. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/pledge/test_delegation.py +0 -0
  33. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/pledge/test_vectors.py +0 -0
  34. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/pledge/test_wrap.py +0 -0
  35. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/test_address.py +0 -0
  36. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/test_bip322_official.py +0 -0
  37. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/test_client.py +0 -0
  38. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/test_client_failure_modes.py +0 -0
  39. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/test_conformance.py +0 -0
  40. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/test_ripemd160.py +0 -0
  41. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/test_signature_parity.py +0 -0
  42. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/index.json +0 -0
  43. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv01.json +0 -0
  44. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv02.json +0 -0
  45. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv03.json +0 -0
  46. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv04.json +0 -0
  47. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv05.json +0 -0
  48. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv06.json +0 -0
  49. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv07.json +0 -0
  50. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv08.json +0 -0
  51. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv09.json +0 -0
  52. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv10.json +0 -0
  53. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv11.json +0 -0
  54. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv12.json +0 -0
  55. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv13.json +0 -0
  56. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv14.json +0 -0
  57. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv15.json +0 -0
  58. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv16.json +0 -0
  59. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv17.json +0 -0
  60. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv18.json +0 -0
  61. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv19.json +0 -0
  62. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv20.json +0 -0
  63. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv21.json +0 -0
  64. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv22.json +0 -0
  65. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv23.json +0 -0
  66. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv24.json +0 -0
  67. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv25.json +0 -0
  68. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv26.json +0 -0
  69. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv27.json +0 -0
  70. {orangecheck-2.5.2 → orangecheck-2.7.0}/tests/vectors/tv28.json +0 -0
@@ -4,6 +4,33 @@ All notable changes to the **`orangecheck`** Python package. Follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [2.7.0] — 2026-10-22
8
+
9
+ ### Added — refuse a session the person ended everywhere
10
+
11
+ As `@orangecheck/auth-core`'s `integratorRevocationCheck`. `RevocationList(project_key,
12
+ signing_secret)` reads the account cutoffs (sign out everywhere, a passkey removed, an
13
+ account deleted) from me.ochk.io's `/api/integrator/revocations` at most once a minute,
14
+ signed with `X-OC-Signature` over the query. `verify_session(..., revocations=, method=)`
15
+ raises `SessionEnded` (an `InvalidSession`, reason `ended`) for a session it ends; while
16
+ no copy younger than ten minutes can be read, a read goes on and anything else is
17
+ refused (`revocations_unavailable`). `RevocationList.status(sub, iat)` answers for a
18
+ site whose own session replaced the token. `revocation_key(kind, value)` derives the
19
+ list's keys. Held to me-client's vectors (`revocation`).
20
+
21
+ ## [2.6.0] — 2026-10-22
22
+
23
+ ### Changed — key rotation and outages, as `@orangecheck/auth-core` 2.10.0
24
+
25
+ - `verify_session` reads `status: "retired"` and `retired_at` on a key in the
26
+ set. A retired key verifies only tokens whose `iat` is before its
27
+ `retired_at`; anything else is refused with reason `retired_key`. The
28
+ shared integrator vectors carry both cases, so the Node and Python SDKs
29
+ agree.
30
+ - A fetched key set stands in through a failed refresh for at most six hours.
31
+ Past that, `verify_session` and `verify_webhook` refuse with
32
+ `key_set_unavailable` until a fetch succeeds.
33
+
7
34
  ## [2.5.2] — 2026-10-22
8
35
 
9
36
  ### Fixed — an agent pledge's agent is never its swearer
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: orangecheck
3
- Version: 2.5.2
3
+ Version: 2.7.0
4
4
  Summary: Python SDK for OrangeCheck — proof of Bitcoin stake, the OC Pledge primitive, and ochk.app sign-in for your backend.
5
5
  Project-URL: Homepage, https://ochk.io
6
6
  Project-URL: Documentation, https://ochk.io/docs
@@ -223,6 +223,23 @@ httpx.post("https://me.ochk.io/api/integrator/event", content=body, headers={
223
223
  event = verify_webhook(request.headers, raw_body) # raises InvalidWebhook
224
224
  ```
225
225
 
226
+ A token verifies until it expires, up to 30 days. To refuse one the person
227
+ ended everywhere (signed out everywhere, removed a passkey, deleted the
228
+ account), keep one `RevocationList` per process and pass it with the request's
229
+ method. It reads those account cutoffs from me.ochk.io at most once a minute,
230
+ signed with your secret:
231
+
232
+ ```python
233
+ from orangecheck import RevocationList, SessionEnded
234
+
235
+ REVOCATIONS = RevocationList(PROJECT_KEY, SIGNING_SECRET)
236
+
237
+ session = verify_session(token, audience="https://your-site.example",
238
+ revocations=REVOCATIONS, method=request.method)
239
+ # SessionEnded (an InvalidSession) when the person ended it. While the list
240
+ # can't be read, reads go on and writes raise reason "revocations_unavailable".
241
+ ```
242
+
226
243
  The full guide is at [ochk.io/docs/sdk/python](https://ochk.io/docs/sdk/python).
227
244
 
228
245
  ---
@@ -186,6 +186,23 @@ httpx.post("https://me.ochk.io/api/integrator/event", content=body, headers={
186
186
  event = verify_webhook(request.headers, raw_body) # raises InvalidWebhook
187
187
  ```
188
188
 
189
+ A token verifies until it expires, up to 30 days. To refuse one the person
190
+ ended everywhere (signed out everywhere, removed a passkey, deleted the
191
+ account), keep one `RevocationList` per process and pass it with the request's
192
+ method. It reads those account cutoffs from me.ochk.io at most once a minute,
193
+ signed with your secret:
194
+
195
+ ```python
196
+ from orangecheck import RevocationList, SessionEnded
197
+
198
+ REVOCATIONS = RevocationList(PROJECT_KEY, SIGNING_SECRET)
199
+
200
+ session = verify_session(token, audience="https://your-site.example",
201
+ revocations=REVOCATIONS, method=request.method)
202
+ # SessionEnded (an InvalidSession) when the person ended it. While the list
203
+ # can't be read, reads go on and writes raise reason "revocations_unavailable".
204
+ ```
205
+
189
206
  The full guide is at [ochk.io/docs/sdk/python](https://ochk.io/docs/sdk/python).
190
207
 
191
208
  ---
@@ -65,7 +65,10 @@ from .errors import OrangeCheckError, RateLimitError, VerificationError
65
65
  from .integrator import (
66
66
  InvalidSession,
67
67
  InvalidWebhook,
68
+ RevocationList,
68
69
  Session,
70
+ SessionEnded,
71
+ revocation_key,
69
72
  sign_event,
70
73
  verify_session,
71
74
  verify_webhook,
@@ -125,6 +128,9 @@ __all__ = [
125
128
  "Session",
126
129
  "InvalidSession",
127
130
  "InvalidWebhook",
131
+ "RevocationList",
132
+ "SessionEnded",
133
+ "revocation_key",
128
134
  # Types
129
135
  "CheckResult",
130
136
  "VerifyOutcome",
@@ -139,7 +145,7 @@ __all__ = [
139
145
  "VerificationError",
140
146
  ]
141
147
 
142
- __version__ = "2.5.2"
148
+ __version__ = "2.7.0"
143
149
 
144
150
  # OC Pledge submodule — sibling primitive for forward-looking commitments
145
151
  # bound to a Bitcoin address. Imported here so consumers can write:
@@ -9,6 +9,10 @@ Three jobs, the same wire formats as ``@orangecheck/me-client``:
9
9
  header = sign_event(signing_secret, body) # X-OC-Signature
10
10
  event = verify_webhook(request.headers, raw_body)
11
11
 
12
+ # Refuse a session the person ended everywhere (one list per process):
13
+ revocations = RevocationList(project_key, signing_secret)
14
+ session = verify_session(token, audience, revocations=revocations, method=request.method)
15
+
12
16
  Both SDKs are held to one set of vectors
13
17
  (``me-client/test-vectors/integrator.json``), so they accept and refuse the
14
18
  same tokens, signatures and deliveries.
@@ -26,6 +30,7 @@ import time
26
30
  from collections.abc import Mapping
27
31
  from dataclasses import dataclass, field
28
32
  from typing import Any, Optional, Union
33
+ from urllib.parse import quote
29
34
 
30
35
  import httpx
31
36
  from cryptography.exceptions import InvalidSignature
@@ -40,6 +45,8 @@ SESSION_JWKS_URL = "https://ochk.io/.well-known/jwks.json"
40
45
  WEBHOOK_JWKS_URL = "https://me.ochk.io/api/dev-jwks"
41
46
 
42
47
  _JWKS_TTL_SECONDS = 3600
48
+ #: How old a key set may be and still stand in for one that can't be fetched.
49
+ _JWKS_MAX_STALE_SECONDS = 6 * 3600
43
50
  _FORCED_REFRESH_MIN_SECONDS = 60
44
51
 
45
52
 
@@ -51,6 +58,13 @@ class InvalidSession(OrangeCheckError):
51
58
  self.reason = reason
52
59
 
53
60
 
61
+ class SessionEnded(InvalidSession):
62
+ """The person ended this session everywhere: signed out everywhere, removed a passkey or deleted the account."""
63
+
64
+ def __init__(self) -> None:
65
+ super().__init__("ended", "session token refused: the person ended it")
66
+
67
+
54
68
  class InvalidWebhook(OrangeCheckError):
55
69
  """The webhook delivery did not verify. ``reason`` says why, in one word."""
56
70
 
@@ -78,11 +92,12 @@ class Session:
78
92
 
79
93
 
80
94
  class _KeySet:
81
- """A fetched JWKS, cached for an hour and kept through a failed refresh."""
95
+ """A fetched JWKS, cached for an hour and kept through a failed refresh for six."""
82
96
 
83
97
  def __init__(self, url: str):
84
98
  self.url = url
85
99
  self._keys: dict[str, Ed25519PublicKey] = {}
100
+ self._retired: dict[str, float] = {}
86
101
  self._fetched_at = 0.0
87
102
  self._forced_at = 0.0
88
103
  self._lock = threading.Lock()
@@ -91,13 +106,18 @@ class _KeySet:
91
106
  try:
92
107
  r = httpx.get(self.url, headers={"Accept": "application/json"}, timeout=10.0)
93
108
  r.raise_for_status()
94
- self._keys = _import_jwks(r.json())
109
+ doc = r.json()
110
+ self._keys = _import_jwks(doc)
111
+ self._retired = _retired_at(doc)
95
112
  self._fetched_at = time.time()
96
113
  except (httpx.HTTPError, ValueError):
97
- # Stale on error: a key set seen before keeps working through an outage.
98
- if not self._keys:
114
+ # Stale on error: a key set seen before keeps working through an outage, for a while.
115
+ if not self._keys or time.time() - self._fetched_at >= _JWKS_MAX_STALE_SECONDS:
99
116
  raise
100
117
 
118
+ def retired_at(self, kid: str) -> Optional[float]:
119
+ return self._retired.get(kid)
120
+
101
121
  def get(self, kid: str) -> Optional[Ed25519PublicKey]:
102
122
  with self._lock:
103
123
  if not self._keys or time.time() - self._fetched_at >= _JWKS_TTL_SECONDS:
@@ -119,6 +139,16 @@ def _b64url(s: str) -> bytes:
119
139
  return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
120
140
 
121
141
 
142
+ def _retired_at(doc: Any) -> dict[str, float]:
143
+ """kid → ``retired_at`` for keys published as retired; 0 when it can't be read."""
144
+ out: dict[str, float] = {}
145
+ for k in doc.get("keys", []) if isinstance(doc, dict) else []:
146
+ if isinstance(k, dict) and isinstance(k.get("kid"), str) and k.get("status") == "retired":
147
+ at = k.get("retired_at")
148
+ out[k["kid"]] = at if isinstance(at, (int, float)) and not isinstance(at, bool) else 0
149
+ return out
150
+
151
+
122
152
  def _import_jwks(doc: Any) -> dict[str, Ed25519PublicKey]:
123
153
  if not isinstance(doc, dict) or not isinstance(doc.get("keys"), list):
124
154
  raise ValueError("JWKS did not return {keys: [...]}")
@@ -135,6 +165,91 @@ def _import_jwks(doc: Any) -> dict[str, Ed25519PublicKey]:
135
165
  return keys
136
166
 
137
167
 
168
+ # ─── account cutoffs ─────────────────────────────────────────────────────
169
+
170
+ REVOCATIONS_URL = "https://me.ochk.io/api/integrator/revocations"
171
+ _REVOCATIONS_TTL_SECONDS = 60
172
+ _REVOCATIONS_MAX_STALE_SECONDS = 600
173
+ _REVOCATIONS_RETRY_SECONDS = 10
174
+ _SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
175
+
176
+
177
+ def revocation_key(kind: str, value: str) -> str:
178
+ """The list's key for a token (``"jti"``) or an account (``"sub"``), as auth-core derives it."""
179
+ digest = hashlib.sha256(f"ocrev1:{kind}:{value}".encode("utf-8")).digest()[:16]
180
+ return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=")
181
+
182
+
183
+ class RevocationList:
184
+ """
185
+ The account cutoffs (sign out everywhere, a passkey removed, an account
186
+ deleted) from me.ochk.io, fetched at most once a minute with a request
187
+ signed by your project secret, as ``@orangecheck/auth-core``'s
188
+ ``integratorRevocationCheck`` does. Make one per process and pass it to
189
+ :func:`verify_session`.
190
+
191
+ ``status`` is ``"revoked"``, ``"live"``, or ``"unverified"`` when no copy
192
+ younger than ten minutes could be read: then reads may go on, but a write
193
+ should not.
194
+ """
195
+
196
+ def __init__(self, project_key: str, signing_secret: str, *, url: str = REVOCATIONS_URL):
197
+ query = "project_key=" + quote(project_key, safe="-_.!~*'()")
198
+ self._url = f"{url}?{query}"
199
+ self._query = query
200
+ self._secret = signing_secret
201
+ self._tokens: set[str] = set()
202
+ self._accounts: dict[str, float] = {}
203
+ self._fetched_at: Optional[float] = None
204
+ self._failed_at = float("-inf")
205
+ self._lock = threading.Lock()
206
+
207
+ def _fetch(self) -> None:
208
+ try:
209
+ r = httpx.get(
210
+ self._url,
211
+ headers={
212
+ "Accept": "application/json",
213
+ "X-OC-Signature": sign_event(self._secret, self._query),
214
+ },
215
+ timeout=3.0,
216
+ )
217
+ r.raise_for_status()
218
+ doc = r.json()
219
+ if (
220
+ not isinstance(doc, dict)
221
+ or doc.get("v") != 1
222
+ or not isinstance(doc.get("tokens"), list)
223
+ or not isinstance(doc.get("accounts"), dict)
224
+ ):
225
+ raise ValueError("revocations: unexpected body")
226
+ self._tokens = {t for t in doc["tokens"] if isinstance(t, str)}
227
+ self._accounts = {
228
+ k: float(v)
229
+ for k, v in doc["accounts"].items()
230
+ if isinstance(v, (int, float)) and not isinstance(v, bool)
231
+ }
232
+ self._fetched_at = time.time()
233
+ except (httpx.HTTPError, ValueError):
234
+ # Keep the last copy; try again after a short wait.
235
+ self._failed_at = time.time()
236
+
237
+ def status(self, sub: str, iat: Optional[float], jti: Optional[str] = None) -> str:
238
+ with self._lock:
239
+ now = time.time()
240
+ fresh = self._fetched_at is not None and now - self._fetched_at < _REVOCATIONS_TTL_SECONDS
241
+ if not fresh and now - self._failed_at >= _REVOCATIONS_RETRY_SECONDS:
242
+ self._fetch()
243
+ if self._fetched_at is None:
244
+ return "unverified"
245
+ if jti is not None and revocation_key("jti", jti) in self._tokens:
246
+ return "revoked"
247
+ cutoff = self._accounts.get(revocation_key("sub", sub))
248
+ if cutoff is not None and not (iat is not None and iat >= cutoff):
249
+ return "revoked"
250
+ return "unverified" if now - self._fetched_at > _REVOCATIONS_MAX_STALE_SECONDS else "live"
251
+
252
+
138
253
  # ─── sign-in tokens ──────────────────────────────────────────────────────
139
254
 
140
255
 
@@ -145,6 +260,8 @@ def verify_session(
145
260
  jwks: Optional[Mapping[str, Any]] = None,
146
261
  issuer: str = SESSION_ISSUER,
147
262
  leeway: int = 0,
263
+ revocations: Optional[RevocationList] = None,
264
+ method: Optional[str] = None,
148
265
  ) -> Session:
149
266
  """
150
267
  Verify a token from the ochk.app sign-in popup and return who signed in.
@@ -157,8 +274,11 @@ def verify_session(
157
274
  ``jwks`` to verify offline.
158
275
 
159
276
  Raises :class:`InvalidSession` on any failure. The token proves who signed
160
- in until it expires (up to 30 days); it does not prove the person has not
161
- signed out since. Keep your own session, and see the docs on ending one.
277
+ in until it expires (up to 30 days). Pass ``revocations`` (a
278
+ :class:`RevocationList`) to refuse one the person ended everywhere with
279
+ :class:`SessionEnded`. Pass the request's ``method`` too: while the list
280
+ can't be read, a read goes on and anything else is refused with reason
281
+ ``revocations_unavailable``; with no method, a request counts as a write.
162
282
  """
163
283
  parts = token.split(".") if isinstance(token, str) else []
164
284
  if len(parts) != 3:
@@ -184,11 +304,13 @@ def verify_session(
184
304
  key = _import_jwks(dict(jwks)).get(kid)
185
305
  except ValueError as err:
186
306
  raise InvalidSession("unknown_key") from err
307
+ retired_at = _retired_at(dict(jwks)).get(kid)
187
308
  else:
188
309
  try:
189
310
  key = _session_keys.get(kid)
190
311
  except (httpx.HTTPError, ValueError) as err:
191
312
  raise InvalidSession("key_set_unavailable") from err
313
+ retired_at = _session_keys.retired_at(kid)
192
314
  if key is None:
193
315
  raise InvalidSession("unknown_key")
194
316
  try:
@@ -210,6 +332,9 @@ def verify_session(
210
332
  iat = payload.get("iat")
211
333
  if iat is not None and not isinstance(iat, (int, float)):
212
334
  raise InvalidSession("claims")
335
+ # A retired key vouches only for what it signed before it retired.
336
+ if retired_at is not None and not (iat is not None and iat < retired_at):
337
+ raise InvalidSession("retired_key")
213
338
  for claim in ("sub", "did_oc", "jti"):
214
339
  if not isinstance(payload.get(claim), str) or not payload[claim]:
215
340
  raise InvalidSession("claims")
@@ -220,6 +345,13 @@ def verify_session(
220
345
  if not any(isinstance(a, str) and a in want for a in have):
221
346
  raise InvalidSession("audience")
222
347
 
348
+ if revocations is not None:
349
+ state = revocations.status(payload["sub"], iat, payload["jti"])
350
+ if state == "revoked":
351
+ raise SessionEnded()
352
+ if state == "unverified" and (method or "").upper() not in _SAFE_METHODS:
353
+ raise InvalidSession("revocations_unavailable")
354
+
223
355
  bond = payload.get("oc_bond")
224
356
  return Session(
225
357
  sub=payload["sub"],
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "orangecheck"
7
- version = "2.5.2"
7
+ version = "2.7.0"
8
8
  description = "Python SDK for OrangeCheck — proof of Bitcoin stake, the OC Pledge primitive, and ochk.app sign-in for your backend."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -22,6 +22,9 @@ import orangecheck.integrator as integrator
22
22
  from orangecheck import (
23
23
  InvalidSession,
24
24
  InvalidWebhook,
25
+ RevocationList,
26
+ SessionEnded,
27
+ revocation_key,
25
28
  sign_event,
26
29
  verify_session,
27
30
  verify_webhook,
@@ -80,11 +83,39 @@ def test_session_keeps_a_key_set_through_an_outage(fresh_key_sets: None) -> None
80
83
  v = V["session"]["valid"][0]
81
84
  verify_session(v["token"], v["audience"])
82
85
  # The hour is up, the refetch fails, and the keys already held still verify.
83
- integrator._session_keys._fetched_at = 0.0
86
+ integrator._session_keys._fetched_at = V["now"] - 3600
84
87
  assert verify_session(v["token"], v["audience"]).did_oc == v["claims"]["did_oc"]
85
88
  assert route.call_count == 2
86
89
 
87
90
 
91
+ @respx.mock
92
+ def test_session_stops_leaning_on_a_key_set_six_hours_old(fresh_key_sets: None) -> None:
93
+ respx.get("https://ochk.io/.well-known/jwks.json").mock(
94
+ side_effect=[httpx.Response(200, json=V["session"]["jwks"])] + [httpx.Response(503)] * 3
95
+ )
96
+ v = V["session"]["valid"][0]
97
+ verify_session(v["token"], v["audience"])
98
+ integrator._session_keys._fetched_at = V["now"] - 5 * 3600
99
+ assert verify_session(v["token"], v["audience"]).did_oc == v["claims"]["did_oc"]
100
+ integrator._session_keys._fetched_at = V["now"] - 6 * 3600 - 1
101
+ with pytest.raises(InvalidSession) as err:
102
+ verify_session(v["token"], v["audience"])
103
+ assert err.value.reason == "key_set_unavailable"
104
+
105
+
106
+ @respx.mock
107
+ def test_webhook_stops_leaning_on_a_key_set_six_hours_old(fresh_key_sets: None) -> None:
108
+ respx.get("https://me.ochk.io/api/dev-jwks").mock(
109
+ side_effect=[httpx.Response(200, json=V["webhook"]["jwks"])] + [httpx.Response(503)] * 3
110
+ )
111
+ v = V["webhook"]["valid"][0]
112
+ verify_webhook(v["headers"], v["body"])
113
+ integrator._webhook_keys._fetched_at = V["now"] - 6 * 3600 - 1
114
+ with pytest.raises(InvalidWebhook) as err:
115
+ verify_webhook(v["headers"], v["body"])
116
+ assert err.value.reason == "key_set_unavailable"
117
+
118
+
88
119
  @respx.mock
89
120
  def test_session_without_any_key_set_is_refused(fresh_key_sets: None) -> None:
90
121
  respx.get("https://ochk.io/.well-known/jwks.json").mock(return_value=httpx.Response(503))
@@ -147,3 +178,71 @@ def test_webhook_fetches_me_ochk_io_dev_jwks(fresh_key_sets: None) -> None:
147
178
  v = V["webhook"]["valid"][0]
148
179
  assert verify_webhook(v["headers"], v["body"])["id"] == "oc-me-tv-1"
149
180
  assert route.call_count == 1
181
+
182
+
183
+ # ─── account cutoffs ─────────────────────────────────────────────────────
184
+
185
+ R = V["revocation"]
186
+
187
+
188
+ def _revocations() -> RevocationList:
189
+ return RevocationList(R["request"]["project_key"], R["request"]["secret"])
190
+
191
+
192
+ @respx.mock
193
+ def test_revocations_request_is_signed_as_the_node_sdk_signs_it() -> None:
194
+ route = respx.get(R["request"]["url"]).mock(return_value=httpx.Response(200, json=R["feed"]))
195
+ _revocations().status("someone", 0)
196
+ assert route.call_count == 1
197
+ sent = route.calls[0].request
198
+ assert str(sent.url) == R["request"]["url"]
199
+ assert sent.headers["x-oc-signature"] == R["request"]["header"]
200
+
201
+
202
+ @pytest.mark.parametrize("v", R["keys"], ids=lambda v: v["sub"])
203
+ def test_revocation_key_matches_the_node_sdk(v: dict[str, Any]) -> None:
204
+ assert revocation_key("sub", v["sub"]) == v["key"]
205
+
206
+
207
+ @respx.mock
208
+ @pytest.mark.parametrize("v", R["sessions"], ids=lambda v: v["name"])
209
+ def test_revocations_decide_as_the_node_sdk_does(v: dict[str, Any]) -> None:
210
+ respx.get(R["request"]["url"]).mock(return_value=httpx.Response(200, json=R["feed"]))
211
+ assert _revocations().status(v["sub"], v["iat"]) == v["status"]
212
+
213
+
214
+ @respx.mock
215
+ def test_revocations_are_fetched_at_most_once_a_minute(monkeypatch: pytest.MonkeyPatch) -> None:
216
+ route = respx.get(R["request"]["url"]).mock(return_value=httpx.Response(200, json=R["feed"]))
217
+ rl = _revocations()
218
+ rl.status("someone", 0)
219
+ rl.status("someone", 0)
220
+ assert route.call_count == 1
221
+ monkeypatch.setattr(integrator.time, "time", lambda: float(V["now"] + 61))
222
+ rl.status("someone", 0)
223
+ assert route.call_count == 2
224
+
225
+
226
+ @respx.mock
227
+ def test_verify_session_refuses_a_session_its_account_cutoff_ends() -> None:
228
+ v = V["session"]["valid"][0]
229
+ s = verify_session(v["token"], v["audience"], jwks=V["session"]["jwks"])
230
+ assert s.iat is not None
231
+ feed = {"v": 1, "at": V["now"], "tokens": [], "accounts": {revocation_key("sub", s.sub): s.iat + 1}}
232
+ respx.get(R["request"]["url"]).mock(return_value=httpx.Response(200, json=feed))
233
+ with pytest.raises(SessionEnded) as err:
234
+ verify_session(v["token"], v["audience"], jwks=V["session"]["jwks"], revocations=_revocations())
235
+ assert isinstance(err.value, InvalidSession)
236
+ assert err.value.reason == "ended"
237
+
238
+
239
+ @respx.mock
240
+ def test_verify_session_keeps_reads_and_refuses_writes_while_cutoffs_cannot_be_read() -> None:
241
+ respx.get(R["request"]["url"]).mock(return_value=httpx.Response(503))
242
+ v = V["session"]["valid"][0]
243
+ rl = _revocations()
244
+ s = verify_session(v["token"], v["audience"], jwks=V["session"]["jwks"], revocations=rl, method="GET")
245
+ assert s.sub == v["claims"]["sub"]
246
+ with pytest.raises(InvalidSession) as err:
247
+ verify_session(v["token"], v["audience"], jwks=V["session"]["jwks"], revocations=rl, method="POST")
248
+ assert err.value.reason == "revocations_unavailable"
File without changes