agentboxd 0.1.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.
agentboxd/identity.py ADDED
@@ -0,0 +1,1199 @@
1
+ """Verify agent message signatures outside Agentboxd (https://agentboxd.com/docs/agent-messaging#verify-a-message-outside-agentboxd).
2
+
3
+ Each copy of an agent-to-agent message carries a JWS that Agentboxd made at delivery
4
+ (``message["agent"]["signature"]``): ES256, ``typ: agentboxd-msg+jwt``, bound to that copy's recipient, the
5
+ Message-ID and hashes of the content. Inside Agentboxd you don't need this (``message["agent"]["verified"]``
6
+ already says so); use it to prove a task's origin to your own backend, an auditor or another service::
7
+
8
+ from agentboxd.identity import MemoryReplayCache, verify_agent_message
9
+
10
+ replay_cache = MemoryReplayCache()
11
+ result = verify_agent_message(message, recipient="billing-agent@homingbox.net", replay_cache=replay_cache)
12
+ result["from"], result["assurance"], result["type"]
13
+
14
+ Needs the ``identity`` extra: ``pip install 'agentboxd[identity]'`` (PyJWT with cryptography, and rfc8785 for
15
+ RFC 8785 JSON canonicalization). A verified sender is not trustworthy content: treat the text and data as
16
+ untrusted input.
17
+ """
18
+
19
+ import base64
20
+ import hashlib
21
+ import json
22
+ import re
23
+ import threading
24
+ import time
25
+ from collections.abc import Mapping, Sequence
26
+ from typing import Any, Literal, Optional, Protocol, TypedDict, Union, cast
27
+
28
+ import httpx
29
+
30
+ __all__ = [
31
+ "AGENT_CLAIM",
32
+ "AGENT_MESSAGE_TYP",
33
+ "AUTHOR_JWS_TYP",
34
+ "DEFAULT_AGENT_MESSAGE_MAX_AGE_SECONDS",
35
+ "DEFAULT_IDENTITY_ISSUER",
36
+ "KEY_PROOF_AUD",
37
+ "KEY_PROOF_TYP",
38
+ "MAILBOX_CLAIM",
39
+ "MAX_IDENTITY_TOKEN_SECONDS",
40
+ "RUNBOXD_CLAIM",
41
+ "WORKSPACE_CLAIM",
42
+ "AgentIdentityError",
43
+ "AgentIdentityErrorCode",
44
+ "AgentKeyPair",
45
+ "AgentMessageVerificationError",
46
+ "AgentWorkspace",
47
+ "AuthorSignatureCoverage",
48
+ "AuthorSignatureVerificationError",
49
+ "MemoryReplayCache",
50
+ "ReplayCache",
51
+ "RevocationCheck",
52
+ "RunboxdAllowance",
53
+ "VerifiedAgentIdentity",
54
+ "VerifiedAgentMessage",
55
+ "VerifiedAuthorSignature",
56
+ "averify_agent_identity_token",
57
+ "averify_agent_message",
58
+ "create_key_proof",
59
+ "generate_agent_key",
60
+ "jwk_thumbprint",
61
+ "sign_agent_message",
62
+ "verify_agent_identity_token",
63
+ "verify_agent_message",
64
+ "verify_author_signature",
65
+ ]
66
+
67
+ DEFAULT_IDENTITY_ISSUER = "https://id.agentboxd.com"
68
+ AGENT_MESSAGE_TYP = "agentboxd-msg+jwt"
69
+ DEFAULT_AGENT_MESSAGE_MAX_AGE_SECONDS = 900
70
+ """Default freshness window for ``task`` and ``event`` messages; plain messages have none by default."""
71
+ _REPLAY_WITHOUT_MAX_AGE_SECONDS = 86_400
72
+ _KEY_CACHE_SECONDS = 300.0
73
+ _KEY_REFETCH_COOLDOWN_SECONDS = 60.0
74
+ """An unknown ``kid`` fetches the key set again at most once per URI in this window; inside it the cached set
75
+ answers, so a sender can't make every verification hit the network."""
76
+
77
+ AgentMessageErrorCode = Literal[
78
+ "dependencies_missing",
79
+ "no_signature",
80
+ "invalid_signature",
81
+ "unknown_key",
82
+ "key_revoked",
83
+ "wrong_issuer",
84
+ "wrong_audience",
85
+ "content_mismatch",
86
+ "too_old",
87
+ "issued_in_future",
88
+ "replayed",
89
+ "agent_revoked",
90
+ "agent_suspended",
91
+ "agent_deleted",
92
+ "revocation_check_failed",
93
+ ]
94
+
95
+
96
+ class RevocationCheck(TypedDict, total=False):
97
+ """``check_revocation``: ask the directory whether the sender is still in good standing
98
+ (``POST /v1/directory/verify``, uncached). ``api_key`` (required) needs ``directory:read``."""
99
+
100
+ api_key: str
101
+ base_url: str
102
+ """Default https://api.agentboxd.com."""
103
+ http_client: Any
104
+ """An ``httpx.Client`` (sync) or ``httpx.AsyncClient`` (async) to use (tests, proxies)."""
105
+
106
+
107
+ class AgentMessageVerificationError(Exception):
108
+ """Raised when an agent message signature does not verify. ``code`` says why."""
109
+
110
+ def __init__(self, code: AgentMessageErrorCode, message: str) -> None:
111
+ super().__init__(message)
112
+ self.code: AgentMessageErrorCode = code
113
+
114
+
115
+ class ReplayCache(Protocol):
116
+ """Remembers accepted nonces until they expire: ``use`` returns True the first time, False for a replay.
117
+
118
+ Implement it on Redis or your database when you run more than one process
119
+ (e.g. ``SET nonce 1 NX EXAT expires_at``)."""
120
+
121
+ def use(self, nonce: str, expires_at: float) -> bool: ...
122
+
123
+
124
+ class MemoryReplayCache:
125
+ """An in-process ReplayCache (one Python process). ``expires_at`` is in seconds since the epoch."""
126
+
127
+ def __init__(self) -> None:
128
+ self._seen: dict[str, float] = {}
129
+ self._lock = threading.Lock()
130
+
131
+ def use(self, nonce: str, expires_at: float) -> bool:
132
+ now = time.time()
133
+ with self._lock:
134
+ for key in [k for k, exp in self._seen.items() if exp < now]:
135
+ del self._seen[key]
136
+ if nonce in self._seen:
137
+ return False
138
+ self._seen[nonce] = expires_at
139
+ return True
140
+
141
+ def __len__(self) -> int:
142
+ return len(self._seen)
143
+
144
+
145
+ VerifiedAgentMessage = TypedDict(
146
+ "VerifiedAgentMessage",
147
+ {
148
+ # The sender, as Agentboxd verified it at delivery.
149
+ "from": str,
150
+ "recipient": str,
151
+ "assurance": str,
152
+ "type": str,
153
+ "msg_id": str,
154
+ "jti": str,
155
+ "nonce": str,
156
+ "kid": str,
157
+ "iat": int,
158
+ "claims": dict[str, Any],
159
+ },
160
+ )
161
+
162
+
163
+ class _Default:
164
+ pass
165
+
166
+
167
+ _DEFAULT = _Default()
168
+ MaxAge = Union[float, None, _Default]
169
+
170
+ _key_cache: dict[str, tuple[float, Mapping[str, Any]]] = {}
171
+ _key_fetched_at: dict[str, float] = {} # last fetch attempt per URI, successful or not
172
+
173
+
174
+ def _deps() -> tuple[Any, Any]:
175
+ try:
176
+ import jwt
177
+ import rfc8785
178
+ except ImportError as err: # pragma: no cover - exercised only without the extra
179
+ raise AgentMessageVerificationError(
180
+ "dependencies_missing",
181
+ f"verify_agent_message needs the identity extra: pip install 'agentboxd[identity]' ({err})",
182
+ ) from err
183
+ return jwt, rfc8785
184
+
185
+
186
+ def _bare(address: str) -> str:
187
+ m = re.search(r"<([^<>]+)>\s*$", address)
188
+ return (m.group(1) if m else address).strip().lower()
189
+
190
+
191
+ def _address_set(values: Sequence[str]) -> list[str]:
192
+ return sorted({_bare(v) for v in values if v and _bare(v)})
193
+
194
+
195
+ def _b64u(data: bytes) -> str:
196
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
197
+
198
+
199
+ def _sha(value: Union[str, bytes]) -> str:
200
+ return _b64u(hashlib.sha256(value.encode("utf-8") if isinstance(value, str) else value).digest())
201
+
202
+
203
+ def _lf(value: str) -> str:
204
+ return value.replace("\r\n", "\n").replace("\r", "\n")
205
+
206
+
207
+ def _content_mismatches(message: Mapping[str, Any], claims: Mapping[str, Any], rfc8785: Any) -> list[str]:
208
+ bad: list[str] = []
209
+
210
+ def hashed(value: Optional[str], claim: Optional[str], name: str, normalize: bool = False) -> None:
211
+ expected = None if value is None else _sha(_lf(value) if normalize else value)
212
+ if expected != claim:
213
+ bad.append(name)
214
+
215
+ if message.get("rfc_message_id") != claims.get("msg_id"):
216
+ bad.append("msg_id")
217
+ if _bare(str(message.get("from", ""))) != claims.get("from"):
218
+ bad.append("from")
219
+ if _address_set(message.get("to") or []) != list(claims.get("to") or []):
220
+ bad.append("to")
221
+ if _address_set(message.get("cc") or []) != list(claims.get("cc") or []):
222
+ bad.append("cc")
223
+ hashed(message.get("subject"), claims.get("subject_sha256"), "subject")
224
+ hashed(message.get("text"), claims.get("text_sha256"), "text", normalize=True)
225
+ hashed(message.get("html"), claims.get("html_sha256"), "html", normalize=True)
226
+ data = message.get("data")
227
+ expected_data = None if data is None else _sha(cast(bytes, rfc8785.dumps(data)))
228
+ if expected_data != claims.get("data_sha256"):
229
+ bad.append("data")
230
+ att = sorted(_b64u(bytes.fromhex(str(a["sha256"]))) for a in message.get("attachments") or [])
231
+ if att != list(claims.get("att") or []):
232
+ bad.append("attachments")
233
+ if (message.get("type") or "message") != claims.get("type"):
234
+ bad.append("type")
235
+ if message.get("in_reply_to") != claims.get("in_reply_to"):
236
+ bad.append("in_reply_to")
237
+ return bad
238
+
239
+
240
+ def _cached_keys(uri: str, fresh: bool) -> Optional[Mapping[str, Any]]:
241
+ """The cached key set unless it is stale, or ``fresh`` asks again after the refetch cooldown."""
242
+ hit = _key_cache.get(uri)
243
+ now = time.time()
244
+ if not hit or now - hit[0] >= _KEY_CACHE_SECONDS:
245
+ return None
246
+ if fresh and now - _key_fetched_at.get(uri, 0.0) >= _KEY_REFETCH_COOLDOWN_SECONDS:
247
+ return None
248
+ return hit[1]
249
+
250
+
251
+ def _fetch_keys(uri: str, fresh: bool) -> Mapping[str, Any]:
252
+ cached = _cached_keys(uri, fresh)
253
+ if cached is not None:
254
+ return cached
255
+ _key_fetched_at[uri] = time.time()
256
+ res = httpx.get(uri, headers={"Accept": "application/json"}, timeout=10)
257
+ if res.status_code != 200:
258
+ raise AgentMessageVerificationError("unknown_key", f"could not fetch {uri}: HTTP {res.status_code}")
259
+ keys = cast(Mapping[str, Any], res.json())
260
+ _key_cache[uri] = (time.time(), keys)
261
+ return keys
262
+
263
+
264
+ async def _afetch_keys(uri: str, fresh: bool) -> Mapping[str, Any]:
265
+ cached = _cached_keys(uri, fresh)
266
+ if cached is not None:
267
+ return cached
268
+ _key_fetched_at[uri] = time.time()
269
+ async with httpx.AsyncClient(timeout=10) as http:
270
+ res = await http.get(uri, headers={"Accept": "application/json"})
271
+ if res.status_code != 200:
272
+ raise AgentMessageVerificationError("unknown_key", f"could not fetch {uri}: HTTP {res.status_code}")
273
+ keys = cast(Mapping[str, Any], res.json())
274
+ _key_cache[uri] = (time.time(), keys)
275
+ return keys
276
+
277
+
278
+ def _find_key(keys: Mapping[str, Any], kid: str) -> Optional[Mapping[str, Any]]:
279
+ for k in keys.get("keys") or []:
280
+ if isinstance(k, Mapping) and k.get("kid") == kid:
281
+ return k
282
+ return None
283
+
284
+
285
+ def _signature_of(message: Mapping[str, Any], signature: Optional[str]) -> str:
286
+ agent = message.get("agent")
287
+ raw = (
288
+ signature
289
+ if signature is not None
290
+ else (agent.get("signature") if isinstance(agent, Mapping) else None)
291
+ )
292
+ sig = re.sub(r"\s+", "", raw or "")
293
+ if not sig:
294
+ raise AgentMessageVerificationError(
295
+ "no_signature", "the message carries no agent signature (not an agent-channel copy)"
296
+ )
297
+ return sig
298
+
299
+
300
+ def _header(jwt: Any, signature: str) -> dict[str, Any]:
301
+ try:
302
+ header = cast(dict[str, Any], jwt.get_unverified_header(signature))
303
+ except Exception as err:
304
+ raise AgentMessageVerificationError("invalid_signature", "not a compact JWS") from err
305
+ if header.get("alg") != "ES256" or header.get("typ") != AGENT_MESSAGE_TYP or not header.get("kid"):
306
+ raise AgentMessageVerificationError(
307
+ "invalid_signature", f"expected alg ES256, typ {AGENT_MESSAGE_TYP} and a kid"
308
+ )
309
+ return header
310
+
311
+
312
+ def _check(
313
+ jwt: Any,
314
+ rfc8785: Any,
315
+ message: Mapping[str, Any],
316
+ signature: str,
317
+ header: Mapping[str, Any],
318
+ key: Optional[Mapping[str, Any]],
319
+ *,
320
+ where: str,
321
+ recipient: str,
322
+ issuer: str,
323
+ max_age_seconds: MaxAge,
324
+ replay_cache: Optional[ReplayCache],
325
+ clock_tolerance: float,
326
+ now: Optional[float],
327
+ ) -> VerifiedAgentMessage:
328
+ kid = str(header["kid"])
329
+ if key is None:
330
+ raise AgentMessageVerificationError("unknown_key", f"no agent signing key {kid} at {where}")
331
+ jwk = {k: v for k, v in key.items() if k not in ("status", "revoked_at", "retired_at", "created_at")}
332
+ try:
333
+ public_key = jwt.PyJWK(jwk, algorithm="ES256").key
334
+ payload = jwt.api_jws.decode(signature, key=public_key, algorithms=["ES256"])
335
+ claims = cast(dict[str, Any], json.loads(payload))
336
+ except Exception as err:
337
+ raise AgentMessageVerificationError("invalid_signature", f"signature does not verify: {err}") from err
338
+ iat = claims.get("iat")
339
+ if (
340
+ not isinstance(iat, int)
341
+ or not isinstance(claims.get("nonce"), str)
342
+ or not isinstance(claims.get("aud"), str)
343
+ ):
344
+ raise AgentMessageVerificationError("invalid_signature", "missing iat, nonce or aud")
345
+ revoked_at = key.get("revoked_at")
346
+ if key.get("status") == "revoked" and isinstance(revoked_at, str):
347
+ from datetime import datetime
348
+
349
+ revoked = datetime.fromisoformat(revoked_at.replace("Z", "+00:00")).timestamp()
350
+ if revoked <= iat:
351
+ raise AgentMessageVerificationError(
352
+ "key_revoked", f"key {kid} was revoked at {revoked_at}, before this signature"
353
+ )
354
+ if claims.get("iss") != issuer:
355
+ raise AgentMessageVerificationError(
356
+ "wrong_issuer", f"issuer is {claims.get('iss')}, expected {issuer}"
357
+ )
358
+ if claims["aud"] != _bare(recipient):
359
+ raise AgentMessageVerificationError(
360
+ "wrong_audience", f"this copy was signed for {claims['aud']}, not {_bare(recipient)}"
361
+ )
362
+ bad = _content_mismatches(message, claims, rfc8785)
363
+ agent_sig = claims.get("agent_sig")
364
+ author = message.get("author")
365
+ author_sig = author.get("signature") if isinstance(author, Mapping) else None
366
+ # aSIM phase 2: the delivery signature binds the sender's own author signature.
367
+ if (
368
+ isinstance(agent_sig, Mapping)
369
+ and isinstance(author_sig, str)
370
+ and author_sig
371
+ and agent_sig.get("jws_sha256") != _sha(re.sub(r"\s+", "", author_sig))
372
+ ):
373
+ bad.append("author")
374
+ if bad:
375
+ raise AgentMessageVerificationError(
376
+ "content_mismatch", f"the message differs from what was signed: {', '.join(bad)}"
377
+ )
378
+ current = time.time() if now is None else now
379
+ if iat > current + clock_tolerance:
380
+ raise AgentMessageVerificationError("issued_in_future", "signature iat is in the future")
381
+ if isinstance(max_age_seconds, _Default):
382
+ max_age: Optional[float] = (
383
+ None if claims.get("type") == "message" else DEFAULT_AGENT_MESSAGE_MAX_AGE_SECONDS
384
+ )
385
+ else:
386
+ max_age = max_age_seconds
387
+ if max_age is not None and current - iat > max_age + clock_tolerance:
388
+ raise AgentMessageVerificationError(
389
+ "too_old", f"signed {round(current - iat)} s ago; the limit is {max_age} s"
390
+ )
391
+ if replay_cache is not None and not replay_cache.use(
392
+ str(claims["nonce"]), iat + (max_age if max_age is not None else _REPLAY_WITHOUT_MAX_AGE_SECONDS)
393
+ ):
394
+ raise AgentMessageVerificationError(
395
+ "replayed", "this signature was already accepted (nonce seen before)"
396
+ )
397
+ return {
398
+ "from": str(claims.get("from")),
399
+ "recipient": str(claims["aud"]),
400
+ "assurance": str(claims.get("assurance")),
401
+ "type": str(claims.get("type")),
402
+ "msg_id": str(claims.get("msg_id")),
403
+ "jti": str(claims.get("jti")),
404
+ "nonce": str(claims["nonce"]),
405
+ "kid": kid,
406
+ "iat": iat,
407
+ "claims": claims,
408
+ }
409
+
410
+
411
+ def _revocation_request(
412
+ check: Mapping[str, Any], signature: str
413
+ ) -> tuple[str, dict[str, str], dict[str, str]]:
414
+ api_key = check.get("api_key")
415
+ if not isinstance(api_key, str) or not api_key:
416
+ raise ValueError("check_revocation needs an api_key")
417
+ base = str(check.get("base_url") or "https://api.agentboxd.com").rstrip("/")
418
+ headers = {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
419
+ return f"{base}/v1/directory/verify", headers, {"signature": signature}
420
+
421
+
422
+ def _standing(res: Optional[httpx.Response], err: Optional[Exception]) -> None:
423
+ if res is None:
424
+ raise AgentMessageVerificationError(
425
+ "revocation_check_failed", f"the directory could not be reached: {err}"
426
+ ) from err
427
+ try:
428
+ body = res.json()
429
+ except ValueError:
430
+ body = {}
431
+ if res.status_code != 200:
432
+ code = (body.get("error") or {}).get("code", "error") if isinstance(body, dict) else "error"
433
+ raise AgentMessageVerificationError(
434
+ "revocation_check_failed", f"directory verify answered HTTP {res.status_code}: {code}"
435
+ )
436
+ status = body.get("status") if isinstance(body, dict) else None
437
+ if status == "revoked":
438
+ raise AgentMessageVerificationError(
439
+ "agent_revoked", "the sender's aSIM is revoked now (directory verify)"
440
+ )
441
+ if status == "suspended":
442
+ raise AgentMessageVerificationError(
443
+ "agent_suspended", "the sender's aSIM is suspended now (directory verify)"
444
+ )
445
+ if status == "deleted":
446
+ raise AgentMessageVerificationError(
447
+ "agent_deleted", "the sender's aSIM is deleted now (directory verify)"
448
+ )
449
+ if status != "active":
450
+ reasons = ", ".join(body.get("reasons") or []) if isinstance(body, dict) else ""
451
+ raise AgentMessageVerificationError(
452
+ "revocation_check_failed", f"the directory did not confirm the signature: {reasons or 'unknown'}"
453
+ )
454
+
455
+
456
+ def _check_standing(check: Mapping[str, Any], signature: str) -> None:
457
+ url, headers, body = _revocation_request(check, signature)
458
+ http = check.get("http_client")
459
+ try:
460
+ res = (http.post if http is not None else httpx.post)(url, headers=headers, json=body, timeout=10)
461
+ except httpx.HTTPError as err:
462
+ _standing(None, err)
463
+ return
464
+ _standing(res, None)
465
+
466
+
467
+ async def _acheck_standing(check: Mapping[str, Any], signature: str) -> None:
468
+ url, headers, body = _revocation_request(check, signature)
469
+ http = check.get("http_client")
470
+ try:
471
+ if http is not None:
472
+ res = await http.post(url, headers=headers, json=body, timeout=10)
473
+ else:
474
+ async with httpx.AsyncClient(timeout=10) as client:
475
+ res = await client.post(url, headers=headers, json=body)
476
+ except httpx.HTTPError as err:
477
+ _standing(None, err)
478
+ return
479
+ _standing(res, None)
480
+
481
+
482
+ def verify_agent_message(
483
+ message: Mapping[str, Any],
484
+ *,
485
+ recipient: str,
486
+ issuer: str = DEFAULT_IDENTITY_ISSUER,
487
+ signature: Optional[str] = None,
488
+ keys: Optional[Mapping[str, Any]] = None,
489
+ keys_uri: Optional[str] = None,
490
+ max_age_seconds: MaxAge = _DEFAULT,
491
+ replay_cache: Optional[ReplayCache] = None,
492
+ clock_tolerance: float = 30,
493
+ now: Optional[float] = None,
494
+ check_revocation: Optional[RevocationCheck] = None,
495
+ ) -> VerifiedAgentMessage:
496
+ """Verify an agent message's delivery signature. Raises :class:`AgentMessageVerificationError`.
497
+
498
+ Checks: ES256 against ``{issuer}/.well-known/agent-keys.json`` (or ``keys``; a key revoked at or before
499
+ ``iat`` fails), ``typ``, ``iss``, ``aud`` equals ``recipient`` (your address), the content hashes against
500
+ ``message`` (an API message dict), freshness (``max_age_seconds``: 900 by default for ``task``/``event``,
501
+ none for ``message``; ``None`` turns it off) and replay (``replay_cache``, keyed by ``nonce``). With
502
+ ``check_revocation`` the directory also confirms the sender is still active (codes ``agent_revoked``,
503
+ ``agent_suspended``, ``agent_deleted``, ``revocation_check_failed``). ``now`` (epoch seconds) is for
504
+ tests.
505
+ """
506
+ jwt, rfc8785 = _deps()
507
+ issuer = issuer.rstrip("/")
508
+ sig = _signature_of(message, signature)
509
+ header = _header(jwt, sig)
510
+ uri = keys_uri or f"{issuer}/.well-known/agent-keys.json"
511
+ key_set = keys if keys is not None else _fetch_keys(uri, False)
512
+ key = _find_key(key_set, str(header["kid"]))
513
+ if key is None and keys is None:
514
+ key = _find_key(_fetch_keys(uri, True), str(header["kid"])) # rotated since the last fetch
515
+ result = _check(
516
+ jwt,
517
+ rfc8785,
518
+ message,
519
+ sig,
520
+ header,
521
+ key,
522
+ where="the given key set" if keys is not None else uri,
523
+ recipient=recipient,
524
+ issuer=issuer,
525
+ max_age_seconds=max_age_seconds,
526
+ replay_cache=replay_cache,
527
+ clock_tolerance=clock_tolerance,
528
+ now=now,
529
+ )
530
+ if check_revocation is not None:
531
+ _check_standing(check_revocation, sig)
532
+ return result
533
+
534
+
535
+ async def averify_agent_message(
536
+ message: Mapping[str, Any],
537
+ *,
538
+ recipient: str,
539
+ issuer: str = DEFAULT_IDENTITY_ISSUER,
540
+ signature: Optional[str] = None,
541
+ keys: Optional[Mapping[str, Any]] = None,
542
+ keys_uri: Optional[str] = None,
543
+ max_age_seconds: MaxAge = _DEFAULT,
544
+ replay_cache: Optional[ReplayCache] = None,
545
+ clock_tolerance: float = 30,
546
+ now: Optional[float] = None,
547
+ check_revocation: Optional[RevocationCheck] = None,
548
+ ) -> VerifiedAgentMessage:
549
+ """:func:`verify_agent_message` that fetches agent-keys.json without blocking the event loop."""
550
+ jwt, rfc8785 = _deps()
551
+ issuer = issuer.rstrip("/")
552
+ sig = _signature_of(message, signature)
553
+ header = _header(jwt, sig)
554
+ uri = keys_uri or f"{issuer}/.well-known/agent-keys.json"
555
+ key_set = keys if keys is not None else await _afetch_keys(uri, False)
556
+ key = _find_key(key_set, str(header["kid"]))
557
+ if key is None and keys is None:
558
+ key = _find_key(await _afetch_keys(uri, True), str(header["kid"]))
559
+ result = _check(
560
+ jwt,
561
+ rfc8785,
562
+ message,
563
+ sig,
564
+ header,
565
+ key,
566
+ where="the given key set" if keys is not None else uri,
567
+ recipient=recipient,
568
+ issuer=issuer,
569
+ max_age_seconds=max_age_seconds,
570
+ replay_cache=replay_cache,
571
+ clock_tolerance=clock_tolerance,
572
+ now=now,
573
+ )
574
+ if check_revocation is not None:
575
+ await _acheck_standing(check_revocation, sig)
576
+ return result
577
+
578
+
579
+ # ---------- aSIM phase 2: agent-held keys and author signatures ----------
580
+ # https://agentboxd.com/docs/agent-directory (docs/asim-phase2-contract.md §1). The agent keeps its private
581
+ # key; Agentboxd only ever sees the public JWK. An author signature proves who wrote a message, also to
582
+ # parties that don't trust Agentboxd; the delivery signature (verify_agent_message) proves who received
583
+ # which copy.
584
+
585
+ AUTHOR_JWS_TYP = "agentboxd-author+jwt"
586
+ KEY_PROOF_TYP = "agentboxd-key-proof+jwt"
587
+ KEY_PROOF_AUD = "agentboxd:agent-key"
588
+ AgentKeyAlg = Literal["EdDSA", "ES256"]
589
+
590
+ AuthorErrorCode = Literal[
591
+ "dependencies_missing",
592
+ "no_signature",
593
+ "malformed",
594
+ "wrong_type",
595
+ "unknown_key",
596
+ "key_revoked",
597
+ "bad_signature",
598
+ "wrong_sender",
599
+ "content_mismatch",
600
+ ]
601
+
602
+
603
+ class AuthorSignatureVerificationError(Exception):
604
+ """Raised when an author signature does not verify. ``code`` says why."""
605
+
606
+ def __init__(self, code: AuthorErrorCode, message: str) -> None:
607
+ super().__init__(message)
608
+ self.code: AuthorErrorCode = code
609
+
610
+
611
+ class AgentKeyPair(TypedDict):
612
+ """An agent-held key pair from :func:`generate_agent_key`. Keep ``private_key`` to yourself; register
613
+ ``public_jwk`` (``client.agents.keys.register``)."""
614
+
615
+ private_key: Any
616
+ """A ``cryptography`` private key object (Ed25519 or P-256)."""
617
+ public_jwk: dict[str, str]
618
+ kid: str
619
+ """The RFC 7638 thumbprint of ``public_jwk``: the key id Agentboxd uses."""
620
+ alg: AgentKeyAlg
621
+
622
+
623
+ class AuthorSignatureCoverage(TypedDict):
624
+ """Which parts of the message the author signature covers (text of a data-only message is Agentboxd's)."""
625
+
626
+ subject: bool
627
+ text: bool
628
+ html: bool
629
+ data: bool
630
+ attachments: bool
631
+ recipients: bool
632
+ in_reply_to: bool
633
+
634
+
635
+ VerifiedAuthorSignature = TypedDict(
636
+ "VerifiedAuthorSignature",
637
+ {
638
+ # The author, as the agent's own key signed it.
639
+ "from": str,
640
+ "kid": str,
641
+ "alg": str,
642
+ "iat": int,
643
+ "covered": AuthorSignatureCoverage,
644
+ "claims": dict[str, Any],
645
+ },
646
+ )
647
+
648
+
649
+ def _author_deps() -> tuple[Any, Any]:
650
+ try:
651
+ return _deps()
652
+ except AgentMessageVerificationError as err: # pragma: no cover - exercised only without the extra
653
+ raise AuthorSignatureVerificationError("dependencies_missing", str(err)) from err
654
+
655
+
656
+ def _key_members(jwk: Mapping[str, Any]) -> dict[str, str]:
657
+ members = ("crv", "kty", "x") if jwk.get("kty") == "OKP" else ("crv", "kty", "x", "y")
658
+ return {k: str(jwk[k]) for k in members}
659
+
660
+
661
+ def jwk_thumbprint(jwk: Mapping[str, Any]) -> str:
662
+ """RFC 7638 thumbprint (SHA-256, base64url) of an Ed25519 (OKP) or P-256 (EC) public JWK."""
663
+ return _sha(json.dumps(_key_members(jwk), separators=(",", ":"), sort_keys=True))
664
+
665
+
666
+ def _alg_of(jwk: Mapping[str, Any]) -> AgentKeyAlg:
667
+ return "EdDSA" if jwk.get("kty") == "OKP" else "ES256"
668
+
669
+
670
+ def generate_agent_key(alg: AgentKeyAlg = "EdDSA") -> AgentKeyPair:
671
+ """A fresh key pair made locally: Ed25519 (``EdDSA``, the default) or P-256 (``ES256``)."""
672
+ _author_deps()
673
+ from cryptography.hazmat.primitives.asymmetric import ec, ed25519
674
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
675
+
676
+ if alg == "EdDSA":
677
+ ed_key = ed25519.Ed25519PrivateKey.generate()
678
+ raw = ed_key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
679
+ jwk = {"kty": "OKP", "crv": "Ed25519", "x": _b64u(raw)}
680
+ return {"private_key": ed_key, "public_jwk": jwk, "kid": jwk_thumbprint(jwk), "alg": "EdDSA"}
681
+ if alg != "ES256":
682
+ raise ValueError("alg must be EdDSA or ES256")
683
+ ec_key = ec.generate_private_key(ec.SECP256R1())
684
+ nums = ec_key.public_key().public_numbers()
685
+ jwk = {
686
+ "kty": "EC",
687
+ "crv": "P-256",
688
+ "x": _b64u(nums.x.to_bytes(32, "big")),
689
+ "y": _b64u(nums.y.to_bytes(32, "big")),
690
+ }
691
+ return {"private_key": ec_key, "public_jwk": jwk, "kid": jwk_thumbprint(jwk), "alg": "ES256"}
692
+
693
+
694
+ def _sign(key: Mapping[str, Any], typ: str, claims: Mapping[str, Any]) -> str:
695
+ jwt, _ = _author_deps()
696
+ private_key = key["private_key"]
697
+ alg = str(key["alg"])
698
+ if isinstance(private_key, Mapping):
699
+ private_key = jwt.PyJWK(dict(private_key), algorithm=alg).key
700
+ payload = json.dumps(dict(claims), separators=(",", ":")).encode("utf-8")
701
+ headers = {"kid": str(key["kid"]), "typ": typ}
702
+ return cast(str, jwt.api_jws.encode(payload, private_key, algorithm=alg, headers=headers))
703
+
704
+
705
+ def _nonce(nonce: Optional[str]) -> str:
706
+ import secrets
707
+
708
+ return nonce if nonce is not None else secrets.token_urlsafe(16)
709
+
710
+
711
+ def create_key_proof(
712
+ key: Mapping[str, Any], address: str, *, iat: Optional[int] = None, nonce: Optional[str] = None
713
+ ) -> str:
714
+ """The proof of possession for ``client.agents.keys.register``: a JWS by the new key, bound to the inbox
715
+ ``address`` and the key's thumbprint, valid 5 minutes and once. ``key``: an :class:`AgentKeyPair`."""
716
+ claims = {
717
+ "aud": KEY_PROOF_AUD,
718
+ "sub": address.strip().lower(),
719
+ "jkt": str(key["kid"]),
720
+ "iat": int(time.time()) if iat is None else iat,
721
+ "nonce": _nonce(nonce),
722
+ }
723
+ return _sign(key, KEY_PROOF_TYP, claims)
724
+
725
+
726
+ Recipients = Union[str, Sequence[str]]
727
+
728
+
729
+ def _recipient_list(value: Optional[Recipients]) -> Optional[list[str]]:
730
+ if value is None:
731
+ return None
732
+ return _address_set([value] if isinstance(value, str) else list(value))
733
+
734
+
735
+ def _attachment_digest(item: Any) -> str:
736
+ """base64url SHA-256 of one attachment: hex ``sha256``, raw bytes, or an attachment dict."""
737
+ if isinstance(item, (bytes, bytearray)):
738
+ return _b64u(hashlib.sha256(bytes(item)).digest())
739
+ if isinstance(item, str):
740
+ return _b64u(bytes.fromhex(item))
741
+ if isinstance(item, Mapping):
742
+ if "sha256" in item:
743
+ return _b64u(bytes.fromhex(str(item["sha256"])))
744
+ if "content_base64" in item:
745
+ return _b64u(hashlib.sha256(base64.b64decode(str(item["content_base64"]))).digest())
746
+ raise ValueError("attachments must be sha256 hex strings, bytes, or dicts with sha256 / content_base64")
747
+
748
+
749
+ def sign_agent_message(
750
+ key: Mapping[str, Any],
751
+ *,
752
+ from_: str,
753
+ subject: Optional[str] = None,
754
+ text: Optional[str] = None,
755
+ html: Optional[str] = None,
756
+ data: Any = None,
757
+ attachments: Optional[Sequence[Any]] = None,
758
+ type: str = "message",
759
+ to: Optional[Recipients] = None,
760
+ cc: Optional[Recipients] = None,
761
+ in_reply_to: Optional[str] = None,
762
+ iat: Optional[int] = None,
763
+ nonce: Optional[str] = None,
764
+ ) -> str:
765
+ """An author signature (``agent_signature`` on ``messages.send`` / ``reply``) over exactly what you send.
766
+
767
+ Pass the same ``text``, ``html``, ``data``, ``attachments`` and ``type`` you send (each is covered iff
768
+ given). ``subject``, ``to``/``cc`` (the final header recipients) and ``in_reply_to`` are optional claims;
769
+ give them on a send (a reply's subject and recipients are computed by Agentboxd). Valid for 5 minutes,
770
+ once.
771
+ ``key``: an :class:`AgentKeyPair` whose public key is registered on the sending inbox."""
772
+ _, rfc8785 = _author_deps()
773
+ claims: dict[str, Any] = {
774
+ "v": 1,
775
+ "from": _bare(from_),
776
+ "iat": int(time.time()) if iat is None else iat,
777
+ "nonce": _nonce(nonce),
778
+ "type": type,
779
+ "att": sorted(_attachment_digest(a) for a in attachments or []),
780
+ }
781
+ if text is not None:
782
+ claims["text_sha256"] = _sha(_lf(text))
783
+ if html is not None:
784
+ claims["html_sha256"] = _sha(_lf(html))
785
+ if data is not None:
786
+ claims["data_sha256"] = _sha(cast(bytes, rfc8785.dumps(data)))
787
+ if subject is not None:
788
+ claims["subject_sha256"] = _sha(subject)
789
+ to_list = _recipient_list(to)
790
+ if to_list is not None:
791
+ claims["to"] = to_list
792
+ cc_list = _recipient_list(cc)
793
+ if cc_list is not None:
794
+ claims["cc"] = cc_list
795
+ if in_reply_to:
796
+ claims["in_reply_to"] = in_reply_to
797
+ return _sign(key, AUTHOR_JWS_TYP, claims)
798
+
799
+
800
+ def _key_list(keys: Union[Mapping[str, Any], Sequence[Mapping[str, Any]]]) -> list[Mapping[str, Any]]:
801
+ raw = (keys.get("keys") or []) if isinstance(keys, Mapping) else keys
802
+ return [k for k in raw if isinstance(k, Mapping)]
803
+
804
+
805
+ def verify_author_signature(
806
+ message: Mapping[str, Any],
807
+ *,
808
+ keys: Union[Mapping[str, Any], Sequence[Mapping[str, Any]]],
809
+ signature: Optional[str] = None,
810
+ ) -> VerifiedAuthorSignature:
811
+ """Verify a message's author signature with the agent's own public keys. Raises
812
+ :class:`AuthorSignatureVerificationError`.
813
+
814
+ ``keys``: the agent's keys, e.g. ``card["keys"]["agent"]`` from ``directory.resolve`` or
815
+ ``public_directory.keys(address)`` (a key revoked at or before ``iat`` fails). Checks the signature, that
816
+ it is from the message's sender, and every claimed hash against ``message`` (an API message dict). The
817
+ result says what was ``covered``: the automatic text of a data-only message, for instance, is not."""
818
+ jwt, rfc8785 = _author_deps()
819
+ author = message.get("author")
820
+ raw = (
821
+ signature
822
+ if signature is not None
823
+ else (author.get("signature") if isinstance(author, Mapping) else None)
824
+ )
825
+ sig = re.sub(r"\s+", "", raw or "")
826
+ if not sig:
827
+ raise AuthorSignatureVerificationError("no_signature", "the message carries no author signature")
828
+ try:
829
+ header = cast(dict[str, Any], jwt.get_unverified_header(sig))
830
+ except Exception as err:
831
+ raise AuthorSignatureVerificationError("malformed", "not a compact JWS") from err
832
+ alg = header.get("alg")
833
+ kid = header.get("kid")
834
+ if header.get("typ") != AUTHOR_JWS_TYP or alg not in ("EdDSA", "ES256") or not isinstance(kid, str):
835
+ raise AuthorSignatureVerificationError(
836
+ "wrong_type", f"expected typ {AUTHOR_JWS_TYP}, alg EdDSA or ES256 and a kid"
837
+ )
838
+ key = next((k for k in _key_list(keys) if k.get("kid") == kid), None)
839
+ if key is None or _alg_of(key) != alg:
840
+ raise AuthorSignatureVerificationError("unknown_key", f"no key {kid} among the agent's keys")
841
+ try:
842
+ public_key = jwt.PyJWK(_key_members(key), algorithm=alg).key
843
+ claims = cast(dict[str, Any], json.loads(jwt.api_jws.decode(sig, key=public_key, algorithms=[alg])))
844
+ except Exception as err:
845
+ raise AuthorSignatureVerificationError("bad_signature", f"signature does not verify: {err}") from err
846
+ iat = claims.get("iat")
847
+ if claims.get("v") != 1 or not isinstance(iat, int):
848
+ raise AuthorSignatureVerificationError("malformed", "missing v or iat")
849
+ revoked_at = key.get("revoked_at")
850
+ if key.get("status") == "revoked" and isinstance(revoked_at, str):
851
+ from datetime import datetime
852
+
853
+ if datetime.fromisoformat(revoked_at.replace("Z", "+00:00")).timestamp() <= iat:
854
+ raise AuthorSignatureVerificationError(
855
+ "key_revoked", f"key {kid} was revoked at {revoked_at}, before this signature"
856
+ )
857
+ sender = _bare(str(message.get("from", "")))
858
+ if claims.get("from") != sender:
859
+ raise AuthorSignatureVerificationError(
860
+ "wrong_sender", f"signed by {claims.get('from')}, but the message is from {sender}"
861
+ )
862
+ bad: list[str] = []
863
+ if (message.get("type") or "message") != claims.get("type"):
864
+ bad.append("type")
865
+ att = sorted(_b64u(bytes.fromhex(str(a["sha256"]))) for a in message.get("attachments") or [])
866
+ if att != sorted(claims.get("att") or []):
867
+ bad.append("attachments")
868
+
869
+ def covered_hash(name: str, value: Any, claim: str, normalize: bool = False) -> bool:
870
+ if claim not in claims:
871
+ return False
872
+ if value is None or _sha(_lf(value) if normalize else value) != claims[claim]:
873
+ bad.append(name)
874
+ return True
875
+
876
+ subject = covered_hash("subject", message.get("subject"), "subject_sha256")
877
+ text = covered_hash("text", message.get("text"), "text_sha256", normalize=True)
878
+ html = covered_hash("html", message.get("html"), "html_sha256", normalize=True)
879
+ data = message.get("data")
880
+ expected_data = None if data is None else _sha(cast(bytes, rfc8785.dumps(data)))
881
+ # data is never changed by Agentboxd: present iff signed.
882
+ if expected_data != claims.get("data_sha256"):
883
+ bad.append("data")
884
+ recipients = "to" in claims or "cc" in claims
885
+ if "to" in claims and _address_set(message.get("to") or []) != list(claims["to"] or []):
886
+ bad.append("to")
887
+ if "cc" in claims and _address_set(message.get("cc") or []) != list(claims["cc"] or []):
888
+ bad.append("cc")
889
+ in_reply_to = "in_reply_to" in claims
890
+ if in_reply_to and message.get("in_reply_to") != claims["in_reply_to"]:
891
+ bad.append("in_reply_to")
892
+ if bad:
893
+ raise AuthorSignatureVerificationError(
894
+ "content_mismatch", f"the message differs from what the agent signed: {', '.join(bad)}"
895
+ )
896
+ return {
897
+ "from": sender,
898
+ "kid": kid,
899
+ "alg": str(alg),
900
+ "iat": iat,
901
+ "covered": {
902
+ "subject": subject,
903
+ "text": text,
904
+ "html": html,
905
+ "data": "data_sha256" in claims,
906
+ "attachments": True,
907
+ "recipients": recipients,
908
+ "in_reply_to": in_reply_to,
909
+ },
910
+ "claims": claims,
911
+ }
912
+
913
+
914
+ # ---------- Sign in with Agentboxd: identity tokens (https://agentboxd.com/docs/agent-identity) ----------
915
+ # The Python counterpart of the TypeScript SDK's verifyAgentIdentityToken. Needs the identity extra for PyJWT.
916
+
917
+ MAX_IDENTITY_TOKEN_SECONDS = 300
918
+ AGENT_CLAIM = "https://agentboxd.com/claims/agent"
919
+ MAILBOX_CLAIM = "https://agentboxd.com/claims/mailbox"
920
+ WORKSPACE_CLAIM = "https://agentboxd.com/claims/workspace"
921
+ RUNBOXD_CLAIM = "https://agentboxd.com/claims/runboxd"
922
+
923
+ AgentIdentityErrorCode = Literal[
924
+ "dependencies_missing",
925
+ "invalid_token",
926
+ "token_expired",
927
+ "nonce_mismatch",
928
+ "not_agent",
929
+ "token_replayed",
930
+ ]
931
+
932
+
933
+ class AgentIdentityError(Exception):
934
+ """Raised when an identity token does not verify. ``code`` says why."""
935
+
936
+ def __init__(self, code: AgentIdentityErrorCode, message: str) -> None:
937
+ super().__init__(message)
938
+ self.code: AgentIdentityErrorCode = code
939
+
940
+
941
+ class AgentWorkspace(TypedDict):
942
+ """The workspace claim: scope ``workspace`` when the workspace shares its name, or first-party apps."""
943
+
944
+ id: str
945
+ name: str
946
+
947
+
948
+ class RunboxdAllowance(TypedDict):
949
+ """The Runboxd claim: on tokens for first-party apps only. ``None`` means unlimited."""
950
+
951
+ v: int
952
+ workspace: str
953
+ plan: str
954
+ computers: Optional[int]
955
+ computer_hours: Optional[int]
956
+ memory_mb: Optional[int]
957
+ vcpus: Optional[int]
958
+
959
+
960
+ class VerifiedAgentIdentity(TypedDict):
961
+ """What ``verify_agent_identity_token`` returns. Key your user record on ``sub``."""
962
+
963
+ sub: str
964
+ email: Optional[str]
965
+ """The inbox address (scope ``email``), else None. Always None for an identity without a mailbox."""
966
+ email_verified: bool
967
+ name: Optional[str]
968
+ username: Optional[str]
969
+ is_agent: bool
970
+ mailbox: bool
971
+ """False for an identity without a mailbox."""
972
+ workspace: Optional[AgentWorkspace]
973
+ runboxd: Optional[RunboxdAllowance]
974
+ jti: str
975
+ issuer: str
976
+ audience: str
977
+ issued_at: int
978
+ expires_at: int
979
+ claims: dict[str, Any]
980
+
981
+
982
+ def _identity_jwt() -> Any:
983
+ try:
984
+ import jwt
985
+ except ImportError as err: # pragma: no cover - exercised only without the extra
986
+ raise AgentIdentityError(
987
+ "dependencies_missing",
988
+ "verify_agent_identity_token needs the identity extra: "
989
+ f"pip install 'agentboxd[identity]' ({err})",
990
+ ) from err
991
+ return jwt
992
+
993
+
994
+ def _identity_header(jwt: Any, token: str) -> str:
995
+ try:
996
+ header = jwt.get_unverified_header(token)
997
+ except Exception as err:
998
+ raise AgentIdentityError("invalid_token", f"invalid identity token: {err}") from err
999
+ if header.get("alg") != "ES256":
1000
+ raise AgentIdentityError("invalid_token", "identity tokens are ES256")
1001
+ if header.get("typ") not in (None, "JWT"):
1002
+ raise AgentIdentityError("invalid_token", f"unexpected token type {header.get('typ')}")
1003
+ kid = header.get("kid")
1004
+ if not isinstance(kid, str) or not kid:
1005
+ raise AgentIdentityError("invalid_token", "identity token has no kid")
1006
+ return kid
1007
+
1008
+
1009
+ def _identity_result(
1010
+ jwt: Any,
1011
+ token: str,
1012
+ key: Optional[Mapping[str, Any]],
1013
+ *,
1014
+ kid: str,
1015
+ audience: str,
1016
+ issuer: str,
1017
+ nonce: Optional[str],
1018
+ replay_cache: Optional[ReplayCache],
1019
+ clock_tolerance: float,
1020
+ require_agent: bool,
1021
+ now: Optional[float],
1022
+ ) -> VerifiedAgentIdentity:
1023
+ if key is None:
1024
+ raise AgentIdentityError("invalid_token", f"no signing key {kid} in the issuer's JWKS")
1025
+ try:
1026
+ public_key = jwt.PyJWK(dict(key), algorithm="ES256").key
1027
+ claims = cast(
1028
+ dict[str, Any],
1029
+ jwt.decode(
1030
+ token,
1031
+ key=public_key,
1032
+ algorithms=["ES256"],
1033
+ audience=audience,
1034
+ issuer=issuer,
1035
+ leeway=clock_tolerance,
1036
+ options={"require": ["iss", "sub", "aud", "iat", "exp", "jti"]},
1037
+ ),
1038
+ )
1039
+ except jwt.ExpiredSignatureError as err:
1040
+ raise AgentIdentityError("token_expired", "identity token expired") from err
1041
+ except Exception as err:
1042
+ raise AgentIdentityError("invalid_token", f"invalid identity token: {err}") from err
1043
+ current = time.time() if now is None else now
1044
+ iat, exp = claims["iat"], claims["exp"]
1045
+ if not isinstance(iat, (int, float)) or not isinstance(exp, (int, float)):
1046
+ raise AgentIdentityError("invalid_token", "identity token iat and exp must be numbers")
1047
+ if iat > current + clock_tolerance:
1048
+ raise AgentIdentityError("invalid_token", "identity token iat is in the future")
1049
+ if exp - iat > MAX_IDENTITY_TOKEN_SECONDS:
1050
+ raise AgentIdentityError(
1051
+ "invalid_token", f"identity token lives longer than {MAX_IDENTITY_TOKEN_SECONDS} s"
1052
+ )
1053
+ if nonce is not None and claims.get("nonce") != nonce:
1054
+ raise AgentIdentityError("nonce_mismatch", "identity token nonce does not match")
1055
+ is_agent = claims.get(AGENT_CLAIM) is True
1056
+ if require_agent and not is_agent:
1057
+ raise AgentIdentityError("not_agent", "identity token is not an agent identity")
1058
+ if replay_cache is not None and not replay_cache.use(str(claims["jti"]), float(exp)):
1059
+ raise AgentIdentityError("token_replayed", "identity token was already used")
1060
+ ws = claims.get(WORKSPACE_CLAIM)
1061
+ workspace: Optional[AgentWorkspace] = (
1062
+ {"id": ws["id"], "name": ws["name"]}
1063
+ if isinstance(ws, Mapping) and isinstance(ws.get("id"), str) and isinstance(ws.get("name"), str)
1064
+ else None
1065
+ )
1066
+ rb = claims.get(RUNBOXD_CLAIM)
1067
+ runboxd = cast(
1068
+ Optional[RunboxdAllowance], dict(rb) if isinstance(rb, Mapping) and rb.get("v") == 1 else None
1069
+ )
1070
+ return {
1071
+ "sub": str(claims["sub"]),
1072
+ "email": claims["email"] if isinstance(claims.get("email"), str) else None,
1073
+ "email_verified": claims.get("email_verified") is True,
1074
+ "name": claims["name"] if isinstance(claims.get("name"), str) else None,
1075
+ "username": claims["preferred_username"]
1076
+ if isinstance(claims.get("preferred_username"), str)
1077
+ else None,
1078
+ "is_agent": is_agent,
1079
+ "mailbox": claims.get(MAILBOX_CLAIM) is not False,
1080
+ "workspace": workspace,
1081
+ "runboxd": runboxd,
1082
+ "jti": str(claims["jti"]),
1083
+ "issuer": str(claims["iss"]),
1084
+ "audience": audience,
1085
+ "issued_at": int(iat),
1086
+ "expires_at": int(exp),
1087
+ "claims": claims,
1088
+ }
1089
+
1090
+
1091
+ def _identity_keys(uri: str, fresh: bool) -> Mapping[str, Any]:
1092
+ try:
1093
+ return _fetch_keys(uri, fresh)
1094
+ except (AgentMessageVerificationError, httpx.HTTPError) as err:
1095
+ raise AgentIdentityError("invalid_token", f"could not fetch the issuer's keys: {err}") from err
1096
+
1097
+
1098
+ async def _aidentity_keys(uri: str, fresh: bool) -> Mapping[str, Any]:
1099
+ try:
1100
+ return await _afetch_keys(uri, fresh)
1101
+ except (AgentMessageVerificationError, httpx.HTTPError) as err:
1102
+ raise AgentIdentityError("invalid_token", f"could not fetch the issuer's keys: {err}") from err
1103
+
1104
+
1105
+ def verify_agent_identity_token(
1106
+ token: str,
1107
+ *,
1108
+ audience: str,
1109
+ issuer: str = DEFAULT_IDENTITY_ISSUER,
1110
+ nonce: Optional[str] = None,
1111
+ replay_cache: Optional[ReplayCache] = None,
1112
+ clock_tolerance: float = 30,
1113
+ require_agent: bool = True,
1114
+ jwks_uri: Optional[str] = None,
1115
+ jwks: Optional[Mapping[str, Any]] = None,
1116
+ now: Optional[float] = None,
1117
+ ) -> VerifiedAgentIdentity:
1118
+ """Verify an Agentboxd identity token ("Sign in with Agentboxd").
1119
+
1120
+ Checks the ES256 signature against the issuer's JWKS (fetched again for an unknown ``kid``, after a key
1121
+ rotation, at most once a minute), ``iss``, ``aud`` (your ``client_id``), ``exp`` and ``iat`` with
1122
+ ``clock_tolerance`` seconds and at most 300 s of lifetime, ``nonce`` when given, the agent claim, and
1123
+ single use through ``replay_cache``::
1124
+
1125
+ from agentboxd.identity import MemoryReplayCache, verify_agent_identity_token
1126
+
1127
+ replay_cache = MemoryReplayCache() # several processes: implement ReplayCache on Redis
1128
+ agent = verify_agent_identity_token(
1129
+ id_token, audience="abxc_...", nonce=nonce, replay_cache=replay_cache
1130
+ )
1131
+ agent["sub"], agent["email"], agent["workspace"]
1132
+
1133
+ Pass a ``replay_cache`` unless you exchange the token at the issuer's ``/token`` (JWT bearer grant), which
1134
+ enforces single use there. Raises ``AgentIdentityError``. Needs ``pip install 'agentboxd[identity]'``.
1135
+ """
1136
+ if not audience:
1137
+ raise TypeError("verify_agent_identity_token: audience (your client_id) is required")
1138
+ jwt = _identity_jwt()
1139
+ iss = issuer.rstrip("/")
1140
+ kid = _identity_header(jwt, token)
1141
+ if jwks is not None:
1142
+ key = _find_key(jwks, kid)
1143
+ else:
1144
+ uri = jwks_uri or f"{iss}/.well-known/jwks.json"
1145
+ key = _find_key(_identity_keys(uri, False), kid) or _find_key(_identity_keys(uri, True), kid)
1146
+ return _identity_result(
1147
+ jwt,
1148
+ token,
1149
+ key,
1150
+ kid=kid,
1151
+ audience=audience,
1152
+ issuer=iss,
1153
+ nonce=nonce,
1154
+ replay_cache=replay_cache,
1155
+ clock_tolerance=clock_tolerance,
1156
+ require_agent=require_agent,
1157
+ now=now,
1158
+ )
1159
+
1160
+
1161
+ async def averify_agent_identity_token(
1162
+ token: str,
1163
+ *,
1164
+ audience: str,
1165
+ issuer: str = DEFAULT_IDENTITY_ISSUER,
1166
+ nonce: Optional[str] = None,
1167
+ replay_cache: Optional[ReplayCache] = None,
1168
+ clock_tolerance: float = 30,
1169
+ require_agent: bool = True,
1170
+ jwks_uri: Optional[str] = None,
1171
+ jwks: Optional[Mapping[str, Any]] = None,
1172
+ now: Optional[float] = None,
1173
+ ) -> VerifiedAgentIdentity:
1174
+ """The async form of ``verify_agent_identity_token`` (fetches the key set with ``httpx.AsyncClient``)."""
1175
+ if not audience:
1176
+ raise TypeError("averify_agent_identity_token: audience (your client_id) is required")
1177
+ jwt = _identity_jwt()
1178
+ iss = issuer.rstrip("/")
1179
+ kid = _identity_header(jwt, token)
1180
+ if jwks is not None:
1181
+ key = _find_key(jwks, kid)
1182
+ else:
1183
+ uri = jwks_uri or f"{iss}/.well-known/jwks.json"
1184
+ key = _find_key(await _aidentity_keys(uri, False), kid) or _find_key(
1185
+ await _aidentity_keys(uri, True), kid
1186
+ )
1187
+ return _identity_result(
1188
+ jwt,
1189
+ token,
1190
+ key,
1191
+ kid=kid,
1192
+ audience=audience,
1193
+ issuer=iss,
1194
+ nonce=nonce,
1195
+ replay_cache=replay_cache,
1196
+ clock_tolerance=clock_tolerance,
1197
+ require_agent=require_agent,
1198
+ now=now,
1199
+ )