@7h3/protocol 0.5.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 (294) hide show
  1. package/README.md +6 -1317
  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 -121
  23. package/policyEnforcer.d.ts +50 -0
  24. package/policyTelemetryFeedback.d.ts +11 -0
  25. package/{src/protocol.d.ts → protocol.d.ts} +1 -2
  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 -152
  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 -406
  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-github.png +0 -0
  115. package/docs/assets/banner.png +0 -0
  116. package/docs/assets/banner.svg +0 -123
  117. package/eslint.config.js +0 -15
  118. package/fuzz/ts/harness-decode.ts +0 -136
  119. package/fuzz/ts/harness-verify.ts +0 -121
  120. package/fuzz/ts/run.ts +0 -35
  121. package/mcp-server/README.md +0 -38
  122. package/mcp-server/package-lock.json +0 -1187
  123. package/mcp-server/package.json +0 -35
  124. package/mcp-server/src/index.ts +0 -236
  125. package/mcp-server/tsconfig.json +0 -14
  126. package/scripts/aip-framework-quickstart.ts +0 -110
  127. package/scripts/aip-mcp-gateway.ts +0 -38
  128. package/scripts/aip-mcp-wrap-demo.ts +0 -72
  129. package/scripts/aip-quickstart.ts +0 -60
  130. package/scripts/bench-diff.ts +0 -118
  131. package/scripts/bench-protocol-e2e.ts +0 -937
  132. package/scripts/bench-protocol-openloop.ts +0 -1397
  133. package/scripts/bench-replay-cache.ts +0 -76
  134. package/scripts/bench-signature-profiles.ts +0 -180
  135. package/scripts/bench-wire-codecs.ts +0 -161
  136. package/scripts/build-binary-conformance.ts +0 -36
  137. package/scripts/build-release-dashboard.ts +0 -175
  138. package/scripts/canary-rollout.ts +0 -38
  139. package/scripts/mcpGatewayCli.test.ts +0 -116
  140. package/scripts/prepare-aip-package.ts +0 -88
  141. package/scripts/regen-conformance-sigs.ts +0 -18
  142. package/scripts/release-gate.ts +0 -19
  143. package/scripts/validate-runtime-policy.ts +0 -18
  144. package/sdk/browser/index.test.ts +0 -162
  145. package/sdk/browser/index.ts +0 -257
  146. package/sdk/browser/package.json +0 -13
  147. package/sdk/go/cbor.go +0 -551
  148. package/sdk/go/cbor_test.go +0 -232
  149. package/sdk/go/encryption.go +0 -280
  150. package/sdk/go/encryption_test.go +0 -318
  151. package/sdk/go/go.mod +0 -7
  152. package/sdk/go/go.sum +0 -4
  153. package/sdk/go/http.go +0 -135
  154. package/sdk/go/protocol.go +0 -324
  155. package/sdk/go/protocol_test.go +0 -334
  156. package/sdk/go/replay.go +0 -121
  157. package/sdk/go/replay_test.go +0 -149
  158. package/sdk/go/webhook.go +0 -136
  159. package/sdk/pq/package-lock.json +0 -1358
  160. package/sdk/pq/package.json +0 -42
  161. package/sdk/pq/src/index.test.ts +0 -143
  162. package/sdk/pq/src/index.ts +0 -166
  163. package/sdk/pq/tsconfig.json +0 -14
  164. package/sdk/pq/vitest.config.ts +0 -7
  165. package/sdk/python/README.md +0 -18
  166. package/sdk/python/protocol_7h3/__init__.py +0 -46
  167. package/sdk/python/protocol_7h3/encryption.py +0 -252
  168. package/sdk/python/protocol_7h3/http.py +0 -212
  169. package/sdk/python/protocol_7h3/keys.py +0 -149
  170. package/sdk/python/protocol_7h3/pq.py +0 -244
  171. package/sdk/python/protocol_7h3/protocol.py +0 -525
  172. package/sdk/python/protocol_7h3/queue.py +0 -118
  173. package/sdk/python/protocol_7h3/replay.py +0 -98
  174. package/sdk/python/protocol_7h3/webhook.py +0 -116
  175. package/sdk/python/pyproject.toml +0 -40
  176. package/sdk/python/tests/test_conformance.py +0 -110
  177. package/sdk/python/tests/test_encryption.py +0 -206
  178. package/sdk/python/tests/test_http.py +0 -305
  179. package/sdk/python/tests/test_keys.py +0 -417
  180. package/sdk/python/tests/test_queue.py +0 -120
  181. package/sdk/python/tests/test_webhook.py +0 -345
  182. package/sdk/rust/Cargo.lock +0 -371
  183. package/sdk/rust/Cargo.toml +0 -25
  184. package/sdk/rust/README.md +0 -31
  185. package/sdk/rust/fuzz/Cargo.toml +0 -29
  186. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +0 -46
  187. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +0 -11
  188. package/sdk/rust/src/bin/aip_mcp_gateway.rs +0 -59
  189. package/sdk/rust/src/http.rs +0 -145
  190. package/sdk/rust/src/keys.rs +0 -161
  191. package/sdk/rust/src/lib.rs +0 -688
  192. package/sdk/rust/src/queue.rs +0 -79
  193. package/sdk/rust/src/webhook.rs +0 -86
  194. package/sdk/rust/tests/conformance.rs +0 -148
  195. package/sdk/rust/tests/gateway.rs +0 -130
  196. package/sdk/rust/tests/http_webhook_queue.rs +0 -201
  197. package/sdk/rust/tests/keys.rs +0 -189
  198. package/sdk/threshold/index.d.ts +0 -68
  199. package/sdk/threshold/index.d.ts.map +0 -1
  200. package/sdk/threshold/index.js +0 -254
  201. package/sdk/threshold/package-lock.json +0 -1361
  202. package/sdk/threshold/package.json +0 -39
  203. package/sdk/threshold/src/index.d.ts +0 -68
  204. package/sdk/threshold/src/index.d.ts.map +0 -1
  205. package/sdk/threshold/src/index.js +0 -254
  206. package/sdk/threshold/src/index.test.ts +0 -238
  207. package/sdk/threshold/src/index.ts +0 -355
  208. package/sdk/threshold/tsconfig.json +0 -19
  209. package/sdk/threshold/vitest.config.ts +0 -12
  210. package/src/agentAdapter.test.ts +0 -48
  211. package/src/agentAdapter.ts +0 -56
  212. package/src/auditLog.test.ts +0 -145
  213. package/src/auditLog.ts +0 -147
  214. package/src/capability.test.ts +0 -504
  215. package/src/capability.ts +0 -380
  216. package/src/cborCodec.test.ts +0 -263
  217. package/src/cborCodec.ts +0 -339
  218. package/src/conformance.test.ts +0 -136
  219. package/src/conformanceVectors.ts +0 -99
  220. package/src/encryption.test.ts +0 -206
  221. package/src/encryption.ts +0 -245
  222. package/src/envelopeCbor.ts +0 -140
  223. package/src/frameworkAdapters.test.ts +0 -290
  224. package/src/frameworkAdapters.ts +0 -261
  225. package/src/gateway.test.ts +0 -343
  226. package/src/gateway.ts +0 -246
  227. package/src/grpcBinding.test.ts +0 -211
  228. package/src/grpcBinding.ts +0 -103
  229. package/src/httpBinding.test.ts +0 -376
  230. package/src/httpBinding.ts +0 -189
  231. package/src/index.ts +0 -39
  232. package/src/keyInfra.test.ts +0 -278
  233. package/src/keyInfra.ts +0 -228
  234. package/src/keyRegistry.ts +0 -59
  235. package/src/keyRotation.test.ts +0 -78
  236. package/src/keyRotation.ts +0 -72
  237. package/src/mcpGateway.test.ts +0 -129
  238. package/src/mcpGateway.ts +0 -250
  239. package/src/mcpTransports.test.ts +0 -92
  240. package/src/mcpTransports.ts +0 -169
  241. package/src/mcpWrapper.test.ts +0 -179
  242. package/src/mcpWrapper.ts +0 -206
  243. package/src/otel.ts +0 -136
  244. package/src/policyEnforcer.test.ts +0 -99
  245. package/src/policyEnforcer.ts +0 -169
  246. package/src/policyTelemetryFeedback.test.ts +0 -25
  247. package/src/policyTelemetryFeedback.ts +0 -38
  248. package/src/protocol.bench.ts +0 -37
  249. package/src/protocol.d.ts.map +0 -1
  250. package/src/protocol.js +0 -294
  251. package/src/protocol.test.ts +0 -155
  252. package/src/protocol.ts +0 -414
  253. package/src/protocolAgent.test.ts +0 -105
  254. package/src/protocolAgent.ts +0 -169
  255. package/src/protocolBinary.test.ts +0 -165
  256. package/src/protocolBinary.ts +0 -312
  257. package/src/protocolCapabilities.ts +0 -70
  258. package/src/protocolFuzz.advanced.test.ts +0 -235
  259. package/src/protocolFuzz.test.ts +0 -111
  260. package/src/protocolNegative.test.ts +0 -97
  261. package/src/protocolReplay.test.ts +0 -71
  262. package/src/protocolReplay.ts +0 -194
  263. package/src/protocolTransport.test.ts +0 -556
  264. package/src/protocolTransport.ts +0 -483
  265. package/src/queueBinding.test.ts +0 -130
  266. package/src/queueBinding.ts +0 -102
  267. package/src/rateLimiter.test.ts +0 -96
  268. package/src/rateLimiter.ts +0 -46
  269. package/src/redisIntegration.test.ts +0 -134
  270. package/src/replayStores.test.ts +0 -273
  271. package/src/replayStores.ts +0 -215
  272. package/src/revocation.test.ts +0 -98
  273. package/src/revocation.ts +0 -0
  274. package/src/routePolicy.test.ts +0 -87
  275. package/src/routePolicy.ts +0 -72
  276. package/src/runtimePolicy.test.ts +0 -49
  277. package/src/runtimePolicy.ts +0 -81
  278. package/src/runtimePolicyManager.test.ts +0 -29
  279. package/src/runtimePolicyManager.ts +0 -50
  280. package/src/runtimePolicyPresets.ts +0 -43
  281. package/src/signedResponse.test.ts +0 -111
  282. package/src/signedResponse.ts +0 -83
  283. package/src/stream.test.ts +0 -254
  284. package/src/stream.ts +0 -417
  285. package/src/telemetry.test.ts +0 -251
  286. package/src/telemetry.ts +0 -299
  287. package/src/webhookBinding.test.ts +0 -144
  288. package/src/webhookBinding.ts +0 -115
  289. package/src/wsBinding.test.ts +0 -221
  290. package/src/wsBinding.ts +0 -200
  291. package/tsconfig.json +0 -15
  292. package/tsconfig.lib.json +0 -23
  293. package/vite.lib.config.ts +0 -16
  294. package/vitest.config.ts +0 -11
@@ -1,525 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import base64
4
- import hashlib
5
- import hmac
6
- import json
7
- from dataclasses import dataclass
8
- from typing import Any, Dict, Optional, TypedDict
9
-
10
- # ---------------------------------------------------------------------------
11
- # Optional native Ed25519 backend — try cryptography, then PyNaCl
12
- # ---------------------------------------------------------------------------
13
-
14
- try:
15
- from cryptography.hazmat.primitives import serialization
16
- from cryptography.hazmat.primitives.asymmetric.ed25519 import (
17
- Ed25519PrivateKey,
18
- Ed25519PublicKey,
19
- )
20
-
21
- _HAS_CRYPTOGRAPHY = True
22
- except Exception:
23
- _HAS_CRYPTOGRAPHY = False
24
-
25
- try:
26
- import nacl.signing as _nacl_signing # type: ignore[import]
27
-
28
- _HAS_NACL = True
29
- except Exception:
30
- _HAS_NACL = False
31
-
32
- # ---------------------------------------------------------------------------
33
- # Pure-Python Ed25519 fallback (no external dependencies)
34
- #
35
- # Uses extended twisted Edwards coordinates (X:Y:Z:T) to eliminate the
36
- # expensive field inversion from the inner loop — inversion runs once at
37
- # point compression only. ~10–50 ms/op in CPython; correct for conformance
38
- # testing. Install 'cryptography' for production-grade performance.
39
- #
40
- # Based on the reference implementation: https://ed25519.cr.yp.to/software.html
41
- # ---------------------------------------------------------------------------
42
-
43
- _P = 2**255 - 19
44
- _L = 2**252 + 27742317777372353535851937790883648493
45
- _D = -121665 * pow(121666, _P - 2, _P) % _P
46
- _SQRT_M1 = pow(2, (_P - 1) // 4, _P)
47
-
48
- # Base point G in extended coordinates (X:Y:Z:T)
49
- _GY = 4 * pow(5, _P - 2, _P) % _P
50
- _GX_SQ = (_GY * _GY - 1) * pow(_D * _GY * _GY + 1, _P - 2, _P) % _P
51
- _GX = pow(_GX_SQ, (_P + 3) // 8, _P)
52
- if (_GX * _GX - _GX_SQ) % _P != 0:
53
- _GX = _GX * _SQRT_M1 % _P
54
- if _GX & 1:
55
- _GX = _P - _GX
56
- _G_BASE = (_GX, _GY, 1, _GX * _GY % _P)
57
-
58
-
59
- def _point_add(P: tuple, Q: tuple) -> tuple:
60
- A = (P[1] - P[0]) * (Q[1] - Q[0]) % _P
61
- B = (P[1] + P[0]) * (Q[1] + Q[0]) % _P
62
- C = 2 * P[3] * Q[3] * _D % _P
63
- D_ = 2 * P[2] * Q[2] % _P
64
- E = B - A
65
- F = D_ - C
66
- G_ = D_ + C
67
- H = B + A
68
- return (E * F % _P, G_ * H % _P, F * G_ % _P, E * H % _P)
69
-
70
-
71
- def _point_mul(s: int, P: tuple) -> tuple:
72
- Q: tuple = (0, 1, 1, 0) # neutral element
73
- while s > 0:
74
- if s & 1:
75
- Q = _point_add(Q, P)
76
- P = _point_add(P, P)
77
- s >>= 1
78
- return Q
79
-
80
-
81
- def _compress(P: tuple) -> bytes:
82
- zi = pow(P[2], _P - 2, _P)
83
- x = P[0] * zi % _P
84
- y = P[1] * zi % _P
85
- return int.to_bytes(y | ((x & 1) << 255), 32, "little")
86
-
87
-
88
- def _decompress(b: bytes) -> Optional[tuple]:
89
- y = int.from_bytes(b, "little")
90
- sign = y >> 255
91
- y &= (1 << 255) - 1
92
- x2 = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P) % _P
93
- if x2 == 0:
94
- return (0, y, 1, 0) if sign == 0 else None
95
- x = pow(x2, (_P + 3) // 8, _P)
96
- if (x * x - x2) % _P != 0:
97
- x = x * _SQRT_M1 % _P
98
- if (x * x - x2) % _P != 0:
99
- return None
100
- if x & 1 != sign:
101
- x = _P - x
102
- return (x, y, 1, x * y % _P)
103
-
104
-
105
- def _py_ed25519_sign(seed: bytes, message: bytes) -> bytes:
106
- h = hashlib.sha512(seed).digest()
107
- a_bytes = bytearray(h[:32])
108
- a_bytes[0] &= 248
109
- a_bytes[31] &= 127
110
- a_bytes[31] |= 64
111
- a = int.from_bytes(a_bytes, "little")
112
- prefix = h[32:]
113
- A = _compress(_point_mul(a, _G_BASE))
114
- r = int.from_bytes(hashlib.sha512(prefix + message).digest(), "little") % _L
115
- R = _compress(_point_mul(r, _G_BASE))
116
- S = (r + int.from_bytes(hashlib.sha512(R + A + message).digest(), "little") * a) % _L
117
- return R + int.to_bytes(S, 32, "little")
118
-
119
-
120
- def _py_ed25519_verify(pub_bytes: bytes, message: bytes, sig: bytes) -> bool:
121
- if len(sig) != 64 or len(pub_bytes) != 32:
122
- return False
123
- A = _decompress(pub_bytes)
124
- if A is None:
125
- return False
126
- R_pt = _decompress(sig[:32])
127
- if R_pt is None:
128
- return False
129
- s = int.from_bytes(sig[32:], "little")
130
- if s >= _L:
131
- return False
132
- h = int.from_bytes(hashlib.sha512(sig[:32] + pub_bytes + message).digest(), "little")
133
- sB = _point_mul(s, _G_BASE)
134
- hA = _point_mul(h, A)
135
- return _compress(sB) == _compress(_point_add(R_pt, hA))
136
-
137
-
138
- # ---------------------------------------------------------------------------
139
- # DER key extraction helpers
140
- #
141
- # WebCrypto exports Ed25519 keys as PKCS8 (private) and SPKI (public) DER.
142
- # Both formats have a fixed structure for Ed25519 with known byte offsets:
143
- #
144
- # PKCS8 v0 (48 bytes):
145
- # 30 2e 02 01 00 30 05 06 03 2b 65 70 04 22 04 20 [32-byte seed]
146
- #
147
- # SPKI (44 bytes):
148
- # 30 2a 30 05 06 03 2b 65 70 03 21 00 [32-byte public key]
149
- # ---------------------------------------------------------------------------
150
-
151
- # fmt: off
152
- _PKCS8_ED25519_LEN = 48 # 30 2e 02 01 00 30 05 06 03 2b 65 70 04 22 04 20 [32-byte seed]
153
- _SPKI_ED25519_LEN = 44 # 30 2a 30 05 06 03 2b 65 70 03 21 00 [32-byte public key]
154
- # fmt: on
155
-
156
-
157
- def _seed_from_pkcs8(pkcs8_der: bytes) -> bytes:
158
- if len(pkcs8_der) != 48:
159
- raise ValueError(
160
- f"Ed25519 PKCS8 DER must be 48 bytes, got {len(pkcs8_der)}. "
161
- "Ensure the key was exported with SubtleCrypto.exportKey('pkcs8', key)."
162
- )
163
- return pkcs8_der[16:48]
164
-
165
-
166
- def _pubkey_from_spki(spki_der: bytes) -> bytes:
167
- if len(spki_der) != 44:
168
- raise ValueError(
169
- f"Ed25519 SPKI DER must be 44 bytes, got {len(spki_der)}. "
170
- "Ensure the key was exported with SubtleCrypto.exportKey('spki', key)."
171
- )
172
- return spki_der[12:44]
173
-
174
-
175
- # ---------------------------------------------------------------------------
176
- # Protocol types
177
- # ---------------------------------------------------------------------------
178
-
179
-
180
- class ProtocolHeader(TypedDict, total=False):
181
- version: str
182
- messageId: str
183
- timestampMs: int
184
- ttlMs: int
185
- sender: str
186
- recipient: str
187
- nonce: str
188
-
189
-
190
- class ProtocolBody(TypedDict, total=False):
191
- intent: str
192
- content: str
193
- capability: str
194
- correlationId: str
195
-
196
-
197
- class ProtocolSignature(TypedDict):
198
- alg: str
199
- keyId: str
200
- value: str
201
-
202
-
203
- class ProtocolEnvelope(TypedDict, total=False):
204
- header: ProtocolHeader
205
- body: ProtocolBody
206
- signature: ProtocolSignature
207
-
208
-
209
- @dataclass(frozen=True)
210
- class ProtocolDiagnostic:
211
- level: str
212
- message: str
213
-
214
-
215
- # ---------------------------------------------------------------------------
216
- # Utility
217
- # ---------------------------------------------------------------------------
218
-
219
-
220
- def _json_string(value: Any) -> str:
221
- return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
222
-
223
-
224
- def _base64url(data: bytes) -> str:
225
- return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
226
-
227
-
228
- def _base64url_decode(value: str) -> bytes:
229
- padding = "=" * ((4 - (len(value) % 4)) % 4)
230
- return base64.urlsafe_b64decode(value + padding)
231
-
232
-
233
- # ---------------------------------------------------------------------------
234
- # Canonicalization
235
- # ---------------------------------------------------------------------------
236
-
237
-
238
- def canonicalize_envelope(envelope: Dict[str, Any]) -> str:
239
- header = envelope["header"]
240
- body = envelope["body"]
241
-
242
- body_parts = []
243
- if "capability" in body and body["capability"] is not None:
244
- body_parts.append(f'"capability":{_json_string(body["capability"])}')
245
- body_parts.append(f'"content":{_json_string(body["content"])}')
246
- if "correlationId" in body and body["correlationId"] is not None:
247
- body_parts.append(f'"correlationId":{_json_string(body["correlationId"])}')
248
- body_parts.append(f'"intent":{_json_string(body["intent"])}')
249
-
250
- header_parts = [
251
- f'"messageId":{_json_string(header["messageId"])}',
252
- f'"nonce":{_json_string(header["nonce"])}',
253
- ]
254
- if "recipient" in header and header["recipient"] is not None:
255
- header_parts.append(f'"recipient":{_json_string(header["recipient"])}')
256
- header_parts.extend(
257
- [
258
- f'"sender":{_json_string(header["sender"])}',
259
- f'"timestampMs":{int(header["timestampMs"])}',
260
- f'"ttlMs":{int(header["ttlMs"])}',
261
- f'"version":{_json_string(header["version"])}',
262
- ]
263
- )
264
-
265
- return (
266
- f'{{"body":{{{",".join(body_parts)}}},"header":{{{",".join(header_parts)}}}}}'
267
- )
268
-
269
-
270
- # ---------------------------------------------------------------------------
271
- # HMAC-SHA256 (HS256)
272
- # ---------------------------------------------------------------------------
273
-
274
-
275
- def sign_canonical_payload_hmac(canonical_payload: str, secret: str) -> str:
276
- digest = hmac.new(
277
- secret.encode("utf-8"), canonical_payload.encode("utf-8"), hashlib.sha256
278
- ).digest()
279
- return _base64url(digest)
280
-
281
-
282
- def verify_canonical_payload_hmac(
283
- canonical_payload: str, signature: str, secret: str
284
- ) -> bool:
285
- expected = sign_canonical_payload_hmac(canonical_payload, secret)
286
- return hmac.compare_digest(signature, expected)
287
-
288
-
289
- # ---------------------------------------------------------------------------
290
- # Ed25519 — tries cryptography → PyNaCl → pure-Python in order
291
- # ---------------------------------------------------------------------------
292
-
293
-
294
- def sign_canonical_payload_ed25519(
295
- canonical_payload: str, private_key_pkcs8_base64url: str
296
- ) -> str:
297
- private_der = _base64url_decode(private_key_pkcs8_base64url)
298
- msg = canonical_payload.encode("utf-8")
299
-
300
- if _HAS_CRYPTOGRAPHY:
301
- key = serialization.load_der_private_key(private_der, password=None)
302
- if not isinstance(key, Ed25519PrivateKey):
303
- raise ValueError("DER key is not an Ed25519 private key")
304
- return _base64url(key.sign(msg))
305
-
306
- if _HAS_NACL:
307
- seed = _seed_from_pkcs8(private_der)
308
- sk = _nacl_signing.SigningKey(seed)
309
- return _base64url(bytes(sk.sign(msg).signature))
310
-
311
- # Pure-Python fallback
312
- seed = _seed_from_pkcs8(private_der)
313
- return _base64url(_py_ed25519_sign(seed, msg))
314
-
315
-
316
- def verify_canonical_payload_ed25519(
317
- canonical_payload: str, signature: str, public_key_spki_base64url: str
318
- ) -> bool:
319
- public_der = _base64url_decode(public_key_spki_base64url)
320
- msg = canonical_payload.encode("utf-8")
321
- sig_bytes = _base64url_decode(signature)
322
-
323
- if _HAS_CRYPTOGRAPHY:
324
- try:
325
- key = serialization.load_der_public_key(public_der)
326
- if not isinstance(key, Ed25519PublicKey):
327
- return False
328
- key.verify(sig_bytes, msg)
329
- return True
330
- except Exception:
331
- return False
332
-
333
- if _HAS_NACL:
334
- try:
335
- pub_bytes = _pubkey_from_spki(public_der)
336
- vk = _nacl_signing.VerifyKey(pub_bytes)
337
- vk.verify(msg, sig_bytes)
338
- return True
339
- except Exception:
340
- return False
341
-
342
- # Pure-Python fallback
343
- try:
344
- pub_bytes = _pubkey_from_spki(public_der)
345
- return _py_ed25519_verify(pub_bytes, msg, sig_bytes)
346
- except Exception:
347
- return False
348
-
349
-
350
- # ---------------------------------------------------------------------------
351
- # Envelope-level sign/verify helpers
352
- # ---------------------------------------------------------------------------
353
-
354
-
355
- def sign_envelope_hmac(
356
- envelope: Dict[str, Any], secret: str, key_id: str = "python-dev-key"
357
- ) -> Dict[str, Any]:
358
- canonical = canonicalize_envelope(envelope)
359
- signature = sign_canonical_payload_hmac(canonical, secret)
360
- return {
361
- "header": dict(envelope["header"]),
362
- "body": dict(envelope["body"]),
363
- "signature": {"alg": "HS256", "keyId": key_id, "value": signature},
364
- }
365
-
366
-
367
- def verify_envelope_hmac(envelope: Dict[str, Any], secret: str) -> bool:
368
- signature = envelope.get("signature")
369
- if not signature:
370
- return False
371
- if signature.get("alg") != "HS256":
372
- return False
373
- unsigned = {"header": envelope["header"], "body": envelope["body"]}
374
- canonical = canonicalize_envelope(unsigned)
375
- return verify_canonical_payload_hmac(canonical, signature.get("value", ""), secret)
376
-
377
-
378
- def sign_envelope_ed25519(
379
- envelope: Dict[str, Any],
380
- private_key_pkcs8_base64url: str,
381
- key_id: str = "python-ed25519-key",
382
- ) -> Dict[str, Any]:
383
- canonical = canonicalize_envelope(envelope)
384
- signature = sign_canonical_payload_ed25519(canonical, private_key_pkcs8_base64url)
385
- return {
386
- "header": dict(envelope["header"]),
387
- "body": dict(envelope["body"]),
388
- "signature": {"alg": "ED25519", "keyId": key_id, "value": signature},
389
- }
390
-
391
-
392
- def verify_envelope_ed25519(
393
- envelope: Dict[str, Any], public_key_spki_base64url: str
394
- ) -> bool:
395
- signature = envelope.get("signature")
396
- if not signature:
397
- return False
398
- if signature.get("alg") != "ED25519":
399
- return False
400
- unsigned = {"header": envelope["header"], "body": envelope["body"]}
401
- canonical = canonicalize_envelope(unsigned)
402
- return verify_canonical_payload_ed25519(
403
- canonical, signature.get("value", ""), public_key_spki_base64url
404
- )
405
-
406
-
407
- # ---------------------------------------------------------------------------
408
- # Wire encode/decode
409
- # ---------------------------------------------------------------------------
410
-
411
-
412
- def encode_envelope_compact(envelope: Dict[str, Any]) -> str:
413
- header = envelope["header"]
414
- body = envelope["body"]
415
- compact: Dict[str, Any] = {
416
- "v": header["version"],
417
- "mid": header["messageId"],
418
- "ts": header["timestampMs"],
419
- "ttl": header["ttlMs"],
420
- "s": header["sender"],
421
- "n": header["nonce"],
422
- "i": body["intent"],
423
- "c": body["content"],
424
- }
425
- if "recipient" in header and header["recipient"] is not None:
426
- compact["r"] = header["recipient"]
427
- if "capability" in body and body["capability"] is not None:
428
- compact["cap"] = body["capability"]
429
- if "correlationId" in body and body["correlationId"] is not None:
430
- compact["cid"] = body["correlationId"]
431
-
432
- signature = envelope.get("signature")
433
- if signature:
434
- compact["sig"] = {
435
- "a": signature.get("alg", "HS256"),
436
- "k": signature["keyId"],
437
- "v": signature["value"],
438
- }
439
-
440
- return _json_string(compact)
441
-
442
-
443
- def decode_envelope(raw: str) -> Dict[str, Any]:
444
- parsed = json.loads(raw)
445
- if "header" in parsed and "body" in parsed:
446
- return parsed
447
-
448
- if parsed.get("v") != "7h3/0.1" or "mid" not in parsed or "i" not in parsed:
449
- raise ValueError("Envelope JSON shape is not recognized")
450
-
451
- header: Dict[str, Any] = {
452
- "version": parsed["v"],
453
- "messageId": parsed["mid"],
454
- "timestampMs": parsed["ts"],
455
- "ttlMs": parsed["ttl"],
456
- "sender": parsed["s"],
457
- "nonce": parsed["n"],
458
- }
459
- if "r" in parsed:
460
- header["recipient"] = parsed["r"]
461
-
462
- body: Dict[str, Any] = {
463
- "intent": parsed["i"],
464
- "content": parsed["c"],
465
- }
466
- if "cap" in parsed:
467
- body["capability"] = parsed["cap"]
468
- if "cid" in parsed:
469
- body["correlationId"] = parsed["cid"]
470
-
471
- envelope: Dict[str, Any] = {"header": header, "body": body}
472
- if parsed.get("sig"):
473
- envelope["signature"] = {
474
- "alg": parsed["sig"].get("a", "HS256"),
475
- "keyId": parsed["sig"]["k"],
476
- "value": parsed["sig"]["v"],
477
- }
478
- return envelope
479
-
480
-
481
- # ---------------------------------------------------------------------------
482
- # Envelope validation
483
- # ---------------------------------------------------------------------------
484
-
485
-
486
- def validate_envelope(
487
- envelope: Dict[str, Any], now_ms: Optional[int] = None
488
- ) -> list[ProtocolDiagnostic]:
489
- header = envelope["header"]
490
- body = envelope["body"]
491
- current = int(now_ms if now_ms is not None else 0)
492
- diagnostics: list[ProtocolDiagnostic] = []
493
-
494
- if header.get("version") != "7h3/0.1":
495
- diagnostics.append(
496
- ProtocolDiagnostic(
497
- level="error",
498
- message=f"Unsupported protocol version '{header.get('version')}'",
499
- )
500
- )
501
- if not str(header.get("messageId", "")).strip():
502
- diagnostics.append(
503
- ProtocolDiagnostic(level="error", message="Missing messageId")
504
- )
505
- if not str(header.get("sender", "")).strip():
506
- diagnostics.append(
507
- ProtocolDiagnostic(level="error", message="Missing sender identity")
508
- )
509
- if int(header.get("ttlMs", 0)) <= 0:
510
- diagnostics.append(
511
- ProtocolDiagnostic(level="error", message="ttlMs must be greater than zero")
512
- )
513
-
514
- if now_ms is not None:
515
- if int(header.get("timestampMs", 0)) + int(header.get("ttlMs", 0)) < current:
516
- diagnostics.append(
517
- ProtocolDiagnostic(level="error", message="Message TTL expired")
518
- )
519
-
520
- if not str(body.get("content", "")).strip():
521
- diagnostics.append(
522
- ProtocolDiagnostic(level="warning", message="Empty content payload")
523
- )
524
-
525
- return diagnostics
@@ -1,118 +0,0 @@
1
- """Queue message binding for 7h3 Protocol — Kafka/SQS/Pub-Sub/RabbitMQ."""
2
- from __future__ import annotations
3
-
4
- import json
5
- import secrets
6
- import time
7
- from typing import Any, Dict, List, Optional
8
-
9
- QUEUE_DEFAULT_TTL_MS = 3_600_000 # 1 hour
10
-
11
-
12
- def _create_envelope(
13
- sender: str,
14
- content: str,
15
- ttl_ms: int,
16
- *,
17
- recipient: Optional[str] = None,
18
- intent: str = "TASK",
19
- ) -> Dict[str, Any]:
20
- """Build a bare (unsigned) protocol envelope dict."""
21
- now_ms = int(time.time() * 1000)
22
- message_id = secrets.token_hex(16)
23
- nonce = secrets.token_hex(8)
24
- header: Dict[str, Any] = {
25
- "version": "7h3/0.1",
26
- "messageId": message_id,
27
- "timestampMs": now_ms,
28
- "ttlMs": ttl_ms,
29
- "sender": sender,
30
- "nonce": nonce,
31
- }
32
- if recipient is not None:
33
- header["recipient"] = recipient
34
-
35
- body: Dict[str, Any] = {
36
- "intent": intent,
37
- "content": content,
38
- }
39
- return {"header": header, "body": body}
40
-
41
-
42
- def sign_queue_message(
43
- payload: Any,
44
- private_key: str,
45
- sender: str,
46
- *,
47
- recipient: Optional[str] = None,
48
- ttl_ms: int = QUEUE_DEFAULT_TTL_MS,
49
- ) -> str:
50
- """
51
- Sign a payload for queue transit.
52
- Returns a JSON string: {"envelope": {...}, "payload": payload}
53
- """
54
- from .protocol import sign_envelope_ed25519
55
-
56
- content = payload if isinstance(payload, str) else json.dumps(payload, separators=(",", ":"))
57
- envelope = _create_envelope(
58
- sender=sender,
59
- content=content,
60
- ttl_ms=ttl_ms,
61
- recipient=recipient,
62
- )
63
- signed = sign_envelope_ed25519(envelope, private_key)
64
- return json.dumps({"envelope": signed, "payload": payload}, separators=(",", ":"))
65
-
66
-
67
- def verify_queue_message(message: str, public_key: str) -> Dict[str, Any]:
68
- """
69
- Verify and unwrap a queue message.
70
- Returns {"payload": Any, "envelope": dict}.
71
- Raises ValueError on failure.
72
- """
73
- from .protocol import verify_envelope_ed25519, validate_envelope
74
-
75
- try:
76
- wrapper = json.loads(message)
77
- except Exception as e:
78
- raise ValueError(f"7h3: malformed queue message: {e}") from e
79
-
80
- envelope = wrapper.get("envelope")
81
- payload = wrapper.get("payload")
82
- if not envelope or not isinstance(envelope, dict):
83
- raise ValueError("7h3: missing envelope in queue message")
84
-
85
- # validate_envelope returns list[ProtocolDiagnostic] (dataclass objects)
86
- diags = validate_envelope(envelope)
87
- errors = [d for d in diags if d.level == "error"]
88
- if errors:
89
- raise ValueError(
90
- f"7h3: envelope validation failed: {'; '.join(d.message for d in errors)}"
91
- )
92
-
93
- valid = verify_envelope_ed25519(envelope, public_key)
94
- if not valid:
95
- raise ValueError("7h3: invalid signature on queue message")
96
-
97
- return {"payload": payload, "envelope": envelope}
98
-
99
-
100
- def verify_queue_batch(
101
- messages: List[str],
102
- public_key: str,
103
- ) -> List[Dict[str, Any]]:
104
- """
105
- Verify a batch of queue messages without throwing.
106
- Each result is {"ok": True, "payload": ..., "envelope": ...} or
107
- {"ok": False, "raw": ..., "error": "..."}.
108
- """
109
- results = []
110
- for msg in messages:
111
- try:
112
- result = verify_queue_message(msg, public_key)
113
- results.append(
114
- {"ok": True, "payload": result["payload"], "envelope": result["envelope"]}
115
- )
116
- except Exception as e:
117
- results.append({"ok": False, "raw": msg, "error": str(e)})
118
- return results