imrobot 0.8.0__py3-none-any.whl
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.
- imrobot/__init__.py +83 -0
- imrobot/_version.py +3 -0
- imrobot/core.py +355 -0
- imrobot/fastapi.py +187 -0
- imrobot/py.typed +0 -0
- imrobot/server.py +607 -0
- imrobot-0.8.0.dist-info/METADATA +157 -0
- imrobot-0.8.0.dist-info/RECORD +10 -0
- imrobot-0.8.0.dist-info/WHEEL +4 -0
- imrobot-0.8.0.dist-info/licenses/LICENSE +21 -0
imrobot/server.py
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Server-side verifier, HMAC utilities, replay guard, and proof-token issuer.
|
|
3
|
+
|
|
4
|
+
Mirrors ``src/server/`` from the JS SDK and produces byte-identical wire output
|
|
5
|
+
(HMAC hex, JWTs, base64url encoding) so a Python server can verify challenges
|
|
6
|
+
issued by the JS SDK, and vice-versa.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import hashlib
|
|
13
|
+
import hmac
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import secrets
|
|
17
|
+
import time
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Any, Literal, Optional, TypedDict, Union
|
|
20
|
+
|
|
21
|
+
from .core import (
|
|
22
|
+
SUPPORTED_DIFFICULTIES,
|
|
23
|
+
SUSPICIOUS_THRESHOLD_MS,
|
|
24
|
+
Challenge,
|
|
25
|
+
Difficulty,
|
|
26
|
+
Operation,
|
|
27
|
+
SignedChallenge,
|
|
28
|
+
execute_pipeline,
|
|
29
|
+
fnv1a,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# ---------------------------------------------------------------------------
|
|
33
|
+
# HMAC / SHA-256 primitives
|
|
34
|
+
# ---------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def hmac_sign(secret: str, message: str) -> str:
|
|
38
|
+
"""HMAC-SHA256, 64-char lowercase hex — matches JS ``hmacSign``."""
|
|
39
|
+
mac = hmac.new(secret.encode("utf-8"), message.encode("utf-8"), hashlib.sha256)
|
|
40
|
+
return mac.hexdigest()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def hmac_verify(secret: str, message: str, signature: str) -> bool:
|
|
44
|
+
"""Constant-time HMAC verification — matches JS ``hmacVerify``."""
|
|
45
|
+
expected = hmac_sign(secret, message)
|
|
46
|
+
return hmac.compare_digest(expected, signature)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def sha256_hex(message: str) -> str:
|
|
50
|
+
"""SHA-256 hex digest of a UTF-8 string."""
|
|
51
|
+
return hashlib.sha256(message.encode("utf-8")).hexdigest()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# ---------------------------------------------------------------------------
|
|
55
|
+
# Challenge generator (server side)
|
|
56
|
+
# ---------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
_HEX_CHARS = "0123456789abcdef"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _random_hex(length: int) -> str:
|
|
62
|
+
return "".join(_HEX_CHARS[b % 16] for b in os.urandom(length))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _random_int(low: int, high: int) -> int:
|
|
66
|
+
"""Inclusive [low, high]."""
|
|
67
|
+
return secrets.randbelow(high - low + 1) + low
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _pick(arr: list[Any]) -> Any:
|
|
71
|
+
return arr[_random_int(0, len(arr) - 1)]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _default_ttl_ms(difficulty: Difficulty) -> int:
|
|
75
|
+
return {"easy": 30_000, "medium": 20_000, "hard": 15_000}[difficulty]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _nonce_length(difficulty: Difficulty) -> int:
|
|
79
|
+
return {"easy": 4, "medium": 6, "hard": 8}[difficulty]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# Op factories mirror the JS ``challenge.ts`` list one-to-one.
|
|
83
|
+
def _easy_factories() -> list[Any]:
|
|
84
|
+
return [
|
|
85
|
+
lambda _val: {"op": "reverse"},
|
|
86
|
+
lambda _val: {"op": "to_upper"},
|
|
87
|
+
lambda _val: {"op": "to_lower"},
|
|
88
|
+
lambda _val: {"op": "sort_chars"},
|
|
89
|
+
lambda _val: {"op": "length"},
|
|
90
|
+
lambda _val: {"op": "slice_alternate"},
|
|
91
|
+
lambda _val: {"op": "vowel_count"},
|
|
92
|
+
lambda _val: {"op": "atbash"},
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _medium_factories() -> list[Any]:
|
|
97
|
+
def _substring(val: str) -> Operation:
|
|
98
|
+
max_end = min(len(val), 16)
|
|
99
|
+
if max_end < 5:
|
|
100
|
+
return {"op": "reverse"}
|
|
101
|
+
start = _random_int(0, max_end // 3)
|
|
102
|
+
end = _random_int(start + 4, max_end)
|
|
103
|
+
return {"op": "substring", "start": start, "end": end}
|
|
104
|
+
|
|
105
|
+
def _count_chars(val: str) -> Operation:
|
|
106
|
+
chars = list(dict.fromkeys(val)) # unique, preserve order
|
|
107
|
+
if not chars:
|
|
108
|
+
return {"op": "length"}
|
|
109
|
+
return {"op": "count_chars", "char": _pick(chars)}
|
|
110
|
+
|
|
111
|
+
return [
|
|
112
|
+
*_easy_factories(),
|
|
113
|
+
lambda _val: {"op": "base64_encode"},
|
|
114
|
+
lambda _val: {"op": "rot13"},
|
|
115
|
+
lambda _val: {"op": "hex_encode"},
|
|
116
|
+
lambda _val: {"op": "char_code_sum"},
|
|
117
|
+
_substring,
|
|
118
|
+
lambda _val: {"op": "consonant_extract"},
|
|
119
|
+
lambda _val: {"op": "run_length_encode"},
|
|
120
|
+
lambda _val: {"op": "caesar", "shift": _random_int(1, 25)},
|
|
121
|
+
_count_chars,
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _hard_factories() -> list[Any]:
|
|
126
|
+
def _replace(val: str) -> Operation:
|
|
127
|
+
if not val:
|
|
128
|
+
return {"op": "reverse"}
|
|
129
|
+
idx = _random_int(0, len(val) - 1)
|
|
130
|
+
return {"op": "replace", "search": val[idx], "replacement": _random_hex(1)}
|
|
131
|
+
|
|
132
|
+
def _pad_start(val: str) -> Operation:
|
|
133
|
+
return {"op": "pad_start", "length": max(len(val), 1) + _random_int(2, 6), "fill": _random_hex(1)}
|
|
134
|
+
|
|
135
|
+
def _byte_xor(_val: str) -> Operation:
|
|
136
|
+
key_len = _random_int(2, 8)
|
|
137
|
+
return {"op": "byte_xor", "key": [_random_int(1, 255) for _ in range(key_len)]}
|
|
138
|
+
|
|
139
|
+
return [
|
|
140
|
+
*_medium_factories(),
|
|
141
|
+
lambda _val: {"op": "repeat", "times": _random_int(2, 3)},
|
|
142
|
+
_replace,
|
|
143
|
+
_pad_start,
|
|
144
|
+
lambda _val: {"op": "xor_encode", "key": _random_int(1, 127)},
|
|
145
|
+
lambda _val: {"op": "fnv1a_hash"},
|
|
146
|
+
lambda _val: {"op": "hash_chain", "rounds": _random_int(2, 5)},
|
|
147
|
+
_byte_xor,
|
|
148
|
+
lambda _val: {"op": "nibble_swap"},
|
|
149
|
+
lambda _val: {"op": "bit_rotate", "bits": _random_int(1, 7)},
|
|
150
|
+
]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _factories_for(difficulty: Difficulty) -> tuple[list[Any], tuple[int, int]]:
|
|
154
|
+
if difficulty == "easy":
|
|
155
|
+
return _easy_factories(), (2, 3)
|
|
156
|
+
if difficulty == "medium":
|
|
157
|
+
return _medium_factories(), (3, 5)
|
|
158
|
+
return _hard_factories(), (5, 7)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _build_pipeline(seed: str, difficulty: Difficulty) -> list[Operation]:
|
|
162
|
+
factories, (lo, hi) = _factories_for(difficulty)
|
|
163
|
+
num_ops = _random_int(lo, hi)
|
|
164
|
+
pipeline: list[Operation] = []
|
|
165
|
+
current = seed
|
|
166
|
+
for _ in range(num_ops):
|
|
167
|
+
factory = _pick(factories)
|
|
168
|
+
op = factory(current)
|
|
169
|
+
pipeline.append(op)
|
|
170
|
+
current = execute_pipeline(current, [op])
|
|
171
|
+
return pipeline
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _now_ms() -> int:
|
|
175
|
+
return int(time.time() * 1000)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _generate_challenge(difficulty: Difficulty, ttl: Optional[int], _depth: int = 0) -> Challenge:
|
|
179
|
+
if _depth > 10:
|
|
180
|
+
raise RuntimeError("Failed to generate valid challenge")
|
|
181
|
+
ttl_ms = ttl if ttl is not None else _default_ttl_ms(difficulty)
|
|
182
|
+
visible_seed = _random_hex(16)
|
|
183
|
+
nonce = _random_hex(_nonce_length(difficulty))
|
|
184
|
+
seed = visible_seed + nonce
|
|
185
|
+
pipeline = _build_pipeline(seed, difficulty)
|
|
186
|
+
try:
|
|
187
|
+
answer = execute_pipeline(seed, pipeline)
|
|
188
|
+
except Exception:
|
|
189
|
+
return _generate_challenge(difficulty, ttl, _depth + 1)
|
|
190
|
+
if not answer or len(answer) == 0 or len(answer) > 10_000:
|
|
191
|
+
return _generate_challenge(difficulty, ttl, _depth + 1)
|
|
192
|
+
challenge_id = _random_hex(16)
|
|
193
|
+
verification = fnv1a(f"{answer}:{challenge_id}")
|
|
194
|
+
return {
|
|
195
|
+
"version": 1,
|
|
196
|
+
"id": challenge_id,
|
|
197
|
+
"timestamp": _now_ms(),
|
|
198
|
+
"ttl": ttl_ms,
|
|
199
|
+
"difficulty": difficulty,
|
|
200
|
+
"seed": seed,
|
|
201
|
+
"visibleSeed": visible_seed,
|
|
202
|
+
"nonce": nonce,
|
|
203
|
+
"pipeline": pipeline,
|
|
204
|
+
"verification": verification,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# ---------------------------------------------------------------------------
|
|
209
|
+
# Replay guard
|
|
210
|
+
# ---------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class ChallengeReplayGuard:
|
|
214
|
+
"""Interface for tracking used challenge IDs.
|
|
215
|
+
|
|
216
|
+
Subclass or provide a duck-typed object with ``mark_used(challenge_id) -> bool``.
|
|
217
|
+
Return ``True`` if the challenge was previously unused (accept), ``False`` if
|
|
218
|
+
it's been seen before (reject as replay).
|
|
219
|
+
"""
|
|
220
|
+
|
|
221
|
+
def mark_used(self, challenge_id: str) -> bool: # pragma: no cover - interface
|
|
222
|
+
raise NotImplementedError
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class InMemoryReplayGuard(ChallengeReplayGuard):
|
|
226
|
+
"""Bounded in-memory replay guard (LRU-ish via insertion order).
|
|
227
|
+
|
|
228
|
+
NOT safe for multi-process deployments — use Redis-backed guard for prod.
|
|
229
|
+
"""
|
|
230
|
+
|
|
231
|
+
def __init__(self, capacity: int = 10_000) -> None:
|
|
232
|
+
self._capacity = capacity
|
|
233
|
+
self._seen: dict[str, int] = {}
|
|
234
|
+
|
|
235
|
+
def mark_used(self, challenge_id: str) -> bool:
|
|
236
|
+
if challenge_id in self._seen:
|
|
237
|
+
return False
|
|
238
|
+
self._seen[challenge_id] = _now_ms()
|
|
239
|
+
if len(self._seen) > self._capacity:
|
|
240
|
+
# drop oldest
|
|
241
|
+
oldest_key = next(iter(self._seen))
|
|
242
|
+
del self._seen[oldest_key]
|
|
243
|
+
return True
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
# ---------------------------------------------------------------------------
|
|
247
|
+
# VerifyResult
|
|
248
|
+
# ---------------------------------------------------------------------------
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class VerifyResult(TypedDict, total=False):
|
|
252
|
+
valid: bool
|
|
253
|
+
reason: Literal["expired", "invalid_hmac", "wrong_answer", "tampered", "replay"]
|
|
254
|
+
elapsed: int
|
|
255
|
+
suspicious: bool
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# ---------------------------------------------------------------------------
|
|
259
|
+
# Verifier
|
|
260
|
+
# ---------------------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
# Match JS JSON.stringify: no spaces, no non-ASCII escaping quirks. Use compact
|
|
263
|
+
# separators so the same message string is produced across runtimes.
|
|
264
|
+
_JSON_COMPACT_SEPARATORS = (",", ":")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _canonical_pipeline_json(pipeline: list[Operation]) -> str:
|
|
268
|
+
return json.dumps(pipeline, separators=_JSON_COMPACT_SEPARATORS, ensure_ascii=False)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class ImRobotVerifier:
|
|
272
|
+
"""Server-side verifier — mirrors the JS ``ImRobotVerifier`` class.
|
|
273
|
+
|
|
274
|
+
Stateless: HMAC signature ensures integrity, no DB required.
|
|
275
|
+
"""
|
|
276
|
+
|
|
277
|
+
def __init__(
|
|
278
|
+
self,
|
|
279
|
+
secret: str,
|
|
280
|
+
*,
|
|
281
|
+
difficulty: Difficulty = "medium",
|
|
282
|
+
ttl: Optional[int] = None,
|
|
283
|
+
replay_guard: Optional[ChallengeReplayGuard] = None,
|
|
284
|
+
) -> None:
|
|
285
|
+
if not secret or len(secret.strip()) < 16:
|
|
286
|
+
raise ValueError("ImRobotVerifier: secret must be at least 16 non-whitespace characters")
|
|
287
|
+
if difficulty not in SUPPORTED_DIFFICULTIES:
|
|
288
|
+
raise ValueError(f"ImRobotVerifier: difficulty must be one of {SUPPORTED_DIFFICULTIES}")
|
|
289
|
+
self._secret = secret
|
|
290
|
+
self._difficulty: Difficulty = difficulty
|
|
291
|
+
self._ttl = ttl
|
|
292
|
+
self._replay_guard = replay_guard
|
|
293
|
+
|
|
294
|
+
def _build_signature_message(
|
|
295
|
+
self,
|
|
296
|
+
challenge_id: str,
|
|
297
|
+
verification: str,
|
|
298
|
+
expires_at: int,
|
|
299
|
+
difficulty: Difficulty,
|
|
300
|
+
pipeline: Optional[list[Operation]] = None,
|
|
301
|
+
) -> str:
|
|
302
|
+
base = f"{challenge_id}:{verification}:{expires_at}:{difficulty}"
|
|
303
|
+
if pipeline is None:
|
|
304
|
+
return base
|
|
305
|
+
return f"{base}:{_canonical_pipeline_json(pipeline)}"
|
|
306
|
+
|
|
307
|
+
async def generate(
|
|
308
|
+
self,
|
|
309
|
+
*,
|
|
310
|
+
difficulty: Optional[Difficulty] = None,
|
|
311
|
+
ttl: Optional[int] = None,
|
|
312
|
+
) -> SignedChallenge:
|
|
313
|
+
chosen_difficulty = difficulty or self._difficulty
|
|
314
|
+
chosen_ttl = ttl if ttl is not None else self._ttl
|
|
315
|
+
challenge = _generate_challenge(chosen_difficulty, chosen_ttl)
|
|
316
|
+
expires_at = challenge["timestamp"] + challenge["ttl"]
|
|
317
|
+
message = self._build_signature_message(
|
|
318
|
+
challenge["id"],
|
|
319
|
+
challenge["verification"],
|
|
320
|
+
expires_at,
|
|
321
|
+
challenge["difficulty"],
|
|
322
|
+
challenge["pipeline"],
|
|
323
|
+
)
|
|
324
|
+
hmac_hex = hmac_sign(self._secret, message)
|
|
325
|
+
signed: SignedChallenge = {
|
|
326
|
+
**challenge, # type: ignore[misc]
|
|
327
|
+
"hmac": hmac_hex,
|
|
328
|
+
"expiresAt": expires_at,
|
|
329
|
+
}
|
|
330
|
+
return signed
|
|
331
|
+
|
|
332
|
+
async def verify(self, challenge: SignedChallenge, answer: str) -> VerifyResult:
|
|
333
|
+
# 1. HMAC — challenge not tampered
|
|
334
|
+
message = self._build_signature_message(
|
|
335
|
+
challenge["id"],
|
|
336
|
+
challenge["verification"],
|
|
337
|
+
challenge["expiresAt"],
|
|
338
|
+
challenge["difficulty"],
|
|
339
|
+
challenge["pipeline"],
|
|
340
|
+
)
|
|
341
|
+
if not hmac_verify(self._secret, message, challenge["hmac"]):
|
|
342
|
+
return {"valid": False, "reason": "invalid_hmac"}
|
|
343
|
+
|
|
344
|
+
# 2. Expiration
|
|
345
|
+
now = _now_ms()
|
|
346
|
+
if now > challenge["expiresAt"]:
|
|
347
|
+
return {"valid": False, "reason": "expired"}
|
|
348
|
+
|
|
349
|
+
# 3. Fast verification hash (HMAC-protected)
|
|
350
|
+
expected_verification = fnv1a(f"{answer}:{challenge['id']}")
|
|
351
|
+
if expected_verification != challenge["verification"]:
|
|
352
|
+
return {"valid": False, "reason": "wrong_answer"}
|
|
353
|
+
|
|
354
|
+
# 4. Re-execute pipeline
|
|
355
|
+
try:
|
|
356
|
+
expected_answer = execute_pipeline(challenge["seed"], challenge["pipeline"])
|
|
357
|
+
except Exception:
|
|
358
|
+
return {"valid": False, "reason": "tampered"}
|
|
359
|
+
if answer != expected_answer:
|
|
360
|
+
return {"valid": False, "reason": "tampered"}
|
|
361
|
+
|
|
362
|
+
# 5. Replay
|
|
363
|
+
if self._replay_guard is not None:
|
|
364
|
+
allowed = self._replay_guard.mark_used(challenge["id"])
|
|
365
|
+
if not allowed:
|
|
366
|
+
return {"valid": False, "reason": "replay"}
|
|
367
|
+
|
|
368
|
+
elapsed = now - challenge["timestamp"]
|
|
369
|
+
return {
|
|
370
|
+
"valid": True,
|
|
371
|
+
"elapsed": elapsed,
|
|
372
|
+
"suspicious": elapsed > SUSPICIOUS_THRESHOLD_MS,
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# ---------------------------------------------------------------------------
|
|
377
|
+
# Proof token (RFC 7519 JWT, HS256) — matches JS ``ProofTokenIssuer``
|
|
378
|
+
# ---------------------------------------------------------------------------
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _b64url_encode(data: Union[str, bytes]) -> str:
|
|
382
|
+
if isinstance(data, str):
|
|
383
|
+
data = data.encode("utf-8")
|
|
384
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _b64url_decode_str(data: str) -> str:
|
|
388
|
+
pad = "=" * ((4 - len(data) % 4) % 4)
|
|
389
|
+
return base64.urlsafe_b64decode((data + pad).encode("ascii")).decode("utf-8")
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _b64url_decode_bytes(data: str) -> bytes:
|
|
393
|
+
pad = "=" * ((4 - len(data) % 4) % 4)
|
|
394
|
+
return base64.urlsafe_b64decode((data + pad).encode("ascii"))
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
class AgentProofToken(TypedDict, total=False):
|
|
398
|
+
iss: str
|
|
399
|
+
sub: str
|
|
400
|
+
aud: Optional[str]
|
|
401
|
+
iat: int
|
|
402
|
+
nbf: int
|
|
403
|
+
exp: int
|
|
404
|
+
jti: str
|
|
405
|
+
imr: dict[str, Any]
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
class ProofTokenVerifyResult(TypedDict, total=False):
|
|
409
|
+
valid: bool
|
|
410
|
+
payload: AgentProofToken
|
|
411
|
+
keyId: str
|
|
412
|
+
reason: Literal[
|
|
413
|
+
"malformed",
|
|
414
|
+
"invalid_signature",
|
|
415
|
+
"expired",
|
|
416
|
+
"not_yet_valid",
|
|
417
|
+
"invalid_issuer",
|
|
418
|
+
"unsupported_alg",
|
|
419
|
+
"unknown_key",
|
|
420
|
+
]
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
MAX_CLOCK_SKEW_SEC = 300
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@dataclass
|
|
427
|
+
class _PreviousSecret:
|
|
428
|
+
key_id: str
|
|
429
|
+
secret: str
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
class ProofTokenIssuer:
|
|
433
|
+
"""Issue and verify RFC 7519 JWTs (HS256) — cross-compatible with the JS SDK."""
|
|
434
|
+
|
|
435
|
+
def __init__(
|
|
436
|
+
self,
|
|
437
|
+
secret: str,
|
|
438
|
+
*,
|
|
439
|
+
key_id: Optional[str] = None,
|
|
440
|
+
previous_secrets: Optional[list[dict[str, str]]] = None,
|
|
441
|
+
issuer: str = "imrobot",
|
|
442
|
+
token_ttl_ms: int = 3_600_000,
|
|
443
|
+
clock_skew_sec: int = 5,
|
|
444
|
+
) -> None:
|
|
445
|
+
if not secret or len(secret.strip()) < 16:
|
|
446
|
+
raise ValueError("ProofTokenIssuer: secret must be at least 16 non-whitespace characters")
|
|
447
|
+
self._secret = secret
|
|
448
|
+
self._key_id = key_id
|
|
449
|
+
self._issuer = issuer
|
|
450
|
+
self._token_ttl_ms = token_ttl_ms
|
|
451
|
+
self._clock_skew_sec = max(0, min(MAX_CLOCK_SKEW_SEC, clock_skew_sec))
|
|
452
|
+
self._secrets: dict[str, str] = {}
|
|
453
|
+
if key_id:
|
|
454
|
+
self._secrets[key_id] = secret
|
|
455
|
+
for prev in previous_secrets or []:
|
|
456
|
+
prev_secret = prev.get("secret") or ""
|
|
457
|
+
prev_kid = prev.get("keyId") or prev.get("key_id") or ""
|
|
458
|
+
if not prev_secret or len(prev_secret.strip()) < 16:
|
|
459
|
+
raise ValueError(
|
|
460
|
+
f"ProofTokenIssuer: previous_secrets[{prev_kid}] must be at least 16 chars"
|
|
461
|
+
)
|
|
462
|
+
self._secrets[prev_kid] = prev_secret
|
|
463
|
+
|
|
464
|
+
async def issue(
|
|
465
|
+
self,
|
|
466
|
+
*,
|
|
467
|
+
agent_id: str,
|
|
468
|
+
challenge_id: str,
|
|
469
|
+
difficulty: Difficulty,
|
|
470
|
+
solve_time_ms: int,
|
|
471
|
+
suspicious: bool,
|
|
472
|
+
audience: Optional[str] = None,
|
|
473
|
+
turnstile_verified: Optional[bool] = None,
|
|
474
|
+
web_bot_auth_verified: Optional[bool] = None,
|
|
475
|
+
) -> str:
|
|
476
|
+
now_ms = _now_ms()
|
|
477
|
+
now_sec = now_ms // 1000
|
|
478
|
+
exp_sec = (now_ms + self._token_ttl_ms) // 1000
|
|
479
|
+
jti = f"imr_{fnv1a(f'{challenge_id}:{now_ms}:{agent_id}')}"
|
|
480
|
+
|
|
481
|
+
header: dict[str, str] = {"alg": "HS256", "typ": "JWT"}
|
|
482
|
+
if self._key_id:
|
|
483
|
+
header["kid"] = self._key_id
|
|
484
|
+
|
|
485
|
+
imr: dict[str, Any] = {
|
|
486
|
+
"challenge_id": challenge_id,
|
|
487
|
+
"difficulty": difficulty,
|
|
488
|
+
"solve_time_ms": solve_time_ms,
|
|
489
|
+
"suspicious": suspicious,
|
|
490
|
+
"version": 2,
|
|
491
|
+
}
|
|
492
|
+
if turnstile_verified is not None:
|
|
493
|
+
imr["turnstile_verified"] = turnstile_verified
|
|
494
|
+
if web_bot_auth_verified is not None:
|
|
495
|
+
imr["web_bot_auth_verified"] = web_bot_auth_verified
|
|
496
|
+
|
|
497
|
+
payload: dict[str, Any] = {
|
|
498
|
+
"iss": self._issuer,
|
|
499
|
+
"sub": agent_id,
|
|
500
|
+
"iat": now_sec,
|
|
501
|
+
"nbf": now_sec,
|
|
502
|
+
"exp": exp_sec,
|
|
503
|
+
"jti": jti,
|
|
504
|
+
"imr": imr,
|
|
505
|
+
}
|
|
506
|
+
if audience is not None:
|
|
507
|
+
payload["aud"] = audience
|
|
508
|
+
|
|
509
|
+
header_b64 = _b64url_encode(json.dumps(header, separators=_JSON_COMPACT_SEPARATORS))
|
|
510
|
+
payload_b64 = _b64url_encode(json.dumps(payload, separators=_JSON_COMPACT_SEPARATORS))
|
|
511
|
+
signing_input = f"{header_b64}.{payload_b64}"
|
|
512
|
+
|
|
513
|
+
# JS signs the hex string of the HMAC (not the raw bytes). We match that
|
|
514
|
+
# exactly so tokens issued by either SDK verify on both sides.
|
|
515
|
+
signature_hex = hmac_sign(self._secret, signing_input)
|
|
516
|
+
signature_b64 = _b64url_encode(signature_hex)
|
|
517
|
+
|
|
518
|
+
return f"{signing_input}.{signature_b64}"
|
|
519
|
+
|
|
520
|
+
async def verify(self, token: str) -> ProofTokenVerifyResult:
|
|
521
|
+
parts = token.split(".")
|
|
522
|
+
if len(parts) != 3:
|
|
523
|
+
return {"valid": False, "reason": "malformed"}
|
|
524
|
+
header_b64, payload_b64, signature_b64 = parts
|
|
525
|
+
|
|
526
|
+
try:
|
|
527
|
+
header = json.loads(_b64url_decode_str(header_b64))
|
|
528
|
+
except Exception:
|
|
529
|
+
return {"valid": False, "reason": "malformed"}
|
|
530
|
+
|
|
531
|
+
if header.get("alg") != "HS256":
|
|
532
|
+
return {"valid": False, "reason": "unsupported_alg"}
|
|
533
|
+
|
|
534
|
+
candidate_secret = self._secret
|
|
535
|
+
kid = header.get("kid")
|
|
536
|
+
if kid:
|
|
537
|
+
mapped = self._secrets.get(kid)
|
|
538
|
+
if not mapped:
|
|
539
|
+
return {"valid": False, "reason": "unknown_key", "keyId": kid}
|
|
540
|
+
candidate_secret = mapped
|
|
541
|
+
|
|
542
|
+
signing_input = f"{header_b64}.{payload_b64}"
|
|
543
|
+
try:
|
|
544
|
+
signature_hex = _b64url_decode_str(signature_b64)
|
|
545
|
+
except Exception:
|
|
546
|
+
return {"valid": False, "reason": "malformed"}
|
|
547
|
+
|
|
548
|
+
if not hmac_verify(candidate_secret, signing_input, signature_hex):
|
|
549
|
+
return {"valid": False, "reason": "invalid_signature", "keyId": kid}
|
|
550
|
+
|
|
551
|
+
try:
|
|
552
|
+
payload: AgentProofToken = json.loads(_b64url_decode_str(payload_b64))
|
|
553
|
+
except Exception:
|
|
554
|
+
return {"valid": False, "reason": "malformed"}
|
|
555
|
+
|
|
556
|
+
now_sec = int(time.time())
|
|
557
|
+
exp = payload.get("exp")
|
|
558
|
+
if not isinstance(exp, int) or now_sec > exp + self._clock_skew_sec:
|
|
559
|
+
return {"valid": False, "reason": "expired", "keyId": kid}
|
|
560
|
+
nbf = payload.get("nbf")
|
|
561
|
+
if isinstance(nbf, int) and now_sec + self._clock_skew_sec < nbf:
|
|
562
|
+
return {"valid": False, "reason": "not_yet_valid", "keyId": kid}
|
|
563
|
+
if payload.get("iss") != self._issuer:
|
|
564
|
+
return {"valid": False, "reason": "invalid_issuer", "keyId": kid}
|
|
565
|
+
|
|
566
|
+
return {"valid": True, "payload": payload, "keyId": kid}
|
|
567
|
+
|
|
568
|
+
@staticmethod
|
|
569
|
+
def decode_unsafe(token: str) -> Optional[AgentProofToken]:
|
|
570
|
+
"""Decode without verifying. For debugging only."""
|
|
571
|
+
try:
|
|
572
|
+
parts = token.split(".")
|
|
573
|
+
if len(parts) != 3:
|
|
574
|
+
return None
|
|
575
|
+
return json.loads(_b64url_decode_str(parts[1]))
|
|
576
|
+
except Exception:
|
|
577
|
+
return None
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def create_verifier(
|
|
581
|
+
secret: str,
|
|
582
|
+
*,
|
|
583
|
+
difficulty: Difficulty = "medium",
|
|
584
|
+
ttl: Optional[int] = None,
|
|
585
|
+
replay_guard: Optional[ChallengeReplayGuard] = None,
|
|
586
|
+
) -> ImRobotVerifier:
|
|
587
|
+
"""Convenience wrapper matching the JS ``createVerifier`` factory."""
|
|
588
|
+
return ImRobotVerifier(secret, difficulty=difficulty, ttl=ttl, replay_guard=replay_guard)
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def create_token_issuer(
|
|
592
|
+
secret: str,
|
|
593
|
+
*,
|
|
594
|
+
key_id: Optional[str] = None,
|
|
595
|
+
previous_secrets: Optional[list[dict[str, str]]] = None,
|
|
596
|
+
issuer: str = "imrobot",
|
|
597
|
+
token_ttl_ms: int = 3_600_000,
|
|
598
|
+
clock_skew_sec: int = 5,
|
|
599
|
+
) -> ProofTokenIssuer:
|
|
600
|
+
return ProofTokenIssuer(
|
|
601
|
+
secret,
|
|
602
|
+
key_id=key_id,
|
|
603
|
+
previous_secrets=previous_secrets,
|
|
604
|
+
issuer=issuer,
|
|
605
|
+
token_ttl_ms=token_ttl_ms,
|
|
606
|
+
clock_skew_sec=clock_skew_sec,
|
|
607
|
+
)
|