@7h3/protocol 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +6 -323
  2. package/agentAdapter.d.ts +26 -0
  3. package/auditLog.d.ts +54 -0
  4. package/capability.d.ts +67 -0
  5. package/cborCodec.d.ts +34 -0
  6. package/conformanceVectors.d.ts +20 -0
  7. package/encryption.d.ts +85 -0
  8. package/envelopeCbor.d.ts +33 -0
  9. package/frameworkAdapters.d.ts +72 -0
  10. package/gateway.d.ts +53 -0
  11. package/grpcBinding.d.ts +29 -0
  12. package/httpBinding.d.ts +50 -0
  13. package/index.d.ts +39 -0
  14. package/index.js +3662 -0
  15. package/keyInfra.d.ts +64 -0
  16. package/keyRegistry.d.ts +9 -0
  17. package/keyRotation.d.ts +20 -0
  18. package/mcpGateway.d.ts +37 -0
  19. package/mcpTransports.d.ts +62 -0
  20. package/mcpWrapper.d.ts +83 -0
  21. package/otel.d.ts +65 -0
  22. package/package.json +13 -79
  23. package/policyEnforcer.d.ts +50 -0
  24. package/policyTelemetryFeedback.d.ts +11 -0
  25. package/protocol.d.ts +66 -0
  26. package/protocolAgent.d.ts +58 -0
  27. package/protocolBinary.d.ts +8 -0
  28. package/protocolCapabilities.d.ts +24 -0
  29. package/protocolReplay.d.ts +35 -0
  30. package/protocolTransport.d.ts +73 -0
  31. package/queueBinding.d.ts +43 -0
  32. package/rateLimiter.d.ts +18 -0
  33. package/{src/redisClient.ts → redisClient.d.ts} +25 -75
  34. package/replayStores.d.ts +98 -0
  35. package/revocation.d.ts +71 -0
  36. package/routePolicy.d.ts +30 -0
  37. package/runtimePolicy.d.ts +24 -0
  38. package/runtimePolicyManager.d.ts +15 -0
  39. package/runtimePolicyPresets.d.ts +11 -0
  40. package/signedResponse.d.ts +21 -0
  41. package/stream.d.ts +59 -0
  42. package/telemetry.d.ts +79 -0
  43. package/webhookBinding.d.ts +30 -0
  44. package/wsBinding.d.ts +52 -0
  45. package/.dockerignore +0 -19
  46. package/.github/dependabot.yml +0 -32
  47. package/.github/workflows/ci.yml +0 -31
  48. package/.github/workflows/publish.yml +0 -59
  49. package/.github/workflows/scorecard.yml +0 -37
  50. package/7h3.example.yaml +0 -125
  51. package/CHANGELOG.md +0 -92
  52. package/CONTRIBUTING.md +0 -82
  53. package/Dockerfile +0 -73
  54. package/GOVERNANCE.md +0 -62
  55. package/SECURITY.md +0 -70
  56. package/bench-results/replay-cache-full-1777891033256.json +0 -10
  57. package/bench-results/replay-cache-full-1777896317488.json +0 -10
  58. package/bench-results/replay-cache-full-1777900993184.json +0 -10
  59. package/bench-results/replay-cache-full-1777901019285.json +0 -10
  60. package/bench-results/replay-cache-quick-1777870170126.json +0 -10
  61. package/bench-results/signature-profiles-quick-1775875160079.json +0 -85
  62. package/bench-results/signature-profiles-quick-1775983539716.json +0 -85
  63. package/bench-results/signature-profiles-quick-1776237913190.json +0 -85
  64. package/bench-results/wire-codecs-full-1777891019803.json +0 -93
  65. package/bench-results/wire-codecs-full-1777896260964.json +0 -93
  66. package/bench-results/wire-codecs-full-1777901004247.json +0 -93
  67. package/bench-results/wire-codecs-quick-1775972879056.json +0 -93
  68. package/bench-results/wire-codecs-quick-1775983541111.json +0 -93
  69. package/bench-results/wire-codecs-quick-1776237914299.json +0 -93
  70. package/bench-results/wire-codecs-quick-1777841285236.json +0 -93
  71. package/bench-results/wire-codecs-quick-1777841321772.json +0 -93
  72. package/bench-results/wire-codecs-quick-1777841330408.json +0 -93
  73. package/bench-results/wire-codecs-quick-1777852886082.json +0 -93
  74. package/bench-results/wire-codecs-quick-1777852988773.json +0 -93
  75. package/bench-results/wire-codecs-quick-1777870188095.json +0 -93
  76. package/bench-results/wire-codecs-quick-1777870263918.json +0 -93
  77. package/bench-results/wire-codecs-quick-1777870455034.json +0 -93
  78. package/bench-results/wire-codecs-quick-1778816163081.json +0 -93
  79. package/bench-results/wire-codecs-quick-1778843936130.json +0 -93
  80. package/bin/7h3.ts +0 -385
  81. package/conformance/7h3_v0_1.json +0 -77
  82. package/conformance/7h3_v0_1_binary.json +0 -20
  83. package/conformance/aip_v0_1_binary.json +0 -20
  84. package/docker-compose.yaml +0 -77
  85. package/docs/ADOPTION_PLAN.md +0 -120
  86. package/docs/AGENTS.md +0 -77
  87. package/docs/AIP_RFC_v0.1.md +0 -97
  88. package/docs/AI_DECISION_CARD.md +0 -122
  89. package/docs/AI_RUNTIME_POLICY.json +0 -126
  90. package/docs/AI_RUNTIME_POLICY.yaml +0 -110
  91. package/docs/BACKPRESSURE_TUNING.md +0 -65
  92. package/docs/BENCHMARK_CLAIM_MATRIX.md +0 -42
  93. package/docs/BENCHMARK_REPORT_TEMPLATE.md +0 -169
  94. package/docs/BINARY_CODEC_BENCH.md +0 -23
  95. package/docs/CLEAN_CLONE_RUNBOOK.md +0 -36
  96. package/docs/CLOCK_SKEW_POLICY.md +0 -30
  97. package/docs/DISTRIBUTED_REPLAY.md +0 -142
  98. package/docs/FUZZ_CAMPAIGN.md +0 -121
  99. package/docs/GATEWAY.md +0 -195
  100. package/docs/KEY_MANAGEMENT_POLICY.md +0 -53
  101. package/docs/KEY_REVOCATION.md +0 -69
  102. package/docs/MCP_WRAPPER.md +0 -159
  103. package/docs/MIGRATION_GUIDE.md +0 -40
  104. package/docs/OPERATORS.md +0 -184
  105. package/docs/PERF_REGRESSION_POLICY.md +0 -34
  106. package/docs/PROJECT_EXAMINATION_2026-05-31.md +0 -219
  107. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +0 -135
  108. package/docs/RELEASE_GATE.md +0 -25
  109. package/docs/RELEASE_NOTES_v0.1.0.md +0 -54
  110. package/docs/SECURITY_REVIEW_2026-06-05.md +0 -165
  111. package/docs/TELEMETRY.md +0 -41
  112. package/docs/THREAT_MODEL.md +0 -89
  113. package/docs/VERSIONING_POLICY.md +0 -30
  114. package/docs/assets/banner.png +0 -0
  115. package/eslint.config.js +0 -15
  116. package/fuzz/ts/harness-decode.ts +0 -136
  117. package/fuzz/ts/harness-verify.ts +0 -121
  118. package/fuzz/ts/run.ts +0 -35
  119. package/mcp-server/README.md +0 -38
  120. package/mcp-server/package-lock.json +0 -1187
  121. package/mcp-server/package.json +0 -35
  122. package/mcp-server/src/index.ts +0 -236
  123. package/mcp-server/tsconfig.json +0 -14
  124. package/scripts/aip-framework-quickstart.ts +0 -110
  125. package/scripts/aip-mcp-gateway.ts +0 -38
  126. package/scripts/aip-mcp-wrap-demo.ts +0 -72
  127. package/scripts/aip-quickstart.ts +0 -60
  128. package/scripts/bench-diff.ts +0 -118
  129. package/scripts/bench-protocol-e2e.ts +0 -937
  130. package/scripts/bench-protocol-openloop.ts +0 -1397
  131. package/scripts/bench-replay-cache.ts +0 -76
  132. package/scripts/bench-signature-profiles.ts +0 -180
  133. package/scripts/bench-wire-codecs.ts +0 -161
  134. package/scripts/build-binary-conformance.ts +0 -36
  135. package/scripts/build-release-dashboard.ts +0 -175
  136. package/scripts/canary-rollout.ts +0 -38
  137. package/scripts/mcpGatewayCli.test.ts +0 -116
  138. package/scripts/prepare-aip-package.ts +0 -88
  139. package/scripts/regen-conformance-sigs.ts +0 -18
  140. package/scripts/release-gate.ts +0 -19
  141. package/scripts/validate-runtime-policy.ts +0 -18
  142. package/sdk/browser/index.test.ts +0 -162
  143. package/sdk/browser/index.ts +0 -257
  144. package/sdk/browser/package.json +0 -13
  145. package/sdk/go/go.mod +0 -3
  146. package/sdk/go/http.go +0 -135
  147. package/sdk/go/protocol.go +0 -324
  148. package/sdk/go/protocol_test.go +0 -334
  149. package/sdk/go/webhook.go +0 -136
  150. package/sdk/python/README.md +0 -18
  151. package/sdk/python/protocol_7h3/__init__.py +0 -46
  152. package/sdk/python/protocol_7h3/http.py +0 -212
  153. package/sdk/python/protocol_7h3/keys.py +0 -149
  154. package/sdk/python/protocol_7h3/protocol.py +0 -525
  155. package/sdk/python/protocol_7h3/queue.py +0 -118
  156. package/sdk/python/protocol_7h3/webhook.py +0 -116
  157. package/sdk/python/pyproject.toml +0 -40
  158. package/sdk/python/tests/test_conformance.py +0 -110
  159. package/sdk/python/tests/test_http.py +0 -305
  160. package/sdk/python/tests/test_keys.py +0 -417
  161. package/sdk/python/tests/test_queue.py +0 -120
  162. package/sdk/python/tests/test_webhook.py +0 -345
  163. package/sdk/rust/Cargo.lock +0 -371
  164. package/sdk/rust/Cargo.toml +0 -25
  165. package/sdk/rust/README.md +0 -31
  166. package/sdk/rust/fuzz/Cargo.toml +0 -29
  167. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +0 -46
  168. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +0 -11
  169. package/sdk/rust/src/bin/aip_mcp_gateway.rs +0 -59
  170. package/sdk/rust/src/http.rs +0 -145
  171. package/sdk/rust/src/keys.rs +0 -161
  172. package/sdk/rust/src/lib.rs +0 -688
  173. package/sdk/rust/src/queue.rs +0 -79
  174. package/sdk/rust/src/webhook.rs +0 -86
  175. package/sdk/rust/tests/conformance.rs +0 -148
  176. package/sdk/rust/tests/gateway.rs +0 -130
  177. package/sdk/rust/tests/http_webhook_queue.rs +0 -201
  178. package/sdk/rust/tests/keys.rs +0 -189
  179. package/src/agentAdapter.test.ts +0 -48
  180. package/src/agentAdapter.ts +0 -56
  181. package/src/auditLog.test.ts +0 -145
  182. package/src/auditLog.ts +0 -147
  183. package/src/conformance.test.ts +0 -136
  184. package/src/conformanceVectors.ts +0 -99
  185. package/src/frameworkAdapters.test.ts +0 -290
  186. package/src/frameworkAdapters.ts +0 -261
  187. package/src/gateway.test.ts +0 -343
  188. package/src/gateway.ts +0 -171
  189. package/src/grpcBinding.test.ts +0 -211
  190. package/src/grpcBinding.ts +0 -103
  191. package/src/httpBinding.test.ts +0 -376
  192. package/src/httpBinding.ts +0 -163
  193. package/src/index.ts +0 -32
  194. package/src/keyInfra.test.ts +0 -278
  195. package/src/keyInfra.ts +0 -228
  196. package/src/keyRegistry.ts +0 -59
  197. package/src/keyRotation.test.ts +0 -78
  198. package/src/keyRotation.ts +0 -72
  199. package/src/mcpGateway.test.ts +0 -129
  200. package/src/mcpGateway.ts +0 -250
  201. package/src/mcpTransports.test.ts +0 -92
  202. package/src/mcpTransports.ts +0 -169
  203. package/src/mcpWrapper.test.ts +0 -179
  204. package/src/mcpWrapper.ts +0 -206
  205. package/src/policyEnforcer.test.ts +0 -99
  206. package/src/policyEnforcer.ts +0 -169
  207. package/src/policyTelemetryFeedback.test.ts +0 -25
  208. package/src/policyTelemetryFeedback.ts +0 -38
  209. package/src/protocol.bench.ts +0 -37
  210. package/src/protocol.test.ts +0 -155
  211. package/src/protocol.ts +0 -413
  212. package/src/protocolAgent.test.ts +0 -105
  213. package/src/protocolAgent.ts +0 -169
  214. package/src/protocolBinary.test.ts +0 -165
  215. package/src/protocolBinary.ts +0 -312
  216. package/src/protocolCapabilities.ts +0 -70
  217. package/src/protocolFuzz.advanced.test.ts +0 -235
  218. package/src/protocolFuzz.test.ts +0 -111
  219. package/src/protocolNegative.test.ts +0 -97
  220. package/src/protocolReplay.test.ts +0 -71
  221. package/src/protocolReplay.ts +0 -194
  222. package/src/protocolTransport.test.ts +0 -556
  223. package/src/protocolTransport.ts +0 -483
  224. package/src/queueBinding.test.ts +0 -130
  225. package/src/queueBinding.ts +0 -102
  226. package/src/rateLimiter.test.ts +0 -96
  227. package/src/rateLimiter.ts +0 -46
  228. package/src/redisIntegration.test.ts +0 -134
  229. package/src/replayStores.test.ts +0 -141
  230. package/src/replayStores.ts +0 -82
  231. package/src/revocation.test.ts +0 -98
  232. package/src/revocation.ts +0 -0
  233. package/src/routePolicy.test.ts +0 -87
  234. package/src/routePolicy.ts +0 -72
  235. package/src/runtimePolicy.test.ts +0 -49
  236. package/src/runtimePolicy.ts +0 -81
  237. package/src/runtimePolicyManager.test.ts +0 -29
  238. package/src/runtimePolicyManager.ts +0 -50
  239. package/src/runtimePolicyPresets.ts +0 -43
  240. package/src/signedResponse.test.ts +0 -111
  241. package/src/signedResponse.ts +0 -83
  242. package/src/webhookBinding.test.ts +0 -144
  243. package/src/webhookBinding.ts +0 -115
  244. package/src/wsBinding.test.ts +0 -221
  245. package/src/wsBinding.ts +0 -100
  246. package/tsconfig.json +0 -15
  247. package/tsconfig.lib.json +0 -23
  248. package/vite.lib.config.ts +0 -16
package/sdk/go/http.go DELETED
@@ -1,135 +0,0 @@
1
- package protocol7h3
2
-
3
- import (
4
- "encoding/json"
5
- "net/http"
6
- )
7
-
8
- // HTTPEnvelopeHeader is the default HTTP header name for the protocol envelope.
9
- const HTTPEnvelopeHeader = "X-7h3-Envelope"
10
-
11
- // VerifyFailReason describes why HTTP envelope verification failed.
12
- type VerifyFailReason string
13
-
14
- const (
15
- ReasonMissingHeader VerifyFailReason = "missing_header"
16
- ReasonMalformed VerifyFailReason = "malformed"
17
- ReasonUnknownSender VerifyFailReason = "unknown_sender"
18
- ReasonInvalidSignature VerifyFailReason = "invalid_signature"
19
- ReasonExpired VerifyFailReason = "expired"
20
- )
21
-
22
- // KeyRegistry looks up public keys by sender ID.
23
- type KeyRegistry interface {
24
- GetPublicKey(senderID string) (string, bool)
25
- }
26
-
27
- // StaticKeyRegistry is a simple in-memory key registry.
28
- type StaticKeyRegistry struct {
29
- Keys map[string]string
30
- }
31
-
32
- // GetPublicKey returns the public key for the given sender ID.
33
- func (r *StaticKeyRegistry) GetPublicKey(senderID string) (string, bool) {
34
- k, ok := r.Keys[senderID]
35
- return k, ok
36
- }
37
-
38
- // HTTPVerifyResult is the result of verifying an HTTP envelope.
39
- type HTTPVerifyResult struct {
40
- OK bool
41
- Envelope *ProtocolEnvelope
42
- Reason VerifyFailReason
43
- Detail string
44
- }
45
-
46
- // headerName returns the header name to use (default: HTTPEnvelopeHeader).
47
- func resolveHeaderName(names []string) string {
48
- if len(names) > 0 && names[0] != "" {
49
- return names[0]
50
- }
51
- return HTTPEnvelopeHeader
52
- }
53
-
54
- // VerifyHTTPEnvelope extracts and verifies the protocol envelope from an HTTP request.
55
- func VerifyHTTPEnvelope(r *http.Request, registry KeyRegistry, headerName ...string) HTTPVerifyResult {
56
- hdr := resolveHeaderName(headerName)
57
- val := r.Header.Get(hdr)
58
- if val == "" {
59
- return HTTPVerifyResult{OK: false, Reason: ReasonMissingHeader, Detail: "header " + hdr + " not present"}
60
- }
61
-
62
- var env ProtocolEnvelope
63
- if err := json.Unmarshal([]byte(val), &env); err != nil {
64
- return HTTPVerifyResult{OK: false, Reason: ReasonMalformed, Detail: err.Error()}
65
- }
66
-
67
- // Check expiry
68
- diags := ValidateEnvelope(env)
69
- for _, d := range diags {
70
- if d.Message == "Message TTL expired" {
71
- return HTTPVerifyResult{OK: false, Envelope: &env, Reason: ReasonExpired, Detail: d.Message}
72
- }
73
- }
74
-
75
- // Check sender
76
- if env.Header.Sender == "" {
77
- return HTTPVerifyResult{OK: false, Envelope: &env, Reason: ReasonMalformed, Detail: "missing sender"}
78
- }
79
-
80
- pubKey, ok := registry.GetPublicKey(env.Header.Sender)
81
- if !ok {
82
- return HTTPVerifyResult{OK: false, Envelope: &env, Reason: ReasonUnknownSender, Detail: "no key for sender: " + env.Header.Sender}
83
- }
84
-
85
- if env.Signature == nil {
86
- return HTTPVerifyResult{OK: false, Envelope: &env, Reason: ReasonInvalidSignature, Detail: "no signature"}
87
- }
88
-
89
- var valid bool
90
- var verifyErr error
91
- switch env.Signature.Alg {
92
- case "ED25519":
93
- valid, verifyErr = VerifyEnvelopeEd25519(env, pubKey)
94
- case "HS256":
95
- valid, verifyErr = VerifyEnvelopeHmac(env, pubKey)
96
- default:
97
- return HTTPVerifyResult{OK: false, Envelope: &env, Reason: ReasonInvalidSignature, Detail: "unknown alg: " + env.Signature.Alg}
98
- }
99
-
100
- if verifyErr != nil {
101
- return HTTPVerifyResult{OK: false, Envelope: &env, Reason: ReasonInvalidSignature, Detail: verifyErr.Error()}
102
- }
103
- if !valid {
104
- return HTTPVerifyResult{OK: false, Envelope: &env, Reason: ReasonInvalidSignature, Detail: "signature mismatch"}
105
- }
106
-
107
- return HTTPVerifyResult{OK: true, Envelope: &env}
108
- }
109
-
110
- // SignHTTPRequest signs the envelope and returns the header name and JSON value to set.
111
- func SignHTTPRequest(env ProtocolEnvelope, privateKey string, headerName ...string) (name, value string, err error) {
112
- signed, err := SignEnvelopeEd25519(env, privateKey)
113
- if err != nil {
114
- return "", "", err
115
- }
116
-
117
- b, err := json.Marshal(signed)
118
- if err != nil {
119
- return "", "", err
120
- }
121
-
122
- return resolveHeaderName(headerName), string(b), nil
123
- }
124
-
125
- // Middleware returns an http.Handler that verifies the protocol envelope before passing to next.
126
- func Middleware(registry KeyRegistry, next http.Handler) http.Handler {
127
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
128
- result := VerifyHTTPEnvelope(r, registry)
129
- if !result.OK {
130
- http.Error(w, string(result.Reason)+": "+result.Detail, http.StatusUnauthorized)
131
- return
132
- }
133
- next.ServeHTTP(w, r)
134
- })
135
- }
@@ -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
- }