orangecheck 3.0.0__tar.gz → 3.2.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 (75) hide show
  1. {orangecheck-3.0.0 → orangecheck-3.2.0}/CHANGELOG.md +61 -0
  2. {orangecheck-3.0.0 → orangecheck-3.2.0}/PKG-INFO +41 -1
  3. {orangecheck-3.0.0 → orangecheck-3.2.0}/README.md +40 -0
  4. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/__init__.py +22 -1
  5. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/integrator.py +196 -16
  6. orangecheck-3.2.0/orangecheck/tokens.py +200 -0
  7. {orangecheck-3.0.0 → orangecheck-3.2.0}/pyproject.toml +1 -1
  8. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_integrator_vectors.py +39 -1
  9. orangecheck-3.2.0/tests/test_server_helpers.py +383 -0
  10. {orangecheck-3.0.0 → orangecheck-3.2.0}/.gitignore +0 -0
  11. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/__main__.py +0 -0
  12. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/address.py +0 -0
  13. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/bond.py +0 -0
  14. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/canonical.py +0 -0
  15. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/client.py +0 -0
  16. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/connect.py +0 -0
  17. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/errors.py +0 -0
  18. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/pledge/__init__.py +0 -0
  19. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/pledge/bond.py +0 -0
  20. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/pledge/canonical.py +0 -0
  21. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/pledge/delegation.py +0 -0
  22. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/pledge/envelopes.py +0 -0
  23. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/pledge/resolution.py +0 -0
  24. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/pledge/state.py +0 -0
  25. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/py.typed +0 -0
  26. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/top_level.py +0 -0
  27. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/types.py +0 -0
  28. {orangecheck-3.0.0 → orangecheck-3.2.0}/orangecheck/verify_sig.py +0 -0
  29. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/fixtures/bip137-parity.json +0 -0
  30. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/fixtures/bip322-js-6.1.8.json +0 -0
  31. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/fixtures/bip322-official-basic.json +0 -0
  32. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/fixtures/bip322-official-generated.json +0 -0
  33. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/pledge/__init__.py +0 -0
  34. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/pledge/test_authority.py +0 -0
  35. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/pledge/test_create_signers.py +0 -0
  36. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/pledge/test_delegation.py +0 -0
  37. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/pledge/test_vectors.py +0 -0
  38. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/pledge/test_wrap.py +0 -0
  39. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_address.py +0 -0
  40. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_bip322_official.py +0 -0
  41. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_client.py +0 -0
  42. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_client_failure_modes.py +0 -0
  43. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_conformance.py +0 -0
  44. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_connect.py +0 -0
  45. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_ripemd160.py +0 -0
  46. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/test_signature_parity.py +0 -0
  47. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/index.json +0 -0
  48. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv01.json +0 -0
  49. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv02.json +0 -0
  50. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv03.json +0 -0
  51. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv04.json +0 -0
  52. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv05.json +0 -0
  53. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv06.json +0 -0
  54. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv07.json +0 -0
  55. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv08.json +0 -0
  56. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv09.json +0 -0
  57. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv10.json +0 -0
  58. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv11.json +0 -0
  59. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv12.json +0 -0
  60. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv13.json +0 -0
  61. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv14.json +0 -0
  62. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv15.json +0 -0
  63. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv16.json +0 -0
  64. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv17.json +0 -0
  65. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv18.json +0 -0
  66. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv19.json +0 -0
  67. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv20.json +0 -0
  68. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv21.json +0 -0
  69. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv22.json +0 -0
  70. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv23.json +0 -0
  71. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv24.json +0 -0
  72. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv25.json +0 -0
  73. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv26.json +0 -0
  74. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv27.json +0 -0
  75. {orangecheck-3.0.0 → orangecheck-3.2.0}/tests/vectors/tv28.json +0 -0
@@ -4,6 +4,67 @@ 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.2.0] — 2026-10-24
8
+
9
+ ### Added
10
+
11
+ - `check_oc_session(token, audience, …)`: `verify_session`'s arguments,
12
+ answered as a `SessionCheck` with the HTTP status and JSON body
13
+ `@orangecheck/me-client`'s adapters send: 200 with `session`; 401
14
+ `unauthenticated` (no token, a bad one, or one the person ended) or
15
+ `no_session_handle`; 403 `bond_required` with `need`, `have` and `back_url`;
16
+ 503 `revocations_unavailable` or `bond_policy_unavailable`; 500
17
+ `unknown_project_key`. Both SDKs are held to
18
+ `me-client/test-vectors/server-helpers.json`, and both answer 503
19
+ `key_set_unavailable` while the key set can't be read (me-client 0.41.0).
20
+ - `spend_once(jti, exp, store)`, `JtiStore` and `MemoryJtiStore`: a token's
21
+ `jti` starts one session. True the first time, False for a repeat or a token
22
+ that has expired. The store is yours, shared by every server; a store that
23
+ fails raises. `spend_once_async` takes a store whose `add` is a coroutine.
24
+ - `revoke_token(token, issuer=, timeout=)`: ends a token, or up to eight, at
25
+ the auth host (`POST <issuer>/api/auth/revoke`). Returns `TokensRevoked` or
26
+ `RevokeRefusal` (`rate_limited`, `bad_request`, `unavailable`), never raises
27
+ on an outage.
28
+ - `warm_session(…, issuer=, jwks=)`, as `verify_session` takes them. With
29
+ `jwks` given nothing is fetched and `keys` reads `"kept"`.
30
+
31
+ ### Changed
32
+
33
+ - `issuer=` on `verify_session` also names where the key set is fetched:
34
+ `<issuer>/.well-known/jwks.json`, as `@orangecheck/me-client` fetches it.
35
+ Before, the key set was always ochk.io's. The issuer must be one origin
36
+ (https, or http on localhost only; no path, query, fragment or user name),
37
+ or it raises `ValueError`; a trailing slash names the same issuer. A `jwks=`
38
+ given explicitly wins, and nothing is fetched.
39
+ - A token whose `kid` is not in the key set held, while the latest fetch of
40
+ that set failed, raises `InvalidSession("key_set_unavailable")`: the key may
41
+ have rotated in during the outage. Once a fetch succeeds it is `unknown_key`
42
+ again. The same for webhooks.
43
+ - `RevocationList(project_key, signing_secret)` raises `ValueError` unless each
44
+ is one non-empty string. An empty one signs requests me.ochk.io refuses, so
45
+ every write would answer `revocations_unavailable` for as long as the
46
+ process runs.
47
+
48
+ ## [3.1.0] — 2026-10-23
49
+
50
+ ### Changed
51
+
52
+ - `verify_session` accepts a token that carries `rh` only when `rh` is a
53
+ non-empty string (`InvalidSession("claims")` otherwise, with
54
+ `require_handle=False`) and `aud` is one string (`InvalidSession("audience")`
55
+ otherwise). A token without `rh` verifies as before.
56
+ - `RevocationList.status(rh, aud, iat)` answers `"revoked"` for a handle that
57
+ is not a non-empty string, or one given without a non-empty string `aud`.
58
+ - The same as `@orangecheck/auth-core` 2.15.0 and `@orangecheck/me-client`
59
+ 0.40.1, held to `me-client/test-vectors/integrator.json`.
60
+
61
+ ### Added
62
+
63
+ - `RevocationList.status_for(claims)`: the same answer from a token's claims,
64
+ telling a missing `rh` (`"live"`) from `"rh": null` (`"revoked"`), as
65
+ auth-core's `integratorRevocationCheck` does. `verify_session` uses it.
66
+ - `Session.rh`: the token's revocation handle.
67
+
7
68
  ## [3.0.0] — 2026-10-23
8
69
 
9
70
  ### Changed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: orangecheck
3
- Version: 3.0.0
3
+ Version: 3.2.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
@@ -274,6 +274,46 @@ def keep_warm() -> None:
274
274
  threading.Thread(target=keep_warm, daemon=True).start()
275
275
  ```
276
276
 
277
+ `check_oc_session` (3.2.0 or later) takes the same arguments and gives the HTTP
278
+ answer instead of raising, with the status and body `@orangecheck/me-client`'s
279
+ adapters send: 401 for no token, a bad one or one the person ended; 403
280
+ `bond_required`; 503 while the list, the key set or the rule can't be read, so
281
+ the client tries again rather than signing the person out.
282
+
283
+ ```python
284
+ from orangecheck import check_oc_session
285
+
286
+ checked = check_oc_session(bearer, "https://your-site.example",
287
+ revocations=REVOCATIONS, policy=POLICY, method=request.method)
288
+ if not checked.ok:
289
+ return JSONResponse(checked.body, status_code=checked.status)
290
+ session = checked.session
291
+ ```
292
+
293
+ When the token starts your own session, spend its `jti` so it starts only one,
294
+ then end it at ochk.io (3.2.0 or later). `store` is yours: anything with an
295
+ atomic `add(jti, exp) -> bool` that every server shares, such as a unique row
296
+ or Redis `SET NX`. `MemoryJtiStore` is for tests and a single process.
297
+
298
+ ```python
299
+ from orangecheck import revoke_token, spend_once
300
+
301
+ if not spend_once(session.jti, session.exp, store): # a repeat, or expired
302
+ return JSONResponse({"ok": False, "error": "token_used"}, status_code=401)
303
+ start_your_session(session)
304
+ revoke_token(token) # TokensRevoked or RevokeRefusal, never an exception
305
+ ```
306
+
307
+ `spend_once_async` takes a store whose `add` is a coroutine (redis.asyncio, an
308
+ async ORM). ochk.io ends at most 60 calls a minute per IP: queue a
309
+ `RevokeRefusal` (`rate_limited` or `unavailable`) and try again, since the
310
+ token stays valid until it expires.
311
+
312
+ `issuer=` on `verify_session`, `check_oc_session`, `warm_session` and
313
+ `revoke_token` names another auth host, such as a test stack's (3.2.0 or
314
+ later): keys are fetched from `<issuer>/.well-known/jwks.json`, over https
315
+ (http only on localhost). `jwks=` given explicitly wins, and nothing is fetched.
316
+
277
317
  The full guide is at [ochk.io/docs/sdk/python](https://ochk.io/docs/sdk/python).
278
318
 
279
319
  ## Keep your own login: OC Connect
@@ -237,6 +237,46 @@ def keep_warm() -> None:
237
237
  threading.Thread(target=keep_warm, daemon=True).start()
238
238
  ```
239
239
 
240
+ `check_oc_session` (3.2.0 or later) takes the same arguments and gives the HTTP
241
+ answer instead of raising, with the status and body `@orangecheck/me-client`'s
242
+ adapters send: 401 for no token, a bad one or one the person ended; 403
243
+ `bond_required`; 503 while the list, the key set or the rule can't be read, so
244
+ the client tries again rather than signing the person out.
245
+
246
+ ```python
247
+ from orangecheck import check_oc_session
248
+
249
+ checked = check_oc_session(bearer, "https://your-site.example",
250
+ revocations=REVOCATIONS, policy=POLICY, method=request.method)
251
+ if not checked.ok:
252
+ return JSONResponse(checked.body, status_code=checked.status)
253
+ session = checked.session
254
+ ```
255
+
256
+ When the token starts your own session, spend its `jti` so it starts only one,
257
+ then end it at ochk.io (3.2.0 or later). `store` is yours: anything with an
258
+ atomic `add(jti, exp) -> bool` that every server shares, such as a unique row
259
+ or Redis `SET NX`. `MemoryJtiStore` is for tests and a single process.
260
+
261
+ ```python
262
+ from orangecheck import revoke_token, spend_once
263
+
264
+ if not spend_once(session.jti, session.exp, store): # a repeat, or expired
265
+ return JSONResponse({"ok": False, "error": "token_used"}, status_code=401)
266
+ start_your_session(session)
267
+ revoke_token(token) # TokensRevoked or RevokeRefusal, never an exception
268
+ ```
269
+
270
+ `spend_once_async` takes a store whose `add` is a coroutine (redis.asyncio, an
271
+ async ORM). ochk.io ends at most 60 calls a minute per IP: queue a
272
+ `RevokeRefusal` (`rate_limited` or `unavailable`) and try again, since the
273
+ token stays valid until it expires.
274
+
275
+ `issuer=` on `verify_session`, `check_oc_session`, `warm_session` and
276
+ `revoke_token` names another auth host, such as a test stack's (3.2.0 or
277
+ later): keys are fetched from `<issuer>/.well-known/jwks.json`, over https
278
+ (http only on localhost). `jwks=` given explicitly wins, and nothing is fetched.
279
+
240
280
  The full guide is at [ochk.io/docs/sdk/python](https://ochk.io/docs/sdk/python).
241
281
 
242
282
  ## Keep your own login: OC Connect
@@ -83,11 +83,13 @@ from .integrator import (
83
83
  InvalidWebhook,
84
84
  RevocationList,
85
85
  Session,
86
+ SessionCheck,
86
87
  SessionEnded,
87
88
  SignInPolicy,
88
89
  WarmPart,
89
90
  WarmResult,
90
91
  bond_meets,
92
+ check_oc_session,
91
93
  read_bond_claim,
92
94
  revocation_key,
93
95
  sign_event,
@@ -95,6 +97,15 @@ from .integrator import (
95
97
  verify_webhook,
96
98
  warm_session,
97
99
  )
100
+ from .tokens import (
101
+ JtiStore,
102
+ MemoryJtiStore,
103
+ RevokeRefusal,
104
+ TokensRevoked,
105
+ revoke_token,
106
+ spend_once,
107
+ spend_once_async,
108
+ )
98
109
  from .top_level import challenge_issue, challenge_verify, check, discover, verify
99
110
  from .types import (
100
111
  AttestationSummary,
@@ -145,6 +156,8 @@ __all__ = [
145
156
  "BOND_MAX_WINDOW_SECONDS",
146
157
  # ochk.app sign-in, billable events and webhooks, for an integrator's backend
147
158
  "verify_session",
159
+ "check_oc_session",
160
+ "SessionCheck",
148
161
  "warm_session",
149
162
  "WarmResult",
150
163
  "WarmPart",
@@ -160,6 +173,14 @@ __all__ = [
160
173
  "BondRequired",
161
174
  "bond_meets",
162
175
  "read_bond_claim",
176
+ # After a sign-in: one session per token, then end the token at ochk.io
177
+ "spend_once",
178
+ "spend_once_async",
179
+ "JtiStore",
180
+ "MemoryJtiStore",
181
+ "revoke_token",
182
+ "TokensRevoked",
183
+ "RevokeRefusal",
163
184
  # OC Connect, for a site that keeps its own login
164
185
  "connect_provision",
165
186
  "connect_claim_link",
@@ -184,7 +205,7 @@ __all__ = [
184
205
  "VerificationError",
185
206
  ]
186
207
 
187
- __version__ = "3.0.0"
208
+ __version__ = "3.2.0"
188
209
 
189
210
  # OC Pledge submodule — sibling primitive for forward-looking commitments
190
211
  # bound to a Bitcoin address. Imported here so consumers can write:
@@ -35,7 +35,7 @@ import weakref
35
35
  from collections.abc import Mapping
36
36
  from dataclasses import dataclass, field
37
37
  from typing import Any, Optional, Union
38
- from urllib.parse import quote
38
+ from urllib.parse import quote, urlsplit
39
39
 
40
40
  import httpx
41
41
  from cryptography.exceptions import InvalidSignature
@@ -93,6 +93,8 @@ class Session:
93
93
  #: Coin backing, when the person backed their account (see require-bond).
94
94
  oc_bond: Optional[dict[str, Any]] = None
95
95
  claims: dict[str, Any] = field(default_factory=dict)
96
+ #: The token's revocation handle on its audience's list of ended sessions.
97
+ rh: Optional[str] = None
96
98
 
97
99
 
98
100
  # ─── key sets ────────────────────────────────────────────────────────────
@@ -254,11 +256,56 @@ class _KeySet:
254
256
  self._forced_at, self._forced_wall = _clock(), time.time()
255
257
  self._fetch()
256
258
  key = self._keys.get(kid)
259
+ # A key may have rotated in while the set can't be fetched: that is an
260
+ # outage, not a token the set does not know.
261
+ if key is None and self._error is not None:
262
+ raise ValueError(f"key set unavailable: {self._error}")
257
263
  return key
258
264
 
259
265
 
260
266
  _session_keys = _KeySet(SESSION_JWKS_URL)
261
267
  _webhook_keys = _KeySet(WEBHOOK_JWKS_URL)
268
+ #: Key sets of issuers other than ochk.io (a test stack's auth host), by issuer.
269
+ _issuer_keys: dict[str, _KeySet] = {}
270
+ _LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
271
+
272
+
273
+ def _issuer_origin(issuer: str) -> str:
274
+ """An issuer as one origin, ``scheme://host[:port]``: https, or http on this machine only.
275
+ A path, a query, a fragment or a user name would send requests somewhere else on the
276
+ host (or carry credentials), so each is refused. A trailing slash is allowed."""
277
+ try:
278
+ parts = urlsplit(issuer) if isinstance(issuer, str) else None
279
+ except ValueError:
280
+ parts = None
281
+ if (
282
+ parts is None
283
+ or any(c in issuer for c in "?#@\\")
284
+ or parts.path not in ("", "/")
285
+ or not parts.hostname
286
+ or not (parts.scheme == "https" or (parts.scheme == "http" and parts.hostname in _LOCAL_HOSTS))
287
+ ):
288
+ raise ValueError(
289
+ f"issuer must be one https origin (http only on localhost), such as https://ochk.io, got {issuer!r}; "
290
+ "pass jwks= to verify offline"
291
+ )
292
+ return f"{parts.scheme}://{parts.netloc}"
293
+
294
+
295
+ def _issuer_url(issuer: str) -> str:
296
+ """Where an issuer's key set is: ``<issuer>/.well-known/jwks.json``."""
297
+ return _issuer_origin(issuer) + "/.well-known/jwks.json"
298
+
299
+
300
+ def _keys_for(issuer: str) -> _KeySet:
301
+ """The key set that signs ``issuer``'s tokens, as auth-core fetches it."""
302
+ url = _issuer_url(issuer)
303
+ if url == SESSION_JWKS_URL:
304
+ return _session_keys
305
+ keys = _issuer_keys.get(url)
306
+ if keys is None:
307
+ keys = _issuer_keys.setdefault(url, _KeySet(url))
308
+ return keys
262
309
 
263
310
 
264
311
  def _b64url(s: str) -> bytes:
@@ -422,10 +469,16 @@ class RevocationList:
422
469
  ``status(rh, aud, iat)`` is ``"revoked"``, ``"live"``, or ``"unverified"`` when
423
470
  no list younger than ten minutes (by its own ``at``) could be read: then reads
424
471
  may go on, but a write should not. A token without ``rh`` is ``"live"``: it is
425
- checked by its signature alone.
472
+ checked by its signature alone. A handle that is not a non-empty string, or
473
+ comes without one string ``aud``, is ``"revoked"``: no list can end it.
426
474
  """
427
475
 
428
476
  def __init__(self, project_key: str, signing_secret: str, *, url: str = REVOCATIONS_URL):
477
+ # An empty key or secret signs requests me.ochk.io refuses, so every write
478
+ # would be refused for as long as the process runs. Say so here instead.
479
+ for name, value in (("project_key", project_key), ("signing_secret", signing_secret)):
480
+ if not isinstance(value, str) or not value.strip():
481
+ raise ValueError(f"RevocationList: {name} must be one non-empty string")
429
482
  self._project_key = project_key
430
483
  self._secret = signing_secret
431
484
  self._base = url[: -len("/api/integrator/revocations")] if url.endswith("/api/integrator/revocations") else url
@@ -451,8 +504,23 @@ class RevocationList:
451
504
  return lst
452
505
 
453
506
  def status(self, rh: Optional[str], aud: Optional[str], iat: Optional[float]) -> str:
454
- if not isinstance(rh, str) or not rh or not isinstance(aud, str) or not aud:
507
+ if rh is None:
508
+ return "live"
509
+ return self._status(rh, aud, iat)
510
+
511
+ def status_for(self, claims: Mapping[str, Any]) -> str:
512
+ """
513
+ ``status`` for a token's claims, as ``integratorRevocationCheck`` reads them: a
514
+ token with no ``rh`` key is ``"live"``, and ``"rh": null`` is a handle that is
515
+ not a string, so ``"revoked"``. :func:`verify_session` uses this.
516
+ """
517
+ if "rh" not in claims:
455
518
  return "live"
519
+ return self._status(claims["rh"], claims.get("aud"), claims.get("iat"))
520
+
521
+ def _status(self, rh: Any, aud: Any, iat: Optional[float]) -> str:
522
+ if not isinstance(rh, str) or not rh or not isinstance(aud, str) or not aud:
523
+ return "revoked"
456
524
  return self._list(aud).status(rh, iat)
457
525
 
458
526
 
@@ -615,14 +683,18 @@ def warm_session(
615
683
  *,
616
684
  revocations: Optional[RevocationList] = None,
617
685
  policy: Optional[SignInPolicy] = None,
686
+ issuer: str = SESSION_ISSUER,
687
+ jwks: Optional[Mapping[str, Any]] = None,
618
688
  ) -> WarmResult:
619
689
  """
620
690
  Fetch now what :func:`verify_session` with the same arguments would otherwise
621
- fetch inside a request: ochk.io's key set, your project's sign-in requirement
622
- and the revocation list for each audience, each only when its copy is due. Call
623
- it at startup and then every ten seconds from a background thread, in each
624
- process. It never raises: it returns a :class:`WarmResult` saying what it
625
- fetched, kept or failed to read, and why (``result.ok``, ``result.failures()``).
691
+ fetch inside a request: the issuer's key set (ochk.io's by default), your
692
+ project's sign-in requirement and the revocation list for each audience, each
693
+ only when its copy is due. With ``jwks`` given, no key set is fetched and
694
+ ``keys`` reads ``"kept"``. Call it at startup and then every ten seconds from a
695
+ background thread, in each process. It never raises: it returns a
696
+ :class:`WarmResult` saying what it fetched, kept or failed to read, and why
697
+ (``result.ok``, ``result.failures()``).
626
698
  """
627
699
 
628
700
  # A warming loop must outlive anything one of these meets.
@@ -639,7 +711,7 @@ def warm_session(
639
711
  if isinstance(aud, str) and aud:
640
712
  lists[aud] = part(lambda aud=aud: revocations._list(aud).warm())
641
713
  return WarmResult(
642
- keys=part(lambda: _session_keys.warm()),
714
+ keys=_KEPT if jwks is not None else part(lambda: _keys_for(issuer).warm()),
643
715
  policy=part(policy._warm) if policy is not None else None,
644
716
  lists=lists,
645
717
  )
@@ -665,8 +737,9 @@ def verify_session(
665
737
  (``https://your-site.example``, or ``http://localhost:5173`` while you
666
738
  develop). A token issued to any other origin, or a family token with no
667
739
  ``aud`` at all, is refused. The key set is fetched from
668
- ``https://ochk.io/.well-known/jwks.json`` and cached for an hour; pass
669
- ``jwks`` to verify offline.
740
+ ``<issuer>/.well-known/jwks.json`` (``https://ochk.io``'s by default, over
741
+ https; http only on localhost) and cached for an hour; pass ``jwks`` to
742
+ verify offline, and it wins over the fetch.
670
743
 
671
744
  Raises :class:`InvalidSession` on any failure. The token proves who signed
672
745
  in until it expires (up to 30 days). Pass ``revocations`` (a
@@ -709,11 +782,12 @@ def verify_session(
709
782
  raise InvalidSession("unknown_key") from err
710
783
  retired_at = _retired_at(dict(jwks)).get(kid)
711
784
  else:
785
+ keys = _keys_for(issuer)
712
786
  try:
713
- key = _session_keys.get(kid)
787
+ key = keys.get(kid)
714
788
  except (httpx.HTTPError, ValueError) as err:
715
789
  raise InvalidSession("key_set_unavailable") from err
716
- retired_at = _session_keys.retired_at(kid)
790
+ retired_at = keys.retired_at(kid)
717
791
  if key is None:
718
792
  raise InvalidSession("unknown_key")
719
793
  try:
@@ -721,7 +795,8 @@ def verify_session(
721
795
  except InvalidSignature as err:
722
796
  raise InvalidSession("signature") from err
723
797
 
724
- if payload.get("iss") != issuer:
798
+ # A trailing slash on the issuer asked for names the same issuer.
799
+ if payload.get("iss") not in (issuer, issuer.rstrip("/")):
725
800
  raise InvalidSession("issuer")
726
801
  now = time.time()
727
802
  exp = payload.get("exp")
@@ -750,10 +825,16 @@ def verify_session(
750
825
  rh = payload.get("rh")
751
826
  if require_handle and not (isinstance(rh, str) and rh):
752
827
  raise InvalidSession("no_session_handle")
828
+ # A handle is kept on one audience's list, so a token carrying one names
829
+ # one audience, as a string; with no handle the token is checked as before.
830
+ if "rh" in payload:
831
+ if not (isinstance(rh, str) and rh):
832
+ raise InvalidSession("claims")
833
+ if not isinstance(aud, str):
834
+ raise InvalidSession("audience")
753
835
 
754
836
  if revocations is not None:
755
- token_aud = aud if isinstance(aud, str) else None
756
- state = revocations.status(payload.get("rh"), token_aud, iat)
837
+ state = revocations.status_for(payload)
757
838
  if state == "revoked":
758
839
  raise SessionEnded()
759
840
  if state == "unverified" and (method or "").upper() not in _SAFE_METHODS:
@@ -783,9 +864,108 @@ def verify_session(
783
864
  exp=int(exp),
784
865
  oc_bond=bond if isinstance(bond, dict) else None,
785
866
  claims=payload,
867
+ rh=rh if isinstance(rh, str) else None,
786
868
  )
787
869
 
788
870
 
871
+ #: Can't tell right now: the client should try again, never sign the person out.
872
+ _UNAVAILABLE = frozenset({"revocations_unavailable", "key_set_unavailable", "bond_policy_unavailable"})
873
+
874
+
875
+ @dataclass(frozen=True)
876
+ class SessionCheck:
877
+ """
878
+ One request's answer, as ``@orangecheck/me-client``'s ``withOcAuth`` (with
879
+ ``required: true``) gives it. ``status`` is 200, with ``session``, when the
880
+ person is signed in. Otherwise it is the HTTP status to answer, and ``body``
881
+ the JSON to send:
882
+
883
+ - 401 ``unauthenticated``: no token, one that does not verify, or one the
884
+ person ended everywhere;
885
+ - 401 ``no_session_handle``: a token sign out everywhere could not end;
886
+ - 403 ``bond_required``: the account is not backed enough here, with
887
+ ``need``, ``have`` and ``back_url``;
888
+ - 503 ``revocations_unavailable`` (a write while the list of ended sessions
889
+ can't be read), ``key_set_unavailable`` or ``bond_policy_unavailable``:
890
+ can't tell right now, so the client tries again instead of signing out;
891
+ - 500 ``unknown_project_key``: the :class:`SignInPolicy` names no project.
892
+ """
893
+
894
+ status: int
895
+ session: Optional[Session] = None
896
+ body: Optional[dict[str, Any]] = None
897
+
898
+ @property
899
+ def ok(self) -> bool:
900
+ return self.status == 200
901
+
902
+
903
+ def check_oc_session(
904
+ token: Optional[str],
905
+ audience: Union[str, list[str]],
906
+ *,
907
+ jwks: Optional[Mapping[str, Any]] = None,
908
+ issuer: str = SESSION_ISSUER,
909
+ leeway: int = 0,
910
+ revocations: Optional[RevocationList] = None,
911
+ method: Optional[str] = None,
912
+ require_bond: Optional[Mapping[str, Any]] = None,
913
+ policy: Optional[SignInPolicy] = None,
914
+ require_handle: bool = True,
915
+ ) -> SessionCheck:
916
+ """
917
+ :func:`verify_session` as the HTTP answer for a request: a :class:`SessionCheck`
918
+ with the status and body me-client's adapters send, held to the same vectors
919
+ (``me-client/test-vectors/server-helpers.json``). ``token`` is the request's
920
+ token, or None when it brought none. It takes ``verify_session``'s arguments
921
+ and raises only on a mistake in the call itself.
922
+
923
+ checked = check_oc_session(bearer, "https://your-site.example",
924
+ revocations=revocations, method=request.method)
925
+ if not checked.ok:
926
+ return JSONResponse(checked.body, status_code=checked.status)
927
+ session = checked.session
928
+ """
929
+ if not isinstance(require_handle, bool):
930
+ raise TypeError("require_handle must be True or False")
931
+ if jwks is None:
932
+ _issuer_url(issuer)
933
+ if not isinstance(token, str) or not token:
934
+ return SessionCheck(401, body={"ok": False, "reason": "unauthenticated"})
935
+ try:
936
+ session = verify_session(
937
+ token,
938
+ audience,
939
+ jwks=jwks,
940
+ issuer=issuer,
941
+ leeway=leeway,
942
+ revocations=revocations,
943
+ method=method,
944
+ require_bond=require_bond,
945
+ policy=policy,
946
+ require_handle=require_handle,
947
+ )
948
+ except BondRequired as err:
949
+ return SessionCheck(
950
+ 403,
951
+ body={
952
+ "ok": False,
953
+ "reason": "bond_required",
954
+ "need": dict(err.need),
955
+ "have": dict(err.have) if err.have is not None else None,
956
+ "back_url": err.back_url,
957
+ },
958
+ )
959
+ except InvalidSession as err:
960
+ if err.reason in _UNAVAILABLE:
961
+ return SessionCheck(503, body={"ok": False, "reason": err.reason})
962
+ if err.reason == "unknown_project_key":
963
+ return SessionCheck(500, body={"ok": False, "reason": err.reason})
964
+ reason = "no_session_handle" if err.reason == "no_session_handle" else "unauthenticated"
965
+ return SessionCheck(401, body={"ok": False, "reason": reason})
966
+ return SessionCheck(200, session=session)
967
+
968
+
789
969
  # ─── billable events ─────────────────────────────────────────────────────
790
970
 
791
971