orangecheck 3.1.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.
- {orangecheck-3.1.0 → orangecheck-3.2.0}/CHANGELOG.md +41 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/PKG-INFO +41 -1
- {orangecheck-3.1.0 → orangecheck-3.2.0}/README.md +40 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/__init__.py +22 -1
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/integrator.py +167 -12
- orangecheck-3.2.0/orangecheck/tokens.py +200 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/pyproject.toml +1 -1
- orangecheck-3.2.0/tests/test_server_helpers.py +383 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/.gitignore +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/__main__.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/address.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/bond.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/canonical.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/client.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/connect.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/errors.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/pledge/__init__.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/pledge/bond.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/pledge/canonical.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/pledge/delegation.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/pledge/envelopes.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/pledge/resolution.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/pledge/state.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/py.typed +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/top_level.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/types.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/orangecheck/verify_sig.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/fixtures/bip137-parity.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/fixtures/bip322-js-6.1.8.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/fixtures/bip322-official-basic.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/fixtures/bip322-official-generated.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/pledge/__init__.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/pledge/test_authority.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/pledge/test_create_signers.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/pledge/test_delegation.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/pledge/test_vectors.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/pledge/test_wrap.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_address.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_bip322_official.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_client.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_client_failure_modes.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_conformance.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_connect.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_integrator_vectors.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_ripemd160.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/test_signature_parity.py +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/index.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv01.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv02.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv03.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv04.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv05.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv06.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv07.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv08.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv09.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv10.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv11.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv12.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv13.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv14.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv15.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv16.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv17.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv18.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv19.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv20.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv21.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv22.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv23.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv24.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv25.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv26.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv27.json +0 -0
- {orangecheck-3.1.0 → orangecheck-3.2.0}/tests/vectors/tv28.json +0 -0
|
@@ -4,6 +4,47 @@ 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
|
+
|
|
7
48
|
## [3.1.0] — 2026-10-23
|
|
8
49
|
|
|
9
50
|
### Changed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: orangecheck
|
|
3
|
-
Version: 3.
|
|
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.
|
|
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
|
|
@@ -256,11 +256,56 @@ class _KeySet:
|
|
|
256
256
|
self._forced_at, self._forced_wall = _clock(), time.time()
|
|
257
257
|
self._fetch()
|
|
258
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}")
|
|
259
263
|
return key
|
|
260
264
|
|
|
261
265
|
|
|
262
266
|
_session_keys = _KeySet(SESSION_JWKS_URL)
|
|
263
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
|
|
264
309
|
|
|
265
310
|
|
|
266
311
|
def _b64url(s: str) -> bytes:
|
|
@@ -429,6 +474,11 @@ class RevocationList:
|
|
|
429
474
|
"""
|
|
430
475
|
|
|
431
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")
|
|
432
482
|
self._project_key = project_key
|
|
433
483
|
self._secret = signing_secret
|
|
434
484
|
self._base = url[: -len("/api/integrator/revocations")] if url.endswith("/api/integrator/revocations") else url
|
|
@@ -633,14 +683,18 @@ def warm_session(
|
|
|
633
683
|
*,
|
|
634
684
|
revocations: Optional[RevocationList] = None,
|
|
635
685
|
policy: Optional[SignInPolicy] = None,
|
|
686
|
+
issuer: str = SESSION_ISSUER,
|
|
687
|
+
jwks: Optional[Mapping[str, Any]] = None,
|
|
636
688
|
) -> WarmResult:
|
|
637
689
|
"""
|
|
638
690
|
Fetch now what :func:`verify_session` with the same arguments would otherwise
|
|
639
|
-
fetch inside a request:
|
|
640
|
-
and the revocation list for each audience, each
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
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()``).
|
|
644
698
|
"""
|
|
645
699
|
|
|
646
700
|
# A warming loop must outlive anything one of these meets.
|
|
@@ -657,7 +711,7 @@ def warm_session(
|
|
|
657
711
|
if isinstance(aud, str) and aud:
|
|
658
712
|
lists[aud] = part(lambda aud=aud: revocations._list(aud).warm())
|
|
659
713
|
return WarmResult(
|
|
660
|
-
keys=part(lambda:
|
|
714
|
+
keys=_KEPT if jwks is not None else part(lambda: _keys_for(issuer).warm()),
|
|
661
715
|
policy=part(policy._warm) if policy is not None else None,
|
|
662
716
|
lists=lists,
|
|
663
717
|
)
|
|
@@ -683,8 +737,9 @@ def verify_session(
|
|
|
683
737
|
(``https://your-site.example``, or ``http://localhost:5173`` while you
|
|
684
738
|
develop). A token issued to any other origin, or a family token with no
|
|
685
739
|
``aud`` at all, is refused. The key set is fetched from
|
|
686
|
-
|
|
687
|
-
``jwks`` to
|
|
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.
|
|
688
743
|
|
|
689
744
|
Raises :class:`InvalidSession` on any failure. The token proves who signed
|
|
690
745
|
in until it expires (up to 30 days). Pass ``revocations`` (a
|
|
@@ -727,11 +782,12 @@ def verify_session(
|
|
|
727
782
|
raise InvalidSession("unknown_key") from err
|
|
728
783
|
retired_at = _retired_at(dict(jwks)).get(kid)
|
|
729
784
|
else:
|
|
785
|
+
keys = _keys_for(issuer)
|
|
730
786
|
try:
|
|
731
|
-
key =
|
|
787
|
+
key = keys.get(kid)
|
|
732
788
|
except (httpx.HTTPError, ValueError) as err:
|
|
733
789
|
raise InvalidSession("key_set_unavailable") from err
|
|
734
|
-
retired_at =
|
|
790
|
+
retired_at = keys.retired_at(kid)
|
|
735
791
|
if key is None:
|
|
736
792
|
raise InvalidSession("unknown_key")
|
|
737
793
|
try:
|
|
@@ -739,7 +795,8 @@ def verify_session(
|
|
|
739
795
|
except InvalidSignature as err:
|
|
740
796
|
raise InvalidSession("signature") from err
|
|
741
797
|
|
|
742
|
-
|
|
798
|
+
# A trailing slash on the issuer asked for names the same issuer.
|
|
799
|
+
if payload.get("iss") not in (issuer, issuer.rstrip("/")):
|
|
743
800
|
raise InvalidSession("issuer")
|
|
744
801
|
now = time.time()
|
|
745
802
|
exp = payload.get("exp")
|
|
@@ -811,6 +868,104 @@ def verify_session(
|
|
|
811
868
|
)
|
|
812
869
|
|
|
813
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
|
+
|
|
814
969
|
# ─── billable events ─────────────────────────────────────────────────────
|
|
815
970
|
|
|
816
971
|
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Two things a site's own backend does with the token from the sign-in popup,
|
|
3
|
+
once it has verified it (ochk.io/docs/me/sdk):
|
|
4
|
+
|
|
5
|
+
from orangecheck import spend_once, revoke_token
|
|
6
|
+
|
|
7
|
+
if not spend_once(session.jti, session.exp, store): # a repeat, or expired
|
|
8
|
+
return refuse()
|
|
9
|
+
start_my_own_session(session)
|
|
10
|
+
revoke_token(token) # ended at the auth host
|
|
11
|
+
|
|
12
|
+
``spend_once`` keeps a token from starting a second session; ``revoke_token``
|
|
13
|
+
ends it at the auth host once the site's own session has taken over. Only a
|
|
14
|
+
mistake in the call itself raises, before anything is read or sent. The same
|
|
15
|
+
calls and results as ``@orangecheck/me-client/server``, held to
|
|
16
|
+
``me-client/test-vectors/server-helpers.json``.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import inspect
|
|
22
|
+
import math
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from typing import Any, Literal, Protocol, Union
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
|
|
30
|
+
from .integrator import SESSION_ISSUER, _issuer_origin
|
|
31
|
+
|
|
32
|
+
_DEFAULT_TIMEOUT = 5.0
|
|
33
|
+
_MAX_TIMEOUT = 30.0
|
|
34
|
+
#: What the auth host's /api/auth/revoke takes in one call.
|
|
35
|
+
_MAX_TOKENS = 8
|
|
36
|
+
_MAX_TOKEN_LENGTH = 4096
|
|
37
|
+
_MAX_SAFE_INTEGER = 2**53 - 1
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class JtiStore(Protocol):
|
|
41
|
+
"""
|
|
42
|
+
Where you record the ``jti`` of each token you accepted, until it expires.
|
|
43
|
+
Yours to provide, shared by every server that accepts sign-ins: a unique row
|
|
44
|
+
in your database, or Redis ``SET jti 1 NX EXAT exp``. ``add`` must be atomic:
|
|
45
|
+
True when it recorded the jti, False when the jti was there already.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def add(self, jti: str, exp: int) -> bool: ...
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class MemoryJtiStore:
|
|
52
|
+
"""
|
|
53
|
+
A :class:`JtiStore` in this process's memory: for tests and a single process.
|
|
54
|
+
Two servers, or a restart, each have their own, so a token could start a
|
|
55
|
+
session on each: in production, use a store they share.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(self) -> None:
|
|
59
|
+
self._spent: dict[str, float] = {}
|
|
60
|
+
self._lock = threading.Lock()
|
|
61
|
+
|
|
62
|
+
def add(self, jti: str, exp: Union[int, float]) -> bool:
|
|
63
|
+
now = math.floor(time.time())
|
|
64
|
+
with self._lock:
|
|
65
|
+
for k in [k for k, until in self._spent.items() if until <= now]:
|
|
66
|
+
del self._spent[k]
|
|
67
|
+
if jti in self._spent:
|
|
68
|
+
return False
|
|
69
|
+
self._spent[jti] = exp
|
|
70
|
+
return True
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _spend_check(jti: Any, exp: Any, store: Any) -> Any:
|
|
74
|
+
"""The store's ``add``, once the call is right; raises TypeError otherwise."""
|
|
75
|
+
if not isinstance(jti, str) or not jti:
|
|
76
|
+
raise TypeError("spend_once: jti must be one non-empty string")
|
|
77
|
+
if isinstance(exp, bool) or not isinstance(exp, (int, float)) or not math.isfinite(exp):
|
|
78
|
+
raise TypeError("spend_once: exp must be the token's expiry, in seconds")
|
|
79
|
+
add = getattr(store, "add", None)
|
|
80
|
+
if not callable(add):
|
|
81
|
+
raise TypeError("spend_once: store must have add(jti, exp)")
|
|
82
|
+
return add
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _spent(answer: Any) -> bool:
|
|
86
|
+
if not isinstance(answer, bool):
|
|
87
|
+
raise TypeError("spend_once: store.add must answer True or False")
|
|
88
|
+
return answer
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def spend_once(jti: str, exp: Union[int, float], store: JtiStore) -> bool:
|
|
92
|
+
"""
|
|
93
|
+
Spend a verified token's ``jti`` so it starts one session: True the first
|
|
94
|
+
time, False for a repeat or a token that has expired (``exp``, in seconds, at
|
|
95
|
+
or before now). Call it after verifying the token and before starting your
|
|
96
|
+
own session; on False, refuse the sign-in. A store that fails raises, so the
|
|
97
|
+
sign-in fails closed. With an async store, use :func:`spend_once_async`.
|
|
98
|
+
"""
|
|
99
|
+
add = _spend_check(jti, exp, store)
|
|
100
|
+
if exp <= math.floor(time.time()):
|
|
101
|
+
return False
|
|
102
|
+
return _spent(add(jti, exp))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
async def spend_once_async(jti: str, exp: Union[int, float], store: Any) -> bool:
|
|
106
|
+
""":func:`spend_once` for an async route: ``store.add`` may be a coroutine
|
|
107
|
+
(redis.asyncio, an async ORM) or a plain function."""
|
|
108
|
+
add = _spend_check(jti, exp, store)
|
|
109
|
+
if exp <= math.floor(time.time()):
|
|
110
|
+
return False
|
|
111
|
+
answer = add(jti, exp)
|
|
112
|
+
if inspect.isawaitable(answer):
|
|
113
|
+
answer = await answer
|
|
114
|
+
return _spent(answer)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class TokensRevoked:
|
|
119
|
+
"""The auth host ended ``revoked`` tokens: 0 when it could not read one as its own
|
|
120
|
+
(expired already, or signed elsewhere)."""
|
|
121
|
+
|
|
122
|
+
revoked: int
|
|
123
|
+
ok: Literal[True] = True
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass(frozen=True)
|
|
127
|
+
class RevokeRefusal:
|
|
128
|
+
"""The auth host did not end them. ``reason`` is ``rate_limited``, ``bad_request``
|
|
129
|
+
or ``unavailable`` (an outage, a timeout, or an answer this SDK can't read: the
|
|
130
|
+
token still ends when it expires). ``status`` is the HTTP status, 0 when nothing
|
|
131
|
+
came back."""
|
|
132
|
+
|
|
133
|
+
reason: str
|
|
134
|
+
status: int
|
|
135
|
+
ok: Literal[False] = False
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def revoke_token(
|
|
139
|
+
token: Union[str, list[str]],
|
|
140
|
+
*,
|
|
141
|
+
issuer: str = SESSION_ISSUER,
|
|
142
|
+
timeout: float = _DEFAULT_TIMEOUT,
|
|
143
|
+
) -> Union[TokensRevoked, RevokeRefusal]:
|
|
144
|
+
"""
|
|
145
|
+
End a sign-in token at the auth host (``POST <issuer>/api/auth/revoke``), on
|
|
146
|
+
every site that reads the list of ended sessions. Holding a token is the
|
|
147
|
+
authority to end it; nothing else is sent. Call it once your own session has
|
|
148
|
+
taken over. Takes one token or a list of up to eight. An outage is a result,
|
|
149
|
+
never an exception, so it can't break a sign-in.
|
|
150
|
+
"""
|
|
151
|
+
tokens: Any = [token] if isinstance(token, str) else list(token) if isinstance(token, (list, tuple)) else None
|
|
152
|
+
if (
|
|
153
|
+
tokens is None
|
|
154
|
+
or not 1 <= len(tokens) <= _MAX_TOKENS
|
|
155
|
+
or not all(isinstance(t, str) and 0 < len(t) <= _MAX_TOKEN_LENGTH for t in tokens)
|
|
156
|
+
):
|
|
157
|
+
raise ValueError(
|
|
158
|
+
f"revoke_token: pass one token, or 1 to {_MAX_TOKENS}, each a non-empty string "
|
|
159
|
+
f"of at most {_MAX_TOKEN_LENGTH} characters"
|
|
160
|
+
)
|
|
161
|
+
try:
|
|
162
|
+
url = _issuer_origin(issuer) + "/api/auth/revoke"
|
|
163
|
+
except ValueError as err:
|
|
164
|
+
raise ValueError(f"revoke_token: {err}") from err
|
|
165
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not 0 < timeout <= _MAX_TIMEOUT:
|
|
166
|
+
raise ValueError(f"revoke_token: timeout must be above 0 and at most {_MAX_TIMEOUT:g} seconds")
|
|
167
|
+
try:
|
|
168
|
+
resp = httpx.post(
|
|
169
|
+
url,
|
|
170
|
+
json={"tokens": tokens},
|
|
171
|
+
headers={"Content-Type": "application/json"},
|
|
172
|
+
timeout=timeout,
|
|
173
|
+
follow_redirects=False,
|
|
174
|
+
)
|
|
175
|
+
except httpx.HTTPError:
|
|
176
|
+
return RevokeRefusal(reason="unavailable", status=0)
|
|
177
|
+
# The endpoint never redirects, so a redirect is an error, as in me-client:
|
|
178
|
+
# the tokens go to the auth host and nowhere else.
|
|
179
|
+
if resp.is_redirect or 300 <= resp.status_code < 400:
|
|
180
|
+
return RevokeRefusal(reason="unavailable", status=0)
|
|
181
|
+
if resp.status_code == 200:
|
|
182
|
+
try:
|
|
183
|
+
body = resp.json()
|
|
184
|
+
except ValueError:
|
|
185
|
+
body = None
|
|
186
|
+
n = body.get("revoked") if isinstance(body, dict) else None
|
|
187
|
+
if (
|
|
188
|
+
isinstance(body, dict)
|
|
189
|
+
and body.get("ok") is True
|
|
190
|
+
and isinstance(n, int)
|
|
191
|
+
and not isinstance(n, bool)
|
|
192
|
+
and 0 <= n <= _MAX_SAFE_INTEGER
|
|
193
|
+
):
|
|
194
|
+
return TokensRevoked(revoked=n)
|
|
195
|
+
return RevokeRefusal(reason="unavailable", status=200)
|
|
196
|
+
if resp.status_code == 429:
|
|
197
|
+
return RevokeRefusal(reason="rate_limited", status=429)
|
|
198
|
+
if resp.status_code == 400:
|
|
199
|
+
return RevokeRefusal(reason="bad_request", status=400)
|
|
200
|
+
return RevokeRefusal(reason="unavailable", status=resp.status_code)
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "orangecheck"
|
|
7
|
-
version = "3.
|
|
7
|
+
version = "3.2.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" }
|