@7h3/protocol 0.4.0 → 0.5.1

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.
Files changed (248) hide show
  1. package/README.md +6 -323
  2. package/agentAdapter.d.ts +26 -0
  3. package/auditLog.d.ts +54 -0
  4. package/capability.d.ts +67 -0
  5. package/cborCodec.d.ts +34 -0
  6. package/conformanceVectors.d.ts +20 -0
  7. package/encryption.d.ts +85 -0
  8. package/envelopeCbor.d.ts +33 -0
  9. package/frameworkAdapters.d.ts +72 -0
  10. package/gateway.d.ts +53 -0
  11. package/grpcBinding.d.ts +29 -0
  12. package/httpBinding.d.ts +50 -0
  13. package/index.d.ts +39 -0
  14. package/index.js +3662 -0
  15. package/keyInfra.d.ts +64 -0
  16. package/keyRegistry.d.ts +9 -0
  17. package/keyRotation.d.ts +20 -0
  18. package/mcpGateway.d.ts +37 -0
  19. package/mcpTransports.d.ts +62 -0
  20. package/mcpWrapper.d.ts +83 -0
  21. package/otel.d.ts +65 -0
  22. package/package.json +13 -79
  23. package/policyEnforcer.d.ts +50 -0
  24. package/policyTelemetryFeedback.d.ts +11 -0
  25. package/protocol.d.ts +66 -0
  26. package/protocolAgent.d.ts +58 -0
  27. package/protocolBinary.d.ts +8 -0
  28. package/protocolCapabilities.d.ts +24 -0
  29. package/protocolReplay.d.ts +35 -0
  30. package/protocolTransport.d.ts +73 -0
  31. package/queueBinding.d.ts +43 -0
  32. package/rateLimiter.d.ts +18 -0
  33. package/{src/redisClient.ts → redisClient.d.ts} +25 -75
  34. package/replayStores.d.ts +98 -0
  35. package/revocation.d.ts +71 -0
  36. package/routePolicy.d.ts +30 -0
  37. package/runtimePolicy.d.ts +24 -0
  38. package/runtimePolicyManager.d.ts +15 -0
  39. package/runtimePolicyPresets.d.ts +11 -0
  40. package/signedResponse.d.ts +21 -0
  41. package/stream.d.ts +59 -0
  42. package/telemetry.d.ts +79 -0
  43. package/webhookBinding.d.ts +30 -0
  44. package/wsBinding.d.ts +52 -0
  45. package/.dockerignore +0 -19
  46. package/.github/dependabot.yml +0 -32
  47. package/.github/workflows/ci.yml +0 -31
  48. package/.github/workflows/publish.yml +0 -59
  49. package/.github/workflows/scorecard.yml +0 -37
  50. package/7h3.example.yaml +0 -125
  51. package/CHANGELOG.md +0 -92
  52. package/CONTRIBUTING.md +0 -82
  53. package/Dockerfile +0 -73
  54. package/GOVERNANCE.md +0 -62
  55. package/SECURITY.md +0 -70
  56. package/bench-results/replay-cache-full-1777891033256.json +0 -10
  57. package/bench-results/replay-cache-full-1777896317488.json +0 -10
  58. package/bench-results/replay-cache-full-1777900993184.json +0 -10
  59. package/bench-results/replay-cache-full-1777901019285.json +0 -10
  60. package/bench-results/replay-cache-quick-1777870170126.json +0 -10
  61. package/bench-results/signature-profiles-quick-1775875160079.json +0 -85
  62. package/bench-results/signature-profiles-quick-1775983539716.json +0 -85
  63. package/bench-results/signature-profiles-quick-1776237913190.json +0 -85
  64. package/bench-results/wire-codecs-full-1777891019803.json +0 -93
  65. package/bench-results/wire-codecs-full-1777896260964.json +0 -93
  66. package/bench-results/wire-codecs-full-1777901004247.json +0 -93
  67. package/bench-results/wire-codecs-quick-1775972879056.json +0 -93
  68. package/bench-results/wire-codecs-quick-1775983541111.json +0 -93
  69. package/bench-results/wire-codecs-quick-1776237914299.json +0 -93
  70. package/bench-results/wire-codecs-quick-1777841285236.json +0 -93
  71. package/bench-results/wire-codecs-quick-1777841321772.json +0 -93
  72. package/bench-results/wire-codecs-quick-1777841330408.json +0 -93
  73. package/bench-results/wire-codecs-quick-1777852886082.json +0 -93
  74. package/bench-results/wire-codecs-quick-1777852988773.json +0 -93
  75. package/bench-results/wire-codecs-quick-1777870188095.json +0 -93
  76. package/bench-results/wire-codecs-quick-1777870263918.json +0 -93
  77. package/bench-results/wire-codecs-quick-1777870455034.json +0 -93
  78. package/bench-results/wire-codecs-quick-1778816163081.json +0 -93
  79. package/bench-results/wire-codecs-quick-1778843936130.json +0 -93
  80. package/bin/7h3.ts +0 -385
  81. package/conformance/7h3_v0_1.json +0 -77
  82. package/conformance/7h3_v0_1_binary.json +0 -20
  83. package/conformance/aip_v0_1_binary.json +0 -20
  84. package/docker-compose.yaml +0 -77
  85. package/docs/ADOPTION_PLAN.md +0 -120
  86. package/docs/AGENTS.md +0 -77
  87. package/docs/AIP_RFC_v0.1.md +0 -97
  88. package/docs/AI_DECISION_CARD.md +0 -122
  89. package/docs/AI_RUNTIME_POLICY.json +0 -126
  90. package/docs/AI_RUNTIME_POLICY.yaml +0 -110
  91. package/docs/BACKPRESSURE_TUNING.md +0 -65
  92. package/docs/BENCHMARK_CLAIM_MATRIX.md +0 -42
  93. package/docs/BENCHMARK_REPORT_TEMPLATE.md +0 -169
  94. package/docs/BINARY_CODEC_BENCH.md +0 -23
  95. package/docs/CLEAN_CLONE_RUNBOOK.md +0 -36
  96. package/docs/CLOCK_SKEW_POLICY.md +0 -30
  97. package/docs/DISTRIBUTED_REPLAY.md +0 -142
  98. package/docs/FUZZ_CAMPAIGN.md +0 -121
  99. package/docs/GATEWAY.md +0 -195
  100. package/docs/KEY_MANAGEMENT_POLICY.md +0 -53
  101. package/docs/KEY_REVOCATION.md +0 -69
  102. package/docs/MCP_WRAPPER.md +0 -159
  103. package/docs/MIGRATION_GUIDE.md +0 -40
  104. package/docs/OPERATORS.md +0 -184
  105. package/docs/PERF_REGRESSION_POLICY.md +0 -34
  106. package/docs/PROJECT_EXAMINATION_2026-05-31.md +0 -219
  107. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +0 -135
  108. package/docs/RELEASE_GATE.md +0 -25
  109. package/docs/RELEASE_NOTES_v0.1.0.md +0 -54
  110. package/docs/SECURITY_REVIEW_2026-06-05.md +0 -165
  111. package/docs/TELEMETRY.md +0 -41
  112. package/docs/THREAT_MODEL.md +0 -89
  113. package/docs/VERSIONING_POLICY.md +0 -30
  114. package/docs/assets/banner.png +0 -0
  115. package/eslint.config.js +0 -15
  116. package/fuzz/ts/harness-decode.ts +0 -136
  117. package/fuzz/ts/harness-verify.ts +0 -121
  118. package/fuzz/ts/run.ts +0 -35
  119. package/mcp-server/README.md +0 -38
  120. package/mcp-server/package-lock.json +0 -1187
  121. package/mcp-server/package.json +0 -35
  122. package/mcp-server/src/index.ts +0 -236
  123. package/mcp-server/tsconfig.json +0 -14
  124. package/scripts/aip-framework-quickstart.ts +0 -110
  125. package/scripts/aip-mcp-gateway.ts +0 -38
  126. package/scripts/aip-mcp-wrap-demo.ts +0 -72
  127. package/scripts/aip-quickstart.ts +0 -60
  128. package/scripts/bench-diff.ts +0 -118
  129. package/scripts/bench-protocol-e2e.ts +0 -937
  130. package/scripts/bench-protocol-openloop.ts +0 -1397
  131. package/scripts/bench-replay-cache.ts +0 -76
  132. package/scripts/bench-signature-profiles.ts +0 -180
  133. package/scripts/bench-wire-codecs.ts +0 -161
  134. package/scripts/build-binary-conformance.ts +0 -36
  135. package/scripts/build-release-dashboard.ts +0 -175
  136. package/scripts/canary-rollout.ts +0 -38
  137. package/scripts/mcpGatewayCli.test.ts +0 -116
  138. package/scripts/prepare-aip-package.ts +0 -88
  139. package/scripts/regen-conformance-sigs.ts +0 -18
  140. package/scripts/release-gate.ts +0 -19
  141. package/scripts/validate-runtime-policy.ts +0 -18
  142. package/sdk/browser/index.test.ts +0 -162
  143. package/sdk/browser/index.ts +0 -257
  144. package/sdk/browser/package.json +0 -13
  145. package/sdk/go/go.mod +0 -3
  146. package/sdk/go/http.go +0 -135
  147. package/sdk/go/protocol.go +0 -324
  148. package/sdk/go/protocol_test.go +0 -334
  149. package/sdk/go/webhook.go +0 -136
  150. package/sdk/python/README.md +0 -18
  151. package/sdk/python/protocol_7h3/__init__.py +0 -46
  152. package/sdk/python/protocol_7h3/http.py +0 -212
  153. package/sdk/python/protocol_7h3/keys.py +0 -149
  154. package/sdk/python/protocol_7h3/protocol.py +0 -525
  155. package/sdk/python/protocol_7h3/queue.py +0 -118
  156. package/sdk/python/protocol_7h3/webhook.py +0 -116
  157. package/sdk/python/pyproject.toml +0 -40
  158. package/sdk/python/tests/test_conformance.py +0 -110
  159. package/sdk/python/tests/test_http.py +0 -305
  160. package/sdk/python/tests/test_keys.py +0 -417
  161. package/sdk/python/tests/test_queue.py +0 -120
  162. package/sdk/python/tests/test_webhook.py +0 -345
  163. package/sdk/rust/Cargo.lock +0 -371
  164. package/sdk/rust/Cargo.toml +0 -25
  165. package/sdk/rust/README.md +0 -31
  166. package/sdk/rust/fuzz/Cargo.toml +0 -29
  167. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +0 -46
  168. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +0 -11
  169. package/sdk/rust/src/bin/aip_mcp_gateway.rs +0 -59
  170. package/sdk/rust/src/http.rs +0 -145
  171. package/sdk/rust/src/keys.rs +0 -161
  172. package/sdk/rust/src/lib.rs +0 -688
  173. package/sdk/rust/src/queue.rs +0 -79
  174. package/sdk/rust/src/webhook.rs +0 -86
  175. package/sdk/rust/tests/conformance.rs +0 -148
  176. package/sdk/rust/tests/gateway.rs +0 -130
  177. package/sdk/rust/tests/http_webhook_queue.rs +0 -201
  178. package/sdk/rust/tests/keys.rs +0 -189
  179. package/src/agentAdapter.test.ts +0 -48
  180. package/src/agentAdapter.ts +0 -56
  181. package/src/auditLog.test.ts +0 -145
  182. package/src/auditLog.ts +0 -147
  183. package/src/conformance.test.ts +0 -136
  184. package/src/conformanceVectors.ts +0 -99
  185. package/src/frameworkAdapters.test.ts +0 -290
  186. package/src/frameworkAdapters.ts +0 -261
  187. package/src/gateway.test.ts +0 -343
  188. package/src/gateway.ts +0 -171
  189. package/src/grpcBinding.test.ts +0 -211
  190. package/src/grpcBinding.ts +0 -103
  191. package/src/httpBinding.test.ts +0 -376
  192. package/src/httpBinding.ts +0 -163
  193. package/src/index.ts +0 -32
  194. package/src/keyInfra.test.ts +0 -278
  195. package/src/keyInfra.ts +0 -228
  196. package/src/keyRegistry.ts +0 -59
  197. package/src/keyRotation.test.ts +0 -78
  198. package/src/keyRotation.ts +0 -72
  199. package/src/mcpGateway.test.ts +0 -129
  200. package/src/mcpGateway.ts +0 -250
  201. package/src/mcpTransports.test.ts +0 -92
  202. package/src/mcpTransports.ts +0 -169
  203. package/src/mcpWrapper.test.ts +0 -179
  204. package/src/mcpWrapper.ts +0 -206
  205. package/src/policyEnforcer.test.ts +0 -99
  206. package/src/policyEnforcer.ts +0 -169
  207. package/src/policyTelemetryFeedback.test.ts +0 -25
  208. package/src/policyTelemetryFeedback.ts +0 -38
  209. package/src/protocol.bench.ts +0 -37
  210. package/src/protocol.test.ts +0 -155
  211. package/src/protocol.ts +0 -413
  212. package/src/protocolAgent.test.ts +0 -105
  213. package/src/protocolAgent.ts +0 -169
  214. package/src/protocolBinary.test.ts +0 -165
  215. package/src/protocolBinary.ts +0 -312
  216. package/src/protocolCapabilities.ts +0 -70
  217. package/src/protocolFuzz.advanced.test.ts +0 -235
  218. package/src/protocolFuzz.test.ts +0 -111
  219. package/src/protocolNegative.test.ts +0 -97
  220. package/src/protocolReplay.test.ts +0 -71
  221. package/src/protocolReplay.ts +0 -194
  222. package/src/protocolTransport.test.ts +0 -556
  223. package/src/protocolTransport.ts +0 -483
  224. package/src/queueBinding.test.ts +0 -130
  225. package/src/queueBinding.ts +0 -102
  226. package/src/rateLimiter.test.ts +0 -96
  227. package/src/rateLimiter.ts +0 -46
  228. package/src/redisIntegration.test.ts +0 -134
  229. package/src/replayStores.test.ts +0 -141
  230. package/src/replayStores.ts +0 -82
  231. package/src/revocation.test.ts +0 -98
  232. package/src/revocation.ts +0 -0
  233. package/src/routePolicy.test.ts +0 -87
  234. package/src/routePolicy.ts +0 -72
  235. package/src/runtimePolicy.test.ts +0 -49
  236. package/src/runtimePolicy.ts +0 -81
  237. package/src/runtimePolicyManager.test.ts +0 -29
  238. package/src/runtimePolicyManager.ts +0 -50
  239. package/src/runtimePolicyPresets.ts +0 -43
  240. package/src/signedResponse.test.ts +0 -111
  241. package/src/signedResponse.ts +0 -83
  242. package/src/webhookBinding.test.ts +0 -144
  243. package/src/webhookBinding.ts +0 -115
  244. package/src/wsBinding.test.ts +0 -221
  245. package/src/wsBinding.ts +0 -100
  246. package/tsconfig.json +0 -15
  247. package/tsconfig.lib.json +0 -23
  248. package/vite.lib.config.ts +0 -16
@@ -1,212 +0,0 @@
1
- """HTTP binding for 7h3 Protocol — signs/verifies per-request envelopes."""
2
- from __future__ import annotations
3
-
4
- import json
5
- import time
6
- import uuid
7
- import os
8
- from typing import Any, Callable, Dict, Optional, Tuple
9
-
10
- from .protocol import (
11
- verify_envelope_ed25519,
12
- verify_envelope_hmac,
13
- sign_envelope_ed25519,
14
- validate_envelope,
15
- ProtocolDiagnostic,
16
- )
17
-
18
- DEFAULT_HEADER = "x-7h3-envelope"
19
-
20
- VerifyFailReason = str # 'missing-header' | 'malformed-envelope' | 'unknown-sender' | 'invalid-signature' | 'ttl-expired'
21
-
22
-
23
- class KeyRegistry:
24
- """Abstract key registry — subclass to implement custom lookup."""
25
-
26
- def get_public_key(self, sender_id: str) -> Optional[str]:
27
- raise NotImplementedError
28
-
29
- def get_shared_secret(self, key_id: str) -> Optional[str]:
30
- return None
31
-
32
-
33
- class StaticKeyRegistry(KeyRegistry):
34
- """In-memory registry backed by a dict {sender_id: public_key_b64url}."""
35
-
36
- def __init__(self, keys: Dict[str, str]):
37
- self._keys = keys
38
-
39
- def get_public_key(self, sender_id: str) -> Optional[str]:
40
- return self._keys.get(sender_id)
41
-
42
-
43
- def _make_envelope(
44
- sender: str,
45
- ttl_ms: int,
46
- body: Dict[str, Any],
47
- recipient: Optional[str] = None,
48
- ) -> Dict[str, Any]:
49
- """Build an unsigned envelope dict."""
50
- header: Dict[str, Any] = {
51
- "version": "7h3/0.1",
52
- "messageId": str(uuid.uuid4()),
53
- "timestampMs": int(time.time() * 1000),
54
- "ttlMs": ttl_ms,
55
- "sender": sender,
56
- "nonce": os.urandom(8).hex(),
57
- }
58
- if recipient is not None:
59
- header["recipient"] = recipient
60
- return {"header": header, "body": body}
61
-
62
-
63
- def verify_http_envelope(
64
- headers: Dict[str, str],
65
- registry: KeyRegistry,
66
- *,
67
- header_name: str = DEFAULT_HEADER,
68
- strict_ttl: bool = True,
69
- ) -> Tuple[bool, Optional[dict], Optional[VerifyFailReason]]:
70
- """
71
- Verify a 7h3 envelope from HTTP headers.
72
- Returns (ok, envelope_dict, reason).
73
- reason is None on success, a VerifyFailReason string on failure.
74
- """
75
- # Headers may arrive with mixed case — normalise
76
- normalised = {k.lower(): v for k, v in headers.items()}
77
- raw = normalised.get(header_name.lower())
78
- if not raw:
79
- return False, None, "missing-header"
80
-
81
- try:
82
- envelope = json.loads(raw)
83
- except Exception:
84
- return False, None, "malformed-envelope"
85
-
86
- if not isinstance(envelope, dict) or "header" not in envelope or "signature" not in envelope:
87
- return False, None, "malformed-envelope"
88
-
89
- if strict_ttl:
90
- now_ms = int(time.time() * 1000)
91
- diags: list[ProtocolDiagnostic] = validate_envelope(envelope, now_ms=now_ms)
92
- errors = [d for d in diags if d.level == "error"]
93
- if errors:
94
- return False, None, "ttl-expired"
95
-
96
- sender = envelope.get("header", {}).get("sender", "")
97
- alg = envelope.get("signature", {}).get("alg", "")
98
-
99
- if alg == "ED25519":
100
- pub_key = registry.get_public_key(sender)
101
- if not pub_key:
102
- return False, None, "unknown-sender"
103
- valid = verify_envelope_ed25519(envelope, pub_key)
104
- if not valid:
105
- return False, None, "invalid-signature"
106
- elif alg == "HS256":
107
- key_id = envelope.get("signature", {}).get("keyId", "")
108
- secret = registry.get_shared_secret(key_id)
109
- if not secret:
110
- return False, None, "unknown-sender"
111
- valid = verify_envelope_hmac(envelope, secret)
112
- if not valid:
113
- return False, None, "invalid-signature"
114
- else:
115
- return False, None, "malformed-envelope"
116
-
117
- return True, envelope, None
118
-
119
-
120
- def sign_http_request(
121
- envelope_without_sig: dict,
122
- private_key: str,
123
- *,
124
- header_name: str = DEFAULT_HEADER,
125
- ) -> Dict[str, str]:
126
- """Sign an envelope and return HTTP headers dict to add to your request."""
127
- signed = sign_envelope_ed25519(envelope_without_sig, private_key)
128
- return {header_name: json.dumps(signed, separators=(",", ":"))}
129
-
130
-
131
- def build_signed_request_headers(
132
- sender: str,
133
- private_key: str,
134
- *,
135
- recipient: Optional[str] = None,
136
- ttl_ms: int = 60_000,
137
- content: str = "",
138
- header_name: str = DEFAULT_HEADER,
139
- ) -> Dict[str, str]:
140
- """Convenience: build envelope + sign in one call. Returns headers dict."""
141
- envelope = _make_envelope(
142
- sender=sender,
143
- ttl_ms=ttl_ms,
144
- body={"intent": "TASK", "content": content},
145
- recipient=recipient,
146
- )
147
- return sign_http_request(envelope, private_key, header_name=header_name)
148
-
149
-
150
- # --- Framework integrations ---
151
-
152
-
153
- def starlette_middleware_factory(registry: KeyRegistry, *, header_name: str = DEFAULT_HEADER):
154
- """
155
- Returns an ASGI middleware class for Starlette/FastAPI.
156
-
157
- Usage:
158
- app.add_middleware(starlette_middleware_factory(registry))
159
- """
160
- try:
161
- from starlette.middleware.base import BaseHTTPMiddleware
162
- from starlette.requests import Request
163
- from starlette.responses import JSONResponse
164
- except ImportError as e:
165
- raise ImportError("starlette is required: pip install starlette") from e
166
-
167
- class Protocol7h3Middleware(BaseHTTPMiddleware):
168
- async def dispatch(self, request: Request, call_next: Callable) -> Any:
169
- headers = dict(request.headers)
170
- ok, envelope, reason = verify_http_envelope(
171
- headers, registry, header_name=header_name
172
- )
173
- if not ok:
174
- return JSONResponse(
175
- {"error": "7h3: request verification failed", "reason": reason},
176
- status_code=401,
177
- )
178
- request.state.envelope_7h3 = envelope
179
- return await call_next(request)
180
-
181
- return Protocol7h3Middleware
182
-
183
-
184
- def flask_before_request_factory(registry: KeyRegistry, *, header_name: str = DEFAULT_HEADER):
185
- """
186
- Returns a Flask before_request handler.
187
-
188
- Usage:
189
- app.before_request(flask_before_request_factory(registry))
190
- """
191
-
192
- def before_request():
193
- try:
194
- from flask import request as flask_req, g
195
- except ImportError as e:
196
- raise ImportError("flask is required: pip install flask") from e
197
-
198
- headers = dict(flask_req.headers)
199
- ok, envelope, reason = verify_http_envelope(headers, registry, header_name=header_name)
200
- if not ok:
201
- from flask import make_response
202
-
203
- resp = make_response(
204
- json.dumps({"error": "7h3: request verification failed", "reason": reason}),
205
- 401,
206
- )
207
- resp.headers["Content-Type"] = "application/json"
208
- return resp
209
- g.envelope_7h3 = envelope
210
- return None # continue
211
-
212
- return before_request
@@ -1,149 +0,0 @@
1
- """Key infrastructure for 7h3 Protocol — discovery, rotation, revocation."""
2
- from __future__ import annotations
3
- import json
4
- import time
5
- import threading
6
- from typing import Dict, List, Optional, Any
7
- from dataclasses import dataclass, field
8
-
9
- WELL_KNOWN_PATH = "/.well-known/7h3-keys"
10
- REVOCATION_PATH = "/.well-known/7h3-revoked"
11
-
12
- @dataclass
13
- class KeyEntry:
14
- id: str
15
- algorithm: str # 'Ed25519'
16
- public_key: str # SPKI base64url
17
- created: int # Unix ms
18
- expires: Optional[int] = None
19
- revoked: bool = False
20
- revoked_at: Optional[int] = None
21
-
22
- @dataclass
23
- class WellKnownKeysDocument:
24
- version: str # '7h3/0.1'
25
- updated: int
26
- keys: List[KeyEntry]
27
-
28
- def to_json(self) -> str:
29
- keys_list = []
30
- for k in self.keys:
31
- entry = {
32
- "id": k.id, "algorithm": k.algorithm, "publicKey": k.public_key,
33
- "created": k.created,
34
- }
35
- if k.expires is not None: entry["expires"] = k.expires
36
- if k.revoked: entry["revoked"] = True
37
- if k.revoked_at is not None: entry["revokedAt"] = k.revoked_at
38
- keys_list.append(entry)
39
- return json.dumps({"version": self.version, "updated": self.updated, "keys": keys_list}, separators=(",", ":"))
40
-
41
- @classmethod
42
- def from_json(cls, data: str) -> "WellKnownKeysDocument":
43
- d = json.loads(data)
44
- keys = []
45
- for k in d.get("keys", []):
46
- keys.append(KeyEntry(
47
- id=k["id"], algorithm=k["algorithm"], public_key=k["publicKey"],
48
- created=k["created"], expires=k.get("expires"), revoked=k.get("revoked", False),
49
- revoked_at=k.get("revokedAt"),
50
- ))
51
- return cls(version=d["version"], updated=d["updated"], keys=keys)
52
-
53
-
54
- def fetch_well_known_keys(base_url: str, *, timeout: float = 5.0) -> WellKnownKeysDocument:
55
- """Fetch the /.well-known/7h3-keys document from a base URL."""
56
- import urllib.request
57
- url = base_url.rstrip("/") + WELL_KNOWN_PATH
58
- with urllib.request.urlopen(url, timeout=timeout) as resp:
59
- data = resp.read().decode("utf-8")
60
- return WellKnownKeysDocument.from_json(data)
61
-
62
-
63
- @dataclass
64
- class ManagedKeyPair:
65
- id: str
66
- public_key: str # SPKI base64url
67
- private_key: str # PKCS8 base64url
68
- created: int
69
- expires_at: Optional[int] = None
70
-
71
-
72
- class KeyRotationManager:
73
- """Manages Ed25519 key pairs with automatic rotation."""
74
-
75
- def __init__(self, max_age_ms: int = 86_400_000, overlap_ms: int = 3_600_000):
76
- self.max_age_ms = max_age_ms
77
- self.overlap_ms = overlap_ms
78
- self._keys: List[ManagedKeyPair] = []
79
- self._lock = threading.Lock()
80
-
81
- def add_key(self, pair: ManagedKeyPair) -> None:
82
- with self._lock:
83
- self._keys.append(pair)
84
-
85
- def get_current_key(self) -> Optional[ManagedKeyPair]:
86
- """Return the most recently created non-expired key."""
87
- now = int(time.time() * 1000)
88
- with self._lock:
89
- active = [k for k in self._keys if not k.expires_at or k.expires_at > now]
90
- if not active:
91
- return None
92
- return sorted(active, key=lambda k: k.created, reverse=True)[0]
93
-
94
- def rotate_if_needed(self) -> Optional[ManagedKeyPair]:
95
- """Generate a new key if the current one is too old.
96
-
97
- NOTE: generate_ed25519_keypair does not exist in protocol.py.
98
- Callers should supply keys externally via add_key() rather than
99
- relying on this method.
100
- """
101
- raise NotImplementedError(
102
- "rotate_if_needed requires generate_ed25519_keypair which is not "
103
- "implemented in protocol.py. Supply new keys externally via add_key()."
104
- )
105
-
106
- def get_well_known_document(self) -> WellKnownKeysDocument:
107
- now = int(time.time() * 1000)
108
- with self._lock:
109
- entries = []
110
- for k in self._keys:
111
- entry = KeyEntry(
112
- id=k.id, algorithm="Ed25519", public_key=k.public_key,
113
- created=k.created, expires=k.expires_at,
114
- revoked=bool(k.expires_at and k.expires_at < now),
115
- )
116
- entries.append(entry)
117
- return WellKnownKeysDocument(version="7h3/0.1", updated=now, keys=entries)
118
-
119
-
120
- class RevocationRegistry:
121
- """Tracks revoked key IDs."""
122
-
123
- def __init__(self):
124
- self._revoked: Dict[str, Dict[str, Any]] = {}
125
- self._lock = threading.Lock()
126
-
127
- def revoke(self, key_id: str, reason: Optional[str] = None) -> None:
128
- with self._lock:
129
- self._revoked[key_id] = {"revokedAt": int(time.time() * 1000), "reason": reason}
130
-
131
- def is_revoked(self, key_id: str) -> bool:
132
- with self._lock:
133
- return key_id in self._revoked
134
-
135
- def get_list(self) -> dict:
136
- now = int(time.time() * 1000)
137
- with self._lock:
138
- revoked = [
139
- {"id": kid, "revokedAt": v["revokedAt"], **({"reason": v["reason"]} if v["reason"] else {})}
140
- for kid, v in self._revoked.items()
141
- ]
142
- return {"version": "7h3/0.1", "updated": now, "revokedKeys": revoked}
143
-
144
- def import_list(self, revocation_list: dict) -> None:
145
- with self._lock:
146
- for entry in revocation_list.get("revokedKeys", []):
147
- kid = entry["id"]
148
- if kid not in self._revoked:
149
- self._revoked[kid] = {"revokedAt": entry["revokedAt"], "reason": entry.get("reason")}