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 ADDED
@@ -0,0 +1,83 @@
1
+ """
2
+ imrobot — Reverse-CAPTCHA that verifies AI agents (Python SDK).
3
+
4
+ Public API — mirrors the JavaScript SDK's ``imrobot`` and ``imrobot/server`` surfaces.
5
+
6
+ Solver (client side, for LangChain / CrewAI / AutoGPT / any AI agent):
7
+
8
+ >>> from imrobot import solve_challenge
9
+ >>> import httpx
10
+ >>> challenge = httpx.get("https://example.com/imrobot/challenge").json()
11
+ >>> answer = solve_challenge(challenge)
12
+ >>> httpx.post("https://example.com/imrobot/verify",
13
+ ... json={"challenge": challenge, "answer": answer})
14
+
15
+ Verifier (server side):
16
+
17
+ >>> from imrobot import ImRobotVerifier
18
+ >>> verifier = ImRobotVerifier(secret="a-32-char-server-secret-string")
19
+ >>> signed = await verifier.generate()
20
+ >>> result = await verifier.verify(signed, answer)
21
+
22
+ Proof tokens (RFC 7519 JWT, HS256):
23
+
24
+ >>> from imrobot import ProofTokenIssuer
25
+ >>> issuer = ProofTokenIssuer(secret="...")
26
+ >>> token = await issuer.issue(agent_id="agent_1", challenge_id=signed["id"],
27
+ ... difficulty="medium", solve_time_ms=42, suspicious=False)
28
+
29
+ FastAPI middleware — see ``imrobot.fastapi``.
30
+ """
31
+
32
+ from ._version import __version__
33
+ from .core import (
34
+ Challenge,
35
+ Difficulty,
36
+ Operation,
37
+ SignedChallenge,
38
+ execute_operation,
39
+ execute_pipeline,
40
+ fnv1a,
41
+ format_operation,
42
+ format_pipeline,
43
+ solve_challenge,
44
+ )
45
+ from .server import (
46
+ AgentProofToken,
47
+ ChallengeReplayGuard,
48
+ ImRobotVerifier,
49
+ InMemoryReplayGuard,
50
+ ProofTokenIssuer,
51
+ ProofTokenVerifyResult,
52
+ VerifyResult,
53
+ hmac_sign,
54
+ hmac_verify,
55
+ sha256_hex,
56
+ )
57
+
58
+ __all__ = [
59
+ "__version__",
60
+ # core types
61
+ "Challenge",
62
+ "Difficulty",
63
+ "Operation",
64
+ "SignedChallenge",
65
+ # core functions
66
+ "execute_operation",
67
+ "execute_pipeline",
68
+ "fnv1a",
69
+ "format_operation",
70
+ "format_pipeline",
71
+ "solve_challenge",
72
+ # server
73
+ "AgentProofToken",
74
+ "ChallengeReplayGuard",
75
+ "ImRobotVerifier",
76
+ "InMemoryReplayGuard",
77
+ "ProofTokenIssuer",
78
+ "ProofTokenVerifyResult",
79
+ "VerifyResult",
80
+ "hmac_sign",
81
+ "hmac_verify",
82
+ "sha256_hex",
83
+ ]
imrobot/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Single source of truth for the package version (mirrors package.json for the JS SDK)."""
2
+
3
+ __version__ = "0.8.0"
imrobot/core.py ADDED
@@ -0,0 +1,355 @@
1
+ """
2
+ Core operations, hashing, and solver — mirrors ``src/core/`` from the JS SDK.
3
+
4
+ All operations produce byte-identical output to the reference JS implementation,
5
+ so a Python-agent-side solver interoperates 1:1 with a JS-server-side verifier
6
+ and vice-versa. This is what makes ``imrobot`` a genuine cross-runtime protocol
7
+ instead of a JS-only library.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import warnings
14
+ from typing import Any, Literal, TypedDict, Union
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Types — Operation is a discriminated union keyed by "op"
18
+ # ---------------------------------------------------------------------------
19
+
20
+ Difficulty = Literal["easy", "medium", "hard"]
21
+ SUPPORTED_DIFFICULTIES: tuple[Difficulty, ...] = ("easy", "medium", "hard")
22
+ SUSPICIOUS_THRESHOLD_MS = 5_000
23
+
24
+ # Operation payloads. We use dict-based typing (matching the JSON wire format)
25
+ # rather than dataclasses so that JSON round-trips are lossless and no
26
+ # custom (de)serializer is needed.
27
+ Operation = dict[str, Any]
28
+
29
+
30
+ class Challenge(TypedDict):
31
+ """A single reverse-CAPTCHA challenge (unsigned)."""
32
+
33
+ version: int
34
+ id: str
35
+ timestamp: int
36
+ ttl: int
37
+ difficulty: Difficulty
38
+ seed: str
39
+ visibleSeed: str
40
+ nonce: str
41
+ pipeline: list[Operation]
42
+ verification: str
43
+
44
+
45
+ class SignedChallenge(Challenge):
46
+ """A challenge with server HMAC + absolute expiration timestamp."""
47
+
48
+ hmac: str
49
+ expiresAt: int
50
+
51
+
52
+ # ---------------------------------------------------------------------------
53
+ # FNV-1a — matches JS implementation bit for bit
54
+ # ---------------------------------------------------------------------------
55
+
56
+
57
+ def fnv1a(text: str) -> str:
58
+ """FNV-1a 32-bit hash — deterministic 8-char lowercase hex.
59
+
60
+ Matches the JS reference in ``src/core/hash.ts`` byte for byte.
61
+ """
62
+ h = 0x811C9DC5
63
+ for ch in text:
64
+ h ^= ord(ch)
65
+ # Math.imul equivalent: multiply mod 2^32, keep low 32 bits, treat as signed-ish
66
+ h = (h * 0x01000193) & 0xFFFFFFFF
67
+ return f"{h:08x}"
68
+
69
+
70
+ def _sync_hash256(input_str: str) -> str:
71
+ """8 rounds of FNV-1a into 64 hex chars — matches JS ``syncHash256``."""
72
+ parts = []
73
+ for i in range(8):
74
+ parts.append(fnv1a(f"{input_str}:{i}"))
75
+ return "".join(parts)
76
+
77
+
78
+ _sha256_hash_deprecation_warned = False
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # Operation execution — 1:1 port of JS ``executeOperation``
83
+ # ---------------------------------------------------------------------------
84
+
85
+
86
+ def _to_u8(code: int) -> int:
87
+ return code & 0xFF
88
+
89
+
90
+ def _to_u16_char(code: int) -> str:
91
+ # Mirror JS String.fromCharCode which uses 16-bit code units
92
+ return chr(code & 0xFFFF)
93
+
94
+
95
+ def execute_operation(input_str: str, op: Operation) -> str: # noqa: C901, PLR0911, PLR0912, PLR0915
96
+ """Execute a single operation on the input string.
97
+
98
+ Every branch matches the JS reference in ``src/core/operations.ts`` exactly,
99
+ including edge cases like ``btoa`` Latin-1 semantics for ``base64_encode``.
100
+ """
101
+ kind = op["op"]
102
+
103
+ if kind == "reverse":
104
+ return input_str[::-1]
105
+
106
+ if kind == "base64_encode":
107
+ # JS uses TextEncoder → utf-8 bytes → btoa(binary).
108
+ # base64 of utf-8 bytes gives the same result.
109
+ return base64.b64encode(input_str.encode("utf-8")).decode("ascii")
110
+
111
+ if kind == "to_upper":
112
+ return input_str.upper()
113
+
114
+ if kind == "to_lower":
115
+ return input_str.lower()
116
+
117
+ if kind == "rot13":
118
+ out = []
119
+ for c in input_str:
120
+ code = ord(c)
121
+ if 0x41 <= code <= 0x5A:
122
+ out.append(chr((code - 0x41 + 13) % 26 + 0x41))
123
+ elif 0x61 <= code <= 0x7A:
124
+ out.append(chr((code - 0x61 + 13) % 26 + 0x61))
125
+ else:
126
+ out.append(c)
127
+ return "".join(out)
128
+
129
+ if kind == "hex_encode":
130
+ return "".join(f"{ord(c):02x}" for c in input_str)
131
+
132
+ if kind == "sort_chars":
133
+ return "".join(sorted(input_str))
134
+
135
+ if kind == "char_code_sum":
136
+ return str(sum(ord(c) for c in input_str))
137
+
138
+ if kind == "substring":
139
+ # JS substring clamps to [0, len] and swaps args if start > end
140
+ start = op["start"]
141
+ end = op["end"]
142
+ length = len(input_str)
143
+ s = max(0, min(int(start), length))
144
+ e = max(0, min(int(end), length))
145
+ if s > e:
146
+ s, e = e, s
147
+ return input_str[s:e]
148
+
149
+ if kind == "repeat":
150
+ times = int(op["times"])
151
+ if times < 0:
152
+ raise ValueError("repeat: times must be non-negative")
153
+ return input_str * times
154
+
155
+ if kind == "replace":
156
+ return input_str.replace(op["search"], op["replacement"])
157
+
158
+ if kind == "pad_start":
159
+ length = int(op["length"])
160
+ fill = op["fill"]
161
+ if length <= len(input_str) or not fill:
162
+ return input_str
163
+ needed = length - len(input_str)
164
+ # Match JS String.prototype.padStart: repeat fill and truncate to needed
165
+ rep = (fill * ((needed // len(fill)) + 1))[:needed]
166
+ return rep + input_str
167
+
168
+ if kind == "xor_encode":
169
+ key = int(op["key"])
170
+ return "".join(_to_u16_char(ord(c) ^ key) for c in input_str)
171
+
172
+ if kind == "count_chars":
173
+ return str(input_str.count(op["char"]))
174
+
175
+ if kind == "caesar":
176
+ shift = int(op["shift"])
177
+ out = []
178
+ for c in input_str:
179
+ code = ord(c)
180
+ if 0x41 <= code <= 0x5A:
181
+ out.append(chr(((code - 0x41 + shift) % 26 + 26) % 26 + 0x41))
182
+ elif 0x61 <= code <= 0x7A:
183
+ out.append(chr(((code - 0x61 + shift) % 26 + 26) % 26 + 0x61))
184
+ else:
185
+ out.append(c)
186
+ return "".join(out)
187
+
188
+ if kind == "slice_alternate":
189
+ return input_str[::2]
190
+
191
+ if kind == "fnv1a_hash":
192
+ return fnv1a(input_str)
193
+
194
+ if kind == "length":
195
+ return str(len(input_str))
196
+
197
+ if kind == "sha256_hash":
198
+ global _sha256_hash_deprecation_warned
199
+ if not _sha256_hash_deprecation_warned:
200
+ _sha256_hash_deprecation_warned = True
201
+ warnings.warn(
202
+ "[im_robot] The { 'op': 'sha256_hash' } operation is deprecated and will be "
203
+ "removed in a future major version. Use { 'op': 'hash_chain', 'rounds': 1 } "
204
+ "for single-pass FNV-1a hashing, or { 'op': 'fnv1a_hash' } for a fast "
205
+ "non-cryptographic hash. See https://github.com/leopechnicki/im_robot for "
206
+ "migration details.",
207
+ DeprecationWarning,
208
+ stacklevel=2,
209
+ )
210
+ return _sync_hash256(input_str)
211
+
212
+ if kind == "fnv1a_cascade":
213
+ return _sync_hash256(input_str)
214
+
215
+ if kind == "byte_xor":
216
+ key_arr = op["key"]
217
+ if not key_arr:
218
+ raise ValueError("byte_xor: key must not be empty")
219
+ return "".join(
220
+ _to_u16_char(ord(c) ^ int(key_arr[i % len(key_arr)]))
221
+ for i, c in enumerate(input_str)
222
+ )
223
+
224
+ if kind == "hash_chain":
225
+ rounds = int(op["rounds"])
226
+ if rounds < 1:
227
+ raise ValueError("hash_chain: rounds must be at least 1")
228
+ val = input_str
229
+ for r in range(rounds):
230
+ val = fnv1a(f"{val}:{r}")
231
+ return val
232
+
233
+ if kind == "nibble_swap":
234
+ out = []
235
+ for c in input_str:
236
+ code = ord(c)
237
+ swapped = ((code & 0x0F) << 4) | ((code & 0xF0) >> 4)
238
+ out.append(_to_u16_char(swapped))
239
+ return "".join(out)
240
+
241
+ if kind == "bit_rotate":
242
+ shift = ((int(op["bits"]) % 8) + 8) % 8
243
+ out = []
244
+ for c in input_str:
245
+ code = _to_u8(ord(c))
246
+ rotated = ((code << shift) | (code >> (8 - shift))) & 0xFF
247
+ out.append(_to_u16_char(rotated))
248
+ return "".join(out)
249
+
250
+ if kind == "vowel_count":
251
+ vowels = set("aeiouAEIOU")
252
+ return str(sum(1 for c in input_str if c in vowels))
253
+
254
+ if kind == "consonant_extract":
255
+ vowels = set("aeiouAEIOU")
256
+ return "".join(
257
+ c for c in input_str if c.isascii() and c.isalpha() and c not in vowels
258
+ )
259
+
260
+ if kind == "run_length_encode":
261
+ if not input_str:
262
+ return ""
263
+ result = []
264
+ count = 1
265
+ for i in range(1, len(input_str) + 1):
266
+ if i < len(input_str) and input_str[i] == input_str[i - 1]:
267
+ count += 1
268
+ else:
269
+ result.append(f"{count}{input_str[i - 1]}" if count > 1 else input_str[i - 1])
270
+ count = 1
271
+ return "".join(result)
272
+
273
+ if kind == "atbash":
274
+ out = []
275
+ for c in input_str:
276
+ code = ord(c)
277
+ if 0x41 <= code <= 0x5A:
278
+ out.append(chr(0x41 + (25 - (code - 0x41))))
279
+ elif 0x61 <= code <= 0x7A:
280
+ out.append(chr(0x61 + (25 - (code - 0x61))))
281
+ else:
282
+ out.append(c)
283
+ return "".join(out)
284
+
285
+ raise ValueError(f"Unknown operation: {kind}")
286
+
287
+
288
+ def execute_pipeline(seed: str, pipeline: list[Operation]) -> str:
289
+ """Execute the full pipeline: seed -> op1 -> op2 -> ... -> answer."""
290
+ value = seed
291
+ for op in pipeline:
292
+ value = execute_operation(value, op)
293
+ return value
294
+
295
+
296
+ # ---------------------------------------------------------------------------
297
+ # Solver — the canonical entry point for AI agents
298
+ # ---------------------------------------------------------------------------
299
+
300
+
301
+ def solve_challenge(challenge: Union[Challenge, SignedChallenge, dict[str, Any]]) -> str:
302
+ """Solve a signed or unsigned challenge.
303
+
304
+ ``challenge`` may be a dict fetched from ``GET /imrobot/challenge`` verbatim.
305
+ Returns the answer string to POST back to ``/imrobot/verify``.
306
+ """
307
+ return execute_pipeline(challenge["seed"], challenge["pipeline"])
308
+
309
+
310
+ # ---------------------------------------------------------------------------
311
+ # Format helpers — mirror JS ``formatOperation``/``formatPipeline`` for debug
312
+ # ---------------------------------------------------------------------------
313
+
314
+
315
+ def format_operation(op: Operation) -> str:
316
+ """Return a short debug string for a single operation."""
317
+ kind = op["op"]
318
+ if kind in {
319
+ "reverse", "base64_encode", "to_upper", "to_lower", "rot13", "hex_encode",
320
+ "sort_chars", "char_code_sum", "slice_alternate", "fnv1a_hash", "length",
321
+ "nibble_swap", "vowel_count", "consonant_extract", "run_length_encode",
322
+ "atbash", "fnv1a_cascade",
323
+ }:
324
+ return f"{kind}()"
325
+ if kind == "substring":
326
+ return f"substring({op['start']}, {op['end']})"
327
+ if kind == "repeat":
328
+ return f"repeat({op['times']})"
329
+ if kind == "replace":
330
+ return f"replace(\"{op['search']}\", \"{op['replacement']}\")"
331
+ if kind == "pad_start":
332
+ return f"pad_start({op['length']}, \"{op['fill']}\")"
333
+ if kind == "xor_encode":
334
+ return f"xor_encode({op['key']})"
335
+ if kind == "count_chars":
336
+ return f"count_chars(\"{op['char']}\")"
337
+ if kind == "caesar":
338
+ return f"caesar({op['shift']})"
339
+ if kind == "sha256_hash":
340
+ return "fnv1a_cascade() /* was: sha256_hash — deprecated alias */"
341
+ if kind == "byte_xor":
342
+ return f"byte_xor([{','.join(str(x) for x in op['key'])}])"
343
+ if kind == "hash_chain":
344
+ return f"hash_chain({op['rounds']})"
345
+ if kind == "bit_rotate":
346
+ return f"bit_rotate({op['bits']})"
347
+ return f"{kind}(?)"
348
+
349
+
350
+ def format_pipeline(seed: str, pipeline: list[Operation]) -> str:
351
+ """Return a multi-line, human-readable representation of the pipeline."""
352
+ lines = [f'seed: "{seed}"']
353
+ for i, op in enumerate(pipeline, start=1):
354
+ lines.append(f" {i}. {format_operation(op)}")
355
+ return "\n".join(lines)
imrobot/fastapi.py ADDED
@@ -0,0 +1,187 @@
1
+ """
2
+ FastAPI / Starlette middleware for imrobot — the Python mirror of
3
+ ``imrobot/hono`` and ``imrobot/next``.
4
+
5
+ Usage:
6
+
7
+ .. code-block:: python
8
+
9
+ from fastapi import FastAPI, Depends
10
+ from imrobot import ImRobotVerifier, ProofTokenIssuer
11
+ from imrobot.fastapi import create_imrobot_router, require_agent
12
+
13
+ app = FastAPI()
14
+ secret = os.environ["IMROBOT_SECRET"]
15
+
16
+ # Mount /imrobot/challenge and /imrobot/verify
17
+ router = create_imrobot_router(secret=secret)
18
+ app.include_router(router, prefix="/imrobot")
19
+
20
+ # Protect a route with a proof token dependency
21
+ @app.get("/api/agent-data", dependencies=[Depends(require_agent(secret=secret))])
22
+ def agent_only():
23
+ return {"secret": "only bots see this"}
24
+
25
+ FastAPI/Starlette are imported lazily so ``imrobot`` remains dep-free for
26
+ consumers that only use the solver/verifier.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from typing import Any, Awaitable, Callable, Optional
32
+
33
+ from .core import fnv1a
34
+ from .server import (
35
+ ChallengeReplayGuard,
36
+ Difficulty,
37
+ ImRobotVerifier,
38
+ ProofTokenIssuer,
39
+ SignedChallenge,
40
+ )
41
+
42
+ DEFAULT_PROOF_HEADER = "X-Agent-Proof"
43
+ DEFAULT_ISSUER = "imrobot"
44
+ DEFAULT_TOKEN_TTL_MS = 3_600_000
45
+
46
+
47
+ def _default_agent_id(_request: Any, challenge: SignedChallenge) -> str:
48
+ return f"agent_{fnv1a(challenge['id'] + ':' + str(challenge['timestamp']))}"
49
+
50
+
51
+ def _import_fastapi() -> Any:
52
+ try:
53
+ import fastapi as _fastapi # type: ignore[import-not-found]
54
+ from fastapi import responses as _responses # type: ignore[import-not-found]
55
+ except ImportError as exc: # pragma: no cover
56
+ raise ImportError(
57
+ "FastAPI is required for imrobot.fastapi. Install with: pip install 'imrobot[fastapi]'"
58
+ ) from exc
59
+ return _fastapi, _responses
60
+
61
+
62
+ def create_imrobot_router(
63
+ *,
64
+ secret: str,
65
+ difficulty: Difficulty = "medium",
66
+ ttl: Optional[int] = None,
67
+ replay_guard: Optional[ChallengeReplayGuard] = None,
68
+ proof_header: str = DEFAULT_PROOF_HEADER,
69
+ issuer_name: str = DEFAULT_ISSUER,
70
+ token_ttl_ms: int = DEFAULT_TOKEN_TTL_MS,
71
+ agent_id_from: Optional[Callable[[Any, SignedChallenge], str]] = None,
72
+ ) -> Any:
73
+ """Build a FastAPI ``APIRouter`` with GET /challenge and POST /verify."""
74
+ _fastapi, _responses = _import_fastapi()
75
+ APIRouter = _fastapi.APIRouter
76
+ Request = _fastapi.Request
77
+ JSONResponse = _responses.JSONResponse
78
+
79
+ verifier = ImRobotVerifier(
80
+ secret=secret, difficulty=difficulty, ttl=ttl, replay_guard=replay_guard
81
+ )
82
+ token_issuer = ProofTokenIssuer(
83
+ secret=secret, issuer=issuer_name, token_ttl_ms=token_ttl_ms
84
+ )
85
+ resolve_agent_id = agent_id_from or _default_agent_id
86
+
87
+ router = APIRouter()
88
+
89
+ @router.get("/challenge")
90
+ async def challenge_route() -> Any:
91
+ signed = await verifier.generate()
92
+ return signed
93
+
94
+ async def verify_route(request) -> Any:
95
+ try:
96
+ body = await request.json()
97
+ except Exception:
98
+ return JSONResponse(
99
+ status_code=400, content={"valid": False, "reason": "invalid_json"}
100
+ )
101
+ challenge_obj = body.get("challenge") if isinstance(body, dict) else None
102
+ answer = body.get("answer") if isinstance(body, dict) else None
103
+ if not challenge_obj or not isinstance(answer, str):
104
+ return JSONResponse(
105
+ status_code=400, content={"valid": False, "reason": "missing_fields"}
106
+ )
107
+ result = await verifier.verify(challenge_obj, answer)
108
+ if not result.get("valid"):
109
+ return JSONResponse(status_code=400, content=result)
110
+ token = await token_issuer.issue(
111
+ agent_id=resolve_agent_id(request, challenge_obj),
112
+ challenge_id=challenge_obj["id"],
113
+ difficulty=challenge_obj["difficulty"],
114
+ solve_time_ms=result.get("elapsed", 0),
115
+ suspicious=result.get("suspicious", False),
116
+ )
117
+ response = JSONResponse(content={**result, "proofToken": token})
118
+ response.headers[proof_header] = token
119
+ return response
120
+
121
+ # Explicit annotation binding so FastAPI DI treats `request` as the
122
+ # Request object (not a body model). Closure-scoped imports would
123
+ # otherwise be invisible to FastAPI's signature inspection.
124
+ verify_route.__annotations__["request"] = Request
125
+ router.add_api_route("/verify", verify_route, methods=["POST"])
126
+
127
+ return router
128
+
129
+
130
+ def require_agent(
131
+ *,
132
+ secret: str,
133
+ header_name: str = DEFAULT_PROOF_HEADER,
134
+ issuer_name: str = DEFAULT_ISSUER,
135
+ clock_skew_sec: int = 5,
136
+ key_id: Optional[str] = None,
137
+ previous_secrets: Optional[list[dict[str, str]]] = None,
138
+ bypass: Optional[Callable[[Any], Awaitable[bool]]] = None,
139
+ ) -> Callable[..., Awaitable[dict[str, Any]]]:
140
+ """FastAPI dependency that enforces a valid ``X-Agent-Proof`` token.
141
+
142
+ Returns the decoded JWT payload as a dict — inject with ``Depends``.
143
+ """
144
+ _fastapi, _ = _import_fastapi()
145
+ HTTPException = _fastapi.HTTPException
146
+ Request = _fastapi.Request
147
+
148
+ token_issuer = ProofTokenIssuer(
149
+ secret=secret,
150
+ issuer=issuer_name,
151
+ clock_skew_sec=clock_skew_sec,
152
+ key_id=key_id,
153
+ previous_secrets=previous_secrets,
154
+ )
155
+
156
+ async def _dep(request: Any) -> dict[str, Any]:
157
+ # `request` is a starlette/FastAPI Request. We use Any here (not
158
+ # Request) because the FastAPI import is closure-scoped for optional
159
+ # peer dependency — mypy can't see the type in the outer scope.
160
+ if bypass is not None:
161
+ skip = await bypass(request)
162
+ if skip:
163
+ return {"agent_verified": True, "bypassed": True}
164
+ token = request.headers.get(header_name)
165
+ if not token:
166
+ raise HTTPException(
167
+ status_code=401,
168
+ detail={
169
+ "error": "agent_proof_required",
170
+ "message": f"Missing {header_name} header — call /imrobot/verify first.",
171
+ },
172
+ )
173
+ result = await token_issuer.verify(token)
174
+ if not result.get("valid") or "payload" not in result:
175
+ raise HTTPException(
176
+ status_code=401,
177
+ detail={
178
+ "error": "agent_proof_invalid",
179
+ "reason": result.get("reason", "unknown"),
180
+ },
181
+ )
182
+ return dict(result["payload"])
183
+
184
+ # Explicit annotation binding so FastAPI's DI knows this parameter is
185
+ # the request object, not a body model — same fix pattern as verify_route.
186
+ _dep.__annotations__["request"] = Request
187
+ return _dep
imrobot/py.typed ADDED
File without changes