@7h3/protocol 0.1.2 → 0.4.0

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 (230) hide show
  1. package/.dockerignore +19 -0
  2. package/.github/dependabot.yml +32 -0
  3. package/.github/workflows/ci.yml +31 -0
  4. package/.github/workflows/publish.yml +59 -0
  5. package/.github/workflows/scorecard.yml +37 -0
  6. package/7h3.example.yaml +125 -0
  7. package/CHANGELOG.md +92 -0
  8. package/CONTRIBUTING.md +82 -0
  9. package/Dockerfile +73 -0
  10. package/GOVERNANCE.md +62 -0
  11. package/README.md +323 -6
  12. package/SECURITY.md +70 -0
  13. package/bench-results/replay-cache-full-1777891033256.json +10 -0
  14. package/bench-results/replay-cache-full-1777896317488.json +10 -0
  15. package/bench-results/replay-cache-full-1777900993184.json +10 -0
  16. package/bench-results/replay-cache-full-1777901019285.json +10 -0
  17. package/bench-results/replay-cache-quick-1777870170126.json +10 -0
  18. package/bench-results/signature-profiles-quick-1775875160079.json +85 -0
  19. package/bench-results/signature-profiles-quick-1775983539716.json +85 -0
  20. package/bench-results/signature-profiles-quick-1776237913190.json +85 -0
  21. package/bench-results/wire-codecs-full-1777891019803.json +93 -0
  22. package/bench-results/wire-codecs-full-1777896260964.json +93 -0
  23. package/bench-results/wire-codecs-full-1777901004247.json +93 -0
  24. package/bench-results/wire-codecs-quick-1775972879056.json +93 -0
  25. package/bench-results/wire-codecs-quick-1775983541111.json +93 -0
  26. package/bench-results/wire-codecs-quick-1776237914299.json +93 -0
  27. package/bench-results/wire-codecs-quick-1777841285236.json +93 -0
  28. package/bench-results/wire-codecs-quick-1777841321772.json +93 -0
  29. package/bench-results/wire-codecs-quick-1777841330408.json +93 -0
  30. package/bench-results/wire-codecs-quick-1777852886082.json +93 -0
  31. package/bench-results/wire-codecs-quick-1777852988773.json +93 -0
  32. package/bench-results/wire-codecs-quick-1777870188095.json +93 -0
  33. package/bench-results/wire-codecs-quick-1777870263918.json +93 -0
  34. package/bench-results/wire-codecs-quick-1777870455034.json +93 -0
  35. package/bench-results/wire-codecs-quick-1778816163081.json +93 -0
  36. package/bench-results/wire-codecs-quick-1778843936130.json +93 -0
  37. package/bin/7h3.ts +385 -0
  38. package/conformance/7h3_v0_1.json +77 -0
  39. package/conformance/7h3_v0_1_binary.json +20 -0
  40. package/conformance/aip_v0_1_binary.json +20 -0
  41. package/docker-compose.yaml +77 -0
  42. package/docs/ADOPTION_PLAN.md +120 -0
  43. package/docs/AGENTS.md +77 -0
  44. package/docs/AIP_RFC_v0.1.md +97 -0
  45. package/docs/AI_DECISION_CARD.md +122 -0
  46. package/docs/AI_RUNTIME_POLICY.json +126 -0
  47. package/docs/AI_RUNTIME_POLICY.yaml +110 -0
  48. package/docs/BACKPRESSURE_TUNING.md +65 -0
  49. package/docs/BENCHMARK_CLAIM_MATRIX.md +42 -0
  50. package/docs/BENCHMARK_REPORT_TEMPLATE.md +169 -0
  51. package/docs/BINARY_CODEC_BENCH.md +23 -0
  52. package/docs/CLEAN_CLONE_RUNBOOK.md +36 -0
  53. package/docs/CLOCK_SKEW_POLICY.md +30 -0
  54. package/docs/DISTRIBUTED_REPLAY.md +142 -0
  55. package/docs/FUZZ_CAMPAIGN.md +121 -0
  56. package/docs/GATEWAY.md +195 -0
  57. package/docs/KEY_MANAGEMENT_POLICY.md +53 -0
  58. package/docs/KEY_REVOCATION.md +69 -0
  59. package/docs/MCP_WRAPPER.md +159 -0
  60. package/docs/MIGRATION_GUIDE.md +40 -0
  61. package/docs/OPERATORS.md +184 -0
  62. package/docs/PERF_REGRESSION_POLICY.md +34 -0
  63. package/docs/PROJECT_EXAMINATION_2026-05-31.md +219 -0
  64. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +135 -0
  65. package/docs/RELEASE_GATE.md +25 -0
  66. package/docs/RELEASE_NOTES_v0.1.0.md +54 -0
  67. package/docs/SECURITY_REVIEW_2026-06-05.md +165 -0
  68. package/docs/TELEMETRY.md +41 -0
  69. package/docs/THREAT_MODEL.md +89 -0
  70. package/docs/VERSIONING_POLICY.md +30 -0
  71. package/docs/assets/banner.png +0 -0
  72. package/eslint.config.js +15 -0
  73. package/fuzz/ts/harness-decode.ts +136 -0
  74. package/fuzz/ts/harness-verify.ts +121 -0
  75. package/fuzz/ts/run.ts +35 -0
  76. package/mcp-server/README.md +38 -0
  77. package/mcp-server/package-lock.json +1187 -0
  78. package/mcp-server/package.json +35 -0
  79. package/mcp-server/src/index.ts +236 -0
  80. package/mcp-server/tsconfig.json +14 -0
  81. package/package.json +79 -13
  82. package/scripts/aip-framework-quickstart.ts +110 -0
  83. package/scripts/aip-mcp-gateway.ts +38 -0
  84. package/scripts/aip-mcp-wrap-demo.ts +72 -0
  85. package/scripts/aip-quickstart.ts +60 -0
  86. package/scripts/bench-diff.ts +118 -0
  87. package/scripts/bench-protocol-e2e.ts +937 -0
  88. package/scripts/bench-protocol-openloop.ts +1397 -0
  89. package/scripts/bench-replay-cache.ts +76 -0
  90. package/scripts/bench-signature-profiles.ts +180 -0
  91. package/scripts/bench-wire-codecs.ts +161 -0
  92. package/scripts/build-binary-conformance.ts +36 -0
  93. package/scripts/build-release-dashboard.ts +175 -0
  94. package/scripts/canary-rollout.ts +38 -0
  95. package/scripts/mcpGatewayCli.test.ts +116 -0
  96. package/scripts/prepare-aip-package.ts +88 -0
  97. package/scripts/regen-conformance-sigs.ts +18 -0
  98. package/scripts/release-gate.ts +19 -0
  99. package/scripts/validate-runtime-policy.ts +18 -0
  100. package/sdk/browser/index.test.ts +162 -0
  101. package/sdk/browser/index.ts +257 -0
  102. package/sdk/browser/package.json +13 -0
  103. package/sdk/go/go.mod +3 -0
  104. package/sdk/go/http.go +135 -0
  105. package/sdk/go/protocol.go +324 -0
  106. package/sdk/go/protocol_test.go +334 -0
  107. package/sdk/go/webhook.go +136 -0
  108. package/sdk/python/README.md +18 -0
  109. package/sdk/python/protocol_7h3/__init__.py +46 -0
  110. package/sdk/python/protocol_7h3/http.py +212 -0
  111. package/sdk/python/protocol_7h3/keys.py +149 -0
  112. package/sdk/python/protocol_7h3/protocol.py +525 -0
  113. package/sdk/python/protocol_7h3/queue.py +118 -0
  114. package/sdk/python/protocol_7h3/webhook.py +116 -0
  115. package/sdk/python/pyproject.toml +40 -0
  116. package/sdk/python/tests/test_conformance.py +110 -0
  117. package/sdk/python/tests/test_http.py +305 -0
  118. package/sdk/python/tests/test_keys.py +417 -0
  119. package/sdk/python/tests/test_queue.py +120 -0
  120. package/sdk/python/tests/test_webhook.py +345 -0
  121. package/sdk/rust/Cargo.lock +371 -0
  122. package/sdk/rust/Cargo.toml +25 -0
  123. package/sdk/rust/README.md +31 -0
  124. package/sdk/rust/fuzz/Cargo.toml +29 -0
  125. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +46 -0
  126. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +11 -0
  127. package/sdk/rust/src/bin/aip_mcp_gateway.rs +59 -0
  128. package/sdk/rust/src/http.rs +145 -0
  129. package/sdk/rust/src/keys.rs +161 -0
  130. package/sdk/rust/src/lib.rs +688 -0
  131. package/sdk/rust/src/queue.rs +79 -0
  132. package/sdk/rust/src/webhook.rs +86 -0
  133. package/sdk/rust/tests/conformance.rs +148 -0
  134. package/sdk/rust/tests/gateway.rs +130 -0
  135. package/sdk/rust/tests/http_webhook_queue.rs +201 -0
  136. package/sdk/rust/tests/keys.rs +189 -0
  137. package/src/agentAdapter.test.ts +48 -0
  138. package/src/agentAdapter.ts +56 -0
  139. package/src/auditLog.test.ts +145 -0
  140. package/src/auditLog.ts +147 -0
  141. package/src/conformance.test.ts +136 -0
  142. package/src/conformanceVectors.ts +99 -0
  143. package/src/frameworkAdapters.test.ts +290 -0
  144. package/src/frameworkAdapters.ts +261 -0
  145. package/src/gateway.test.ts +343 -0
  146. package/src/gateway.ts +171 -0
  147. package/src/grpcBinding.test.ts +211 -0
  148. package/src/grpcBinding.ts +103 -0
  149. package/src/httpBinding.test.ts +376 -0
  150. package/src/httpBinding.ts +163 -0
  151. package/src/index.ts +32 -0
  152. package/src/keyInfra.test.ts +278 -0
  153. package/src/keyInfra.ts +228 -0
  154. package/src/keyRegistry.ts +59 -0
  155. package/src/keyRotation.test.ts +78 -0
  156. package/src/keyRotation.ts +72 -0
  157. package/src/mcpGateway.test.ts +129 -0
  158. package/src/mcpGateway.ts +250 -0
  159. package/src/mcpTransports.test.ts +92 -0
  160. package/src/mcpTransports.ts +169 -0
  161. package/src/mcpWrapper.test.ts +179 -0
  162. package/src/mcpWrapper.ts +206 -0
  163. package/src/policyEnforcer.test.ts +99 -0
  164. package/src/policyEnforcer.ts +169 -0
  165. package/src/policyTelemetryFeedback.test.ts +25 -0
  166. package/src/policyTelemetryFeedback.ts +38 -0
  167. package/src/protocol.bench.ts +37 -0
  168. package/src/protocol.test.ts +155 -0
  169. package/src/protocol.ts +413 -0
  170. package/src/protocolAgent.test.ts +105 -0
  171. package/src/protocolAgent.ts +169 -0
  172. package/src/protocolBinary.test.ts +165 -0
  173. package/src/protocolBinary.ts +312 -0
  174. package/src/protocolCapabilities.ts +70 -0
  175. package/src/protocolFuzz.advanced.test.ts +235 -0
  176. package/src/protocolFuzz.test.ts +111 -0
  177. package/src/protocolNegative.test.ts +97 -0
  178. package/src/protocolReplay.test.ts +71 -0
  179. package/src/protocolReplay.ts +194 -0
  180. package/src/protocolTransport.test.ts +556 -0
  181. package/src/protocolTransport.ts +483 -0
  182. package/src/queueBinding.test.ts +130 -0
  183. package/src/queueBinding.ts +102 -0
  184. package/src/rateLimiter.test.ts +96 -0
  185. package/src/rateLimiter.ts +46 -0
  186. package/src/redisClient.ts +140 -0
  187. package/src/redisIntegration.test.ts +134 -0
  188. package/src/replayStores.test.ts +141 -0
  189. package/src/replayStores.ts +82 -0
  190. package/src/revocation.test.ts +98 -0
  191. package/src/revocation.ts +0 -0
  192. package/src/routePolicy.test.ts +87 -0
  193. package/src/routePolicy.ts +72 -0
  194. package/src/runtimePolicy.test.ts +49 -0
  195. package/src/runtimePolicy.ts +81 -0
  196. package/src/runtimePolicyManager.test.ts +29 -0
  197. package/src/runtimePolicyManager.ts +50 -0
  198. package/src/runtimePolicyPresets.ts +43 -0
  199. package/src/signedResponse.test.ts +111 -0
  200. package/src/signedResponse.ts +83 -0
  201. package/src/webhookBinding.test.ts +144 -0
  202. package/src/webhookBinding.ts +115 -0
  203. package/src/wsBinding.test.ts +221 -0
  204. package/src/wsBinding.ts +100 -0
  205. package/tsconfig.json +15 -0
  206. package/tsconfig.lib.json +23 -0
  207. package/vite.lib.config.ts +16 -0
  208. package/agentAdapter.d.ts +0 -26
  209. package/conformanceVectors.d.ts +0 -20
  210. package/frameworkAdapters.d.ts +0 -72
  211. package/index.d.ts +0 -20
  212. package/index.js +0 -1702
  213. package/keyRotation.d.ts +0 -20
  214. package/mcpGateway.d.ts +0 -37
  215. package/mcpTransports.d.ts +0 -62
  216. package/mcpWrapper.d.ts +0 -83
  217. package/policyEnforcer.d.ts +0 -50
  218. package/policyTelemetryFeedback.d.ts +0 -11
  219. package/protocol.d.ts +0 -66
  220. package/protocolAgent.d.ts +0 -58
  221. package/protocolBinary.d.ts +0 -8
  222. package/protocolCapabilities.d.ts +0 -24
  223. package/protocolReplay.d.ts +0 -35
  224. package/protocolTransport.d.ts +0 -73
  225. package/redisClient.d.ts +0 -49
  226. package/replayStores.d.ts +0 -32
  227. package/revocation.d.ts +0 -71
  228. package/runtimePolicy.d.ts +0 -24
  229. package/runtimePolicyManager.d.ts +0 -15
  230. package/runtimePolicyPresets.d.ts +0 -11
@@ -0,0 +1,334 @@
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
+ }
@@ -0,0 +1,136 @@
1
+ package protocol7h3
2
+
3
+ import (
4
+ "crypto/ed25519"
5
+ "crypto/hmac"
6
+ "crypto/sha256"
7
+ "crypto/x509"
8
+ "fmt"
9
+ "strconv"
10
+ "time"
11
+ )
12
+
13
+ // WebhookSigHeader is the HTTP header carrying the webhook signature.
14
+ const WebhookSigHeader = "X-7h3-Sig"
15
+
16
+ // WebhookTsHeader is the HTTP header carrying the webhook timestamp.
17
+ const WebhookTsHeader = "X-7h3-Ts"
18
+
19
+ // WebhookDefaultTTLMs is the default maximum age for webhook signatures.
20
+ const WebhookDefaultTTLMs int64 = 300_000
21
+
22
+ // webhookPayload constructs the signed payload: "<tsMs>.<body>"
23
+ func webhookPayload(tsMs int64, body string) string {
24
+ return fmt.Sprintf("%d.%s", tsMs, body)
25
+ }
26
+
27
+ // SignWebhook signs a webhook body with an Ed25519 private key (PKCS8 base64url).
28
+ // Returns sig (base64url) and tsMs (string timestamp milliseconds).
29
+ func SignWebhook(body, privateKeyPkcs8Base64Url string) (sig, tsMs string, err error) {
30
+ privDER, err := decodeBase64Url(privateKeyPkcs8Base64Url)
31
+ if err != nil {
32
+ return "", "", fmt.Errorf("protocol7h3: decode private key: %w", err)
33
+ }
34
+
35
+ privKey, err := x509.ParsePKCS8PrivateKey(privDER)
36
+ if err != nil {
37
+ return "", "", fmt.Errorf("protocol7h3: parse private key: %w", err)
38
+ }
39
+
40
+ edPriv, ok := privKey.(ed25519.PrivateKey)
41
+ if !ok {
42
+ return "", "", fmt.Errorf("protocol7h3: key is not Ed25519")
43
+ }
44
+
45
+ nowMs := time.Now().UnixMilli()
46
+ payload := webhookPayload(nowMs, body)
47
+ sigBytes := ed25519.Sign(edPriv, []byte(payload))
48
+
49
+ return encodeBase64Url(sigBytes), strconv.FormatInt(nowMs, 10), nil
50
+ }
51
+
52
+ // VerifyWebhook verifies a webhook signature.
53
+ // maxAgeMs defaults to WebhookDefaultTTLMs if not provided.
54
+ func VerifyWebhook(body, sig, tsStr, publicKeySpkiBase64Url string, maxAgeMs ...int64) (bool, error) {
55
+ tsMs, err := strconv.ParseInt(tsStr, 10, 64)
56
+ if err != nil {
57
+ return false, fmt.Errorf("protocol7h3: invalid timestamp: %w", err)
58
+ }
59
+
60
+ maxAge := WebhookDefaultTTLMs
61
+ if len(maxAgeMs) > 0 {
62
+ maxAge = maxAgeMs[0]
63
+ }
64
+
65
+ nowMs := time.Now().UnixMilli()
66
+ if nowMs-tsMs > maxAge {
67
+ return false, nil
68
+ }
69
+
70
+ pubDER, err := decodeBase64Url(publicKeySpkiBase64Url)
71
+ if err != nil {
72
+ return false, fmt.Errorf("protocol7h3: decode public key: %w", err)
73
+ }
74
+
75
+ pubKey, err := x509.ParsePKIXPublicKey(pubDER)
76
+ if err != nil {
77
+ return false, fmt.Errorf("protocol7h3: parse public key: %w", err)
78
+ }
79
+
80
+ edPub, ok := pubKey.(ed25519.PublicKey)
81
+ if !ok {
82
+ return false, fmt.Errorf("protocol7h3: key is not Ed25519")
83
+ }
84
+
85
+ sigBytes, err := decodeBase64Url(sig)
86
+ if err != nil {
87
+ return false, fmt.Errorf("protocol7h3: decode signature: %w", err)
88
+ }
89
+
90
+ payload := webhookPayload(tsMs, body)
91
+ return ed25519.Verify(edPub, []byte(payload), sigBytes), nil
92
+ }
93
+
94
+ // SignWebhookHmac signs a webhook body with HMAC-SHA256.
95
+ // Returns sig (base64url) and tsMs (string timestamp milliseconds).
96
+ func SignWebhookHmac(body, secret string) (sig, tsMs string, err error) {
97
+ nowMs := time.Now().UnixMilli()
98
+ payload := webhookPayload(nowMs, body)
99
+
100
+ mac := hmac.New(sha256.New, []byte(secret))
101
+ mac.Write([]byte(payload))
102
+ sigBytes := mac.Sum(nil)
103
+
104
+ return encodeBase64Url(sigBytes), strconv.FormatInt(nowMs, 10), nil
105
+ }
106
+
107
+ // VerifyWebhookHmac verifies a webhook HMAC-SHA256 signature.
108
+ // maxAgeMs defaults to WebhookDefaultTTLMs if not provided.
109
+ func VerifyWebhookHmac(body, sig, tsStr, secret string, maxAgeMs ...int64) (bool, error) {
110
+ tsMs, err := strconv.ParseInt(tsStr, 10, 64)
111
+ if err != nil {
112
+ return false, fmt.Errorf("protocol7h3: invalid timestamp: %w", err)
113
+ }
114
+
115
+ maxAge := WebhookDefaultTTLMs
116
+ if len(maxAgeMs) > 0 {
117
+ maxAge = maxAgeMs[0]
118
+ }
119
+
120
+ nowMs := time.Now().UnixMilli()
121
+ if nowMs-tsMs > maxAge {
122
+ return false, nil
123
+ }
124
+
125
+ sigBytes, err := decodeBase64Url(sig)
126
+ if err != nil {
127
+ return false, fmt.Errorf("protocol7h3: decode signature: %w", err)
128
+ }
129
+
130
+ payload := webhookPayload(tsMs, body)
131
+ mac := hmac.New(sha256.New, []byte(secret))
132
+ mac.Write([]byte(payload))
133
+ expected := mac.Sum(nil)
134
+
135
+ return hmac.Equal(expected, sigBytes), nil
136
+ }
@@ -0,0 +1,18 @@
1
+ # 7h3 Protocol AIP Python SDK (Skeleton)
2
+
3
+ Minimal reference SDK for `aip/0.1` parity with the TypeScript implementation.
4
+
5
+ ## Included
6
+
7
+ - deterministic canonicalization
8
+ - HS256 HMAC signing and verification
9
+ - ED25519 signing and verification (requires `cryptography` package)
10
+ - compact wire encode/decode
11
+ - envelope validation helpers (version, required fields, TTL)
12
+ - conformance tests using shared vectors from `conformance/aip_v0_1.json`
13
+
14
+ ## Run conformance tests
15
+
16
+ ```bash
17
+ PYTHONPATH=sdk/python python3 -m unittest discover -s sdk/python/tests -v
18
+ ```
@@ -0,0 +1,46 @@
1
+ from .protocol import ( # noqa: F401
2
+ canonicalize_envelope,
3
+ decode_envelope,
4
+ encode_envelope_compact,
5
+ sign_canonical_payload_ed25519,
6
+ sign_canonical_payload_hmac,
7
+ sign_envelope_ed25519,
8
+ sign_envelope_hmac,
9
+ validate_envelope,
10
+ verify_canonical_payload_ed25519,
11
+ verify_canonical_payload_hmac,
12
+ verify_envelope_ed25519,
13
+ verify_envelope_hmac,
14
+ )
15
+
16
+ try:
17
+ from .http import ( # noqa: F401
18
+ DEFAULT_HEADER, KeyRegistry, StaticKeyRegistry,
19
+ verify_http_envelope, sign_http_request, build_signed_request_headers,
20
+ )
21
+ except ImportError:
22
+ pass
23
+
24
+ try:
25
+ from .webhook import ( # noqa: F401
26
+ WEBHOOK_SIG_HEADER, WEBHOOK_TS_HEADER,
27
+ sign_webhook, sign_webhook_hmac, verify_webhook, verify_webhook_hmac, consume_webhook,
28
+ )
29
+ except ImportError:
30
+ pass
31
+
32
+ try:
33
+ from .queue import ( # noqa: F401
34
+ sign_queue_message, verify_queue_message, verify_queue_batch,
35
+ )
36
+ except ImportError:
37
+ pass
38
+
39
+ try:
40
+ from .keys import ( # noqa: F401
41
+ KeyEntry, WellKnownKeysDocument, ManagedKeyPair,
42
+ KeyRotationManager, RevocationRegistry,
43
+ fetch_well_known_keys,
44
+ )
45
+ except ImportError:
46
+ pass