orangecheck 3.2.1__tar.gz → 3.3.1__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 (75) hide show
  1. {orangecheck-3.2.1 → orangecheck-3.3.1}/CHANGELOG.md +26 -0
  2. {orangecheck-3.2.1 → orangecheck-3.3.1}/PKG-INFO +19 -1
  3. {orangecheck-3.2.1 → orangecheck-3.3.1}/README.md +18 -0
  4. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/__init__.py +3 -1
  5. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/integrator.py +109 -27
  6. {orangecheck-3.2.1 → orangecheck-3.3.1}/pyproject.toml +1 -1
  7. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_integrator_vectors.py +7 -2
  8. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_server_helpers.py +93 -0
  9. {orangecheck-3.2.1 → orangecheck-3.3.1}/.gitignore +0 -0
  10. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/__main__.py +0 -0
  11. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/address.py +0 -0
  12. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/bond.py +0 -0
  13. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/canonical.py +0 -0
  14. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/client.py +0 -0
  15. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/connect.py +0 -0
  16. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/errors.py +0 -0
  17. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/pledge/__init__.py +0 -0
  18. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/pledge/bond.py +0 -0
  19. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/pledge/canonical.py +0 -0
  20. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/pledge/delegation.py +0 -0
  21. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/pledge/envelopes.py +0 -0
  22. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/pledge/resolution.py +0 -0
  23. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/pledge/state.py +0 -0
  24. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/py.typed +0 -0
  25. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/tokens.py +0 -0
  26. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/top_level.py +0 -0
  27. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/types.py +0 -0
  28. {orangecheck-3.2.1 → orangecheck-3.3.1}/orangecheck/verify_sig.py +0 -0
  29. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/fixtures/bip137-parity.json +0 -0
  30. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/fixtures/bip322-js-6.1.8.json +0 -0
  31. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/fixtures/bip322-official-basic.json +0 -0
  32. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/fixtures/bip322-official-generated.json +0 -0
  33. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/pledge/__init__.py +0 -0
  34. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/pledge/test_authority.py +0 -0
  35. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/pledge/test_create_signers.py +0 -0
  36. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/pledge/test_delegation.py +0 -0
  37. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/pledge/test_vectors.py +0 -0
  38. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/pledge/test_wrap.py +0 -0
  39. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_address.py +0 -0
  40. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_bip322_official.py +0 -0
  41. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_client.py +0 -0
  42. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_client_failure_modes.py +0 -0
  43. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_conformance.py +0 -0
  44. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_connect.py +0 -0
  45. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_ripemd160.py +0 -0
  46. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/test_signature_parity.py +0 -0
  47. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/index.json +0 -0
  48. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv01.json +0 -0
  49. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv02.json +0 -0
  50. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv03.json +0 -0
  51. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv04.json +0 -0
  52. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv05.json +0 -0
  53. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv06.json +0 -0
  54. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv07.json +0 -0
  55. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv08.json +0 -0
  56. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv09.json +0 -0
  57. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv10.json +0 -0
  58. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv11.json +0 -0
  59. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv12.json +0 -0
  60. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv13.json +0 -0
  61. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv14.json +0 -0
  62. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv15.json +0 -0
  63. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv16.json +0 -0
  64. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv17.json +0 -0
  65. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv18.json +0 -0
  66. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv19.json +0 -0
  67. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv20.json +0 -0
  68. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv21.json +0 -0
  69. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv22.json +0 -0
  70. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv23.json +0 -0
  71. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv24.json +0 -0
  72. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv25.json +0 -0
  73. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv26.json +0 -0
  74. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv27.json +0 -0
  75. {orangecheck-3.2.1 → orangecheck-3.3.1}/tests/vectors/tv28.json +0 -0
@@ -4,6 +4,32 @@ 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
+ ## [3.3.1] — 2026-10-24
8
+
9
+ ### Changed
10
+
11
+ - `RevocationList` reads the `tokens` of its audience's list and answers
12
+ `"revoked"` for a token whose own `jti` is there, as
13
+ `@orangecheck/auth-core`'s `integratorRevocationCheck` does, so a token ended
14
+ with `revoke_token` stops passing once me.ochk.io lists it. `status()` and
15
+ `status_for()` take the jti (shared vectors "a token ended on its own").
16
+
17
+ ## [3.3.0] — 2026-10-24
18
+
19
+ ### Added
20
+
21
+ - `check_sign_in_rule(session, project_key=…)`: your project's "who can sign
22
+ in" rule for a session you verified yourself, as `@orangecheck/me-client`
23
+ 0.43.0's `checkSignInRule`. One `SignInPolicy` per project is kept, so the
24
+ rule is read once a minute, and its stand-in and refusal rules hold. It
25
+ answers a `SessionCheck`: 200, 403 `bond_required` with `need`, `have` and
26
+ `back_url`, 503 `bond_policy_unavailable`, or 500 `unknown_project_key`.
27
+ Pass `policy=` to use a `SignInPolicy` you already warm, or `require_bond=`
28
+ to set the floor yourself (nothing is read). It takes only the `Session`
29
+ that `verify_session` or `check_oc_session` returned, and raises TypeError
30
+ for a dict of claims or a Session built any other way. Both SDKs are held to
31
+ `me-client/test-vectors/server-helpers.json` (`sign_in_rule`).
32
+
7
33
  ## [3.2.1] — 2026-10-24
8
34
 
9
35
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: orangecheck
3
- Version: 3.2.1
3
+ Version: 3.3.1
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
@@ -290,6 +290,24 @@ if not checked.ok:
290
290
  session = checked.session
291
291
  ```
292
292
 
293
+ Where you verify the token without `policy=`, apply the project's rule in the
294
+ route that starts your own session with `check_sign_in_rule` (3.3.0 or later),
295
+ which gives the same answers. Pass the `POLICY` you warm, or `project_key=` and
296
+ it keeps one per project:
297
+
298
+ ```python
299
+ from orangecheck import check_sign_in_rule, verify_session
300
+
301
+ session = verify_session(token, audience="https://your-site.example")
302
+ checked = check_sign_in_rule(session, policy=POLICY)
303
+ if not checked.ok:
304
+ return JSONResponse(checked.body, status_code=checked.status)
305
+ ```
306
+
307
+ It takes only the `Session` that `verify_session` or `check_oc_session` returned
308
+ and raises TypeError for claims as a dict, or a Session built any other way:
309
+ those could name anyone.
310
+
293
311
  When the token starts your own session, spend its `jti` so it starts only one,
294
312
  then end it at ochk.io (3.2.0 or later). `store` is yours: anything with an
295
313
  atomic `add(jti, exp) -> bool` that every server shares, such as a unique row
@@ -253,6 +253,24 @@ if not checked.ok:
253
253
  session = checked.session
254
254
  ```
255
255
 
256
+ Where you verify the token without `policy=`, apply the project's rule in the
257
+ route that starts your own session with `check_sign_in_rule` (3.3.0 or later),
258
+ which gives the same answers. Pass the `POLICY` you warm, or `project_key=` and
259
+ it keeps one per project:
260
+
261
+ ```python
262
+ from orangecheck import check_sign_in_rule, verify_session
263
+
264
+ session = verify_session(token, audience="https://your-site.example")
265
+ checked = check_sign_in_rule(session, policy=POLICY)
266
+ if not checked.ok:
267
+ return JSONResponse(checked.body, status_code=checked.status)
268
+ ```
269
+
270
+ It takes only the `Session` that `verify_session` or `check_oc_session` returned
271
+ and raises TypeError for claims as a dict, or a Session built any other way:
272
+ those could name anyone.
273
+
256
274
  When the token starts your own session, spend its `jti` so it starts only one,
257
275
  then end it at ochk.io (3.2.0 or later). `store` is yours: anything with an
258
276
  atomic `add(jti, exp) -> bool` that every server shares, such as a unique row
@@ -90,6 +90,7 @@ from .integrator import (
90
90
  WarmResult,
91
91
  bond_meets,
92
92
  check_oc_session,
93
+ check_sign_in_rule,
93
94
  read_bond_claim,
94
95
  revocation_key,
95
96
  sign_event,
@@ -157,6 +158,7 @@ __all__ = [
157
158
  # ochk.app sign-in, billable events and webhooks, for an integrator's backend
158
159
  "verify_session",
159
160
  "check_oc_session",
161
+ "check_sign_in_rule",
160
162
  "SessionCheck",
161
163
  "warm_session",
162
164
  "WarmResult",
@@ -205,7 +207,7 @@ __all__ = [
205
207
  "VerificationError",
206
208
  ]
207
209
 
208
- __version__ = "3.2.1"
210
+ __version__ = "3.3.1"
209
211
 
210
212
  # OC Pledge submodule — sibling primitive for forward-looking commitments
211
213
  # bound to a Bitcoin address. Imported here so consumers can write:
@@ -371,6 +371,7 @@ class _AudienceList:
371
371
  + quote(aud, safe="-_.!~*'()")
372
372
  )
373
373
  self._handles: dict[str, float] = {}
374
+ self._tokens: frozenset[str] = frozenset()
374
375
  self._at: Optional[float] = None
375
376
  # How old the list already was when fetched, by the wall clock.
376
377
  self._age_at_fetch = float("inf")
@@ -408,6 +409,7 @@ class _AudienceList:
408
409
  raw = doc.get("handles")
409
410
  handles: dict[str, Any] = raw if isinstance(raw, dict) else {}
410
411
  self._handles = {k: float(v) for k, v in handles.items() if _finite(v)}
412
+ self._tokens = frozenset(t for t in doc["tokens"] if isinstance(t, str))
411
413
  at: Any = doc.get("at")
412
414
  self._at = float(at) if _finite(at) else None
413
415
  self._age_at_fetch = float("inf") if self._at is None else time.time() - self._at
@@ -449,11 +451,14 @@ class _AudienceList:
449
451
  return WarmPart("failed", problem)
450
452
  return _FETCHED if self._fetched_at != before else _KEPT
451
453
 
452
- def status(self, rh: str, iat: Optional[float]) -> str:
454
+ def status(self, rh: str, iat: Optional[float], jti: Optional[str] = None) -> str:
453
455
  with self._lock:
454
456
  self._refresh()
455
457
  if self._fetched_at is None:
456
458
  return "unverified"
459
+ # A token known to be ended stays ended, however old the copy.
460
+ if isinstance(jti, str) and revocation_key("jti", jti) in self._tokens:
461
+ return "revoked"
457
462
  cutoff = self._handles.get(rh)
458
463
  if cutoff is not None and not (iat is not None and iat >= cutoff):
459
464
  return "revoked"
@@ -507,10 +512,12 @@ class RevocationList:
507
512
  lst = self._lists[aud] = _AudienceList(self, aud)
508
513
  return lst
509
514
 
510
- def status(self, rh: Optional[str], aud: Optional[str], iat: Optional[float]) -> str:
515
+ def status(
516
+ self, rh: Optional[str], aud: Optional[str], iat: Optional[float], jti: Optional[str] = None
517
+ ) -> str:
511
518
  if rh is None:
512
519
  return "live"
513
- return self._status(rh, aud, iat)
520
+ return self._status(rh, aud, iat, jti)
514
521
 
515
522
  def status_for(self, claims: Mapping[str, Any]) -> str:
516
523
  """
@@ -520,12 +527,12 @@ class RevocationList:
520
527
  """
521
528
  if "rh" not in claims:
522
529
  return "live"
523
- return self._status(claims["rh"], claims.get("aud"), claims.get("iat"))
530
+ return self._status(claims["rh"], claims.get("aud"), claims.get("iat"), claims.get("jti"))
524
531
 
525
- def _status(self, rh: Any, aud: Any, iat: Optional[float]) -> str:
532
+ def _status(self, rh: Any, aud: Any, iat: Optional[float], jti: Any = None) -> str:
526
533
  if not isinstance(rh, str) or not rh or not isinstance(aud, str) or not aud:
527
534
  return "revoked"
528
- return self._list(aud).status(rh, iat)
535
+ return self._list(aud).status(rh, iat, jti)
529
536
 
530
537
 
531
538
  # ─── who may sign in (coin backing) ──────────────────────────────────────
@@ -679,6 +686,41 @@ def _need_from(require_bond: Mapping[str, Any]) -> dict[str, int]:
679
686
  return need
680
687
 
681
688
 
689
+ def _apply_rule(
690
+ claims: Union[Session, Mapping[str, Any]],
691
+ require_bond: Optional[Mapping[str, Any]],
692
+ policy: Optional[SignInPolicy],
693
+ ) -> None:
694
+ """Raise :class:`BondRequired` when the account is not backed enough. An explicit requirement wins over the project's."""
695
+ need = _need_from(require_bond) if require_bond is not None else (policy.requirement() if policy else None)
696
+ if need is not None and not bond_meets(
697
+ claims,
698
+ min_sats=need.get("min_sats", 0),
699
+ min_days=need.get("min_days", 0),
700
+ max_age_secs=need.get("max_age_secs"),
701
+ ):
702
+ backing = read_bond_claim(claims)
703
+ floors = (
704
+ {"sats_floor": int(backing["sats_floor"]), "days_floor": int(backing["days_floor"])} if backing else None
705
+ )
706
+ raise BondRequired(need, floors)
707
+
708
+
709
+ _policies: dict[tuple[str, str], SignInPolicy] = {}
710
+
711
+ # Each Session verify_session returned, so check_sign_in_rule takes nothing else:
712
+ # claims anyone built could carry any did and any backing.
713
+ _verified: "weakref.WeakValueDictionary[int, Session]" = weakref.WeakValueDictionary()
714
+
715
+
716
+ def _policy_for(project_key: str, me_origin: str) -> SignInPolicy:
717
+ """One :class:`SignInPolicy` per project, so its minute holds from call to call."""
718
+ policy = _policies.get((me_origin, project_key))
719
+ if policy is None:
720
+ policy = _policies.setdefault((me_origin, project_key), SignInPolicy(project_key, me_origin=me_origin))
721
+ return policy
722
+
723
+
682
724
  # ─── sign-in tokens ──────────────────────────────────────────────────────
683
725
 
684
726
 
@@ -844,22 +886,10 @@ def verify_session(
844
886
  if state == "unverified" and (method or "").upper() not in _SAFE_METHODS:
845
887
  raise InvalidSession("revocations_unavailable")
846
888
 
847
- # Who may sign in: an explicit requirement wins over the project's.
848
- need = _need_from(require_bond) if require_bond is not None else (policy.requirement() if policy else None)
849
- if need is not None and not bond_meets(
850
- payload,
851
- min_sats=need.get("min_sats", 0),
852
- min_days=need.get("min_days", 0),
853
- max_age_secs=need.get("max_age_secs"),
854
- ):
855
- backing = read_bond_claim(payload)
856
- floors = (
857
- {"sats_floor": int(backing["sats_floor"]), "days_floor": int(backing["days_floor"])} if backing else None
858
- )
859
- raise BondRequired(need, floors)
889
+ _apply_rule(payload, require_bond, policy)
860
890
 
861
891
  bond = payload.get("oc_bond")
862
- return Session(
892
+ session = Session(
863
893
  sub=payload["sub"],
864
894
  did_oc=payload["did_oc"],
865
895
  jti=payload["jti"],
@@ -870,6 +900,8 @@ def verify_session(
870
900
  claims=payload,
871
901
  rh=rh if isinstance(rh, str) else None,
872
902
  )
903
+ _verified[id(session)] = session
904
+ return session
873
905
 
874
906
 
875
907
  #: Can't tell right now: the client should try again, never sign the person out.
@@ -949,7 +981,13 @@ def check_oc_session(
949
981
  policy=policy,
950
982
  require_handle=require_handle,
951
983
  )
952
- except BondRequired as err:
984
+ except InvalidSession as err:
985
+ return _refused(err)
986
+ return SessionCheck(200, session=session)
987
+
988
+
989
+ def _refused(err: InvalidSession) -> SessionCheck:
990
+ if isinstance(err, BondRequired):
953
991
  return SessionCheck(
954
992
  403,
955
993
  body={
@@ -960,13 +998,57 @@ def check_oc_session(
960
998
  "back_url": err.back_url,
961
999
  },
962
1000
  )
1001
+ if err.reason in _UNAVAILABLE:
1002
+ return SessionCheck(503, body={"ok": False, "reason": err.reason})
1003
+ if err.reason == "unknown_project_key":
1004
+ return SessionCheck(500, body={"ok": False, "reason": err.reason})
1005
+ reason = "no_session_handle" if err.reason == "no_session_handle" else "unauthenticated"
1006
+ return SessionCheck(401, body={"ok": False, "reason": reason})
1007
+
1008
+
1009
+ def check_sign_in_rule(
1010
+ session: Session,
1011
+ *,
1012
+ project_key: Optional[str] = None,
1013
+ me_origin: str = "https://me.ochk.io",
1014
+ policy: Optional[SignInPolicy] = None,
1015
+ require_bond: Optional[Mapping[str, Any]] = None,
1016
+ ) -> SessionCheck:
1017
+ """
1018
+ Your project's "who can sign in" rule for a session you verified yourself,
1019
+ as me-client's ``checkSignInRule``. For a site that verifies the token with
1020
+ :func:`verify_session` and then starts a session of its own, and still wants
1021
+ the rule set on ochk.app. ``session`` is the :class:`Session` that
1022
+ :func:`verify_session` or :func:`check_oc_session` returned, as is; claims
1023
+ as a dict, or a Session built any other way, raise TypeError. Apply the rule
1024
+ where your own session starts, while you hold the verified one.
1025
+
1026
+ The rule is read and held as :class:`SignInPolicy` holds it: a minute, the
1027
+ last one read standing ten more while it can't be read, and then refused
1028
+ (503 ``bond_policy_unavailable``) rather than let through unchecked. The
1029
+ answer is a :class:`SessionCheck`: 200, 403 ``bond_required`` with
1030
+ ``need``, ``have`` and ``back_url``, 503, or 500 ``unknown_project_key``.
1031
+ Pass ``require_bond`` to set the floor yourself; it wins, and nothing is
1032
+ read. It raises only on a mistake in the call itself.
1033
+
1034
+ checked = check_sign_in_rule(session, project_key=os.environ["OC_PROJECT_KEY"])
1035
+ if not checked.ok:
1036
+ return JSONResponse(checked.body, status_code=checked.status)
1037
+ """
1038
+ if not isinstance(session, Session) or _verified.get(id(session)) is not session:
1039
+ raise TypeError("check_sign_in_rule takes the Session verify_session returned, as is, not claims")
1040
+ if project_key is not None and policy is not None:
1041
+ raise TypeError("pass project_key or policy, not both")
1042
+ if project_key is not None and (not isinstance(project_key, str) or not project_key):
1043
+ raise TypeError("project_key must be your project's key")
1044
+ if project_key is None and policy is None and require_bond is None:
1045
+ raise TypeError("check_sign_in_rule needs project_key, policy or require_bond")
1046
+ if project_key is not None:
1047
+ policy = _policy_for(project_key, me_origin)
1048
+ try:
1049
+ _apply_rule(session, require_bond, policy)
963
1050
  except InvalidSession as err:
964
- if err.reason in _UNAVAILABLE:
965
- return SessionCheck(503, body={"ok": False, "reason": err.reason})
966
- if err.reason == "unknown_project_key":
967
- return SessionCheck(500, body={"ok": False, "reason": err.reason})
968
- reason = "no_session_handle" if err.reason == "no_session_handle" else "unauthenticated"
969
- return SessionCheck(401, body={"ok": False, "reason": reason})
1051
+ return _refused(err)
970
1052
  return SessionCheck(200, session=session)
971
1053
 
972
1054
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "orangecheck"
7
- version = "3.2.1"
7
+ version = "3.3.1"
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" }
@@ -258,15 +258,20 @@ def test_revocation_key_matches_the_node_sdk(v: dict[str, Any]) -> None:
258
258
  assert revocation_key("sub", v["sub"]) == v["key"]
259
259
 
260
260
 
261
+ @pytest.mark.parametrize("v", R["token_keys"], ids=lambda v: v["jti"])
262
+ def test_token_key_matches_the_node_sdk(v: dict[str, Any]) -> None:
263
+ assert revocation_key("jti", v["jti"]) == v["key"]
264
+
265
+
261
266
  @respx.mock
262
267
  @pytest.mark.parametrize("v", R["sessions"], ids=lambda v: v["name"])
263
268
  def test_revocations_decide_as_the_node_sdk_does(v: dict[str, Any]) -> None:
264
269
  _serve_lists()
265
270
  # A key absent from the vector is absent from the claims; null stays null.
266
- claims = {k: v[k] for k in ("rh", "aud", "iat") if k in v}
271
+ claims = {k: v[k] for k in ("rh", "aud", "iat", "jti") if k in v}
267
272
  assert _revocations().status_for(claims) == v["status"]
268
273
  if "rh" not in v or v["rh"] is not None:
269
- assert _revocations().status(v.get("rh"), v["aud"], v["iat"]) == v["status"]
274
+ assert _revocations().status(v.get("rh"), v["aud"], v["iat"], v.get("jti")) == v["status"]
270
275
 
271
276
 
272
277
  @respx.mock
@@ -9,6 +9,7 @@ the same HTTP answer, spend the same tokens and read ochk.io's answers alike.
9
9
 
10
10
  from __future__ import annotations
11
11
 
12
+ import dataclasses
12
13
  import json
13
14
  from pathlib import Path
14
15
  from typing import Any, Optional
@@ -28,6 +29,7 @@ from orangecheck import (
28
29
  SignInPolicy,
29
30
  TokensRevoked,
30
31
  check_oc_session,
32
+ check_sign_in_rule,
31
33
  revoke_token,
32
34
  spend_once,
33
35
  verify_session,
@@ -50,6 +52,7 @@ def fixed_clock(monkeypatch: pytest.MonkeyPatch) -> None:
50
52
  _move_to(monkeypatch, H["now"])
51
53
  monkeypatch.setattr(integrator, "_session_keys", integrator._KeySet(integrator.SESSION_JWKS_URL))
52
54
  monkeypatch.setattr(integrator, "_issuer_keys", {})
55
+ monkeypatch.setattr(integrator, "_policies", {})
53
56
 
54
57
 
55
58
  def _token(ref: Optional[list[str]]) -> Optional[str]:
@@ -106,6 +109,96 @@ def test_check_takes_only_what_verify_session_takes() -> None:
106
109
  check_oc_session("a.b.c", "https://soniq.example", audiences=["x"]) # type: ignore[call-arg]
107
110
 
108
111
 
112
+ # ─── check_sign_in_rule: the rule for a session the site verified ────────
113
+
114
+
115
+ def _session(ref: list[str], verified: bool = True) -> Any:
116
+ """The Session verify_session returns for a token in integrator.json, or its claims as read."""
117
+ section, kind, name = ref
118
+ v = next(v for v in V[section][kind] if v["name"] == name)
119
+ if not verified:
120
+ return dict(v["claims"])
121
+ return verify_session(v["token"], v["audience"], jwks=V["session"]["jwks"])
122
+
123
+
124
+ @respx.mock
125
+ @pytest.mark.parametrize("c", H["sign_in_rule"]["cases"], ids=lambda c: c["name"])
126
+ def test_sign_in_rule_answers_as_me_client_does(c: dict[str, Any]) -> None:
127
+ route = respx.get(f"https://me.ochk.io/api/integrator/{c['project_key']}/sign-in").mock(
128
+ return_value=_response(c["policy"])
129
+ )
130
+ kwargs: dict[str, Any] = {"project_key": c["project_key"]}
131
+ if "require_bond" in c:
132
+ kwargs["require_bond"] = c["require_bond"]
133
+ got = check_sign_in_rule(_session(c["session"]), **kwargs)
134
+ assert isinstance(got, SessionCheck)
135
+ assert got.status == c["expect"]["status"]
136
+ if got.status == 200:
137
+ assert got.ok and got.body is None and got.session is not None
138
+ else:
139
+ assert not got.ok and got.body == c["expect"]["body"]
140
+ # An explicit floor wins: the project's rule is never read.
141
+ if "require_bond" in c:
142
+ assert route.call_count == 0
143
+
144
+
145
+ @respx.mock
146
+ @pytest.mark.parametrize("r", H["sign_in_rule"]["refused"], ids=lambda r: r["name"])
147
+ def test_sign_in_rule_refuses_a_mistake_in_the_call(r: dict[str, Any]) -> None:
148
+ session = _session(r["session"], r.get("verified", True)) if r["session"] else None
149
+ with pytest.raises(TypeError):
150
+ check_sign_in_rule(session, **r["options"])
151
+
152
+
153
+ def test_sign_in_rule_refuses_a_session_built_by_hand() -> None:
154
+ verified = _session(["session", "valid", "backed by a coin (a complete claim)"])
155
+ assert check_sign_in_rule(verified, require_bond={"min_sats": 10000}).ok
156
+ with pytest.raises(TypeError):
157
+ check_sign_in_rule(dataclasses.replace(verified), require_bond={"min_sats": 10000})
158
+
159
+
160
+ @respx.mock
161
+ def test_sign_in_rule_takes_the_session_check_oc_session_returns() -> None:
162
+ respx.get("https://me.ochk.io/api/integrator/pk_test_srule_paths/sign-in").mock(
163
+ return_value=httpx.Response(200, json={"ok": True, "require_bond": None})
164
+ )
165
+ v = next(v for v in V["session"]["valid"] if v["name"] == "bound to this site")
166
+ checked = check_oc_session(v["token"], v["audience"], jwks=V["session"]["jwks"], method="POST")
167
+ assert checked.ok and checked.session is not None
168
+ assert check_sign_in_rule(checked.session, project_key="pk_test_srule_paths").ok
169
+
170
+
171
+ def test_sign_in_rule_takes_one_project() -> None:
172
+ session = _session(["session", "valid", "bound to this site"])
173
+ with pytest.raises(TypeError):
174
+ check_sign_in_rule(session, project_key="pk_test_srule_a", policy=SignInPolicy("pk_test_srule_b"))
175
+ with pytest.raises(TypeError):
176
+ check_sign_in_rule(session, project_key="")
177
+
178
+
179
+ @respx.mock
180
+ def test_sign_in_rule_reads_the_rule_once_a_minute(monkeypatch: pytest.MonkeyPatch) -> None:
181
+ route = respx.get("https://me.ochk.io/api/integrator/pk_test_srule_cache/sign-in").mock(
182
+ return_value=httpx.Response(200, json={"ok": True, "require_bond": None})
183
+ )
184
+ session = _session(["session", "valid", "bound to this site"])
185
+ assert check_sign_in_rule(session, project_key="pk_test_srule_cache").ok
186
+ assert check_sign_in_rule(session, project_key="pk_test_srule_cache").ok
187
+ assert route.call_count == 1
188
+ _move_to(monkeypatch, H["now"] + 61)
189
+ assert check_sign_in_rule(session, project_key="pk_test_srule_cache").ok
190
+ assert route.call_count == 2
191
+
192
+
193
+ @respx.mock
194
+ def test_sign_in_rule_takes_a_policy_or_a_verified_session() -> None:
195
+ respx.get("https://me.ochk.io/api/integrator/pk_test_srule_obj/sign-in").mock(
196
+ return_value=httpx.Response(200, json={"ok": True, "require_bond": {"min_sats": 10000, "min_days": 0}})
197
+ )
198
+ got = check_sign_in_rule(_session(["session", "valid", "bound to this site"]), policy=SignInPolicy("pk_test_srule_obj"))
199
+ assert (got.status, got.body["reason"] if got.body else None) == (403, "bond_required")
200
+
201
+
109
202
  # ─── spend_once ──────────────────────────────────────────────────────────
110
203
 
111
204
 
File without changes