orangecheck 2.7.0__tar.gz → 2.9.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.7.0 → orangecheck-2.9.0}/CHANGELOG.md +37 -0
  2. {orangecheck-2.7.0 → orangecheck-2.9.0}/PKG-INFO +11 -3
  3. {orangecheck-2.7.0 → orangecheck-2.9.0}/README.md +10 -2
  4. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/__init__.py +9 -1
  5. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/integrator.py +211 -41
  6. {orangecheck-2.7.0 → orangecheck-2.9.0}/pyproject.toml +1 -1
  7. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/test_integrator_vectors.py +155 -23
  8. {orangecheck-2.7.0 → orangecheck-2.9.0}/.gitignore +0 -0
  9. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/__main__.py +0 -0
  10. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/address.py +0 -0
  11. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/bond.py +0 -0
  12. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/canonical.py +0 -0
  13. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/client.py +0 -0
  14. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/errors.py +0 -0
  15. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/pledge/__init__.py +0 -0
  16. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/pledge/bond.py +0 -0
  17. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/pledge/canonical.py +0 -0
  18. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/pledge/delegation.py +0 -0
  19. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/pledge/envelopes.py +0 -0
  20. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/pledge/resolution.py +0 -0
  21. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/pledge/state.py +0 -0
  22. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/py.typed +0 -0
  23. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/top_level.py +0 -0
  24. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/types.py +0 -0
  25. {orangecheck-2.7.0 → orangecheck-2.9.0}/orangecheck/verify_sig.py +0 -0
  26. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/fixtures/bip137-parity.json +0 -0
  27. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/fixtures/bip322-js-6.1.8.json +0 -0
  28. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/fixtures/bip322-official-basic.json +0 -0
  29. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/fixtures/bip322-official-generated.json +0 -0
  30. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/pledge/__init__.py +0 -0
  31. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/pledge/test_authority.py +0 -0
  32. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/pledge/test_delegation.py +0 -0
  33. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/pledge/test_vectors.py +0 -0
  34. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/pledge/test_wrap.py +0 -0
  35. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/test_address.py +0 -0
  36. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/test_bip322_official.py +0 -0
  37. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/test_client.py +0 -0
  38. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/test_client_failure_modes.py +0 -0
  39. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/test_conformance.py +0 -0
  40. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/test_ripemd160.py +0 -0
  41. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/test_signature_parity.py +0 -0
  42. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/index.json +0 -0
  43. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv01.json +0 -0
  44. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv02.json +0 -0
  45. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv03.json +0 -0
  46. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv04.json +0 -0
  47. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv05.json +0 -0
  48. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv06.json +0 -0
  49. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv07.json +0 -0
  50. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv08.json +0 -0
  51. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv09.json +0 -0
  52. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv10.json +0 -0
  53. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv11.json +0 -0
  54. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv12.json +0 -0
  55. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv13.json +0 -0
  56. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv14.json +0 -0
  57. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv15.json +0 -0
  58. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv16.json +0 -0
  59. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv17.json +0 -0
  60. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv18.json +0 -0
  61. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv19.json +0 -0
  62. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv20.json +0 -0
  63. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv21.json +0 -0
  64. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv22.json +0 -0
  65. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv23.json +0 -0
  66. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv24.json +0 -0
  67. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv25.json +0 -0
  68. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv26.json +0 -0
  69. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv27.json +0 -0
  70. {orangecheck-2.7.0 → orangecheck-2.9.0}/tests/vectors/tv28.json +0 -0
@@ -4,6 +4,43 @@ 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.9.0] — 2026-10-22
8
+
9
+ ### Added — who may sign in, at parity with me-client
10
+
11
+ - `SignInPolicy(project_key)`: your project's "who can sign in" requirement, set on
12
+ ochk.app, read from me.ochk.io's `/api/integrator/<key>/sign-in` and held a minute,
13
+ as `withOcAuth({ projectKey })` reads it. While it can't be read the last one read
14
+ stands; with none read yet, sign-in is refused (`bond_policy_unavailable`). A key
15
+ that names no project is refused (`unknown_project_key`).
16
+ - `verify_session(..., policy=, require_bond=)`: raises `BondRequired` (an
17
+ `InvalidSession`, reason `bond_required`, with `need`, `have` and `back_url`) when
18
+ the account's coin backing doesn't meet it. `require_bond` in code wins over the
19
+ project's.
20
+ - `bond_meets(claims, min_sats=, min_days=, max_age_secs=)` and `read_bond_claim`,
21
+ as auth-core's `bondMeets` / `readBondClaim`, held to shared vectors (`bond`).
22
+
23
+ ## [2.8.0] — 2026-10-22
24
+
25
+ ### Changed — revocation by per-audience handle
26
+
27
+ As `@orangecheck/auth-core` 2.12.0. A sign-in token carries `rh`, its revocation
28
+ handle for its own audience; `RevocationList` looks it up in me.ochk.io's list of
29
+ ended handles for that audience, one list per audience, fetched at most once a
30
+ minute with a request signed over method, path and audience
31
+ (`<t>.GET /api/integrator/revocations?project_key=…&aud=…`). The handles name
32
+ nobody, and two sites' handles for one person never match.
33
+ - `RevocationList.status(rh, aud, iat)` replaces `status(sub, iat)`. A token
34
+ without `rh` is `"live"`: checked by its signature alone.
35
+ - A list's age is measured from its own `at`; one older than ten minutes, or dated
36
+ more than 60 s ahead, cannot vouch for a write.
37
+ - The first failed fetch logs one warning (`orangecheck` logger).
38
+
39
+ ### Deprecated
40
+
41
+ - 2.7.0. me.ochk.io answers its request with an empty list, which it reads as
42
+ "nothing ended". Use 2.8.0 or later.
43
+
7
44
  ## [2.7.0] — 2026-10-22
8
45
 
9
46
  ### Added — refuse a session the person ended everywhere
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: orangecheck
3
- Version: 2.7.0
3
+ Version: 2.9.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
@@ -207,12 +207,18 @@ speak the same wire formats as `@orangecheck/me-client`.
207
207
 
208
208
  ```python
209
209
  import json, httpx
210
- from orangecheck import verify_session, sign_event, verify_webhook, InvalidSession
210
+ from orangecheck import verify_session, sign_event, verify_webhook, InvalidSession, SignInPolicy
211
211
 
212
212
  # The origin of the page that opened the popup, exactly.
213
213
  session = verify_session(token, audience="https://your-site.example")
214
214
  session.did_oc # who signed in
215
215
 
216
+ # Who may sign in: your project's requirement, set on ochk.app (2.9.0 or later).
217
+ # BondRequired (an InvalidSession) carries need, have and back_url.
218
+ POLICY = SignInPolicy(PROJECT_KEY)
219
+ session = verify_session(token, audience="https://your-site.example", policy=POLICY)
220
+ # Or in code, which wins over the project's: require_bond={"min_sats": 100000, "min_days": 30}
221
+
216
222
  body = json.dumps({"project_key": PROJECT_KEY, "subtype": "account_created",
217
223
  "user_address": session.did_oc})
218
224
  httpx.post("https://me.ochk.io/api/integrator/event", content=body, headers={
@@ -225,7 +231,7 @@ event = verify_webhook(request.headers, raw_body) # raises InvalidWebhook
225
231
 
226
232
  A token verifies until it expires, up to 30 days. To refuse one the person
227
233
  ended everywhere (signed out everywhere, removed a passkey, deleted the
228
- account), keep one `RevocationList` per process and pass it with the request's
234
+ account), keep one `RevocationList` (2.8.0 or later) per process and pass it with the request's
229
235
  method. It reads those account cutoffs from me.ochk.io at most once a minute,
230
236
  signed with your secret:
231
237
 
@@ -238,6 +244,8 @@ session = verify_session(token, audience="https://your-site.example",
238
244
  revocations=REVOCATIONS, method=request.method)
239
245
  # SessionEnded (an InvalidSession) when the person ended it. While the list
240
246
  # can't be read, reads go on and writes raise reason "revocations_unavailable".
247
+ # If your own session replaces the token, keep its rh, aud and iat with that
248
+ # session and ask REVOCATIONS.status(rh, aud, iat): "revoked" ends it.
241
249
  ```
242
250
 
243
251
  The full guide is at [ochk.io/docs/sdk/python](https://ochk.io/docs/sdk/python).
@@ -170,12 +170,18 @@ speak the same wire formats as `@orangecheck/me-client`.
170
170
 
171
171
  ```python
172
172
  import json, httpx
173
- from orangecheck import verify_session, sign_event, verify_webhook, InvalidSession
173
+ from orangecheck import verify_session, sign_event, verify_webhook, InvalidSession, SignInPolicy
174
174
 
175
175
  # The origin of the page that opened the popup, exactly.
176
176
  session = verify_session(token, audience="https://your-site.example")
177
177
  session.did_oc # who signed in
178
178
 
179
+ # Who may sign in: your project's requirement, set on ochk.app (2.9.0 or later).
180
+ # BondRequired (an InvalidSession) carries need, have and back_url.
181
+ POLICY = SignInPolicy(PROJECT_KEY)
182
+ session = verify_session(token, audience="https://your-site.example", policy=POLICY)
183
+ # Or in code, which wins over the project's: require_bond={"min_sats": 100000, "min_days": 30}
184
+
179
185
  body = json.dumps({"project_key": PROJECT_KEY, "subtype": "account_created",
180
186
  "user_address": session.did_oc})
181
187
  httpx.post("https://me.ochk.io/api/integrator/event", content=body, headers={
@@ -188,7 +194,7 @@ event = verify_webhook(request.headers, raw_body) # raises InvalidWebhook
188
194
 
189
195
  A token verifies until it expires, up to 30 days. To refuse one the person
190
196
  ended everywhere (signed out everywhere, removed a passkey, deleted the
191
- account), keep one `RevocationList` per process and pass it with the request's
197
+ account), keep one `RevocationList` (2.8.0 or later) per process and pass it with the request's
192
198
  method. It reads those account cutoffs from me.ochk.io at most once a minute,
193
199
  signed with your secret:
194
200
 
@@ -201,6 +207,8 @@ session = verify_session(token, audience="https://your-site.example",
201
207
  revocations=REVOCATIONS, method=request.method)
202
208
  # SessionEnded (an InvalidSession) when the person ended it. While the list
203
209
  # can't be read, reads go on and writes raise reason "revocations_unavailable".
210
+ # If your own session replaces the token, keep its rh, aud and iat with that
211
+ # session and ask REVOCATIONS.status(rh, aud, iat): "revoked" ends it.
204
212
  ```
205
213
 
206
214
  The full guide is at [ochk.io/docs/sdk/python](https://ochk.io/docs/sdk/python).
@@ -63,11 +63,15 @@ from .bond import (
63
63
  from .client import AsyncClient, Client
64
64
  from .errors import OrangeCheckError, RateLimitError, VerificationError
65
65
  from .integrator import (
66
+ BondRequired,
66
67
  InvalidSession,
67
68
  InvalidWebhook,
68
69
  RevocationList,
69
70
  Session,
70
71
  SessionEnded,
72
+ SignInPolicy,
73
+ bond_meets,
74
+ read_bond_claim,
71
75
  revocation_key,
72
76
  sign_event,
73
77
  verify_session,
@@ -131,6 +135,10 @@ __all__ = [
131
135
  "RevocationList",
132
136
  "SessionEnded",
133
137
  "revocation_key",
138
+ "SignInPolicy",
139
+ "BondRequired",
140
+ "bond_meets",
141
+ "read_bond_claim",
134
142
  # Types
135
143
  "CheckResult",
136
144
  "VerifyOutcome",
@@ -145,7 +153,7 @@ __all__ = [
145
153
  "VerificationError",
146
154
  ]
147
155
 
148
- __version__ = "2.7.0"
156
+ __version__ = "2.9.0"
149
157
 
150
158
  # OC Pledge submodule — sibling primitive for forward-looking commitments
151
159
  # bound to a Bitcoin address. Imported here so consumers can write:
@@ -25,6 +25,8 @@ import binascii
25
25
  import hashlib
26
26
  import hmac
27
27
  import json
28
+ import logging
29
+ import re
28
30
  import threading
29
31
  import time
30
32
  from collections.abc import Mapping
@@ -165,41 +167,36 @@ def _import_jwks(doc: Any) -> dict[str, Ed25519PublicKey]:
165
167
  return keys
166
168
 
167
169
 
168
- # ─── account cutoffs ─────────────────────────────────────────────────────
170
+ # ─── revocation handles ──────────────────────────────────────────────────
169
171
 
170
172
  REVOCATIONS_URL = "https://me.ochk.io/api/integrator/revocations"
171
173
  _REVOCATIONS_TTL_SECONDS = 60
172
174
  _REVOCATIONS_MAX_STALE_SECONDS = 600
175
+ _REVOCATIONS_SKEW_SECONDS = 60
173
176
  _REVOCATIONS_RETRY_SECONDS = 10
174
177
  _SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
178
+ _log = logging.getLogger("orangecheck")
175
179
 
176
180
 
177
181
  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."""
182
+ """The revocation store's key for a token (``"jti"``) or an account (``"sub"``), as auth-core derives it."""
179
183
  digest = hashlib.sha256(f"ocrev1:{kind}:{value}".encode("utf-8")).digest()[:16]
180
184
  return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=")
181
185
 
182
186
 
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
- """
187
+ class _AudienceList:
188
+ """me.ochk.io's ended handles for one audience, fetched at most once a minute."""
195
189
 
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] = {}
190
+ def __init__(self, owner: "RevocationList", aud: str):
191
+ self._owner = owner
192
+ self._path = (
193
+ "/api/integrator/revocations?project_key="
194
+ + quote(owner._project_key, safe="-_.!~*'()")
195
+ + "&aud="
196
+ + quote(aud, safe="-_.!~*'()")
197
+ )
198
+ self._handles: dict[str, float] = {}
199
+ self._at: Optional[float] = None
203
200
  self._fetched_at: Optional[float] = None
204
201
  self._failed_at = float("-inf")
205
202
  self._lock = threading.Lock()
@@ -207,34 +204,31 @@ class RevocationList:
207
204
  def _fetch(self) -> None:
208
205
  try:
209
206
  r = httpx.get(
210
- self._url,
207
+ self._owner._base + self._path,
211
208
  headers={
212
209
  "Accept": "application/json",
213
- "X-OC-Signature": sign_event(self._secret, self._query),
210
+ "X-OC-Signature": sign_event(self._owner._secret, f"GET {self._path}"),
214
211
  },
215
212
  timeout=3.0,
216
213
  )
217
214
  r.raise_for_status()
218
215
  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
- ):
216
+ if not isinstance(doc, dict) or doc.get("v") != 1:
225
217
  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)
218
+ raw = doc.get("handles")
219
+ handles: dict[str, Any] = raw if isinstance(raw, dict) else {}
220
+ self._handles = {
221
+ k: float(v) for k, v in handles.items() if isinstance(v, (int, float)) and not isinstance(v, bool)
231
222
  }
223
+ at = doc.get("at")
224
+ self._at = float(at) if isinstance(at, (int, float)) and not isinstance(at, bool) else None
232
225
  self._fetched_at = time.time()
233
- except (httpx.HTTPError, ValueError):
226
+ except (httpx.HTTPError, ValueError) as err:
234
227
  # Keep the last copy; try again after a short wait.
235
228
  self._failed_at = time.time()
229
+ self._owner._warn_once(err)
236
230
 
237
- def status(self, sub: str, iat: Optional[float], jti: Optional[str] = None) -> str:
231
+ def status(self, rh: str, iat: Optional[float]) -> str:
238
232
  with self._lock:
239
233
  now = time.time()
240
234
  fresh = self._fetched_at is not None and now - self._fetched_at < _REVOCATIONS_TTL_SECONDS
@@ -242,12 +236,171 @@ class RevocationList:
242
236
  self._fetch()
243
237
  if self._fetched_at is None:
244
238
  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))
239
+ cutoff = self._handles.get(rh)
248
240
  if cutoff is not None and not (iat is not None and iat >= cutoff):
249
241
  return "revoked"
250
- return "unverified" if now - self._fetched_at > _REVOCATIONS_MAX_STALE_SECONDS else "live"
242
+ # The list's age is its own: an old copy served fresh is still old.
243
+ if self._at is None or self._at > now + _REVOCATIONS_SKEW_SECONDS:
244
+ return "unverified"
245
+ return "unverified" if now - self._at > _REVOCATIONS_MAX_STALE_SECONDS else "live"
246
+
247
+
248
+ class RevocationList:
249
+ """
250
+ Sessions the person ended everywhere (sign out everywhere, a passkey removed,
251
+ an account deleted), as ``@orangecheck/auth-core``'s ``integratorRevocationCheck``
252
+ sees them. A sign-in token carries ``rh``, its revocation handle for its own
253
+ audience; this looks it up in me.ochk.io's list of ended handles for that
254
+ audience, fetched at most once a minute per audience with a request signed by
255
+ your project secret over method, path and audience. Make one per process and
256
+ pass it to :func:`verify_session`.
257
+
258
+ ``status(rh, aud, iat)`` is ``"revoked"``, ``"live"``, or ``"unverified"`` when
259
+ no list younger than ten minutes (by its own ``at``) could be read: then reads
260
+ may go on, but a write should not. A token without ``rh`` is ``"live"``: it is
261
+ checked by its signature alone.
262
+ """
263
+
264
+ def __init__(self, project_key: str, signing_secret: str, *, url: str = REVOCATIONS_URL):
265
+ self._project_key = project_key
266
+ self._secret = signing_secret
267
+ self._base = url[: -len("/api/integrator/revocations")] if url.endswith("/api/integrator/revocations") else url
268
+ self._lists: dict[str, _AudienceList] = {}
269
+ self._lists_lock = threading.Lock()
270
+ self._warned = False
271
+
272
+ def _warn_once(self, err: Exception) -> None:
273
+ if self._warned:
274
+ return
275
+ self._warned = True
276
+ _log.warning("orangecheck: the revocation list could not be read (%s); reads go on, writes are refused until it can", err)
277
+
278
+ def status(self, rh: Optional[str], aud: Optional[str], iat: Optional[float]) -> str:
279
+ if not isinstance(rh, str) or not rh or not isinstance(aud, str) or not aud:
280
+ return "live"
281
+ with self._lists_lock:
282
+ lst = self._lists.get(aud)
283
+ if lst is None:
284
+ lst = self._lists[aud] = _AudienceList(self, aud)
285
+ return lst.status(rh, iat)
286
+
287
+
288
+ # ─── who may sign in (coin backing) ──────────────────────────────────────
289
+
290
+ #: Where someone turned away for want of backing can back their account.
291
+ BACK_ACCOUNT_URL = "https://ochk.app/me/account#backing"
292
+ _POLICY_TTL_SECONDS = 60
293
+ _POLICY_RETRY_SECONDS = 10
294
+ _NULLIFIER = re.compile(r"^[0-9a-f]{64}$")
295
+
296
+
297
+ class BondRequired(InvalidSession):
298
+ """The account is not backed enough to sign in here. ``need``, ``have`` and ``back_url`` say why and where to fix it."""
299
+
300
+ def __init__(self, need: dict[str, int], have: Optional[dict[str, int]]):
301
+ super().__init__("bond_required", "session token refused: the account is not backed enough to sign in here")
302
+ self.need = need
303
+ self.have = have
304
+ self.back_url = BACK_ACCOUNT_URL
305
+
306
+
307
+ def read_bond_claim(claims: Union[Session, Mapping[str, Any]]) -> Optional[dict[str, Any]]:
308
+ """The token's coin backing claim (``oc_bond``) when well-formed, else None. As auth-core's ``readBondClaim``."""
309
+ b = claims.oc_bond if isinstance(claims, Session) else claims.get("oc_bond")
310
+ if not isinstance(b, dict) or b.get("v") != 1:
311
+ return None
312
+ for k in ("sats_floor", "days_floor", "height", "checked_at"):
313
+ n = b.get(k)
314
+ if not isinstance(n, (int, float)) or isinstance(n, bool) or n < 0:
315
+ return None
316
+ if not isinstance(b.get("nullifier"), str) or not _NULLIFIER.match(b["nullifier"]):
317
+ return None
318
+ return b
319
+
320
+
321
+ def bond_meets(
322
+ claims: Union[Session, Mapping[str, Any]],
323
+ *,
324
+ min_sats: int = 0,
325
+ min_days: int = 0,
326
+ max_age_secs: Optional[int] = None,
327
+ ) -> bool:
328
+ """
329
+ True when a coin backs the account with floors reaching ``min_sats`` and
330
+ ``min_days``, checked by the issuer within ``max_age_secs`` (default: any
331
+ age). As auth-core's ``bondMeets``: compare against the floor ladder, so
332
+ ``min_sats=50000`` is met by a ``sats_floor`` of 100000, not 10000.
333
+ """
334
+ b = read_bond_claim(claims)
335
+ if b is None:
336
+ return False
337
+ if b["sats_floor"] < min_sats or b["days_floor"] < min_days:
338
+ return False
339
+ if max_age_secs is not None:
340
+ age = int(time.time()) - int(b["checked_at"])
341
+ if age < 0 or age > max_age_secs:
342
+ return False
343
+ return True
344
+
345
+
346
+ class SignInPolicy:
347
+ """
348
+ Your project's "who can sign in" requirement, set on ochk.app, read from
349
+ me.ochk.io (``/api/integrator/<key>/sign-in``) and held a minute, as
350
+ me-client's ``withOcAuth({ projectKey })`` reads it. Pass it to
351
+ :func:`verify_session`. While it can't be read, the last one read stands;
352
+ with none read yet, sign-in is refused (reason ``bond_policy_unavailable``)
353
+ rather than let through unchecked. A key that names no project is refused
354
+ with reason ``unknown_project_key``.
355
+ """
356
+
357
+ def __init__(self, project_key: str, *, me_origin: str = "https://me.ochk.io"):
358
+ self._url = me_origin.rstrip("/") + "/api/integrator/" + quote(project_key, safe="") + "/sign-in"
359
+ self._need: Optional[dict[str, int]] = None
360
+ self._read_at: Optional[float] = None
361
+ self._failed_at = float("-inf")
362
+ self._unknown_at = float("-inf")
363
+ self._lock = threading.Lock()
364
+
365
+ def requirement(self) -> Optional[dict[str, int]]:
366
+ """``{"min_sats", "min_days"}``, or None for no requirement. Raises :class:`InvalidSession` as described above."""
367
+ with self._lock:
368
+ now = time.time()
369
+ if now - self._unknown_at < _POLICY_TTL_SECONDS:
370
+ raise InvalidSession("unknown_project_key")
371
+ if self._read_at is not None and now - self._read_at < _POLICY_TTL_SECONDS:
372
+ return self._need
373
+ if now - self._failed_at < _POLICY_RETRY_SECONDS:
374
+ return self._stand_in()
375
+ try:
376
+ r = httpx.get(self._url, headers={"Accept": "application/json"}, timeout=4.0)
377
+ if r.status_code == 404:
378
+ self._unknown_at = now
379
+ raise InvalidSession("unknown_project_key")
380
+ r.raise_for_status()
381
+ req = r.json().get("require_bond")
382
+ self._need = (
383
+ {"min_sats": int(req.get("min_sats", 0)), "min_days": int(req.get("min_days", 0))}
384
+ if isinstance(req, dict)
385
+ else None
386
+ )
387
+ self._read_at = now
388
+ return self._need
389
+ except (httpx.HTTPError, ValueError, AttributeError):
390
+ self._failed_at = now
391
+ return self._stand_in()
392
+
393
+ def _stand_in(self) -> Optional[dict[str, int]]:
394
+ if self._read_at is None:
395
+ raise InvalidSession("bond_policy_unavailable")
396
+ return self._need
397
+
398
+
399
+ def _need_from(require_bond: Mapping[str, Any]) -> dict[str, int]:
400
+ need = {"min_sats": int(require_bond.get("min_sats", 0)), "min_days": int(require_bond.get("min_days", 0))}
401
+ if require_bond.get("max_age_secs") is not None:
402
+ need["max_age_secs"] = int(require_bond["max_age_secs"])
403
+ return need
251
404
 
252
405
 
253
406
  # ─── sign-in tokens ──────────────────────────────────────────────────────
@@ -262,6 +415,8 @@ def verify_session(
262
415
  leeway: int = 0,
263
416
  revocations: Optional[RevocationList] = None,
264
417
  method: Optional[str] = None,
418
+ require_bond: Optional[Mapping[str, Any]] = None,
419
+ policy: Optional[SignInPolicy] = None,
265
420
  ) -> Session:
266
421
  """
267
422
  Verify a token from the ochk.app sign-in popup and return who signed in.
@@ -346,12 +501,27 @@ def verify_session(
346
501
  raise InvalidSession("audience")
347
502
 
348
503
  if revocations is not None:
349
- state = revocations.status(payload["sub"], iat, payload["jti"])
504
+ token_aud = aud if isinstance(aud, str) else None
505
+ state = revocations.status(payload.get("rh"), token_aud, iat)
350
506
  if state == "revoked":
351
507
  raise SessionEnded()
352
508
  if state == "unverified" and (method or "").upper() not in _SAFE_METHODS:
353
509
  raise InvalidSession("revocations_unavailable")
354
510
 
511
+ # Who may sign in: an explicit requirement wins over the project's.
512
+ need = _need_from(require_bond) if require_bond is not None else (policy.requirement() if policy else None)
513
+ if need is not None and not bond_meets(
514
+ payload,
515
+ min_sats=need.get("min_sats", 0),
516
+ min_days=need.get("min_days", 0),
517
+ max_age_secs=need.get("max_age_secs"),
518
+ ):
519
+ backing = read_bond_claim(payload)
520
+ floors = (
521
+ {"sats_floor": int(backing["sats_floor"]), "days_floor": int(backing["days_floor"])} if backing else None
522
+ )
523
+ raise BondRequired(need, floors)
524
+
355
525
  bond = payload.get("oc_bond")
356
526
  return Session(
357
527
  sub=payload["sub"],
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "orangecheck"
7
- version = "2.7.0"
7
+ version = "2.9.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" }
@@ -15,12 +15,16 @@ from pathlib import Path
15
15
  from typing import Any
16
16
 
17
17
  import httpx
18
+ from urllib.parse import quote
18
19
  import pytest
19
20
  import respx
20
21
 
21
22
  import orangecheck.integrator as integrator
22
23
  from orangecheck import (
24
+ BondRequired,
23
25
  InvalidSession,
26
+ SignInPolicy,
27
+ bond_meets,
24
28
  InvalidWebhook,
25
29
  RevocationList,
26
30
  SessionEnded,
@@ -180,7 +184,7 @@ def test_webhook_fetches_me_ochk_io_dev_jwks(fresh_key_sets: None) -> None:
180
184
  assert route.call_count == 1
181
185
 
182
186
 
183
- # ─── account cutoffs ─────────────────────────────────────────────────────
187
+ # ─── revocation handles ──────────────────────────────────────────────────
184
188
 
185
189
  R = V["revocation"]
186
190
 
@@ -189,10 +193,16 @@ def _revocations() -> RevocationList:
189
193
  return RevocationList(R["request"]["project_key"], R["request"]["secret"])
190
194
 
191
195
 
196
+ def _serve_lists() -> None:
197
+ for aud, body in R["lists"].items():
198
+ url = f"https://me.ochk.io/api/integrator/revocations?project_key={R['request']['project_key']}&aud={quote(aud, safe='')}"
199
+ respx.get(url).mock(return_value=httpx.Response(200, json=body))
200
+
201
+
192
202
  @respx.mock
193
203
  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)
204
+ route = respx.get(R["request"]["url"]).mock(return_value=httpx.Response(200, json=R["lists"][R["request"]["aud"]]))
205
+ _revocations().status("any", R["request"]["aud"], 0)
196
206
  assert route.call_count == 1
197
207
  sent = route.calls[0].request
198
208
  assert str(sent.url) == R["request"]["url"]
@@ -207,29 +217,54 @@ def test_revocation_key_matches_the_node_sdk(v: dict[str, Any]) -> None:
207
217
  @respx.mock
208
218
  @pytest.mark.parametrize("v", R["sessions"], ids=lambda v: v["name"])
209
219
  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"]
220
+ _serve_lists()
221
+ assert _revocations().status(v["rh"], v["aud"], v["iat"]) == v["status"]
222
+
223
+
224
+ @respx.mock
225
+ def test_a_token_with_no_handle_is_never_looked_up() -> None:
226
+ route = respx.get(url__startswith="https://me.ochk.io/api/integrator/revocations").mock(
227
+ return_value=httpx.Response(200, json={})
228
+ )
229
+ assert _revocations().status(None, R["request"]["aud"], 0) == "live"
230
+ assert route.call_count == 0
212
231
 
213
232
 
214
233
  @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"]))
234
+ def test_revocations_are_fetched_at_most_once_a_minute_per_audience(monkeypatch: pytest.MonkeyPatch) -> None:
235
+ route = respx.get(R["request"]["url"]).mock(return_value=httpx.Response(200, json=R["lists"][R["request"]["aud"]]))
217
236
  rl = _revocations()
218
- rl.status("someone", 0)
219
- rl.status("someone", 0)
237
+ rl.status("x", R["request"]["aud"], 0)
238
+ rl.status("x", R["request"]["aud"], 0)
220
239
  assert route.call_count == 1
221
240
  monkeypatch.setattr(integrator.time, "time", lambda: float(V["now"] + 61))
222
- rl.status("someone", 0)
241
+ rl.status("x", R["request"]["aud"], 0)
223
242
  assert route.call_count == 2
224
243
 
225
244
 
226
245
  @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))
246
+ def test_a_list_dated_too_old_or_too_far_ahead_cannot_vouch(monkeypatch: pytest.MonkeyPatch) -> None:
247
+ body = dict(R["lists"][R["request"]["aud"]])
248
+ respx.get(R["request"]["url"]).mock(return_value=httpx.Response(200, json=body))
249
+ monkeypatch.setattr(integrator.time, "time", lambda: float(V["now"] + 11 * 60))
250
+ assert _revocations().status("x", R["request"]["aud"], 0) == "unverified"
251
+ monkeypatch.setattr(integrator.time, "time", lambda: float(V["now"] - 5 * 60))
252
+ assert _revocations().status("x", R["request"]["aud"], 0) == "unverified"
253
+ monkeypatch.setattr(integrator.time, "time", lambda: float(V["now"] - 30))
254
+ assert _revocations().status("x", R["request"]["aud"], 0) == "live"
255
+
256
+
257
+ def _rh_vector() -> dict[str, Any]:
258
+ return next(v for v in V["session"]["valid"] if v["claims"].get("rh"))
259
+
260
+
261
+ @respx.mock
262
+ def test_verify_session_refuses_a_session_whose_handle_is_ended() -> None:
263
+ v = _rh_vector()
264
+ url = f"https://me.ochk.io/api/integrator/revocations?project_key={R['request']['project_key']}&aud={quote(v['audience'], safe='')}"
265
+ respx.get(url).mock(return_value=httpx.Response(200, json={
266
+ "v": 1, "at": V["now"], "tokens": [], "accounts": {}, "handles": {v["claims"]["rh"]: v["claims"]["iat"] + 1},
267
+ }))
233
268
  with pytest.raises(SessionEnded) as err:
234
269
  verify_session(v["token"], v["audience"], jwks=V["session"]["jwks"], revocations=_revocations())
235
270
  assert isinstance(err.value, InvalidSession)
@@ -237,12 +272,109 @@ def test_verify_session_refuses_a_session_its_account_cutoff_ends() -> None:
237
272
 
238
273
 
239
274
  @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]
275
+ def test_verify_session_keeps_reads_refuses_writes_and_warns_once_while_the_list_cannot_be_read(
276
+ caplog: pytest.LogCaptureFixture,
277
+ ) -> None:
278
+ respx.get(url__startswith="https://me.ochk.io/api/integrator/revocations").mock(return_value=httpx.Response(503))
279
+ v = _rh_vector()
243
280
  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"]
281
+ with caplog.at_level("WARNING", logger="orangecheck"):
282
+ s = verify_session(v["token"], v["audience"], jwks=V["session"]["jwks"], revocations=rl, method="GET")
283
+ assert s.sub == v["claims"]["sub"]
284
+ with pytest.raises(InvalidSession) as err:
285
+ verify_session(v["token"], v["audience"], jwks=V["session"]["jwks"], revocations=rl, method="POST")
286
+ assert err.value.reason == "revocations_unavailable"
287
+ warnings = [r for r in caplog.records if r.name == "orangecheck" and r.levelname == "WARNING"]
288
+ assert len(warnings) == 1
289
+
290
+
291
+ # ─── who may sign in (coin backing) ──────────────────────────────────────
292
+
293
+ B = V["bond"]
294
+
295
+
296
+ @pytest.mark.parametrize("v", B, ids=lambda v: v["name"])
297
+ def test_bond_meets_as_the_node_sdk_decides(v: dict[str, Any]) -> None:
298
+ claims = {"sub": "s", "did_oc": "d", "jti": "j", **({"oc_bond": v["bond"]} if v["bond"] else {})}
299
+ need = v["need"]
300
+ assert bond_meets(claims, min_sats=need.get("min_sats", 0), min_days=need.get("min_days", 0),
301
+ max_age_secs=need.get("max_age_secs")) is v["meets"]
302
+
303
+
304
+ def _bond_vector() -> dict[str, Any]:
305
+ return next(v for v in V["session"]["valid"] if v["name"] == "backed by a coin (a complete claim)")
306
+
307
+
308
+ def test_verify_session_require_bond_refuses_an_unbacked_or_short_account() -> None:
309
+ plain = V["session"]["valid"][0]
310
+ with pytest.raises(BondRequired) as err:
311
+ verify_session(plain["token"], plain["audience"], jwks=V["session"]["jwks"], require_bond={"min_sats": 1000})
312
+ assert isinstance(err.value, InvalidSession)
313
+ assert err.value.reason == "bond_required"
314
+ assert err.value.need == {"min_sats": 1000, "min_days": 0}
315
+ assert err.value.have is None
316
+ assert err.value.back_url == "https://ochk.app/me/account#backing"
317
+ backed = _bond_vector()
318
+ s = verify_session(backed["token"], backed["audience"], jwks=V["session"]["jwks"], require_bond={"min_sats": 100000})
319
+ assert s.oc_bond is not None
320
+
321
+
322
+ SIGN_IN = "https://me.ochk.io/api/integrator/pk_test_tv/sign-in"
323
+
324
+
325
+ @respx.mock
326
+ def test_sign_in_policy_reads_the_project_requirement_once_a_minute(monkeypatch: pytest.MonkeyPatch) -> None:
327
+ route = respx.get(SIGN_IN).mock(return_value=httpx.Response(200, json={"require_bond": {"min_sats": 100000, "min_days": 30}}))
328
+ policy = SignInPolicy("pk_test_tv")
329
+ plain = V["session"]["valid"][0]
330
+ with pytest.raises(BondRequired) as err:
331
+ verify_session(plain["token"], plain["audience"], jwks=V["session"]["jwks"], policy=policy)
332
+ assert err.value.need == {"min_sats": 100000, "min_days": 30}
333
+ backed = _bond_vector()
334
+ assert verify_session(backed["token"], backed["audience"], jwks=V["session"]["jwks"], policy=policy).sub
335
+ assert route.call_count == 1
336
+ monkeypatch.setattr(integrator.time, "time", lambda: float(V["now"] + 61))
337
+ policy.requirement()
338
+ assert route.call_count == 2
339
+
340
+
341
+ @respx.mock
342
+ def test_sign_in_policy_with_no_requirement_admits_everyone() -> None:
343
+ respx.get(SIGN_IN).mock(return_value=httpx.Response(200, json={"require_bond": None}))
344
+ plain = V["session"]["valid"][0]
345
+ assert verify_session(plain["token"], plain["audience"], jwks=V["session"]["jwks"], policy=SignInPolicy("pk_test_tv")).sub
346
+
347
+
348
+ @respx.mock
349
+ def test_require_bond_in_code_wins_over_the_project_policy() -> None:
350
+ route = respx.get(SIGN_IN).mock(return_value=httpx.Response(200, json={"require_bond": {"min_sats": 10000000, "min_days": 365}}))
351
+ backed = _bond_vector()
352
+ s = verify_session(backed["token"], backed["audience"], jwks=V["session"]["jwks"],
353
+ policy=SignInPolicy("pk_test_tv"), require_bond={"min_sats": 1000})
354
+ assert s.sub
355
+ assert route.call_count == 0
356
+
357
+
358
+ @respx.mock
359
+ def test_an_unknown_project_or_an_unreadable_policy_refuses_rather_than_admits() -> None:
360
+ plain = V["session"]["valid"][0]
361
+ respx.get("https://me.ochk.io/api/integrator/pk_test_nope/sign-in").mock(return_value=httpx.Response(404))
246
362
  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"
363
+ verify_session(plain["token"], plain["audience"], jwks=V["session"]["jwks"], policy=SignInPolicy("pk_test_nope"))
364
+ assert err.value.reason == "unknown_project_key"
365
+ respx.get(SIGN_IN).mock(return_value=httpx.Response(503))
366
+ with pytest.raises(InvalidSession) as err2:
367
+ verify_session(plain["token"], plain["audience"], jwks=V["session"]["jwks"], policy=SignInPolicy("pk_test_tv"))
368
+ assert err2.value.reason == "bond_policy_unavailable"
369
+
370
+
371
+ @respx.mock
372
+ def test_the_last_requirement_read_stands_through_an_outage(monkeypatch: pytest.MonkeyPatch) -> None:
373
+ respx.get(SIGN_IN).mock(side_effect=[
374
+ httpx.Response(200, json={"require_bond": {"min_sats": 100000, "min_days": 30}}),
375
+ httpx.Response(503),
376
+ ])
377
+ policy = SignInPolicy("pk_test_tv")
378
+ assert policy.requirement() == {"min_sats": 100000, "min_days": 30}
379
+ monkeypatch.setattr(integrator.time, "time", lambda: float(V["now"] + 61))
380
+ assert policy.requirement() == {"min_sats": 100000, "min_days": 30}
File without changes