@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.
- package/.dockerignore +19 -0
- package/.github/dependabot.yml +32 -0
- package/.github/workflows/ci.yml +31 -0
- package/.github/workflows/publish.yml +59 -0
- package/.github/workflows/scorecard.yml +37 -0
- package/7h3.example.yaml +125 -0
- package/CHANGELOG.md +92 -0
- package/CONTRIBUTING.md +82 -0
- package/Dockerfile +73 -0
- package/GOVERNANCE.md +62 -0
- package/README.md +323 -6
- package/SECURITY.md +70 -0
- package/bench-results/replay-cache-full-1777891033256.json +10 -0
- package/bench-results/replay-cache-full-1777896317488.json +10 -0
- package/bench-results/replay-cache-full-1777900993184.json +10 -0
- package/bench-results/replay-cache-full-1777901019285.json +10 -0
- package/bench-results/replay-cache-quick-1777870170126.json +10 -0
- package/bench-results/signature-profiles-quick-1775875160079.json +85 -0
- package/bench-results/signature-profiles-quick-1775983539716.json +85 -0
- package/bench-results/signature-profiles-quick-1776237913190.json +85 -0
- package/bench-results/wire-codecs-full-1777891019803.json +93 -0
- package/bench-results/wire-codecs-full-1777896260964.json +93 -0
- package/bench-results/wire-codecs-full-1777901004247.json +93 -0
- package/bench-results/wire-codecs-quick-1775972879056.json +93 -0
- package/bench-results/wire-codecs-quick-1775983541111.json +93 -0
- package/bench-results/wire-codecs-quick-1776237914299.json +93 -0
- package/bench-results/wire-codecs-quick-1777841285236.json +93 -0
- package/bench-results/wire-codecs-quick-1777841321772.json +93 -0
- package/bench-results/wire-codecs-quick-1777841330408.json +93 -0
- package/bench-results/wire-codecs-quick-1777852886082.json +93 -0
- package/bench-results/wire-codecs-quick-1777852988773.json +93 -0
- package/bench-results/wire-codecs-quick-1777870188095.json +93 -0
- package/bench-results/wire-codecs-quick-1777870263918.json +93 -0
- package/bench-results/wire-codecs-quick-1777870455034.json +93 -0
- package/bench-results/wire-codecs-quick-1778816163081.json +93 -0
- package/bench-results/wire-codecs-quick-1778843936130.json +93 -0
- package/bin/7h3.ts +385 -0
- package/conformance/7h3_v0_1.json +77 -0
- package/conformance/7h3_v0_1_binary.json +20 -0
- package/conformance/aip_v0_1_binary.json +20 -0
- package/docker-compose.yaml +77 -0
- package/docs/ADOPTION_PLAN.md +120 -0
- package/docs/AGENTS.md +77 -0
- package/docs/AIP_RFC_v0.1.md +97 -0
- package/docs/AI_DECISION_CARD.md +122 -0
- package/docs/AI_RUNTIME_POLICY.json +126 -0
- package/docs/AI_RUNTIME_POLICY.yaml +110 -0
- package/docs/BACKPRESSURE_TUNING.md +65 -0
- package/docs/BENCHMARK_CLAIM_MATRIX.md +42 -0
- package/docs/BENCHMARK_REPORT_TEMPLATE.md +169 -0
- package/docs/BINARY_CODEC_BENCH.md +23 -0
- package/docs/CLEAN_CLONE_RUNBOOK.md +36 -0
- package/docs/CLOCK_SKEW_POLICY.md +30 -0
- package/docs/DISTRIBUTED_REPLAY.md +142 -0
- package/docs/FUZZ_CAMPAIGN.md +121 -0
- package/docs/GATEWAY.md +195 -0
- package/docs/KEY_MANAGEMENT_POLICY.md +53 -0
- package/docs/KEY_REVOCATION.md +69 -0
- package/docs/MCP_WRAPPER.md +159 -0
- package/docs/MIGRATION_GUIDE.md +40 -0
- package/docs/OPERATORS.md +184 -0
- package/docs/PERF_REGRESSION_POLICY.md +34 -0
- package/docs/PROJECT_EXAMINATION_2026-05-31.md +219 -0
- package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +135 -0
- package/docs/RELEASE_GATE.md +25 -0
- package/docs/RELEASE_NOTES_v0.1.0.md +54 -0
- package/docs/SECURITY_REVIEW_2026-06-05.md +165 -0
- package/docs/TELEMETRY.md +41 -0
- package/docs/THREAT_MODEL.md +89 -0
- package/docs/VERSIONING_POLICY.md +30 -0
- package/docs/assets/banner.png +0 -0
- package/eslint.config.js +15 -0
- package/fuzz/ts/harness-decode.ts +136 -0
- package/fuzz/ts/harness-verify.ts +121 -0
- package/fuzz/ts/run.ts +35 -0
- package/mcp-server/README.md +38 -0
- package/mcp-server/package-lock.json +1187 -0
- package/mcp-server/package.json +35 -0
- package/mcp-server/src/index.ts +236 -0
- package/mcp-server/tsconfig.json +14 -0
- package/package.json +79 -13
- package/scripts/aip-framework-quickstart.ts +110 -0
- package/scripts/aip-mcp-gateway.ts +38 -0
- package/scripts/aip-mcp-wrap-demo.ts +72 -0
- package/scripts/aip-quickstart.ts +60 -0
- package/scripts/bench-diff.ts +118 -0
- package/scripts/bench-protocol-e2e.ts +937 -0
- package/scripts/bench-protocol-openloop.ts +1397 -0
- package/scripts/bench-replay-cache.ts +76 -0
- package/scripts/bench-signature-profiles.ts +180 -0
- package/scripts/bench-wire-codecs.ts +161 -0
- package/scripts/build-binary-conformance.ts +36 -0
- package/scripts/build-release-dashboard.ts +175 -0
- package/scripts/canary-rollout.ts +38 -0
- package/scripts/mcpGatewayCli.test.ts +116 -0
- package/scripts/prepare-aip-package.ts +88 -0
- package/scripts/regen-conformance-sigs.ts +18 -0
- package/scripts/release-gate.ts +19 -0
- package/scripts/validate-runtime-policy.ts +18 -0
- package/sdk/browser/index.test.ts +162 -0
- package/sdk/browser/index.ts +257 -0
- package/sdk/browser/package.json +13 -0
- package/sdk/go/go.mod +3 -0
- package/sdk/go/http.go +135 -0
- package/sdk/go/protocol.go +324 -0
- package/sdk/go/protocol_test.go +334 -0
- package/sdk/go/webhook.go +136 -0
- package/sdk/python/README.md +18 -0
- package/sdk/python/protocol_7h3/__init__.py +46 -0
- package/sdk/python/protocol_7h3/http.py +212 -0
- package/sdk/python/protocol_7h3/keys.py +149 -0
- package/sdk/python/protocol_7h3/protocol.py +525 -0
- package/sdk/python/protocol_7h3/queue.py +118 -0
- package/sdk/python/protocol_7h3/webhook.py +116 -0
- package/sdk/python/pyproject.toml +40 -0
- package/sdk/python/tests/test_conformance.py +110 -0
- package/sdk/python/tests/test_http.py +305 -0
- package/sdk/python/tests/test_keys.py +417 -0
- package/sdk/python/tests/test_queue.py +120 -0
- package/sdk/python/tests/test_webhook.py +345 -0
- package/sdk/rust/Cargo.lock +371 -0
- package/sdk/rust/Cargo.toml +25 -0
- package/sdk/rust/README.md +31 -0
- package/sdk/rust/fuzz/Cargo.toml +29 -0
- package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +46 -0
- package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +11 -0
- package/sdk/rust/src/bin/aip_mcp_gateway.rs +59 -0
- package/sdk/rust/src/http.rs +145 -0
- package/sdk/rust/src/keys.rs +161 -0
- package/sdk/rust/src/lib.rs +688 -0
- package/sdk/rust/src/queue.rs +79 -0
- package/sdk/rust/src/webhook.rs +86 -0
- package/sdk/rust/tests/conformance.rs +148 -0
- package/sdk/rust/tests/gateway.rs +130 -0
- package/sdk/rust/tests/http_webhook_queue.rs +201 -0
- package/sdk/rust/tests/keys.rs +189 -0
- package/src/agentAdapter.test.ts +48 -0
- package/src/agentAdapter.ts +56 -0
- package/src/auditLog.test.ts +145 -0
- package/src/auditLog.ts +147 -0
- package/src/conformance.test.ts +136 -0
- package/src/conformanceVectors.ts +99 -0
- package/src/frameworkAdapters.test.ts +290 -0
- package/src/frameworkAdapters.ts +261 -0
- package/src/gateway.test.ts +343 -0
- package/src/gateway.ts +171 -0
- package/src/grpcBinding.test.ts +211 -0
- package/src/grpcBinding.ts +103 -0
- package/src/httpBinding.test.ts +376 -0
- package/src/httpBinding.ts +163 -0
- package/src/index.ts +32 -0
- package/src/keyInfra.test.ts +278 -0
- package/src/keyInfra.ts +228 -0
- package/src/keyRegistry.ts +59 -0
- package/src/keyRotation.test.ts +78 -0
- package/src/keyRotation.ts +72 -0
- package/src/mcpGateway.test.ts +129 -0
- package/src/mcpGateway.ts +250 -0
- package/src/mcpTransports.test.ts +92 -0
- package/src/mcpTransports.ts +169 -0
- package/src/mcpWrapper.test.ts +179 -0
- package/src/mcpWrapper.ts +206 -0
- package/src/policyEnforcer.test.ts +99 -0
- package/src/policyEnforcer.ts +169 -0
- package/src/policyTelemetryFeedback.test.ts +25 -0
- package/src/policyTelemetryFeedback.ts +38 -0
- package/src/protocol.bench.ts +37 -0
- package/src/protocol.test.ts +155 -0
- package/src/protocol.ts +413 -0
- package/src/protocolAgent.test.ts +105 -0
- package/src/protocolAgent.ts +169 -0
- package/src/protocolBinary.test.ts +165 -0
- package/src/protocolBinary.ts +312 -0
- package/src/protocolCapabilities.ts +70 -0
- package/src/protocolFuzz.advanced.test.ts +235 -0
- package/src/protocolFuzz.test.ts +111 -0
- package/src/protocolNegative.test.ts +97 -0
- package/src/protocolReplay.test.ts +71 -0
- package/src/protocolReplay.ts +194 -0
- package/src/protocolTransport.test.ts +556 -0
- package/src/protocolTransport.ts +483 -0
- package/src/queueBinding.test.ts +130 -0
- package/src/queueBinding.ts +102 -0
- package/src/rateLimiter.test.ts +96 -0
- package/src/rateLimiter.ts +46 -0
- package/src/redisClient.ts +140 -0
- package/src/redisIntegration.test.ts +134 -0
- package/src/replayStores.test.ts +141 -0
- package/src/replayStores.ts +82 -0
- package/src/revocation.test.ts +98 -0
- package/src/revocation.ts +0 -0
- package/src/routePolicy.test.ts +87 -0
- package/src/routePolicy.ts +72 -0
- package/src/runtimePolicy.test.ts +49 -0
- package/src/runtimePolicy.ts +81 -0
- package/src/runtimePolicyManager.test.ts +29 -0
- package/src/runtimePolicyManager.ts +50 -0
- package/src/runtimePolicyPresets.ts +43 -0
- package/src/signedResponse.test.ts +111 -0
- package/src/signedResponse.ts +83 -0
- package/src/webhookBinding.test.ts +144 -0
- package/src/webhookBinding.ts +115 -0
- package/src/wsBinding.test.ts +221 -0
- package/src/wsBinding.ts +100 -0
- package/tsconfig.json +15 -0
- package/tsconfig.lib.json +23 -0
- package/vite.lib.config.ts +16 -0
- package/agentAdapter.d.ts +0 -26
- package/conformanceVectors.d.ts +0 -20
- package/frameworkAdapters.d.ts +0 -72
- package/index.d.ts +0 -20
- package/index.js +0 -1702
- package/keyRotation.d.ts +0 -20
- package/mcpGateway.d.ts +0 -37
- package/mcpTransports.d.ts +0 -62
- package/mcpWrapper.d.ts +0 -83
- package/policyEnforcer.d.ts +0 -50
- package/policyTelemetryFeedback.d.ts +0 -11
- package/protocol.d.ts +0 -66
- package/protocolAgent.d.ts +0 -58
- package/protocolBinary.d.ts +0 -8
- package/protocolCapabilities.d.ts +0 -24
- package/protocolReplay.d.ts +0 -35
- package/protocolTransport.d.ts +0 -73
- package/redisClient.d.ts +0 -49
- package/replayStores.d.ts +0 -32
- package/revocation.d.ts +0 -71
- package/runtimePolicy.d.ts +0 -24
- package/runtimePolicyManager.d.ts +0 -15
- package/runtimePolicyPresets.d.ts +0 -11
package/sdk/go/http.go
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,324 @@
|
|
|
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
|
+
}
|