altcha 2.2.0__tar.gz → 2.4.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.
@@ -0,0 +1,94 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
+
7
+ ## [2.4.0] - 2026-11-17
8
+
9
+ ### Added
10
+
11
+ - `verify_server` supports Sentinel v2's `POST /v2/verify/signature`. Pass the ID and
12
+ secret of a `restricted` or `full` API key as `api_key` and `secret`: they are sent as
13
+ HTTP Basic credentials and `secret` is left out of the body. `api_key` without `secret`
14
+ raises `ValueError`. Sentinel v1 (`/v1/verify/signature`) works as before when `api_key`
15
+ is omitted.
16
+ - `ServerSignaturePayload` carries the optional `apiKey` and `id` fields (`api_key`, `id`)
17
+ and keeps them in `to_dict`, so a payload object passed to `verify_server` still names
18
+ its signing key.
19
+
20
+ ### Changed
21
+
22
+ - `verify_server` no longer retries `4xx` responses (e.g. `401`/`403` for missing or wrong
23
+ credentials, `429`); they return `verified=False` at once. For error responses, `reason`
24
+ is the body's `code`, else its `error`, else `HTTP_<status>`; `5xx` responses that
25
+ exhaust the retries report it too (was always `HTTP_<status>`).
26
+
27
+ ### Fixed
28
+
29
+ - `verify_server` returns `reason='INVALID_RESPONSE'` (after retrying) instead of raising
30
+ when a `2xx` response body is not a JSON object.
31
+
32
+ ## [2.3.0] - 2026-10-04
33
+
34
+ Aligns the v2 API (`altcha.v2`) with the reference JavaScript implementation
35
+ ([altcha-lib](https://github.com/altcha-org/altcha-lib)) and hardens verification
36
+ against malformed payloads.
37
+
38
+ ### Upgrade notes
39
+
40
+ - Challenges signed by earlier versions may fail verification after upgrading if
41
+ their `data` contains `None`, floats, integer-like keys, or integers above 2^53, or
42
+ if they use a non-standard algorithm string (e.g. `'sha-512'`, `'SHA-1'`). Other
43
+ challenges keep the same signature and derived key. Challenges are short-lived, so
44
+ this only affects challenges issued just before the upgrade.
45
+ - `verify_solution` and `verify_server_signature` raise `ValueError` if `hmac_secret`
46
+ is empty.
47
+
48
+ ### Added
49
+
50
+ - `counter_mode` option (`'uint32'` default, or `'string'`) for `create_challenge`,
51
+ `solve_challenge` and `verify_solution`, matching altcha-lib's `counterMode`.
52
+ `'string'` encodes the counter as decimal digits, as in v1-compatible challenges.
53
+
54
+ ### Changed
55
+
56
+ - Challenge signatures use canonical JSON that is byte-identical to altcha-lib's
57
+ `canonicalJSON`. `null` values are kept. Numbers are formatted as in JavaScript
58
+ (`1e-7`, `1` for `1.0`, integers above 2^53 rounded to a double, `NaN` and
59
+ `Infinity` as `null`). Integer-like keys come first in numeric order, and other
60
+ keys are sorted by UTF-16 code units. Dicts inside arrays keep their key order, and
61
+ lone surrogates are escaped.
62
+ - Built-in SHA and PBKDF2 key derivation selects SHA-384 or SHA-512 only for the exact
63
+ algorithm strings `SHA-384`, `SHA-512`, `PBKDF2/SHA-384` and `PBKDF2/SHA-512`. Any
64
+ other string falls back to SHA-256, as in altcha-lib.
65
+ - `create_challenge` stores `key_prefix` in lowercase.
66
+ - `create_challenge` treats an empty `hmac_secret` as unset (unsigned challenge) and an
67
+ empty `hmac_key_secret` as unset (no `keySignature`).
68
+ - `create_challenge` raises `ValueError` when signing `data` that contains a
69
+ `__proto__` key outside arrays. altcha-lib leaves such keys out of the signature, so
70
+ they are rejected instead. Payloads containing them fail verification with
71
+ `invalid_signature`.
72
+ - `verify_server_signature` accepts only `SHA-1`, `SHA-256`, `SHA-384` and `SHA-512` as
73
+ the payload `algorithm`. These are the digests available to altcha-lib.
74
+
75
+ ### Fixed
76
+
77
+ - `verify_solution` returns a result instead of raising on malformed client input:
78
+ - non-hex, odd-length or non-string `derivedKey`;
79
+ - non-integer or out-of-range `counter`;
80
+ - non-string or non-ASCII `signature` or `derivedKey`;
81
+ - non-numeric `expiresAt`;
82
+ - deeply nested `data`.
83
+ - With `hmac_key_secret`, a `derivedKey` containing whitespace no longer verifies.
84
+ - `verify_server_signature` returns `invalid_signature` instead of raising on a
85
+ malformed `algorithm` or `verificationData`. Lone surrogates in `verificationData`
86
+ are hashed as JavaScript's `TextEncoder` encodes them.
87
+ - `solve_challenge` now enforces `timeout` when `counter_start` and `counter_step`
88
+ never reach a multiple of 10 (e.g. `1` and `2`). Previously it could run forever.
89
+ - Uppercase key prefixes from other issuers: `verify_solution` no longer rejects valid
90
+ solutions for even-length prefixes, and `solve_challenge` now solves odd-length ones.
91
+ - Challenges issued by altcha-lib with explicit `null` parameters (`data`, `expiresAt`,
92
+ `memoryCost`, `parallelism`) now verify.
93
+ - Challenges whose `data` contains `null` or floats now verify between this library
94
+ and altcha-lib in both directions.
@@ -0,0 +1,2 @@
1
+ include README.md
2
+ include CHANGELOG.md
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: altcha
3
- Version: 2.2.0
3
+ Version: 2.4.0
4
4
  Summary: A library for creating and verifying challenges for ALTCHA.
5
5
  Home-page: https://github.com/altcha-org/altcha-lib-py
6
6
  Author: Daniel Regeci
@@ -170,7 +170,7 @@ The original ALTCHA proof of work. The client brute-forces a number `n` such tha
170
170
 
171
171
  ### V2
172
172
 
173
- #### `create_challenge(algorithm, cost, *, derive_key, counter, key_length, key_prefix, key_prefix_length, memory_cost, parallelism, expires_at, data, hmac_secret, hmac_key_secret, hmac_algorithm) → Challenge`
173
+ #### `create_challenge(algorithm, cost, *, derive_key, counter, counter_mode, key_length, key_prefix, key_prefix_length, memory_cost, parallelism, expires_at, data, hmac_secret, hmac_key_secret, hmac_algorithm) → Challenge`
174
174
 
175
175
  Create a new v2 proof-of-work challenge.
176
176
 
@@ -180,6 +180,7 @@ Create a new v2 proof-of-work challenge.
180
180
  | `cost` | `int` | — | Algorithm-specific cost (iterations / passes). |
181
181
  | `derive_key` | callable | auto | `(parameters, salt: bytes, password: bytes) -> bytes`. Defaults to built-in for the algorithm. |
182
182
  | `counter` | `int` | `None` | Pre-solve with this counter (deterministic mode). |
183
+ | `counter_mode` | `str` | `'uint32'` | Counter encoding in the KDF password: `'uint32'` (big-endian) or `'string'` (decimal digits, V1 compatibility). Solver and verifier must use the same mode. |
183
184
  | `key_length` | `int` | `32` | Derived key length in bytes. |
184
185
  | `key_prefix` | `str` | `'00'` | Hex prefix the derived key must start with. |
185
186
  | `key_prefix_length` | `int` | `key_length // 2` | Bytes of the derived key used as prefix in deterministic mode. |
@@ -187,15 +188,15 @@ Create a new v2 proof-of-work challenge.
187
188
  | `parallelism` | `int` | `None` | Parallelism factor (Argon2id / scrypt). |
188
189
  | `expires_at` | `int` \| `datetime` | `None` | Expiry as a Unix timestamp or `datetime`. |
189
190
  | `data` | `dict` | `None` | Arbitrary metadata embedded in the challenge. |
190
- | `hmac_secret` | `str` | `None` | Secret for signing the challenge. If omitted, challenge is unsigned. |
191
- | `hmac_key_secret` | `str` | `None` | Secret for signing the derived key (fast verification path). |
191
+ | `hmac_secret` | `str` | `None` | Secret for signing the challenge. If omitted or empty, challenge is unsigned. |
192
+ | `hmac_key_secret` | `str` | `None` | Secret for signing the derived key (fast verification path). Ignored if empty. |
192
193
  | `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
193
194
 
194
195
  Returns `Challenge`.
195
196
 
196
197
  ---
197
198
 
198
- #### `solve_challenge(challenge, derive_key, *, counter_start, counter_step, timeout) → Solution | None`
199
+ #### `solve_challenge(challenge, derive_key, *, counter_start, counter_step, timeout, counter_mode) → Solution | None`
199
200
 
200
201
  Solve a v2 challenge by brute-forcing counter values.
201
202
 
@@ -206,22 +207,24 @@ Solve a v2 challenge by brute-forcing counter values.
206
207
  | `counter_start` | `int` | `0` | First counter value to try. |
207
208
  | `counter_step` | `int` | `1` | Increment between attempts (use > 1 for partitioned parallel solving). |
208
209
  | `timeout` | `float` | `90.0` | Maximum seconds to spend. Returns `None` on timeout. |
210
+ | `counter_mode` | `str` | `'uint32'` | Counter encoding; must match the issuer's. |
209
211
 
210
212
  Returns `Solution` or `None`.
211
213
 
212
214
  ---
213
215
 
214
- #### `verify_solution(payload, hmac_secret, derive_key, *, hmac_key_secret, hmac_algorithm) → VerifySolutionResult`
216
+ #### `verify_solution(payload, hmac_secret, derive_key, *, hmac_key_secret, hmac_algorithm, counter_mode) → VerifySolutionResult`
215
217
 
216
218
  Verify a v2 challenge solution.
217
219
 
218
220
  | Parameter | Type | Default | Description |
219
221
  |---|---|---|---|
220
222
  | `payload` | `str` \| `Payload` | — | Base64-encoded JSON string or `Payload` object. |
221
- | `hmac_secret` | `str` | — | Secret used to verify the challenge signature. |
223
+ | `hmac_secret` | `str` | — | Secret used to verify the challenge signature. Raises `ValueError` if empty. |
222
224
  | `derive_key` | callable | auto | KDF function for re-derivation. |
223
225
  | `hmac_key_secret` | `str` | `None` | Secret for the fast verification path. |
224
226
  | `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
227
+ | `counter_mode` | `str` | `'uint32'` | Counter encoding used when re-deriving the key; must match the issuer's. |
225
228
 
226
229
  Returns `VerifySolutionResult` with fields:
227
230
 
@@ -251,17 +254,99 @@ Returns `VerifySolutionResult` with fields:
251
254
 
252
255
  #### `verify_fields_hash(form_data, fields, fields_hash, algorithm) → bool`
253
256
 
254
- Verifies the hash of specific form fields.
257
+ Verifies the hash of specific form fields: the hex hash (`algorithm`, e.g. `'SHA-256'`) of
258
+ the values of `fields` in `form_data`, joined with `\n`, must equal `fields_hash`.
255
259
 
256
- #### `verify_server_signature(payload, hmac_key) → (bool, ServerSignatureVerificationData | None, str | None)`
260
+ #### `verify_server_signature(payload, hmac_secret, *, hmac_algorithm) → VerifyServerSignatureResult`
257
261
 
258
- Verifies an ALTCHA server signature.
262
+ Verifies an ALTCHA server signature locally, e.g. the `payload` of Sentinel's
263
+ `POST /v2/verify` (or `/v1/verify`) response, with the secret of the API key that signed
264
+ it. Sentinel v1 and v2 sign the same way, so this works for both. To have Sentinel check
265
+ the payload instead, use `verify_server` (below).
259
266
 
260
- #### `verify_server(payload, url, secret, *, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
267
+ ```python
268
+ from altcha import verify_fields_hash, verify_server_signature
269
+
270
+ result = verify_server_signature(payload, API_KEY_SECRET)
271
+
272
+ if result.verified:
273
+ data = result.verification_data
274
+ # Detect tampering with the submitted form fields
275
+ if data.get("fields") and not verify_fields_hash(
276
+ form_data, data["fields"], data["fieldsHash"], "SHA-256"
277
+ ):
278
+ ...
279
+ ```
280
+
281
+ | Parameter | Type | Default | Description |
282
+ |---|---|---|---|
283
+ | `payload` | `str` \| `ServerSignaturePayload` | — | Base64-encoded JSON string or `ServerSignaturePayload` object. Its `algorithm` (hash of `verificationData`) must be `'SHA-1'`, `'SHA-256'`, `'SHA-384'` or `'SHA-512'`. |
284
+ | `hmac_secret` | `str` \| `bytes` | — | Secret used to verify the HMAC signature (the API key secret for Sentinel). Raises `ValueError` if empty. |
285
+ | `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
286
+
287
+ Returns `VerifyServerSignatureResult` with fields:
261
288
 
262
- Verifies a payload remotely via the ALTCHA Sentinel `/v1/verify/signature` API, instead of
289
+ | Field | Type | Description |
290
+ |---|---|---|
291
+ | `verified` | `bool` | `True` if the signature is valid, the payload has not expired, and `verified` is `true` in both the payload and the signed verification data. |
292
+ | `expired` | `bool` | `True` if the signed `expire` is in the past. |
293
+ | `invalid_signature` | `bool` | `True` if the signature does not match, or the payload is malformed. |
294
+ | `invalid_solution` | `bool` | `True` if `verified` is not `true` in the payload or in the signed verification data. |
295
+ | `time` | `float` | Time taken for verification in milliseconds. |
296
+ | `verification_data` | `dict \| None` | The signed verification data, parsed with `parse_verification_data`; `None` unless `verified`. |
297
+
298
+ `parse_verification_data(data)` turns the URL-encoded verification data into a flat dict:
299
+
300
+ - Keys stay as signed, e.g. `data["challenge.algorithm"]` and `data["device.edk"]`
301
+ (`verify_server` returns these nested instead).
302
+ - `'true'`/`'false'` become `bool`, all-digit values `int` (including e.g. a
303
+ `params.zip` of `01234`, which becomes `1234`), and `digits.digits` values `float`.
304
+ - `fields` and `reasons` become lists.
305
+ - Keys with empty values are left out.
306
+
307
+ Unlike Sentinel v2's `/v2/verify/signature` (via `verify_server`), local verification does
308
+ not prevent reuse: a valid payload verifies again until `expire`. Reject repeated `id`s
309
+ yourself if that matters.
310
+
311
+ #### `verify_server(payload, url, secret, *, api_key, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
312
+
313
+ Verifies a payload remotely via the ALTCHA Sentinel verify signature API, instead of
263
314
  checking the HMAC signature locally. Avoids managing the HMAC secret on your server, at the
264
- cost of a network round-trip.
315
+ cost of a network round-trip. Both Sentinel v2 (`POST /v2/verify/signature`) and Sentinel v1
316
+ (`POST /v1/verify/signature`) are supported; they differ in how the request is authenticated.
317
+
318
+ ##### Sentinel v2
319
+
320
+ ```python
321
+ from altcha import verify_server
322
+
323
+ result = verify_server(
324
+ payload, # the payload received from POST /v2/verify
325
+ url="https://sentinel.example.com/v2/verify/signature",
326
+ api_key=SENTINEL_API_KEY, # id of a restricted or full API key (key_...)
327
+ secret=SENTINEL_API_KEY_SECRET, # its secret (sec_...)
328
+ timeout=10,
329
+ retries=2,
330
+ )
331
+
332
+ if result.verified:
333
+ ...
334
+ ```
335
+
336
+ - `api_key` and `secret` are the ID and secret of a `restricted` or `full` API key of the
337
+ account that owns the payload's (public) API key. They are sent as
338
+ `Authorization: Basic base64(api_key:secret)`; an `Authorization` header in `headers` is
339
+ replaced. `api_key` without `secret` raises `ValueError` before any request is sent.
340
+ - The request body is `{"payload": ...}`; `secret` is not sent in the body (Sentinel v2
341
+ rejects it).
342
+ - Without credentials, Sentinel v2 answers `401` and `reason` is `'API_KEY_REQUIRED'`. A
343
+ payload signed by a key of another account gets `reason='API_KEY_NOT_ALLOWED'`.
344
+ - `verification_data` is the signed verification data as a nested dict, with keys split on
345
+ `.`: `result.verification_data["challenge"]["algorithm"]` (v1's `challengeAlgorithm`),
346
+ `result.verification_data["device"]["edk"]`. `fields` and `reasons` are lists; `id`,
347
+ `fieldsHash`, `device.edk` and `params.*` stay strings.
348
+
349
+ ##### Sentinel v1
265
350
 
266
351
  ```python
267
352
  from altcha import verify_server
@@ -278,11 +363,20 @@ if result.verified:
278
363
  ...
279
364
  ```
280
365
 
366
+ - `/v1/verify/signature` takes no credentials: omit `api_key`. `secret` (the payload's API
367
+ key secret) is optional and sent in the body as `{"payload": ..., "secret": ...}`; Sentinel
368
+ answers `reason='WRONG_API_KEY_SECRET'` when it is not the payload key's secret.
369
+ - This also applies to the `/v1/verify/signature` alias Sentinel v2 serves with
370
+ `[server] v1_compat = true`.
371
+
372
+ ##### Parameters
373
+
281
374
  | Parameter | Type | Default | Description |
282
375
  |---|---|---|---|
283
376
  | `payload` | `str` \| `ServerSignaturePayload` \| `dict` | — | The payload to verify. |
284
- | `url` | `str` | — | Full URL of the Sentinel `/v1/verify/signature` endpoint. |
285
- | `secret` | `str` | `None` | API key secret, checked against the payload's API key. |
377
+ | `url` | `str` | — | Full URL of the Sentinel endpoint: `/v2/verify/signature` (v2) or `/v1/verify/signature` (v1). |
378
+ | `secret` | `str` | `None` | v2: secret of `api_key`, required with it. v1: API key secret sent in the body and checked against the payload's API key. |
379
+ | `api_key` | `str` | `None` | v2 only: ID of a `restricted` or `full` API key, sent with `secret` as HTTP Basic credentials. |
286
380
  | `headers` | `dict` | `None` | Additional headers to send with the request. |
287
381
  | `timeout` | `float` | `10` | Per-attempt request timeout in seconds. |
288
382
  | `retries` | `int` | `0` | Number of retry attempts after the first try. |
@@ -290,14 +384,22 @@ if result.verified:
290
384
  | `retry_backoff` | `str` | `'exponential'` | `'fixed'` or `'exponential'` backoff. |
291
385
  | `http_post` | callable | stdlib `urllib` | Transport override: `(url, body, headers, timeout) -> (status, body)`. |
292
386
 
387
+ ##### Errors and retries
388
+
389
+ Failures never raise; they return `verified=False` with a `reason`. `4xx` responses (bad
390
+ payload, missing or wrong credentials, rate limit) are definitive and returned at once.
391
+ Network errors, other error statuses (e.g. `5xx`) and invalid response bodies are retried up
392
+ to `retries` times. For an error response, `reason` is the `code` of Sentinel's error body
393
+ (v2: `{"code", "error", "statusCode"}`), else its `error` (v1), else `'HTTP_<status>'`.
394
+
293
395
  Returns `VerifyServerResult` with fields:
294
396
 
295
397
  | Field | Type | Description |
296
398
  |---|---|---|
297
399
  | `verified` | `bool` | `True` if Sentinel confirmed the payload is valid. |
298
- | `reason` | `str \| None` | Failure reason, if any. |
400
+ | `reason` | `str \| None` | Why verification failed: Sentinel's `reason` (e.g. `'PAYLOAD_ALREADY_USED'`, `'INVALID_PAYLOAD'`, `'API_KEY_NOT_ALLOWED'` (v2), `'WRONG_API_KEY_SECRET'` (v1)), the error code of an HTTP error response, `'INVALID_RESPONSE'`, or a network error message. |
299
401
  | `api_key` | `str \| None` | The API key associated with the payload, if returned. |
300
- | `verification_data` | `dict \| None` | Parsed verification data, if returned. |
402
+ | `verification_data` | `dict \| None` | Verification data returned by Sentinel (nested dict), if returned. |
301
403
 
302
404
  ---
303
405
 
@@ -320,6 +422,12 @@ Creates a new v1 challenge.
320
422
  | `expires` | `datetime` | `None` | Optional expiration time. |
321
423
  | `params` | `dict` | `None` | Optional URL-encoded query parameters appended to the salt. |
322
424
 
425
+ #### `verify_server_signature_v1(payload, hmac_key) → (bool, ServerSignatureVerificationData | None, str | None)`
426
+
427
+ Verifies a server signature with the v1 API. Returns `(verified, data, error)`, where `data`
428
+ exposes the known fields (`classification`, `expire`, `fields`, `fieldsHash`, `score`, …)
429
+ as attributes. Prefer `verify_server_signature`.
430
+
323
431
  #### `verify_solution_v1(payload, hmac_secret, check_expires) → (bool, str | None)`
324
432
 
325
433
  Verifies a v1 solution payload.
@@ -147,7 +147,7 @@ The original ALTCHA proof of work. The client brute-forces a number `n` such tha
147
147
 
148
148
  ### V2
149
149
 
150
- #### `create_challenge(algorithm, cost, *, derive_key, counter, key_length, key_prefix, key_prefix_length, memory_cost, parallelism, expires_at, data, hmac_secret, hmac_key_secret, hmac_algorithm) → Challenge`
150
+ #### `create_challenge(algorithm, cost, *, derive_key, counter, counter_mode, key_length, key_prefix, key_prefix_length, memory_cost, parallelism, expires_at, data, hmac_secret, hmac_key_secret, hmac_algorithm) → Challenge`
151
151
 
152
152
  Create a new v2 proof-of-work challenge.
153
153
 
@@ -157,6 +157,7 @@ Create a new v2 proof-of-work challenge.
157
157
  | `cost` | `int` | — | Algorithm-specific cost (iterations / passes). |
158
158
  | `derive_key` | callable | auto | `(parameters, salt: bytes, password: bytes) -> bytes`. Defaults to built-in for the algorithm. |
159
159
  | `counter` | `int` | `None` | Pre-solve with this counter (deterministic mode). |
160
+ | `counter_mode` | `str` | `'uint32'` | Counter encoding in the KDF password: `'uint32'` (big-endian) or `'string'` (decimal digits, V1 compatibility). Solver and verifier must use the same mode. |
160
161
  | `key_length` | `int` | `32` | Derived key length in bytes. |
161
162
  | `key_prefix` | `str` | `'00'` | Hex prefix the derived key must start with. |
162
163
  | `key_prefix_length` | `int` | `key_length // 2` | Bytes of the derived key used as prefix in deterministic mode. |
@@ -164,15 +165,15 @@ Create a new v2 proof-of-work challenge.
164
165
  | `parallelism` | `int` | `None` | Parallelism factor (Argon2id / scrypt). |
165
166
  | `expires_at` | `int` \| `datetime` | `None` | Expiry as a Unix timestamp or `datetime`. |
166
167
  | `data` | `dict` | `None` | Arbitrary metadata embedded in the challenge. |
167
- | `hmac_secret` | `str` | `None` | Secret for signing the challenge. If omitted, challenge is unsigned. |
168
- | `hmac_key_secret` | `str` | `None` | Secret for signing the derived key (fast verification path). |
168
+ | `hmac_secret` | `str` | `None` | Secret for signing the challenge. If omitted or empty, challenge is unsigned. |
169
+ | `hmac_key_secret` | `str` | `None` | Secret for signing the derived key (fast verification path). Ignored if empty. |
169
170
  | `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
170
171
 
171
172
  Returns `Challenge`.
172
173
 
173
174
  ---
174
175
 
175
- #### `solve_challenge(challenge, derive_key, *, counter_start, counter_step, timeout) → Solution | None`
176
+ #### `solve_challenge(challenge, derive_key, *, counter_start, counter_step, timeout, counter_mode) → Solution | None`
176
177
 
177
178
  Solve a v2 challenge by brute-forcing counter values.
178
179
 
@@ -183,22 +184,24 @@ Solve a v2 challenge by brute-forcing counter values.
183
184
  | `counter_start` | `int` | `0` | First counter value to try. |
184
185
  | `counter_step` | `int` | `1` | Increment between attempts (use > 1 for partitioned parallel solving). |
185
186
  | `timeout` | `float` | `90.0` | Maximum seconds to spend. Returns `None` on timeout. |
187
+ | `counter_mode` | `str` | `'uint32'` | Counter encoding; must match the issuer's. |
186
188
 
187
189
  Returns `Solution` or `None`.
188
190
 
189
191
  ---
190
192
 
191
- #### `verify_solution(payload, hmac_secret, derive_key, *, hmac_key_secret, hmac_algorithm) → VerifySolutionResult`
193
+ #### `verify_solution(payload, hmac_secret, derive_key, *, hmac_key_secret, hmac_algorithm, counter_mode) → VerifySolutionResult`
192
194
 
193
195
  Verify a v2 challenge solution.
194
196
 
195
197
  | Parameter | Type | Default | Description |
196
198
  |---|---|---|---|
197
199
  | `payload` | `str` \| `Payload` | — | Base64-encoded JSON string or `Payload` object. |
198
- | `hmac_secret` | `str` | — | Secret used to verify the challenge signature. |
200
+ | `hmac_secret` | `str` | — | Secret used to verify the challenge signature. Raises `ValueError` if empty. |
199
201
  | `derive_key` | callable | auto | KDF function for re-derivation. |
200
202
  | `hmac_key_secret` | `str` | `None` | Secret for the fast verification path. |
201
203
  | `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
204
+ | `counter_mode` | `str` | `'uint32'` | Counter encoding used when re-deriving the key; must match the issuer's. |
202
205
 
203
206
  Returns `VerifySolutionResult` with fields:
204
207
 
@@ -228,17 +231,99 @@ Returns `VerifySolutionResult` with fields:
228
231
 
229
232
  #### `verify_fields_hash(form_data, fields, fields_hash, algorithm) → bool`
230
233
 
231
- Verifies the hash of specific form fields.
234
+ Verifies the hash of specific form fields: the hex hash (`algorithm`, e.g. `'SHA-256'`) of
235
+ the values of `fields` in `form_data`, joined with `\n`, must equal `fields_hash`.
232
236
 
233
- #### `verify_server_signature(payload, hmac_key) → (bool, ServerSignatureVerificationData | None, str | None)`
237
+ #### `verify_server_signature(payload, hmac_secret, *, hmac_algorithm) → VerifyServerSignatureResult`
234
238
 
235
- Verifies an ALTCHA server signature.
239
+ Verifies an ALTCHA server signature locally, e.g. the `payload` of Sentinel's
240
+ `POST /v2/verify` (or `/v1/verify`) response, with the secret of the API key that signed
241
+ it. Sentinel v1 and v2 sign the same way, so this works for both. To have Sentinel check
242
+ the payload instead, use `verify_server` (below).
236
243
 
237
- #### `verify_server(payload, url, secret, *, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
244
+ ```python
245
+ from altcha import verify_fields_hash, verify_server_signature
246
+
247
+ result = verify_server_signature(payload, API_KEY_SECRET)
248
+
249
+ if result.verified:
250
+ data = result.verification_data
251
+ # Detect tampering with the submitted form fields
252
+ if data.get("fields") and not verify_fields_hash(
253
+ form_data, data["fields"], data["fieldsHash"], "SHA-256"
254
+ ):
255
+ ...
256
+ ```
257
+
258
+ | Parameter | Type | Default | Description |
259
+ |---|---|---|---|
260
+ | `payload` | `str` \| `ServerSignaturePayload` | — | Base64-encoded JSON string or `ServerSignaturePayload` object. Its `algorithm` (hash of `verificationData`) must be `'SHA-1'`, `'SHA-256'`, `'SHA-384'` or `'SHA-512'`. |
261
+ | `hmac_secret` | `str` \| `bytes` | — | Secret used to verify the HMAC signature (the API key secret for Sentinel). Raises `ValueError` if empty. |
262
+ | `hmac_algorithm` | `str` | `'SHA-256'` | HMAC digest algorithm. |
263
+
264
+ Returns `VerifyServerSignatureResult` with fields:
238
265
 
239
- Verifies a payload remotely via the ALTCHA Sentinel `/v1/verify/signature` API, instead of
266
+ | Field | Type | Description |
267
+ |---|---|---|
268
+ | `verified` | `bool` | `True` if the signature is valid, the payload has not expired, and `verified` is `true` in both the payload and the signed verification data. |
269
+ | `expired` | `bool` | `True` if the signed `expire` is in the past. |
270
+ | `invalid_signature` | `bool` | `True` if the signature does not match, or the payload is malformed. |
271
+ | `invalid_solution` | `bool` | `True` if `verified` is not `true` in the payload or in the signed verification data. |
272
+ | `time` | `float` | Time taken for verification in milliseconds. |
273
+ | `verification_data` | `dict \| None` | The signed verification data, parsed with `parse_verification_data`; `None` unless `verified`. |
274
+
275
+ `parse_verification_data(data)` turns the URL-encoded verification data into a flat dict:
276
+
277
+ - Keys stay as signed, e.g. `data["challenge.algorithm"]` and `data["device.edk"]`
278
+ (`verify_server` returns these nested instead).
279
+ - `'true'`/`'false'` become `bool`, all-digit values `int` (including e.g. a
280
+ `params.zip` of `01234`, which becomes `1234`), and `digits.digits` values `float`.
281
+ - `fields` and `reasons` become lists.
282
+ - Keys with empty values are left out.
283
+
284
+ Unlike Sentinel v2's `/v2/verify/signature` (via `verify_server`), local verification does
285
+ not prevent reuse: a valid payload verifies again until `expire`. Reject repeated `id`s
286
+ yourself if that matters.
287
+
288
+ #### `verify_server(payload, url, secret, *, api_key, headers, timeout, retries, retry_delay, retry_backoff, http_post) → VerifyServerResult`
289
+
290
+ Verifies a payload remotely via the ALTCHA Sentinel verify signature API, instead of
240
291
  checking the HMAC signature locally. Avoids managing the HMAC secret on your server, at the
241
- cost of a network round-trip.
292
+ cost of a network round-trip. Both Sentinel v2 (`POST /v2/verify/signature`) and Sentinel v1
293
+ (`POST /v1/verify/signature`) are supported; they differ in how the request is authenticated.
294
+
295
+ ##### Sentinel v2
296
+
297
+ ```python
298
+ from altcha import verify_server
299
+
300
+ result = verify_server(
301
+ payload, # the payload received from POST /v2/verify
302
+ url="https://sentinel.example.com/v2/verify/signature",
303
+ api_key=SENTINEL_API_KEY, # id of a restricted or full API key (key_...)
304
+ secret=SENTINEL_API_KEY_SECRET, # its secret (sec_...)
305
+ timeout=10,
306
+ retries=2,
307
+ )
308
+
309
+ if result.verified:
310
+ ...
311
+ ```
312
+
313
+ - `api_key` and `secret` are the ID and secret of a `restricted` or `full` API key of the
314
+ account that owns the payload's (public) API key. They are sent as
315
+ `Authorization: Basic base64(api_key:secret)`; an `Authorization` header in `headers` is
316
+ replaced. `api_key` without `secret` raises `ValueError` before any request is sent.
317
+ - The request body is `{"payload": ...}`; `secret` is not sent in the body (Sentinel v2
318
+ rejects it).
319
+ - Without credentials, Sentinel v2 answers `401` and `reason` is `'API_KEY_REQUIRED'`. A
320
+ payload signed by a key of another account gets `reason='API_KEY_NOT_ALLOWED'`.
321
+ - `verification_data` is the signed verification data as a nested dict, with keys split on
322
+ `.`: `result.verification_data["challenge"]["algorithm"]` (v1's `challengeAlgorithm`),
323
+ `result.verification_data["device"]["edk"]`. `fields` and `reasons` are lists; `id`,
324
+ `fieldsHash`, `device.edk` and `params.*` stay strings.
325
+
326
+ ##### Sentinel v1
242
327
 
243
328
  ```python
244
329
  from altcha import verify_server
@@ -255,11 +340,20 @@ if result.verified:
255
340
  ...
256
341
  ```
257
342
 
343
+ - `/v1/verify/signature` takes no credentials: omit `api_key`. `secret` (the payload's API
344
+ key secret) is optional and sent in the body as `{"payload": ..., "secret": ...}`; Sentinel
345
+ answers `reason='WRONG_API_KEY_SECRET'` when it is not the payload key's secret.
346
+ - This also applies to the `/v1/verify/signature` alias Sentinel v2 serves with
347
+ `[server] v1_compat = true`.
348
+
349
+ ##### Parameters
350
+
258
351
  | Parameter | Type | Default | Description |
259
352
  |---|---|---|---|
260
353
  | `payload` | `str` \| `ServerSignaturePayload` \| `dict` | — | The payload to verify. |
261
- | `url` | `str` | — | Full URL of the Sentinel `/v1/verify/signature` endpoint. |
262
- | `secret` | `str` | `None` | API key secret, checked against the payload's API key. |
354
+ | `url` | `str` | — | Full URL of the Sentinel endpoint: `/v2/verify/signature` (v2) or `/v1/verify/signature` (v1). |
355
+ | `secret` | `str` | `None` | v2: secret of `api_key`, required with it. v1: API key secret sent in the body and checked against the payload's API key. |
356
+ | `api_key` | `str` | `None` | v2 only: ID of a `restricted` or `full` API key, sent with `secret` as HTTP Basic credentials. |
263
357
  | `headers` | `dict` | `None` | Additional headers to send with the request. |
264
358
  | `timeout` | `float` | `10` | Per-attempt request timeout in seconds. |
265
359
  | `retries` | `int` | `0` | Number of retry attempts after the first try. |
@@ -267,14 +361,22 @@ if result.verified:
267
361
  | `retry_backoff` | `str` | `'exponential'` | `'fixed'` or `'exponential'` backoff. |
268
362
  | `http_post` | callable | stdlib `urllib` | Transport override: `(url, body, headers, timeout) -> (status, body)`. |
269
363
 
364
+ ##### Errors and retries
365
+
366
+ Failures never raise; they return `verified=False` with a `reason`. `4xx` responses (bad
367
+ payload, missing or wrong credentials, rate limit) are definitive and returned at once.
368
+ Network errors, other error statuses (e.g. `5xx`) and invalid response bodies are retried up
369
+ to `retries` times. For an error response, `reason` is the `code` of Sentinel's error body
370
+ (v2: `{"code", "error", "statusCode"}`), else its `error` (v1), else `'HTTP_<status>'`.
371
+
270
372
  Returns `VerifyServerResult` with fields:
271
373
 
272
374
  | Field | Type | Description |
273
375
  |---|---|---|
274
376
  | `verified` | `bool` | `True` if Sentinel confirmed the payload is valid. |
275
- | `reason` | `str \| None` | Failure reason, if any. |
377
+ | `reason` | `str \| None` | Why verification failed: Sentinel's `reason` (e.g. `'PAYLOAD_ALREADY_USED'`, `'INVALID_PAYLOAD'`, `'API_KEY_NOT_ALLOWED'` (v2), `'WRONG_API_KEY_SECRET'` (v1)), the error code of an HTTP error response, `'INVALID_RESPONSE'`, or a network error message. |
276
378
  | `api_key` | `str \| None` | The API key associated with the payload, if returned. |
277
- | `verification_data` | `dict \| None` | Parsed verification data, if returned. |
379
+ | `verification_data` | `dict \| None` | Verification data returned by Sentinel (nested dict), if returned. |
278
380
 
279
381
  ---
280
382
 
@@ -297,6 +399,12 @@ Creates a new v1 challenge.
297
399
  | `expires` | `datetime` | `None` | Optional expiration time. |
298
400
  | `params` | `dict` | `None` | Optional URL-encoded query parameters appended to the salt. |
299
401
 
402
+ #### `verify_server_signature_v1(payload, hmac_key) → (bool, ServerSignatureVerificationData | None, str | None)`
403
+
404
+ Verifies a server signature with the v1 API. Returns `(verified, data, error)`, where `data`
405
+ exposes the known fields (`classification`, `expire`, `fields`, `fieldsHash`, `score`, …)
406
+ as attributes. Prefer `verify_server_signature`.
407
+
300
408
  #### `verify_solution_v1(payload, hmac_secret, check_expires) → (bool, str | None)`
301
409
 
302
410
  Verifies a v1 solution payload.