@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/src/gateway.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { type KeyRegistry } from './keyRegistry'
|
|
2
|
+
import { type RoutePolicy, matchPolicy, isAllowedSender } from './routePolicy'
|
|
3
|
+
import { SlidingWindowRateLimiter } from './rateLimiter'
|
|
4
|
+
import { verifyHttpEnvelope } from './httpBinding'
|
|
5
|
+
import { signResponse } from './signedResponse'
|
|
6
|
+
|
|
7
|
+
export type { KeyRegistry, RoutePolicy }
|
|
8
|
+
|
|
9
|
+
export interface GatewayConfig {
|
|
10
|
+
upstream: string
|
|
11
|
+
keyRegistry: KeyRegistry
|
|
12
|
+
policies?: RoutePolicy[]
|
|
13
|
+
privateKey?: string
|
|
14
|
+
sender?: string
|
|
15
|
+
signResponses?: boolean // default true when privateKey set
|
|
16
|
+
defaultPolicy?: 'allow' | 'deny' // default 'allow'
|
|
17
|
+
headerName?: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface GatewayRequest {
|
|
21
|
+
method: string
|
|
22
|
+
path: string
|
|
23
|
+
headers: Record<string, string | string[]>
|
|
24
|
+
body?: string
|
|
25
|
+
url?: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface GatewayResponse {
|
|
29
|
+
status: number
|
|
30
|
+
headers: Record<string, string>
|
|
31
|
+
body: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type GatewayVerifyOutcome =
|
|
35
|
+
| { ok: true; sender: string; envelopeId?: string }
|
|
36
|
+
| { ok: false; status: 401 | 403 | 429; reason: string }
|
|
37
|
+
|
|
38
|
+
class Protocol7h3Gateway {
|
|
39
|
+
private config: GatewayConfig
|
|
40
|
+
private rateLimiter: SlidingWindowRateLimiter
|
|
41
|
+
|
|
42
|
+
constructor(config: GatewayConfig) {
|
|
43
|
+
this.config = config
|
|
44
|
+
this.rateLimiter = new SlidingWindowRateLimiter()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async verify(req: GatewayRequest): Promise<GatewayVerifyOutcome> {
|
|
48
|
+
const policy = matchPolicy(this.config.policies ?? [], req.path)
|
|
49
|
+
|
|
50
|
+
// Determine if we skip verification
|
|
51
|
+
const skipVerify =
|
|
52
|
+
policy?.require === 'none' ||
|
|
53
|
+
(!policy && (this.config.defaultPolicy ?? 'allow') === 'allow')
|
|
54
|
+
|
|
55
|
+
if (skipVerify) {
|
|
56
|
+
return { ok: true, sender: '' }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// deny if no policy and defaultPolicy is 'deny'
|
|
60
|
+
if (!policy && (this.config.defaultPolicy ?? 'allow') === 'deny') {
|
|
61
|
+
return { ok: false, status: 403, reason: 'no-matching-policy' }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Verify the envelope
|
|
65
|
+
const result = await verifyHttpEnvelope(req.headers, {
|
|
66
|
+
keyRegistry: this.config.keyRegistry,
|
|
67
|
+
headerName: this.config.headerName,
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
if (!result.ok) {
|
|
71
|
+
return { ok: false, status: 401, reason: result.reason }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const envelope = result.envelope
|
|
75
|
+
const sender = envelope.header.sender
|
|
76
|
+
const envelopeId = envelope.header.messageId
|
|
77
|
+
|
|
78
|
+
// Enforce algorithm requirement when policy specifies a specific alg
|
|
79
|
+
if (policy && policy.require !== 'any') {
|
|
80
|
+
const actualAlg = envelope.signature?.alg
|
|
81
|
+
const requiresEd25519 = policy.require === 'ed25519' && actualAlg !== 'ED25519'
|
|
82
|
+
const requiresHmac = policy.require === 'hmac' && actualAlg !== 'HS256'
|
|
83
|
+
if (requiresEd25519 || requiresHmac) {
|
|
84
|
+
return { ok: false, status: 401, reason: 'invalid-signature' }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Check allowedSenders
|
|
89
|
+
if (policy && !isAllowedSender(policy, sender)) {
|
|
90
|
+
return { ok: false, status: 403, reason: 'sender-denied' }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Check rate limit
|
|
94
|
+
if (policy?.rateLimit) {
|
|
95
|
+
const rl = this.rateLimiter.consume(sender, policy.rateLimit)
|
|
96
|
+
if (!rl.allowed) {
|
|
97
|
+
return { ok: false, status: 429, reason: 'rate-limited' }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return { ok: true, sender, envelopeId }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async handle(req: GatewayRequest): Promise<GatewayResponse> {
|
|
105
|
+
const outcome = await this.verify(req)
|
|
106
|
+
|
|
107
|
+
if (!outcome.ok) {
|
|
108
|
+
return {
|
|
109
|
+
status: outcome.status,
|
|
110
|
+
headers: { 'content-type': 'application/json' },
|
|
111
|
+
body: JSON.stringify({ error: outcome.reason }),
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Build upstream URL
|
|
116
|
+
const upstreamUrl = this.config.upstream.replace(/\/$/, '') + req.path
|
|
117
|
+
|
|
118
|
+
// Build forwarded headers, adding 7h3 metadata
|
|
119
|
+
const forwardHeaders: Record<string, string> = {}
|
|
120
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
121
|
+
forwardHeaders[k] = Array.isArray(v) ? v[0] : v
|
|
122
|
+
}
|
|
123
|
+
if (outcome.sender) {
|
|
124
|
+
forwardHeaders['x-7h3-sender'] = outcome.sender
|
|
125
|
+
}
|
|
126
|
+
forwardHeaders['x-7h3-verified'] = 'true'
|
|
127
|
+
|
|
128
|
+
// Fetch upstream
|
|
129
|
+
const fetchResponse = await fetch(upstreamUrl, {
|
|
130
|
+
method: req.method,
|
|
131
|
+
headers: forwardHeaders,
|
|
132
|
+
body: req.body,
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
const responseBody = await fetchResponse.text()
|
|
136
|
+
const responseHeaders: Record<string, string> = {
|
|
137
|
+
'content-type': fetchResponse.headers.get('content-type') ?? 'application/json',
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Sign response if configured
|
|
141
|
+
const shouldSign =
|
|
142
|
+
this.config.privateKey !== undefined &&
|
|
143
|
+
(this.config.signResponses ?? true) &&
|
|
144
|
+
this.config.sender !== undefined
|
|
145
|
+
|
|
146
|
+
if (shouldSign) {
|
|
147
|
+
const signed = await signResponse(responseBody, {
|
|
148
|
+
privateKey: this.config.privateKey!,
|
|
149
|
+
sender: this.config.sender!,
|
|
150
|
+
recipient: outcome.sender || undefined,
|
|
151
|
+
})
|
|
152
|
+
Object.assign(responseHeaders, signed.headers)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
status: fetchResponse.status,
|
|
157
|
+
headers: responseHeaders,
|
|
158
|
+
body: responseBody,
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
getRateLimiter(): SlidingWindowRateLimiter {
|
|
163
|
+
return this.rateLimiter
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function createGateway(config: GatewayConfig): Protocol7h3Gateway {
|
|
168
|
+
return new Protocol7h3Gateway(config)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export { Protocol7h3Gateway }
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
signGrpcCall,
|
|
4
|
+
verifyGrpcCall,
|
|
5
|
+
withGrpcVerification,
|
|
6
|
+
GRPC_METADATA_KEY,
|
|
7
|
+
} from './grpcBinding'
|
|
8
|
+
import { createStaticKeyRegistry, type KeyRegistry } from './keyRegistry'
|
|
9
|
+
import {
|
|
10
|
+
generateEd25519KeypairBase64Url,
|
|
11
|
+
createEnvelope,
|
|
12
|
+
signEnvelopeEd25519,
|
|
13
|
+
type ProtocolEnvelope,
|
|
14
|
+
} from './protocol'
|
|
15
|
+
|
|
16
|
+
// Helper: build a KeyRegistry that holds HMAC shared secrets but no public keys
|
|
17
|
+
function createHmacKeyRegistry(secrets: Record<string, string>): KeyRegistry {
|
|
18
|
+
return {
|
|
19
|
+
async getPublicKey() { return null },
|
|
20
|
+
async getSharedSecret(keyId) { return secrets[keyId] ?? null },
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
describe('signGrpcCall', () => {
|
|
25
|
+
it('produces metadata with the correct key', async () => {
|
|
26
|
+
const { privateKey } = await generateEd25519KeypairBase64Url()
|
|
27
|
+
const sender = 'grpc-client-agent'
|
|
28
|
+
|
|
29
|
+
const metadata = await signGrpcCall({ privateKey, sender })
|
|
30
|
+
|
|
31
|
+
expect(metadata[GRPC_METADATA_KEY]).toBeDefined()
|
|
32
|
+
expect(typeof metadata[GRPC_METADATA_KEY]).toBe('string')
|
|
33
|
+
|
|
34
|
+
// Parse and validate structure
|
|
35
|
+
const parsed = JSON.parse(metadata[GRPC_METADATA_KEY]) as ProtocolEnvelope
|
|
36
|
+
expect(parsed.header.sender).toBe(sender)
|
|
37
|
+
expect(parsed.signature?.alg).toBe('ED25519')
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('uses a custom metadataKey when provided', async () => {
|
|
41
|
+
const { privateKey } = await generateEd25519KeypairBase64Url()
|
|
42
|
+
const customKey = 'x-custom-grpc-sig'
|
|
43
|
+
|
|
44
|
+
const metadata = await signGrpcCall({ privateKey, sender: 'agent-x', metadataKey: customKey })
|
|
45
|
+
|
|
46
|
+
expect(metadata[customKey]).toBeDefined()
|
|
47
|
+
expect(metadata[GRPC_METADATA_KEY]).toBeUndefined()
|
|
48
|
+
})
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
describe('verifyGrpcCall', () => {
|
|
52
|
+
it('valid signed call returns ok:true with envelope', async () => {
|
|
53
|
+
const { publicKey, privateKey } = await generateEd25519KeypairBase64Url()
|
|
54
|
+
const sender = 'grpc-server-agent'
|
|
55
|
+
const registry = createStaticKeyRegistry({ [sender]: publicKey })
|
|
56
|
+
|
|
57
|
+
const metadata = await signGrpcCall({ privateKey, sender })
|
|
58
|
+
const result = await verifyGrpcCall(metadata, { keyRegistry: registry })
|
|
59
|
+
|
|
60
|
+
expect(result.ok).toBe(true)
|
|
61
|
+
if (result.ok) {
|
|
62
|
+
expect(result.envelope.header.sender).toBe(sender)
|
|
63
|
+
expect(result.envelope.body.intent).toBe('TASK')
|
|
64
|
+
}
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('missing metadata returns ok:false with code 16', async () => {
|
|
68
|
+
const registry = createStaticKeyRegistry({})
|
|
69
|
+
const result = await verifyGrpcCall({}, { keyRegistry: registry })
|
|
70
|
+
|
|
71
|
+
expect(result.ok).toBe(false)
|
|
72
|
+
if (!result.ok) {
|
|
73
|
+
expect(result.code).toBe(16)
|
|
74
|
+
expect(result.message).toContain('missing')
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('tampered envelope returns ok:false with code 16', async () => {
|
|
79
|
+
const { publicKey, privateKey } = await generateEd25519KeypairBase64Url()
|
|
80
|
+
const sender = 'grpc-tamper-agent'
|
|
81
|
+
const registry = createStaticKeyRegistry({ [sender]: publicKey })
|
|
82
|
+
|
|
83
|
+
const env = createEnvelope({ sender, intent: 'TASK', content: 'original', ttlMs: 60_000 })
|
|
84
|
+
const signed = await signEnvelopeEd25519(env, privateKey)
|
|
85
|
+
|
|
86
|
+
// Tamper with content after signing
|
|
87
|
+
const tampered: ProtocolEnvelope = {
|
|
88
|
+
...signed,
|
|
89
|
+
body: { ...signed.body, content: 'tampered' },
|
|
90
|
+
}
|
|
91
|
+
const metadata = { [GRPC_METADATA_KEY]: JSON.stringify(tampered) }
|
|
92
|
+
|
|
93
|
+
const result = await verifyGrpcCall(metadata, { keyRegistry: registry })
|
|
94
|
+
|
|
95
|
+
expect(result.ok).toBe(false)
|
|
96
|
+
if (!result.ok) {
|
|
97
|
+
expect(result.code).toBe(16)
|
|
98
|
+
}
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it('expired envelope returns ok:false with code 4', async () => {
|
|
102
|
+
const { publicKey, privateKey } = await generateEd25519KeypairBase64Url()
|
|
103
|
+
const sender = 'grpc-expired-agent'
|
|
104
|
+
const registry = createStaticKeyRegistry({ [sender]: publicKey })
|
|
105
|
+
|
|
106
|
+
const pastNow = Date.now() - 120_000 // 2 minutes ago
|
|
107
|
+
const env = createEnvelope({
|
|
108
|
+
sender,
|
|
109
|
+
intent: 'TASK',
|
|
110
|
+
content: 'expired-task',
|
|
111
|
+
ttlMs: 1_000, // 1 second TTL — already expired
|
|
112
|
+
nowMs: pastNow,
|
|
113
|
+
})
|
|
114
|
+
const signed = await signEnvelopeEd25519(env, privateKey)
|
|
115
|
+
const metadata = { [GRPC_METADATA_KEY]: JSON.stringify(signed) }
|
|
116
|
+
|
|
117
|
+
const result = await verifyGrpcCall(metadata, { keyRegistry: registry, strictTtl: true })
|
|
118
|
+
|
|
119
|
+
expect(result.ok).toBe(false)
|
|
120
|
+
if (!result.ok) {
|
|
121
|
+
expect(result.code).toBe(4)
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
it('unknown sender returns ok:false with code 16', async () => {
|
|
126
|
+
const { privateKey } = await generateEd25519KeypairBase64Url()
|
|
127
|
+
const registry = createStaticKeyRegistry({}) // empty registry
|
|
128
|
+
|
|
129
|
+
const env = createEnvelope({ sender: 'unknown-grpc-agent', intent: 'TASK', content: 'hi', ttlMs: 60_000 })
|
|
130
|
+
const signed = await signEnvelopeEd25519(env, privateKey)
|
|
131
|
+
const metadata = { [GRPC_METADATA_KEY]: JSON.stringify(signed) }
|
|
132
|
+
|
|
133
|
+
const result = await verifyGrpcCall(metadata, { keyRegistry: registry })
|
|
134
|
+
|
|
135
|
+
expect(result.ok).toBe(false)
|
|
136
|
+
if (!result.ok) {
|
|
137
|
+
expect(result.code).toBe(16)
|
|
138
|
+
expect(result.message).toContain('unknown-grpc-agent')
|
|
139
|
+
}
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
it('accepts Buffer values in metadata', async () => {
|
|
143
|
+
const { publicKey, privateKey } = await generateEd25519KeypairBase64Url()
|
|
144
|
+
const sender = 'grpc-buffer-agent'
|
|
145
|
+
const registry = createStaticKeyRegistry({ [sender]: publicKey })
|
|
146
|
+
|
|
147
|
+
const env = createEnvelope({ sender, intent: 'TASK', content: 'buf-test', ttlMs: 60_000 })
|
|
148
|
+
const signed = await signEnvelopeEd25519(env, privateKey)
|
|
149
|
+
const metadata: Record<string, Buffer> = {
|
|
150
|
+
[GRPC_METADATA_KEY]: Buffer.from(JSON.stringify(signed), 'utf8'),
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const result = await verifyGrpcCall(metadata, { keyRegistry: registry })
|
|
154
|
+
expect(result.ok).toBe(true)
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
it('accepts string array values in metadata', async () => {
|
|
158
|
+
const { publicKey, privateKey } = await generateEd25519KeypairBase64Url()
|
|
159
|
+
const sender = 'grpc-array-agent'
|
|
160
|
+
const registry = createStaticKeyRegistry({ [sender]: publicKey })
|
|
161
|
+
|
|
162
|
+
const env = createEnvelope({ sender, intent: 'TASK', content: 'arr-test', ttlMs: 60_000 })
|
|
163
|
+
const signed = await signEnvelopeEd25519(env, privateKey)
|
|
164
|
+
const metadata: Record<string, string[]> = {
|
|
165
|
+
[GRPC_METADATA_KEY]: [JSON.stringify(signed)],
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const result = await verifyGrpcCall(metadata, { keyRegistry: registry })
|
|
169
|
+
expect(result.ok).toBe(true)
|
|
170
|
+
})
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
describe('withGrpcVerification', () => {
|
|
174
|
+
it('calls handler on valid call and attaches envelope to call object', async () => {
|
|
175
|
+
const { publicKey, privateKey } = await generateEd25519KeypairBase64Url()
|
|
176
|
+
const sender = 'grpc-wrap-agent'
|
|
177
|
+
const registry = createStaticKeyRegistry({ [sender]: publicKey })
|
|
178
|
+
|
|
179
|
+
const signedMeta = await signGrpcCall({ privateKey, sender })
|
|
180
|
+
const call = { metadata: signedMeta, someField: 'value' }
|
|
181
|
+
|
|
182
|
+
const handler = vi.fn().mockResolvedValue({ status: 'ok' })
|
|
183
|
+
const wrapped = withGrpcVerification(handler, { keyRegistry: registry })
|
|
184
|
+
|
|
185
|
+
const response = await wrapped(call)
|
|
186
|
+
|
|
187
|
+
expect(handler).toHaveBeenCalledOnce()
|
|
188
|
+
expect(handler).toHaveBeenCalledWith(call)
|
|
189
|
+
expect(response).toEqual({ status: 'ok' })
|
|
190
|
+
expect((call as any)['7h3Envelope']).toBeDefined()
|
|
191
|
+
expect((call as any)['7h3Envelope'].header.sender).toBe(sender)
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
it('throws on invalid call and does not invoke handler', async () => {
|
|
195
|
+
const registry = createStaticKeyRegistry({})
|
|
196
|
+
const call = { metadata: {} } // no envelope metadata
|
|
197
|
+
|
|
198
|
+
const handler = vi.fn().mockResolvedValue({ status: 'ok' })
|
|
199
|
+
const wrapped = withGrpcVerification(handler, { keyRegistry: registry })
|
|
200
|
+
|
|
201
|
+
await expect(wrapped(call)).rejects.toThrow()
|
|
202
|
+
expect(handler).not.toHaveBeenCalled()
|
|
203
|
+
|
|
204
|
+
// The thrown error should carry the gRPC status code
|
|
205
|
+
try {
|
|
206
|
+
await wrapped(call)
|
|
207
|
+
} catch (err: any) {
|
|
208
|
+
expect(err.code).toBe(16)
|
|
209
|
+
}
|
|
210
|
+
})
|
|
211
|
+
})
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import {
|
|
2
|
+
signEnvelopeEd25519,
|
|
3
|
+
verifyEnvelopeEd25519, verifyEnvelopeHmac,
|
|
4
|
+
createEnvelope, validateEnvelope,
|
|
5
|
+
type ProtocolEnvelope,
|
|
6
|
+
} from './protocol'
|
|
7
|
+
import type { KeyRegistry } from './keyRegistry'
|
|
8
|
+
|
|
9
|
+
export { type KeyRegistry }
|
|
10
|
+
|
|
11
|
+
export const GRPC_METADATA_KEY = '7h3-envelope-bin' // -bin suffix = binary safe in gRPC
|
|
12
|
+
|
|
13
|
+
export interface GrpcSignOptions {
|
|
14
|
+
privateKey: string
|
|
15
|
+
sender: string
|
|
16
|
+
recipient?: string
|
|
17
|
+
ttlMs?: number
|
|
18
|
+
metadataKey?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface GrpcVerifyOptions {
|
|
22
|
+
keyRegistry: KeyRegistry
|
|
23
|
+
metadataKey?: string
|
|
24
|
+
strictTtl?: boolean
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type GrpcVerifyResult =
|
|
28
|
+
| { ok: true; envelope: ProtocolEnvelope }
|
|
29
|
+
| { ok: false; code: number; message: string } // code = gRPC status code
|
|
30
|
+
|
|
31
|
+
// Client side: produce metadata to attach to outbound call
|
|
32
|
+
export async function signGrpcCall(
|
|
33
|
+
opts: GrpcSignOptions
|
|
34
|
+
): Promise<Record<string, string>> {
|
|
35
|
+
const envelope = createEnvelope({
|
|
36
|
+
sender: opts.sender,
|
|
37
|
+
recipient: opts.recipient,
|
|
38
|
+
ttlMs: opts.ttlMs ?? 60_000,
|
|
39
|
+
intent: 'TASK',
|
|
40
|
+
content: 'grpc-call',
|
|
41
|
+
})
|
|
42
|
+
const signed = await signEnvelopeEd25519(envelope, opts.privateKey)
|
|
43
|
+
return { [opts.metadataKey ?? GRPC_METADATA_KEY]: JSON.stringify(signed) }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Server side: verify metadata from incoming call
|
|
47
|
+
export async function verifyGrpcCall(
|
|
48
|
+
metadata: Record<string, string | Buffer | string[]>,
|
|
49
|
+
opts: GrpcVerifyOptions
|
|
50
|
+
): Promise<GrpcVerifyResult> {
|
|
51
|
+
const key = opts.metadataKey ?? GRPC_METADATA_KEY
|
|
52
|
+
const raw = metadata[key]
|
|
53
|
+
const rawStr = Array.isArray(raw) ? raw[0] : (raw instanceof Uint8Array ? new TextDecoder().decode(raw) : raw)
|
|
54
|
+
if (!rawStr) return { ok: false, code: 16, message: '7h3: missing gRPC envelope metadata' }
|
|
55
|
+
|
|
56
|
+
let envelope: ProtocolEnvelope
|
|
57
|
+
try { envelope = JSON.parse(typeof rawStr === 'string' ? rawStr : String(rawStr)) as ProtocolEnvelope }
|
|
58
|
+
catch { return { ok: false, code: 3, message: '7h3: malformed envelope metadata' } }
|
|
59
|
+
|
|
60
|
+
if (opts.strictTtl !== false) {
|
|
61
|
+
const diags = validateEnvelope(envelope)
|
|
62
|
+
if (diags.some(d => d.level === 'error')) {
|
|
63
|
+
return { ok: false, code: 4, message: '7h3: envelope expired or invalid' }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const sender = envelope.header?.sender
|
|
68
|
+
const alg = envelope.signature?.alg
|
|
69
|
+
if (!sender || !alg) return { ok: false, code: 3, message: '7h3: missing sender or alg' }
|
|
70
|
+
|
|
71
|
+
if (alg === 'ED25519') {
|
|
72
|
+
const publicKey = await opts.keyRegistry.getPublicKey(sender)
|
|
73
|
+
if (!publicKey) return { ok: false, code: 16, message: `7h3: unknown sender ${sender}` }
|
|
74
|
+
const valid = await verifyEnvelopeEd25519(envelope, publicKey)
|
|
75
|
+
if (!valid) return { ok: false, code: 16, message: '7h3: invalid signature' }
|
|
76
|
+
} else if (alg === 'HS256') {
|
|
77
|
+
const secret = await opts.keyRegistry.getSharedSecret?.(envelope.signature!.keyId)
|
|
78
|
+
if (!secret) return { ok: false, code: 16, message: '7h3: unknown key' }
|
|
79
|
+
const valid = await verifyEnvelopeHmac(envelope, secret)
|
|
80
|
+
if (!valid) return { ok: false, code: 16, message: '7h3: invalid signature' }
|
|
81
|
+
} else {
|
|
82
|
+
return { ok: false, code: 3, message: `7h3: unsupported alg ${String(alg)}` }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return { ok: true, envelope }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Factory: creates a function that wraps any async gRPC handler with verify logic
|
|
89
|
+
// Usage: const handler = withGrpcVerification(myHandler, verifyOpts)
|
|
90
|
+
export function withGrpcVerification<TCall extends { metadata: Record<string, string | Buffer | string[]> }, TResp>(
|
|
91
|
+
handler: (call: TCall) => Promise<TResp>,
|
|
92
|
+
opts: GrpcVerifyOptions
|
|
93
|
+
): (call: TCall) => Promise<TResp> {
|
|
94
|
+
return async (call: TCall) => {
|
|
95
|
+
const result = await verifyGrpcCall(call.metadata, opts)
|
|
96
|
+
if (!result.ok) {
|
|
97
|
+
const err = Object.assign(new Error(result.message), { code: result.code })
|
|
98
|
+
throw err
|
|
99
|
+
}
|
|
100
|
+
;(call as any)['7h3Envelope'] = result.envelope
|
|
101
|
+
return handler(call)
|
|
102
|
+
}
|
|
103
|
+
}
|