@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
@@ -1,688 +0,0 @@
1
- pub mod http;
2
- pub mod keys;
3
- pub mod queue;
4
- pub mod webhook;
5
-
6
- use base64::engine::general_purpose::URL_SAFE_NO_PAD;
7
- use base64::Engine;
8
- use ed25519_dalek::pkcs8::{DecodePrivateKey, DecodePublicKey};
9
- use ed25519_dalek::{Signature as Ed25519Signature, Signer, SigningKey, Verifier, VerifyingKey};
10
- use hmac::{Hmac, Mac};
11
- use serde::{Deserialize, Serialize};
12
- use serde_json::Value;
13
- use sha2::Sha256;
14
-
15
- type HmacSha256 = Hmac<Sha256>;
16
-
17
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18
- pub struct ProtocolHeader {
19
- pub version: String,
20
- #[serde(rename = "messageId")]
21
- pub message_id: String,
22
- #[serde(rename = "timestampMs")]
23
- pub timestamp_ms: i64,
24
- #[serde(rename = "ttlMs")]
25
- pub ttl_ms: i64,
26
- pub sender: String,
27
- #[serde(skip_serializing_if = "Option::is_none")]
28
- pub recipient: Option<String>,
29
- pub nonce: String,
30
- }
31
-
32
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
33
- pub struct ProtocolBody {
34
- pub intent: String,
35
- pub content: String,
36
- #[serde(skip_serializing_if = "Option::is_none")]
37
- pub capability: Option<String>,
38
- #[serde(rename = "correlationId", skip_serializing_if = "Option::is_none")]
39
- pub correlation_id: Option<String>,
40
- }
41
-
42
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
43
- pub struct ProtocolSignature {
44
- pub alg: String,
45
- #[serde(rename = "keyId")]
46
- pub key_id: String,
47
- pub value: String,
48
- }
49
-
50
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
51
- pub struct ProtocolEnvelope {
52
- pub header: ProtocolHeader,
53
- pub body: ProtocolBody,
54
- #[serde(skip_serializing_if = "Option::is_none")]
55
- pub signature: Option<ProtocolSignature>,
56
- }
57
-
58
- #[derive(Debug, Clone, PartialEq, Eq)]
59
- pub struct ProtocolDiagnostic {
60
- pub level: String,
61
- pub message: String,
62
- }
63
-
64
- #[derive(Debug, Clone, Serialize, Deserialize)]
65
- struct CompactSignature {
66
- #[serde(skip_serializing_if = "Option::is_none")]
67
- a: Option<String>,
68
- k: String,
69
- v: String,
70
- }
71
-
72
- #[derive(Debug, Clone, Serialize, Deserialize)]
73
- struct CompactEnvelope {
74
- v: String,
75
- mid: String,
76
- ts: i64,
77
- ttl: i64,
78
- s: String,
79
- n: String,
80
- i: String,
81
- c: String,
82
- #[serde(skip_serializing_if = "Option::is_none")]
83
- r: Option<String>,
84
- #[serde(skip_serializing_if = "Option::is_none")]
85
- cap: Option<String>,
86
- #[serde(skip_serializing_if = "Option::is_none")]
87
- cid: Option<String>,
88
- #[serde(skip_serializing_if = "Option::is_none")]
89
- sig: Option<CompactSignature>,
90
- }
91
-
92
- fn json_string<T: Serialize>(value: &T) -> String {
93
- serde_json::to_string(value).expect("json serialization should not fail")
94
- }
95
-
96
- pub fn canonicalize_envelope(envelope: &ProtocolEnvelope) -> String {
97
- let mut body_parts: Vec<String> = Vec::new();
98
- if let Some(capability) = &envelope.body.capability {
99
- body_parts.push(format!("\"capability\":{}", json_string(capability)));
100
- }
101
- body_parts.push(format!(
102
- "\"content\":{}",
103
- json_string(&envelope.body.content)
104
- ));
105
- if let Some(correlation_id) = &envelope.body.correlation_id {
106
- body_parts.push(format!("\"correlationId\":{}", json_string(correlation_id)));
107
- }
108
- body_parts.push(format!("\"intent\":{}", json_string(&envelope.body.intent)));
109
-
110
- let mut header_parts: Vec<String> = vec![
111
- format!("\"messageId\":{}", json_string(&envelope.header.message_id)),
112
- format!("\"nonce\":{}", json_string(&envelope.header.nonce)),
113
- ];
114
- if let Some(recipient) = &envelope.header.recipient {
115
- header_parts.push(format!("\"recipient\":{}", json_string(recipient)));
116
- }
117
- header_parts.push(format!(
118
- "\"sender\":{}",
119
- json_string(&envelope.header.sender)
120
- ));
121
- header_parts.push(format!("\"timestampMs\":{}", envelope.header.timestamp_ms));
122
- header_parts.push(format!("\"ttlMs\":{}", envelope.header.ttl_ms));
123
- header_parts.push(format!(
124
- "\"version\":{}",
125
- json_string(&envelope.header.version)
126
- ));
127
-
128
- format!(
129
- "{{\"body\":{{{}}},\"header\":{{{}}}}}",
130
- body_parts.join(","),
131
- header_parts.join(",")
132
- )
133
- }
134
-
135
- pub fn sign_canonical_payload_hmac(canonical_payload: &str, secret: &str) -> String {
136
- let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC key should be valid");
137
- mac.update(canonical_payload.as_bytes());
138
- let digest = mac.finalize().into_bytes();
139
- URL_SAFE_NO_PAD.encode(digest)
140
- }
141
-
142
- pub fn verify_canonical_payload_hmac(
143
- canonical_payload: &str,
144
- signature: &str,
145
- secret: &str,
146
- ) -> bool {
147
- let expected = sign_canonical_payload_hmac(canonical_payload, secret);
148
- expected == signature
149
- }
150
-
151
- pub fn sign_canonical_payload_ed25519(
152
- canonical_payload: &str,
153
- private_key_pkcs8_base64url: &str,
154
- ) -> Result<String, String> {
155
- let private_der = URL_SAFE_NO_PAD
156
- .decode(private_key_pkcs8_base64url)
157
- .map_err(|_| "Invalid ED25519 private key encoding".to_string())?;
158
- let signing_key = SigningKey::from_pkcs8_der(&private_der)
159
- .map_err(|_| "Invalid ED25519 private key".to_string())?;
160
- let signature = signing_key.sign(canonical_payload.as_bytes());
161
- Ok(URL_SAFE_NO_PAD.encode(signature.to_bytes()))
162
- }
163
-
164
- pub fn verify_canonical_payload_ed25519(
165
- canonical_payload: &str,
166
- signature_base64url: &str,
167
- public_key_spki_base64url: &str,
168
- ) -> Result<bool, String> {
169
- let public_der = URL_SAFE_NO_PAD
170
- .decode(public_key_spki_base64url)
171
- .map_err(|_| "Invalid ED25519 public key encoding".to_string())?;
172
- let verifying_key = VerifyingKey::from_public_key_der(&public_der)
173
- .map_err(|_| "Invalid ED25519 public key".to_string())?;
174
-
175
- let signature_raw = URL_SAFE_NO_PAD
176
- .decode(signature_base64url)
177
- .map_err(|_| "Invalid ED25519 signature encoding".to_string())?;
178
- let signature = Ed25519Signature::from_slice(&signature_raw)
179
- .map_err(|_| "Invalid ED25519 signature".to_string())?;
180
-
181
- Ok(verifying_key
182
- .verify(canonical_payload.as_bytes(), &signature)
183
- .is_ok())
184
- }
185
-
186
- pub fn sign_envelope_hmac(
187
- envelope: &ProtocolEnvelope,
188
- secret: &str,
189
- key_id: &str,
190
- ) -> ProtocolEnvelope {
191
- let mut unsigned = envelope.clone();
192
- unsigned.signature = None;
193
- let canonical = canonicalize_envelope(&unsigned);
194
- let signature = sign_canonical_payload_hmac(&canonical, secret);
195
- let mut signed = unsigned;
196
- signed.signature = Some(ProtocolSignature {
197
- alg: "HS256".to_string(),
198
- key_id: key_id.to_string(),
199
- value: signature,
200
- });
201
- signed
202
- }
203
-
204
- pub fn verify_envelope_hmac(envelope: &ProtocolEnvelope, secret: &str) -> bool {
205
- let Some(signature) = &envelope.signature else {
206
- return false;
207
- };
208
- if signature.alg != "HS256" {
209
- return false;
210
- }
211
- let mut unsigned = envelope.clone();
212
- unsigned.signature = None;
213
- let canonical = canonicalize_envelope(&unsigned);
214
- verify_canonical_payload_hmac(&canonical, &signature.value, secret)
215
- }
216
-
217
- pub fn sign_envelope_ed25519(
218
- envelope: &ProtocolEnvelope,
219
- private_key_pkcs8_base64url: &str,
220
- key_id: &str,
221
- ) -> Result<ProtocolEnvelope, String> {
222
- let mut unsigned = envelope.clone();
223
- unsigned.signature = None;
224
- let canonical = canonicalize_envelope(&unsigned);
225
- let signature = sign_canonical_payload_ed25519(&canonical, private_key_pkcs8_base64url)?;
226
- let mut signed = unsigned;
227
- signed.signature = Some(ProtocolSignature {
228
- alg: "ED25519".to_string(),
229
- key_id: key_id.to_string(),
230
- value: signature,
231
- });
232
- Ok(signed)
233
- }
234
-
235
- pub fn verify_envelope_ed25519(
236
- envelope: &ProtocolEnvelope,
237
- public_key_spki_base64url: &str,
238
- ) -> Result<bool, String> {
239
- let Some(signature) = &envelope.signature else {
240
- return Ok(false);
241
- };
242
- if signature.alg != "ED25519" {
243
- return Ok(false);
244
- }
245
- let mut unsigned = envelope.clone();
246
- unsigned.signature = None;
247
- let canonical = canonicalize_envelope(&unsigned);
248
- verify_canonical_payload_ed25519(&canonical, &signature.value, public_key_spki_base64url)
249
- }
250
-
251
- pub fn encode_envelope_compact(envelope: &ProtocolEnvelope) -> String {
252
- let compact = CompactEnvelope {
253
- v: envelope.header.version.clone(),
254
- mid: envelope.header.message_id.clone(),
255
- ts: envelope.header.timestamp_ms,
256
- ttl: envelope.header.ttl_ms,
257
- s: envelope.header.sender.clone(),
258
- n: envelope.header.nonce.clone(),
259
- i: envelope.body.intent.clone(),
260
- c: envelope.body.content.clone(),
261
- r: envelope.header.recipient.clone(),
262
- cap: envelope.body.capability.clone(),
263
- cid: envelope.body.correlation_id.clone(),
264
- sig: envelope.signature.as_ref().map(|sig| CompactSignature {
265
- a: Some(sig.alg.clone()),
266
- k: sig.key_id.clone(),
267
- v: sig.value.clone(),
268
- }),
269
- };
270
- serde_json::to_string(&compact).expect("compact envelope serialization should not fail")
271
- }
272
-
273
- pub fn decode_envelope(raw: &str) -> Result<ProtocolEnvelope, String> {
274
- let parsed: Value =
275
- serde_json::from_str(raw).map_err(|_| "Invalid JSON payload".to_string())?;
276
-
277
- if parsed.get("header").is_some() && parsed.get("body").is_some() {
278
- return serde_json::from_value(parsed)
279
- .map_err(|_| "Envelope JSON shape is not recognized".to_string());
280
- }
281
-
282
- let compact: CompactEnvelope = serde_json::from_value(parsed)
283
- .map_err(|_| "Envelope JSON shape is not recognized".to_string())?;
284
- if compact.v != "7h3/0.1" {
285
- return Err("Envelope JSON shape is not recognized".to_string());
286
- }
287
-
288
- Ok(ProtocolEnvelope {
289
- header: ProtocolHeader {
290
- version: compact.v,
291
- message_id: compact.mid,
292
- timestamp_ms: compact.ts,
293
- ttl_ms: compact.ttl,
294
- sender: compact.s,
295
- recipient: compact.r,
296
- nonce: compact.n,
297
- },
298
- body: ProtocolBody {
299
- intent: compact.i,
300
- content: compact.c,
301
- capability: compact.cap,
302
- correlation_id: compact.cid,
303
- },
304
- signature: compact.sig.map(|sig| ProtocolSignature {
305
- alg: sig.a.unwrap_or_else(|| "HS256".to_string()),
306
- key_id: sig.k,
307
- value: sig.v,
308
- }),
309
- })
310
- }
311
-
312
- pub fn validate_envelope(
313
- envelope: &ProtocolEnvelope,
314
- now_ms: Option<i64>,
315
- ) -> Vec<ProtocolDiagnostic> {
316
- let mut diagnostics: Vec<ProtocolDiagnostic> = Vec::new();
317
-
318
- if envelope.header.version != "7h3/0.1" {
319
- diagnostics.push(ProtocolDiagnostic {
320
- level: "error".to_string(),
321
- message: format!("Unsupported protocol version '{}'", envelope.header.version),
322
- });
323
- }
324
- if envelope.header.message_id.trim().is_empty() {
325
- diagnostics.push(ProtocolDiagnostic {
326
- level: "error".to_string(),
327
- message: "Missing messageId".to_string(),
328
- });
329
- }
330
- if envelope.header.sender.trim().is_empty() {
331
- diagnostics.push(ProtocolDiagnostic {
332
- level: "error".to_string(),
333
- message: "Missing sender identity".to_string(),
334
- });
335
- }
336
- if envelope.header.ttl_ms <= 0 {
337
- diagnostics.push(ProtocolDiagnostic {
338
- level: "error".to_string(),
339
- message: "ttlMs must be greater than zero".to_string(),
340
- });
341
- }
342
- if let Some(now) = now_ms {
343
- if envelope.header.timestamp_ms + envelope.header.ttl_ms < now {
344
- diagnostics.push(ProtocolDiagnostic {
345
- level: "error".to_string(),
346
- message: "Message TTL expired".to_string(),
347
- });
348
- }
349
- }
350
- if envelope.body.content.trim().is_empty() {
351
- diagnostics.push(ProtocolDiagnostic {
352
- level: "warning".to_string(),
353
- message: "Empty content payload".to_string(),
354
- });
355
- }
356
-
357
- diagnostics
358
- }
359
-
360
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
361
- #[serde(untagged)]
362
- pub enum JsonRpcId {
363
- Null,
364
- String(String),
365
- Number(i64),
366
- }
367
-
368
- impl JsonRpcId {
369
- fn as_string(&self) -> String {
370
- match self {
371
- JsonRpcId::Null => "null".to_string(),
372
- JsonRpcId::String(value) => value.clone(),
373
- JsonRpcId::Number(value) => value.to_string(),
374
- }
375
- }
376
- }
377
-
378
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
379
- pub struct JsonRpcRequestLike {
380
- pub jsonrpc: String,
381
- pub id: JsonRpcId,
382
- pub method: String,
383
- #[serde(skip_serializing_if = "Option::is_none")]
384
- pub params: Option<Value>,
385
- }
386
-
387
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
388
- pub struct JsonRpcError {
389
- pub code: i64,
390
- pub message: String,
391
- #[serde(skip_serializing_if = "Option::is_none")]
392
- pub data: Option<Value>,
393
- }
394
-
395
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
396
- pub struct JsonRpcResponseLike {
397
- pub jsonrpc: String,
398
- pub id: JsonRpcId,
399
- #[serde(skip_serializing_if = "Option::is_none")]
400
- pub result: Option<Value>,
401
- #[serde(skip_serializing_if = "Option::is_none")]
402
- pub error: Option<JsonRpcError>,
403
- }
404
-
405
- #[derive(Debug, Clone, PartialEq, Eq)]
406
- pub struct JsonRpcPolicyContext {
407
- pub intent: String,
408
- pub recipient: Option<String>,
409
- pub capability: String,
410
- pub correlation_id: String,
411
- pub created_at_ms: i64,
412
- }
413
-
414
- #[derive(Debug, Clone)]
415
- pub struct JsonRpcBridgeConfig {
416
- pub recipient: Option<String>,
417
- pub allowed_methods: Option<Vec<String>>,
418
- pub capability_prefix: String,
419
- }
420
-
421
- impl Default for JsonRpcBridgeConfig {
422
- fn default() -> Self {
423
- Self {
424
- recipient: None,
425
- allowed_methods: None,
426
- capability_prefix: "mcp.".to_string(),
427
- }
428
- }
429
- }
430
-
431
- pub fn create_envelope(
432
- sender: &str,
433
- recipient: Option<&str>,
434
- intent: &str,
435
- content: &str,
436
- capability: Option<&str>,
437
- correlation_id: Option<&str>,
438
- now_ms: i64,
439
- ttl_ms: i64,
440
- ) -> ProtocolEnvelope {
441
- ProtocolEnvelope {
442
- header: ProtocolHeader {
443
- version: "7h3/0.1".to_string(),
444
- message_id: format!("msg-{}-{}", now_ms, sender),
445
- timestamp_ms: now_ms,
446
- ttl_ms,
447
- sender: sender.to_string(),
448
- recipient: recipient.map(|value| value.to_string()),
449
- nonce: format!("n-{}", now_ms),
450
- },
451
- body: ProtocolBody {
452
- intent: intent.to_string(),
453
- content: content.to_string(),
454
- capability: capability.map(|value| value.to_string()),
455
- correlation_id: correlation_id.map(|value| value.to_string()),
456
- },
457
- signature: None,
458
- }
459
- }
460
-
461
- pub fn create_signed_task_from_jsonrpc<F, G>(
462
- request: &JsonRpcRequestLike,
463
- sender: &str,
464
- secret: &str,
465
- key_id: &str,
466
- now_ms: i64,
467
- config: &JsonRpcBridgeConfig,
468
- authorize: Option<F>,
469
- rate_limit: Option<G>,
470
- ) -> Result<ProtocolEnvelope, String>
471
- where
472
- F: Fn(&JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool,
473
- G: Fn(&str, &JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool,
474
- {
475
- if request.jsonrpc != "2.0" {
476
- return Err("JSON-RPC request must have jsonrpc='2.0'".to_string());
477
- }
478
- if request.method.trim().is_empty() {
479
- return Err("JSON-RPC request must include method".to_string());
480
- }
481
- if let Some(allowlist) = &config.allowed_methods {
482
- if !allowlist.iter().any(|method| method == &request.method) {
483
- return Err(format!(
484
- "JSON-RPC method '{}' is not allowed",
485
- request.method
486
- ));
487
- }
488
- }
489
-
490
- let correlation_id = request.id.as_string();
491
- let capability = format!("{}{}", config.capability_prefix, request.method);
492
- let context = JsonRpcPolicyContext {
493
- intent: "TASK".to_string(),
494
- recipient: config.recipient.clone(),
495
- capability: capability.clone(),
496
- correlation_id: correlation_id.clone(),
497
- created_at_ms: now_ms,
498
- };
499
-
500
- if let Some(authorize_fn) = authorize {
501
- if !authorize_fn(request, &context) {
502
- return Err(format!(
503
- "JSON-RPC method '{}' is not authorized",
504
- request.method
505
- ));
506
- }
507
- }
508
-
509
- let rate_key = request.method.clone();
510
- if let Some(rate_limit_fn) = rate_limit {
511
- if !rate_limit_fn(&rate_key, request, &context) {
512
- return Err(format!(
513
- "JSON-RPC method '{}' is rate-limited",
514
- request.method
515
- ));
516
- }
517
- }
518
-
519
- let content = json_string(&serde_json::json!({
520
- "method": request.method,
521
- "params": request.params.clone().unwrap_or(Value::Null),
522
- }));
523
- let envelope = create_envelope(
524
- sender,
525
- config.recipient.as_deref(),
526
- "TASK",
527
- &content,
528
- Some(&capability),
529
- Some(&correlation_id),
530
- now_ms,
531
- 60_000,
532
- );
533
- Ok(sign_envelope_hmac(&envelope, secret, key_id))
534
- }
535
-
536
- pub fn jsonrpc_response_from_envelope(
537
- envelope: &ProtocolEnvelope,
538
- id: JsonRpcId,
539
- ) -> JsonRpcResponseLike {
540
- if envelope.body.intent == "ERROR" {
541
- return JsonRpcResponseLike {
542
- jsonrpc: "2.0".to_string(),
543
- id,
544
- result: None,
545
- error: Some(JsonRpcError {
546
- code: -32000,
547
- message: envelope.body.content.clone(),
548
- data: Some(serde_json::json!({
549
- "capability": envelope.body.capability,
550
- "correlationId": envelope.body.correlation_id,
551
- })),
552
- }),
553
- };
554
- }
555
-
556
- let result = serde_json::from_str::<Value>(&envelope.body.content)
557
- .unwrap_or_else(|_| Value::String(envelope.body.content.clone()));
558
- JsonRpcResponseLike {
559
- jsonrpc: "2.0".to_string(),
560
- id,
561
- result: Some(result),
562
- error: None,
563
- }
564
- }
565
-
566
- #[derive(Debug, Clone)]
567
- pub struct AipMcpGatewayOptions {
568
- pub shared_secret: String,
569
- pub gateway_agent_id: String,
570
- pub worker_agent_id: String,
571
- pub allowed_methods: Vec<String>,
572
- pub capability_prefix: String,
573
- }
574
-
575
- impl Default for AipMcpGatewayOptions {
576
- fn default() -> Self {
577
- Self {
578
- shared_secret: "mcp-gateway-secret".to_string(),
579
- gateway_agent_id: "agent.gateway".to_string(),
580
- worker_agent_id: "agent.worker".to_string(),
581
- allowed_methods: vec![
582
- "tools/call".to_string(),
583
- "resources/read".to_string(),
584
- "prompts/get".to_string(),
585
- ],
586
- capability_prefix: "mcp.".to_string(),
587
- }
588
- }
589
- }
590
-
591
- #[derive(Debug, Clone)]
592
- pub struct AipMcpGatewayRuntime {
593
- options: AipMcpGatewayOptions,
594
- }
595
-
596
- pub fn create_aip_mcp_gateway_runtime(options: AipMcpGatewayOptions) -> AipMcpGatewayRuntime {
597
- AipMcpGatewayRuntime { options }
598
- }
599
-
600
- impl AipMcpGatewayRuntime {
601
- fn error_response(id: Option<JsonRpcId>, code: i64, message: &str) -> String {
602
- let response = JsonRpcResponseLike {
603
- jsonrpc: "2.0".to_string(),
604
- id: id.unwrap_or(JsonRpcId::Null),
605
- result: None,
606
- error: Some(JsonRpcError {
607
- code,
608
- message: message.to_string(),
609
- data: None,
610
- }),
611
- };
612
- json_string(&response)
613
- }
614
-
615
- pub fn handle_line(&self, line: &str, now_ms: i64) -> Option<String> {
616
- let raw = line.trim();
617
- if raw.is_empty() {
618
- return None;
619
- }
620
-
621
- let request: JsonRpcRequestLike = match serde_json::from_str(raw) {
622
- Ok(parsed) => parsed,
623
- Err(_) => {
624
- return Some(Self::error_response(None, -32600, "Invalid Request"));
625
- }
626
- };
627
-
628
- let bridge_config = JsonRpcBridgeConfig {
629
- recipient: Some(self.options.worker_agent_id.clone()),
630
- allowed_methods: Some(self.options.allowed_methods.clone()),
631
- capability_prefix: self.options.capability_prefix.clone(),
632
- };
633
-
634
- let outbound = match create_signed_task_from_jsonrpc(
635
- &request,
636
- &self.options.gateway_agent_id,
637
- &self.options.shared_secret,
638
- "gateway-k1",
639
- now_ms,
640
- &bridge_config,
641
- Option::<fn(&JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool>::None,
642
- Option::<fn(&str, &JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool>::None,
643
- ) {
644
- Ok(envelope) => envelope,
645
- Err(message) => {
646
- let code = if message.contains("not allowed") {
647
- -32601
648
- } else if message.contains("not authorized") {
649
- -32001
650
- } else if message.contains("rate-limited") {
651
- -32002
652
- } else {
653
- -32603
654
- };
655
- return Some(Self::error_response(Some(request.id), code, &message));
656
- }
657
- };
658
-
659
- let worker_payload = serde_json::json!({
660
- "ok": true,
661
- "capability": outbound.body.capability,
662
- "content": outbound.body.content,
663
- });
664
- let worker_envelope = create_envelope(
665
- &self.options.worker_agent_id,
666
- Some(&self.options.gateway_agent_id),
667
- "RESULT",
668
- &json_string(&worker_payload),
669
- outbound.body.capability.as_deref(),
670
- outbound.body.correlation_id.as_deref(),
671
- now_ms,
672
- 60_000,
673
- );
674
- let signed_worker =
675
- sign_envelope_hmac(&worker_envelope, &self.options.shared_secret, "worker-k1");
676
-
677
- if !verify_envelope_hmac(&signed_worker, &self.options.shared_secret) {
678
- return Some(Self::error_response(
679
- Some(request.id),
680
- -32603,
681
- "AIP verification failed",
682
- ));
683
- }
684
-
685
- let response = jsonrpc_response_from_envelope(&signed_worker, request.id);
686
- Some(json_string(&response))
687
- }
688
- }