@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,324 +0,0 @@
1
- // Package protocol7h3 implements the 7h3 agent messaging protocol.
2
- // Canonical form is byte-identical to the TypeScript reference implementation.
3
- package protocol7h3
4
-
5
- import (
6
- "bytes"
7
- "crypto/ed25519"
8
- "crypto/hmac"
9
- "crypto/rand"
10
- "crypto/sha256"
11
- "crypto/x509"
12
- "encoding/base64"
13
- "encoding/json"
14
- "fmt"
15
- "strings"
16
- "time"
17
- )
18
-
19
- // WireVersion is the protocol version string.
20
- const WireVersion = "7h3/0.1"
21
-
22
- // ProtocolHeader contains routing and metadata for a message.
23
- type ProtocolHeader struct {
24
- Version string `json:"version"`
25
- MessageID string `json:"messageId"`
26
- TimestampMs int64 `json:"timestampMs"`
27
- TTLMs int64 `json:"ttlMs"`
28
- Sender string `json:"sender"`
29
- Recipient string `json:"recipient,omitempty"`
30
- Nonce string `json:"nonce"`
31
- }
32
-
33
- // ProtocolBody contains the payload of a message.
34
- type ProtocolBody struct {
35
- Intent string `json:"intent"`
36
- Content string `json:"content"`
37
- Capability string `json:"capability,omitempty"`
38
- CorrelationID string `json:"correlationId,omitempty"`
39
- }
40
-
41
- // ProtocolSignature holds the signature over the canonical envelope.
42
- type ProtocolSignature struct {
43
- Alg string `json:"alg"`
44
- KeyID string `json:"keyId"`
45
- Value string `json:"value"`
46
- }
47
-
48
- // ProtocolEnvelope is the top-level wire message.
49
- type ProtocolEnvelope struct {
50
- Header ProtocolHeader `json:"header"`
51
- Body ProtocolBody `json:"body"`
52
- Signature *ProtocolSignature `json:"signature,omitempty"`
53
- }
54
-
55
- // Diagnostic reports a validation issue.
56
- type Diagnostic struct {
57
- Level string `json:"level"`
58
- Message string `json:"message"`
59
- }
60
-
61
- // encodeBase64Url encodes bytes as base64url without padding.
62
- func encodeBase64Url(b []byte) string {
63
- s := base64.URLEncoding.EncodeToString(b)
64
- return strings.TrimRight(s, "=")
65
- }
66
-
67
- // decodeBase64Url decodes base64url, handling missing padding.
68
- func decodeBase64Url(s string) ([]byte, error) {
69
- // Re-add padding
70
- switch len(s) % 4 {
71
- case 2:
72
- s += "=="
73
- case 3:
74
- s += "="
75
- }
76
- return base64.URLEncoding.DecodeString(s)
77
- }
78
-
79
- // jsonStr JSON-encodes a string value (returns with surrounding quotes).
80
- // Uses a non-HTML-escaping encoder to match TypeScript's JSON.stringify behavior
81
- // (e.g. ">" stays as ">" rather than being escaped to ">").
82
- func jsonStr(s string) string {
83
- var buf bytes.Buffer
84
- enc := json.NewEncoder(&buf)
85
- enc.SetEscapeHTML(false)
86
- _ = enc.Encode(s)
87
- // Encode appends a newline; trim it
88
- return strings.TrimSuffix(buf.String(), "\n")
89
- }
90
-
91
- // generateNonce returns 16 random bytes as base64url.
92
- func generateNonce() string {
93
- b := make([]byte, 16)
94
- if _, err := rand.Read(b); err != nil {
95
- panic(fmt.Sprintf("protocol7h3: generateNonce: %v", err))
96
- }
97
- return encodeBase64Url(b)
98
- }
99
-
100
- // CanonicalizeEnvelope produces the canonical JSON string used for signing.
101
- // The output is byte-identical to the TypeScript canonicalizeEnvelope function.
102
- //
103
- // Format: {"body":{...},"header":{...}}
104
- //
105
- // Header field order: messageId, nonce, recipient? (omit if empty), sender, timestampMs, ttlMs, version
106
- // Body field order: capability? (omit if empty), content, correlationId? (omit if empty), intent
107
- func CanonicalizeEnvelope(h ProtocolHeader, b ProtocolBody) string {
108
- // Serialize header
109
- hParts := []string{
110
- fmt.Sprintf(`"messageId":%s`, jsonStr(h.MessageID)),
111
- fmt.Sprintf(`"nonce":%s`, jsonStr(h.Nonce)),
112
- }
113
- if h.Recipient != "" {
114
- hParts = append(hParts, fmt.Sprintf(`"recipient":%s`, jsonStr(h.Recipient)))
115
- }
116
- hParts = append(hParts,
117
- fmt.Sprintf(`"sender":%s`, jsonStr(h.Sender)),
118
- fmt.Sprintf(`"timestampMs":%d`, h.TimestampMs),
119
- fmt.Sprintf(`"ttlMs":%d`, h.TTLMs),
120
- fmt.Sprintf(`"version":%s`, jsonStr(h.Version)),
121
- )
122
- headerJSON := "{" + strings.Join(hParts, ",") + "}"
123
-
124
- // Serialize body
125
- var bParts []string
126
- if b.Capability != "" {
127
- bParts = append(bParts, fmt.Sprintf(`"capability":%s`, jsonStr(b.Capability)))
128
- }
129
- bParts = append(bParts, fmt.Sprintf(`"content":%s`, jsonStr(b.Content)))
130
- if b.CorrelationID != "" {
131
- bParts = append(bParts, fmt.Sprintf(`"correlationId":%s`, jsonStr(b.CorrelationID)))
132
- }
133
- bParts = append(bParts, fmt.Sprintf(`"intent":%s`, jsonStr(b.Intent)))
134
- bodyJSON := "{" + strings.Join(bParts, ",") + "}"
135
-
136
- return fmt.Sprintf(`{"body":%s,"header":%s}`, bodyJSON, headerJSON)
137
- }
138
-
139
- // GenerateKeypair generates an Ed25519 keypair.
140
- // Returns publicKey as SPKI base64url and privateKey as PKCS8 base64url.
141
- func GenerateKeypair() (publicKey, privateKey string, err error) {
142
- pub, priv, err := ed25519.GenerateKey(rand.Reader)
143
- if err != nil {
144
- return "", "", fmt.Errorf("protocol7h3: GenerateKeypair: %w", err)
145
- }
146
-
147
- privDER, err := x509.MarshalPKCS8PrivateKey(priv)
148
- if err != nil {
149
- return "", "", fmt.Errorf("protocol7h3: marshal private key: %w", err)
150
- }
151
-
152
- pubDER, err := x509.MarshalPKIXPublicKey(pub)
153
- if err != nil {
154
- return "", "", fmt.Errorf("protocol7h3: marshal public key: %w", err)
155
- }
156
-
157
- return encodeBase64Url(pubDER), encodeBase64Url(privDER), nil
158
- }
159
-
160
- // CreateEnvelope creates a new unsigned ProtocolEnvelope.
161
- func CreateEnvelope(sender, recipient string, ttlMs int64, body ProtocolBody) ProtocolEnvelope {
162
- nowMs := time.Now().UnixMilli()
163
- msgID := fmt.Sprintf("msg-%d-%s", nowMs, generateNonce()[:8])
164
- h := ProtocolHeader{
165
- Version: WireVersion,
166
- MessageID: msgID,
167
- TimestampMs: nowMs,
168
- TTLMs: ttlMs,
169
- Sender: sender,
170
- Recipient: recipient,
171
- Nonce: generateNonce(),
172
- }
173
- return ProtocolEnvelope{Header: h, Body: body}
174
- }
175
-
176
- // ValidateEnvelope validates the envelope and returns any diagnostics.
177
- func ValidateEnvelope(env ProtocolEnvelope) []Diagnostic {
178
- var diags []Diagnostic
179
- h := env.Header
180
-
181
- if h.Version != WireVersion {
182
- diags = append(diags, Diagnostic{Level: "error", Message: fmt.Sprintf("Unsupported protocol version '%s'", h.Version)})
183
- }
184
- if strings.TrimSpace(h.MessageID) == "" {
185
- diags = append(diags, Diagnostic{Level: "error", Message: "Missing messageId"})
186
- }
187
- if strings.TrimSpace(h.Sender) == "" {
188
- diags = append(diags, Diagnostic{Level: "error", Message: "Missing sender identity"})
189
- }
190
- if strings.TrimSpace(h.Nonce) == "" {
191
- diags = append(diags, Diagnostic{Level: "error", Message: "Missing nonce — replay protection requires a unique nonce per message"})
192
- }
193
- if h.TTLMs <= 0 {
194
- diags = append(diags, Diagnostic{Level: "error", Message: "ttlMs must be greater than zero"})
195
- }
196
- nowMs := time.Now().UnixMilli()
197
- if h.TimestampMs+h.TTLMs < nowMs {
198
- diags = append(diags, Diagnostic{Level: "error", Message: "Message TTL expired"})
199
- }
200
- if strings.TrimSpace(env.Body.Content) == "" {
201
- diags = append(diags, Diagnostic{Level: "warning", Message: "Empty content payload"})
202
- }
203
-
204
- return diags
205
- }
206
-
207
- // deriveKeyID derives the keyId from a public key DER bytes (first 16 chars of base64url).
208
- func deriveKeyID(pubDER []byte) string {
209
- s := encodeBase64Url(pubDER)
210
- if len(s) > 16 {
211
- return s[:16]
212
- }
213
- return s
214
- }
215
-
216
- // SignEnvelopeEd25519 signs the envelope with an Ed25519 private key (PKCS8 base64url).
217
- func SignEnvelopeEd25519(env ProtocolEnvelope, privateKeyPkcs8Base64Url string) (ProtocolEnvelope, error) {
218
- privDER, err := decodeBase64Url(privateKeyPkcs8Base64Url)
219
- if err != nil {
220
- return env, fmt.Errorf("protocol7h3: decode private key: %w", err)
221
- }
222
-
223
- privKey, err := x509.ParsePKCS8PrivateKey(privDER)
224
- if err != nil {
225
- return env, fmt.Errorf("protocol7h3: parse private key: %w", err)
226
- }
227
-
228
- edPriv, ok := privKey.(ed25519.PrivateKey)
229
- if !ok {
230
- return env, fmt.Errorf("protocol7h3: key is not Ed25519")
231
- }
232
-
233
- // Derive public key to get keyId
234
- edPub := edPriv.Public().(ed25519.PublicKey)
235
- pubDER, err := x509.MarshalPKIXPublicKey(edPub)
236
- if err != nil {
237
- return env, fmt.Errorf("protocol7h3: marshal public key: %w", err)
238
- }
239
- keyID := deriveKeyID(pubDER)
240
-
241
- // Canonicalize and sign
242
- payload := CanonicalizeEnvelope(env.Header, env.Body)
243
- sig := ed25519.Sign(edPriv, []byte(payload))
244
-
245
- signed := env
246
- signed.Signature = &ProtocolSignature{
247
- Alg: "ED25519",
248
- KeyID: keyID,
249
- Value: encodeBase64Url(sig),
250
- }
251
- return signed, nil
252
- }
253
-
254
- // VerifyEnvelopeEd25519 verifies the envelope signature using an Ed25519 public key (SPKI base64url).
255
- func VerifyEnvelopeEd25519(env ProtocolEnvelope, publicKeySpkiBase64Url string) (bool, error) {
256
- if env.Signature == nil {
257
- return false, nil
258
- }
259
- if env.Signature.Alg != "ED25519" {
260
- return false, nil
261
- }
262
-
263
- pubDER, err := decodeBase64Url(publicKeySpkiBase64Url)
264
- if err != nil {
265
- return false, fmt.Errorf("protocol7h3: decode public key: %w", err)
266
- }
267
-
268
- pubKey, err := x509.ParsePKIXPublicKey(pubDER)
269
- if err != nil {
270
- return false, fmt.Errorf("protocol7h3: parse public key: %w", err)
271
- }
272
-
273
- edPub, ok := pubKey.(ed25519.PublicKey)
274
- if !ok {
275
- return false, fmt.Errorf("protocol7h3: key is not Ed25519")
276
- }
277
-
278
- sigBytes, err := decodeBase64Url(env.Signature.Value)
279
- if err != nil {
280
- return false, fmt.Errorf("protocol7h3: decode signature: %w", err)
281
- }
282
-
283
- payload := CanonicalizeEnvelope(env.Header, env.Body)
284
- return ed25519.Verify(edPub, []byte(payload), sigBytes), nil
285
- }
286
-
287
- // SignEnvelopeHmac signs the envelope with HMAC-SHA256.
288
- func SignEnvelopeHmac(env ProtocolEnvelope, secret, keyID string) (ProtocolEnvelope, error) {
289
- payload := CanonicalizeEnvelope(env.Header, env.Body)
290
-
291
- mac := hmac.New(sha256.New, []byte(secret))
292
- mac.Write([]byte(payload))
293
- sig := mac.Sum(nil)
294
-
295
- signed := env
296
- signed.Signature = &ProtocolSignature{
297
- Alg: "HS256",
298
- KeyID: keyID,
299
- Value: encodeBase64Url(sig),
300
- }
301
- return signed, nil
302
- }
303
-
304
- // VerifyEnvelopeHmac verifies the envelope HMAC-SHA256 signature.
305
- func VerifyEnvelopeHmac(env ProtocolEnvelope, secret string) (bool, error) {
306
- if env.Signature == nil {
307
- return false, nil
308
- }
309
- if env.Signature.Alg != "HS256" {
310
- return false, nil
311
- }
312
-
313
- sigBytes, err := decodeBase64Url(env.Signature.Value)
314
- if err != nil {
315
- return false, fmt.Errorf("protocol7h3: decode signature: %w", err)
316
- }
317
-
318
- payload := CanonicalizeEnvelope(env.Header, env.Body)
319
- mac := hmac.New(sha256.New, []byte(secret))
320
- mac.Write([]byte(payload))
321
- expected := mac.Sum(nil)
322
-
323
- return hmac.Equal(expected, sigBytes), nil
324
- }
@@ -1,334 +0,0 @@
1
- package protocol7h3
2
-
3
- import (
4
- "crypto/ed25519"
5
- "crypto/x509"
6
- "encoding/json"
7
- "fmt"
8
- "net/http"
9
- "net/http/httptest"
10
- "strconv"
11
- "strings"
12
- "testing"
13
- "time"
14
- )
15
-
16
- // Test 1: CanonicalizeEnvelope matches the conformance vector exactly.
17
- func TestCanonicalizeEnvelopeConformanceVector(t *testing.T) {
18
- h := ProtocolHeader{
19
- Version: "7h3/0.1",
20
- MessageID: "vec-1",
21
- Nonce: "nonce-vec-1",
22
- Sender: "agent.alpha",
23
- Recipient: "agent.beta",
24
- TimestampMs: 1712500000000,
25
- TTLMs: 60000,
26
- }
27
- b := ProtocolBody{
28
- Intent: "TASK",
29
- Content: "route:alpha->beta",
30
- Capability: "task.plan",
31
- CorrelationID: "corr-1",
32
- }
33
-
34
- expected := `{"body":{"capability":"task.plan","content":"route:alpha->beta","correlationId":"corr-1","intent":"TASK"},"header":{"messageId":"vec-1","nonce":"nonce-vec-1","recipient":"agent.beta","sender":"agent.alpha","timestampMs":1712500000000,"ttlMs":60000,"version":"7h3/0.1"}}`
35
- got := CanonicalizeEnvelope(h, b)
36
-
37
- if got != expected {
38
- t.Errorf("canonical mismatch:\ngot: %s\nwant: %s", got, expected)
39
- }
40
- }
41
-
42
- // Test 2: CanonicalizeEnvelope with no optional fields.
43
- func TestCanonicalizeEnvelopeNoOptionals(t *testing.T) {
44
- h := ProtocolHeader{
45
- Version: "7h3/0.1",
46
- MessageID: "msg-1",
47
- Nonce: "nonce-1",
48
- Sender: "agent.a",
49
- TimestampMs: 1000000,
50
- TTLMs: 30000,
51
- }
52
- b := ProtocolBody{
53
- Intent: "PING",
54
- Content: "hello",
55
- }
56
-
57
- got := CanonicalizeEnvelope(h, b)
58
-
59
- // Must not contain recipient, capability, correlationId keys
60
- if strings.Contains(got, "recipient") {
61
- t.Errorf("canonical should not contain 'recipient' when empty: %s", got)
62
- }
63
- if strings.Contains(got, "capability") {
64
- t.Errorf("canonical should not contain 'capability' when empty: %s", got)
65
- }
66
- if strings.Contains(got, "correlationId") {
67
- t.Errorf("canonical should not contain 'correlationId' when empty: %s", got)
68
- }
69
-
70
- // Verify it's valid JSON
71
- var v interface{}
72
- if err := json.Unmarshal([]byte(got), &v); err != nil {
73
- t.Errorf("canonical is not valid JSON: %v\n%s", err, got)
74
- }
75
- }
76
-
77
- // Test 3: GenerateKeypair returns non-empty strings.
78
- func TestGenerateKeypair(t *testing.T) {
79
- pub, priv, err := GenerateKeypair()
80
- if err != nil {
81
- t.Fatalf("GenerateKeypair error: %v", err)
82
- }
83
- if pub == "" {
84
- t.Error("public key is empty")
85
- }
86
- if priv == "" {
87
- t.Error("private key is empty")
88
- }
89
- }
90
-
91
- // Test 4: SignEnvelopeEd25519 + VerifyEnvelopeEd25519 round trip.
92
- func TestSignVerifyEd25519RoundTrip(t *testing.T) {
93
- pub, priv, err := GenerateKeypair()
94
- if err != nil {
95
- t.Fatalf("GenerateKeypair: %v", err)
96
- }
97
-
98
- env := CreateEnvelope("agent.a", "agent.b", 60000, ProtocolBody{
99
- Intent: "TASK",
100
- Content: "hello",
101
- })
102
-
103
- signed, err := SignEnvelopeEd25519(env, priv)
104
- if err != nil {
105
- t.Fatalf("SignEnvelopeEd25519: %v", err)
106
- }
107
-
108
- ok, err := VerifyEnvelopeEd25519(signed, pub)
109
- if err != nil {
110
- t.Fatalf("VerifyEnvelopeEd25519: %v", err)
111
- }
112
- if !ok {
113
- t.Error("expected verification to succeed")
114
- }
115
- }
116
-
117
- // Test 5: VerifyEnvelopeEd25519 tampered envelope returns false.
118
- func TestVerifyEd25519Tampered(t *testing.T) {
119
- pub, priv, err := GenerateKeypair()
120
- if err != nil {
121
- t.Fatalf("GenerateKeypair: %v", err)
122
- }
123
-
124
- env := CreateEnvelope("agent.a", "agent.b", 60000, ProtocolBody{
125
- Intent: "TASK",
126
- Content: "hello",
127
- })
128
-
129
- signed, err := SignEnvelopeEd25519(env, priv)
130
- if err != nil {
131
- t.Fatalf("SignEnvelopeEd25519: %v", err)
132
- }
133
-
134
- // Tamper with the body content
135
- signed.Body.Content = "tampered"
136
-
137
- ok, err := VerifyEnvelopeEd25519(signed, pub)
138
- if err != nil {
139
- t.Fatalf("VerifyEnvelopeEd25519: %v", err)
140
- }
141
- if ok {
142
- t.Error("expected verification to fail for tampered envelope")
143
- }
144
- }
145
-
146
- // Test 6: SignEnvelopeHmac + VerifyEnvelopeHmac round trip.
147
- func TestSignVerifyHmacRoundTrip(t *testing.T) {
148
- secret := "super-secret-key"
149
- env := CreateEnvelope("agent.a", "agent.b", 60000, ProtocolBody{
150
- Intent: "PING",
151
- Content: "ping",
152
- })
153
-
154
- signed, err := SignEnvelopeHmac(env, secret, "key-1")
155
- if err != nil {
156
- t.Fatalf("SignEnvelopeHmac: %v", err)
157
- }
158
-
159
- ok, err := VerifyEnvelopeHmac(signed, secret)
160
- if err != nil {
161
- t.Fatalf("VerifyEnvelopeHmac: %v", err)
162
- }
163
- if !ok {
164
- t.Error("expected HMAC verification to succeed")
165
- }
166
- }
167
-
168
- // Test 7: ValidateEnvelope expired returns error diagnostic.
169
- func TestValidateEnvelopeExpired(t *testing.T) {
170
- env := ProtocolEnvelope{
171
- Header: ProtocolHeader{
172
- Version: WireVersion,
173
- MessageID: "msg-old",
174
- Nonce: "nonce-old",
175
- Sender: "agent.a",
176
- TimestampMs: time.Now().UnixMilli() - 120000, // 2 minutes ago
177
- TTLMs: 60000, // 1 minute TTL → expired
178
- },
179
- Body: ProtocolBody{
180
- Intent: "PING",
181
- Content: "old",
182
- },
183
- }
184
-
185
- diags := ValidateEnvelope(env)
186
- found := false
187
- for _, d := range diags {
188
- if d.Message == "Message TTL expired" {
189
- found = true
190
- break
191
- }
192
- }
193
- if !found {
194
- t.Errorf("expected 'Message TTL expired' diagnostic, got: %+v", diags)
195
- }
196
- }
197
-
198
- // Test 8: HTTP: VerifyHTTPEnvelope valid signed request.
199
- func TestHTTPVerifyValidSignedRequest(t *testing.T) {
200
- pub, priv, err := GenerateKeypair()
201
- if err != nil {
202
- t.Fatalf("GenerateKeypair: %v", err)
203
- }
204
-
205
- env := CreateEnvelope("agent.a", "agent.b", 60000, ProtocolBody{
206
- Intent: "TASK",
207
- Content: "do something",
208
- })
209
-
210
- signed, err := SignEnvelopeEd25519(env, priv)
211
- if err != nil {
212
- t.Fatalf("SignEnvelopeEd25519: %v", err)
213
- }
214
-
215
- b, err := json.Marshal(signed)
216
- if err != nil {
217
- t.Fatalf("json.Marshal: %v", err)
218
- }
219
-
220
- req := httptest.NewRequest(http.MethodPost, "/", nil)
221
- req.Header.Set(HTTPEnvelopeHeader, string(b))
222
-
223
- registry := &StaticKeyRegistry{Keys: map[string]string{"agent.a": pub}}
224
- result := VerifyHTTPEnvelope(req, registry)
225
-
226
- if !result.OK {
227
- t.Errorf("expected OK=true, got reason=%s detail=%s", result.Reason, result.Detail)
228
- }
229
- }
230
-
231
- // Test 9: HTTP: VerifyHTTPEnvelope missing header returns ReasonMissingHeader.
232
- func TestHTTPVerifyMissingHeader(t *testing.T) {
233
- req := httptest.NewRequest(http.MethodPost, "/", nil)
234
- registry := &StaticKeyRegistry{Keys: map[string]string{}}
235
- result := VerifyHTTPEnvelope(req, registry)
236
-
237
- if result.OK {
238
- t.Error("expected OK=false")
239
- }
240
- if result.Reason != ReasonMissingHeader {
241
- t.Errorf("expected reason=%s got=%s", ReasonMissingHeader, result.Reason)
242
- }
243
- }
244
-
245
- // Test 10: Webhook: SignWebhook + VerifyWebhook round trip.
246
- func TestWebhookSignVerifyRoundTrip(t *testing.T) {
247
- pub, priv, err := GenerateKeypair()
248
- if err != nil {
249
- t.Fatalf("GenerateKeypair: %v", err)
250
- }
251
-
252
- body := `{"event":"order.created","id":"ord-1"}`
253
- sig, tsMs, err := SignWebhook(body, priv)
254
- if err != nil {
255
- t.Fatalf("SignWebhook: %v", err)
256
- }
257
-
258
- ok, err := VerifyWebhook(body, sig, tsMs, pub)
259
- if err != nil {
260
- t.Fatalf("VerifyWebhook: %v", err)
261
- }
262
- if !ok {
263
- t.Error("expected webhook verification to succeed")
264
- }
265
- }
266
-
267
- // signWithTimestamp is a test helper that signs a webhook payload with a specific timestamp.
268
- func signWithTimestamp(body, privKeyBase64Url string, tsMs int64) (string, error) {
269
- privDER, err := decodeBase64Url(privKeyBase64Url)
270
- if err != nil {
271
- return "", fmt.Errorf("decode: %w", err)
272
- }
273
- privKeyIface, err := x509.ParsePKCS8PrivateKey(privDER)
274
- if err != nil {
275
- return "", fmt.Errorf("parse: %w", err)
276
- }
277
- edPriv, ok := privKeyIface.(ed25519.PrivateKey)
278
- if !ok {
279
- return "", fmt.Errorf("not ed25519")
280
- }
281
- payload := webhookPayload(tsMs, body)
282
- sigBytes := ed25519.Sign(edPriv, []byte(payload))
283
- return encodeBase64Url(sigBytes), nil
284
- }
285
-
286
- // Test 11: Webhook: expired timestamp returns false.
287
- func TestWebhookExpiredTimestamp(t *testing.T) {
288
- pub, priv, err := GenerateKeypair()
289
- if err != nil {
290
- t.Fatalf("GenerateKeypair: %v", err)
291
- }
292
-
293
- body := `{"event":"test"}`
294
-
295
- // Create a signature with a timestamp 10 minutes in the past
296
- oldTs := time.Now().UnixMilli() - 600000
297
- sig, err := signWithTimestamp(body, priv, oldTs)
298
- if err != nil {
299
- t.Fatalf("signWithTimestamp: %v", err)
300
- }
301
- tsStr := strconv.FormatInt(oldTs, 10)
302
-
303
- ok, err := VerifyWebhook(body, sig, tsStr, pub, WebhookDefaultTTLMs)
304
- if err != nil {
305
- t.Fatalf("VerifyWebhook: %v", err)
306
- }
307
- if ok {
308
- t.Error("expected expired webhook to return false")
309
- }
310
- }
311
-
312
- // Test 12: Webhook: tampered body returns false.
313
- func TestWebhookTamperedBody(t *testing.T) {
314
- pub, priv, err := GenerateKeypair()
315
- if err != nil {
316
- t.Fatalf("GenerateKeypair: %v", err)
317
- }
318
-
319
- body := `{"event":"order.created"}`
320
- sig, tsMs, err := SignWebhook(body, priv)
321
- if err != nil {
322
- t.Fatalf("SignWebhook: %v", err)
323
- }
324
-
325
- // Tamper with body
326
- tamperedBody := `{"event":"order.deleted"}`
327
- ok, err := VerifyWebhook(tamperedBody, sig, tsMs, pub)
328
- if err != nil {
329
- t.Fatalf("VerifyWebhook: %v", err)
330
- }
331
- if ok {
332
- t.Error("expected tampered webhook body to return false")
333
- }
334
- }