@7h3/protocol 0.5.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 (294) hide show
  1. package/README.md +6 -1317
  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 -121
  23. package/policyEnforcer.d.ts +50 -0
  24. package/policyTelemetryFeedback.d.ts +11 -0
  25. package/{src/protocol.d.ts → protocol.d.ts} +1 -2
  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 -152
  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 -406
  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-github.png +0 -0
  115. package/docs/assets/banner.png +0 -0
  116. package/docs/assets/banner.svg +0 -123
  117. package/eslint.config.js +0 -15
  118. package/fuzz/ts/harness-decode.ts +0 -136
  119. package/fuzz/ts/harness-verify.ts +0 -121
  120. package/fuzz/ts/run.ts +0 -35
  121. package/mcp-server/README.md +0 -38
  122. package/mcp-server/package-lock.json +0 -1187
  123. package/mcp-server/package.json +0 -35
  124. package/mcp-server/src/index.ts +0 -236
  125. package/mcp-server/tsconfig.json +0 -14
  126. package/scripts/aip-framework-quickstart.ts +0 -110
  127. package/scripts/aip-mcp-gateway.ts +0 -38
  128. package/scripts/aip-mcp-wrap-demo.ts +0 -72
  129. package/scripts/aip-quickstart.ts +0 -60
  130. package/scripts/bench-diff.ts +0 -118
  131. package/scripts/bench-protocol-e2e.ts +0 -937
  132. package/scripts/bench-protocol-openloop.ts +0 -1397
  133. package/scripts/bench-replay-cache.ts +0 -76
  134. package/scripts/bench-signature-profiles.ts +0 -180
  135. package/scripts/bench-wire-codecs.ts +0 -161
  136. package/scripts/build-binary-conformance.ts +0 -36
  137. package/scripts/build-release-dashboard.ts +0 -175
  138. package/scripts/canary-rollout.ts +0 -38
  139. package/scripts/mcpGatewayCli.test.ts +0 -116
  140. package/scripts/prepare-aip-package.ts +0 -88
  141. package/scripts/regen-conformance-sigs.ts +0 -18
  142. package/scripts/release-gate.ts +0 -19
  143. package/scripts/validate-runtime-policy.ts +0 -18
  144. package/sdk/browser/index.test.ts +0 -162
  145. package/sdk/browser/index.ts +0 -257
  146. package/sdk/browser/package.json +0 -13
  147. package/sdk/go/cbor.go +0 -551
  148. package/sdk/go/cbor_test.go +0 -232
  149. package/sdk/go/encryption.go +0 -280
  150. package/sdk/go/encryption_test.go +0 -318
  151. package/sdk/go/go.mod +0 -7
  152. package/sdk/go/go.sum +0 -4
  153. package/sdk/go/http.go +0 -135
  154. package/sdk/go/protocol.go +0 -324
  155. package/sdk/go/protocol_test.go +0 -334
  156. package/sdk/go/replay.go +0 -121
  157. package/sdk/go/replay_test.go +0 -149
  158. package/sdk/go/webhook.go +0 -136
  159. package/sdk/pq/package-lock.json +0 -1358
  160. package/sdk/pq/package.json +0 -42
  161. package/sdk/pq/src/index.test.ts +0 -143
  162. package/sdk/pq/src/index.ts +0 -166
  163. package/sdk/pq/tsconfig.json +0 -14
  164. package/sdk/pq/vitest.config.ts +0 -7
  165. package/sdk/python/README.md +0 -18
  166. package/sdk/python/protocol_7h3/__init__.py +0 -46
  167. package/sdk/python/protocol_7h3/encryption.py +0 -252
  168. package/sdk/python/protocol_7h3/http.py +0 -212
  169. package/sdk/python/protocol_7h3/keys.py +0 -149
  170. package/sdk/python/protocol_7h3/pq.py +0 -244
  171. package/sdk/python/protocol_7h3/protocol.py +0 -525
  172. package/sdk/python/protocol_7h3/queue.py +0 -118
  173. package/sdk/python/protocol_7h3/replay.py +0 -98
  174. package/sdk/python/protocol_7h3/webhook.py +0 -116
  175. package/sdk/python/pyproject.toml +0 -40
  176. package/sdk/python/tests/test_conformance.py +0 -110
  177. package/sdk/python/tests/test_encryption.py +0 -206
  178. package/sdk/python/tests/test_http.py +0 -305
  179. package/sdk/python/tests/test_keys.py +0 -417
  180. package/sdk/python/tests/test_queue.py +0 -120
  181. package/sdk/python/tests/test_webhook.py +0 -345
  182. package/sdk/rust/Cargo.lock +0 -371
  183. package/sdk/rust/Cargo.toml +0 -25
  184. package/sdk/rust/README.md +0 -31
  185. package/sdk/rust/fuzz/Cargo.toml +0 -29
  186. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +0 -46
  187. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +0 -11
  188. package/sdk/rust/src/bin/aip_mcp_gateway.rs +0 -59
  189. package/sdk/rust/src/http.rs +0 -145
  190. package/sdk/rust/src/keys.rs +0 -161
  191. package/sdk/rust/src/lib.rs +0 -688
  192. package/sdk/rust/src/queue.rs +0 -79
  193. package/sdk/rust/src/webhook.rs +0 -86
  194. package/sdk/rust/tests/conformance.rs +0 -148
  195. package/sdk/rust/tests/gateway.rs +0 -130
  196. package/sdk/rust/tests/http_webhook_queue.rs +0 -201
  197. package/sdk/rust/tests/keys.rs +0 -189
  198. package/sdk/threshold/index.d.ts +0 -68
  199. package/sdk/threshold/index.d.ts.map +0 -1
  200. package/sdk/threshold/index.js +0 -254
  201. package/sdk/threshold/package-lock.json +0 -1361
  202. package/sdk/threshold/package.json +0 -39
  203. package/sdk/threshold/src/index.d.ts +0 -68
  204. package/sdk/threshold/src/index.d.ts.map +0 -1
  205. package/sdk/threshold/src/index.js +0 -254
  206. package/sdk/threshold/src/index.test.ts +0 -238
  207. package/sdk/threshold/src/index.ts +0 -355
  208. package/sdk/threshold/tsconfig.json +0 -19
  209. package/sdk/threshold/vitest.config.ts +0 -12
  210. package/src/agentAdapter.test.ts +0 -48
  211. package/src/agentAdapter.ts +0 -56
  212. package/src/auditLog.test.ts +0 -145
  213. package/src/auditLog.ts +0 -147
  214. package/src/capability.test.ts +0 -504
  215. package/src/capability.ts +0 -380
  216. package/src/cborCodec.test.ts +0 -263
  217. package/src/cborCodec.ts +0 -339
  218. package/src/conformance.test.ts +0 -136
  219. package/src/conformanceVectors.ts +0 -99
  220. package/src/encryption.test.ts +0 -206
  221. package/src/encryption.ts +0 -245
  222. package/src/envelopeCbor.ts +0 -140
  223. package/src/frameworkAdapters.test.ts +0 -290
  224. package/src/frameworkAdapters.ts +0 -261
  225. package/src/gateway.test.ts +0 -343
  226. package/src/gateway.ts +0 -246
  227. package/src/grpcBinding.test.ts +0 -211
  228. package/src/grpcBinding.ts +0 -103
  229. package/src/httpBinding.test.ts +0 -376
  230. package/src/httpBinding.ts +0 -189
  231. package/src/index.ts +0 -39
  232. package/src/keyInfra.test.ts +0 -278
  233. package/src/keyInfra.ts +0 -228
  234. package/src/keyRegistry.ts +0 -59
  235. package/src/keyRotation.test.ts +0 -78
  236. package/src/keyRotation.ts +0 -72
  237. package/src/mcpGateway.test.ts +0 -129
  238. package/src/mcpGateway.ts +0 -250
  239. package/src/mcpTransports.test.ts +0 -92
  240. package/src/mcpTransports.ts +0 -169
  241. package/src/mcpWrapper.test.ts +0 -179
  242. package/src/mcpWrapper.ts +0 -206
  243. package/src/otel.ts +0 -136
  244. package/src/policyEnforcer.test.ts +0 -99
  245. package/src/policyEnforcer.ts +0 -169
  246. package/src/policyTelemetryFeedback.test.ts +0 -25
  247. package/src/policyTelemetryFeedback.ts +0 -38
  248. package/src/protocol.bench.ts +0 -37
  249. package/src/protocol.d.ts.map +0 -1
  250. package/src/protocol.js +0 -294
  251. package/src/protocol.test.ts +0 -155
  252. package/src/protocol.ts +0 -414
  253. package/src/protocolAgent.test.ts +0 -105
  254. package/src/protocolAgent.ts +0 -169
  255. package/src/protocolBinary.test.ts +0 -165
  256. package/src/protocolBinary.ts +0 -312
  257. package/src/protocolCapabilities.ts +0 -70
  258. package/src/protocolFuzz.advanced.test.ts +0 -235
  259. package/src/protocolFuzz.test.ts +0 -111
  260. package/src/protocolNegative.test.ts +0 -97
  261. package/src/protocolReplay.test.ts +0 -71
  262. package/src/protocolReplay.ts +0 -194
  263. package/src/protocolTransport.test.ts +0 -556
  264. package/src/protocolTransport.ts +0 -483
  265. package/src/queueBinding.test.ts +0 -130
  266. package/src/queueBinding.ts +0 -102
  267. package/src/rateLimiter.test.ts +0 -96
  268. package/src/rateLimiter.ts +0 -46
  269. package/src/redisIntegration.test.ts +0 -134
  270. package/src/replayStores.test.ts +0 -273
  271. package/src/replayStores.ts +0 -215
  272. package/src/revocation.test.ts +0 -98
  273. package/src/revocation.ts +0 -0
  274. package/src/routePolicy.test.ts +0 -87
  275. package/src/routePolicy.ts +0 -72
  276. package/src/runtimePolicy.test.ts +0 -49
  277. package/src/runtimePolicy.ts +0 -81
  278. package/src/runtimePolicyManager.test.ts +0 -29
  279. package/src/runtimePolicyManager.ts +0 -50
  280. package/src/runtimePolicyPresets.ts +0 -43
  281. package/src/signedResponse.test.ts +0 -111
  282. package/src/signedResponse.ts +0 -83
  283. package/src/stream.test.ts +0 -254
  284. package/src/stream.ts +0 -417
  285. package/src/telemetry.test.ts +0 -251
  286. package/src/telemetry.ts +0 -299
  287. package/src/webhookBinding.test.ts +0 -144
  288. package/src/webhookBinding.ts +0 -115
  289. package/src/wsBinding.test.ts +0 -221
  290. package/src/wsBinding.ts +0 -200
  291. package/tsconfig.json +0 -15
  292. package/tsconfig.lib.json +0 -23
  293. package/vite.lib.config.ts +0 -16
  294. package/vitest.config.ts +0 -11
package/src/protocol.ts DELETED
@@ -1,414 +0,0 @@
1
- export type ProtocolVersion = '7h3/0.1'
2
-
3
- export type IntentKind =
4
- | 'PING'
5
- | 'PONG'
6
- | 'CAPS'
7
- | 'TASK'
8
- | 'RESULT'
9
- | 'ERROR'
10
- | 'ENCRYPTED'
11
-
12
- export interface ProtocolHeader {
13
- version: ProtocolVersion
14
- messageId: string
15
- timestampMs: number
16
- ttlMs: number
17
- sender: string
18
- recipient?: string
19
- nonce: string
20
- }
21
-
22
- export interface ProtocolBody {
23
- intent: IntentKind
24
- content: string
25
- capability?: string
26
- correlationId?: string
27
- }
28
-
29
- export interface ProtocolSignature {
30
- alg: 'HS256' | 'ED25519'
31
- keyId: string
32
- value: string
33
- }
34
-
35
- export interface ProtocolEnvelope {
36
- header: ProtocolHeader
37
- body: ProtocolBody
38
- signature?: ProtocolSignature
39
- }
40
-
41
- export interface ProtocolDiagnostic {
42
- level: 'error' | 'warning'
43
- message: string
44
- }
45
-
46
- const textEncoder = new TextEncoder()
47
- const HMAC_KEY_CACHE_LIMIT = 256
48
- const hmacKeyCache = new Map<string, Promise<CryptoKey>>()
49
- const ED25519_KEY_CACHE_LIMIT = 256
50
- const ed25519PrivateKeyCache = new Map<string, Promise<CryptoKey>>()
51
- const ed25519PublicKeyCache = new Map<string, Promise<CryptoKey>>()
52
-
53
- export type SignatureVerificationMaterial =
54
- | { alg: 'HS256'; secret: string }
55
- | { alg: 'ED25519'; publicKey: string }
56
-
57
- type BufferLike = {
58
- from: (input: string | Uint8Array, encoding?: string) => Uint8Array & { toString: (encoding?: string) => string }
59
- }
60
-
61
- function getBufferLike(): BufferLike | null {
62
- const candidate = globalThis as unknown as { Buffer?: BufferLike }
63
- return candidate.Buffer ?? null
64
- }
65
-
66
- function serializeHeaderCanonical(header: ProtocolHeader): string {
67
- const parts: string[] = [
68
- `"messageId":${JSON.stringify(header.messageId)}`,
69
- `"nonce":${JSON.stringify(header.nonce)}`,
70
- ]
71
- if (header.recipient !== undefined) {
72
- parts.push(`"recipient":${JSON.stringify(header.recipient)}`)
73
- }
74
- parts.push(`"sender":${JSON.stringify(header.sender)}`)
75
- parts.push(`"timestampMs":${header.timestampMs}`)
76
- parts.push(`"ttlMs":${header.ttlMs}`)
77
- parts.push(`"version":${JSON.stringify(header.version)}`)
78
- return `{${parts.join(',')}}`
79
- }
80
-
81
- function serializeBodyCanonical(body: ProtocolBody): string {
82
- const parts: string[] = []
83
- if (body.capability !== undefined) {
84
- parts.push(`"capability":${JSON.stringify(body.capability)}`)
85
- }
86
- parts.push(`"content":${JSON.stringify(body.content)}`)
87
- if (body.correlationId !== undefined) {
88
- parts.push(`"correlationId":${JSON.stringify(body.correlationId)}`)
89
- }
90
- parts.push(`"intent":${JSON.stringify(body.intent)}`)
91
- return `{${parts.join(',')}}`
92
- }
93
-
94
- function getCachedHmacKey(secret: string): Promise<CryptoKey> {
95
- const cacheKey = `hs256:${secret}`
96
- const cached = hmacKeyCache.get(cacheKey)
97
- if (cached) return cached
98
-
99
- if (hmacKeyCache.size >= HMAC_KEY_CACHE_LIMIT) {
100
- hmacKeyCache.clear()
101
- }
102
-
103
- const subtle = requireCryptoSubtle()
104
- const imported = subtle
105
- .importKey(
106
- 'raw',
107
- textEncoder.encode(secret),
108
- { name: 'HMAC', hash: 'SHA-256' },
109
- false,
110
- ['sign', 'verify'],
111
- )
112
- .catch((error: unknown) => {
113
- hmacKeyCache.delete(cacheKey)
114
- throw error
115
- })
116
-
117
- hmacKeyCache.set(cacheKey, imported)
118
- return imported
119
- }
120
-
121
- function getCachedEd25519PrivateKey(privateKeyPkcs8Base64Url: string): Promise<CryptoKey> {
122
- const cacheKey = `ed25519:pkcs8:${privateKeyPkcs8Base64Url}`
123
- const cached = ed25519PrivateKeyCache.get(cacheKey)
124
- if (cached) return cached
125
-
126
- if (ed25519PrivateKeyCache.size >= ED25519_KEY_CACHE_LIMIT) {
127
- ed25519PrivateKeyCache.clear()
128
- }
129
-
130
- const subtle = requireCryptoSubtle()
131
- const imported = subtle
132
- .importKey('pkcs8', toArrayBuffer(fromBase64Url(privateKeyPkcs8Base64Url)), { name: 'Ed25519' }, false, ['sign'])
133
- .catch((error: unknown) => {
134
- ed25519PrivateKeyCache.delete(cacheKey)
135
- throw error
136
- })
137
- ed25519PrivateKeyCache.set(cacheKey, imported)
138
- return imported
139
- }
140
-
141
- function getCachedEd25519PublicKey(publicKeySpkiBase64Url: string): Promise<CryptoKey> {
142
- const cacheKey = `ed25519:spki:${publicKeySpkiBase64Url}`
143
- const cached = ed25519PublicKeyCache.get(cacheKey)
144
- if (cached) return cached
145
-
146
- if (ed25519PublicKeyCache.size >= ED25519_KEY_CACHE_LIMIT) {
147
- ed25519PublicKeyCache.clear()
148
- }
149
-
150
- const subtle = requireCryptoSubtle()
151
- const imported = subtle
152
- .importKey('spki', toArrayBuffer(fromBase64Url(publicKeySpkiBase64Url)), { name: 'Ed25519' }, false, ['verify'])
153
- .catch((error: unknown) => {
154
- ed25519PublicKeyCache.delete(cacheKey)
155
- throw error
156
- })
157
- ed25519PublicKeyCache.set(cacheKey, imported)
158
- return imported
159
- }
160
-
161
- function toBase64Url(bytes: Uint8Array): string {
162
- const bufferLike = getBufferLike()
163
- const base64 = bufferLike ? bufferLike.from(bytes).toString('base64') : btoa(String.fromCharCode(...bytes))
164
- return base64
165
- .replace(/\+/g, '-')
166
- .replace(/\//g, '_')
167
- .replace(/=+$/g, '')
168
- }
169
-
170
- function fromBase64Url(value: string): Uint8Array {
171
- const padded = value
172
- .replace(/-/g, '+')
173
- .replace(/_/g, '/')
174
- .padEnd(Math.ceil(value.length / 4) * 4, '=')
175
-
176
- const bufferLike = getBufferLike()
177
- if (bufferLike) {
178
- return new Uint8Array(bufferLike.from(padded, 'base64'))
179
- }
180
-
181
- const binary = atob(padded)
182
- const bytes = new Uint8Array(binary.length)
183
- for (let i = 0; i < binary.length; i += 1) {
184
- bytes[i] = binary.charCodeAt(i)
185
- }
186
- return bytes
187
- }
188
-
189
- function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
190
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer
191
- }
192
-
193
- export function canonicalizeEnvelope(envelope: Omit<ProtocolEnvelope, 'signature'>): string {
194
- return `{"body":${serializeBodyCanonical(envelope.body)},"header":${serializeHeaderCanonical(envelope.header)}}`
195
- }
196
-
197
- function requireCryptoSubtle(): SubtleCrypto {
198
- if (typeof crypto === 'undefined' || !crypto.subtle) {
199
- throw new Error('Web Crypto API is not available in this runtime')
200
- }
201
- return crypto.subtle
202
- }
203
-
204
- async function hmacSign(payload: string, secret: string): Promise<string> {
205
- const subtle = requireCryptoSubtle()
206
- const key = await getCachedHmacKey(secret)
207
- const signature = await subtle.sign('HMAC', key, textEncoder.encode(payload))
208
- return toBase64Url(new Uint8Array(signature))
209
- }
210
-
211
- async function hmacVerify(payload: string, signature: string, secret: string): Promise<boolean> {
212
- const subtle = requireCryptoSubtle()
213
- const key = await getCachedHmacKey(secret)
214
- const signatureBytes = fromBase64Url(signature)
215
- return subtle.verify('HMAC', key, signatureBytes.buffer as ArrayBuffer, textEncoder.encode(payload))
216
- }
217
-
218
- async function ed25519Sign(payload: string, privateKeyPkcs8Base64Url: string): Promise<string> {
219
- const subtle = requireCryptoSubtle()
220
- const key = await getCachedEd25519PrivateKey(privateKeyPkcs8Base64Url)
221
- const signature = await subtle.sign('Ed25519', key, textEncoder.encode(payload))
222
- return toBase64Url(new Uint8Array(signature))
223
- }
224
-
225
- async function ed25519Verify(payload: string, signature: string, publicKeySpkiBase64Url: string): Promise<boolean> {
226
- const subtle = requireCryptoSubtle()
227
- const key = await getCachedEd25519PublicKey(publicKeySpkiBase64Url)
228
- const signatureBytes = fromBase64Url(signature)
229
- return subtle.verify('Ed25519', key, signatureBytes.buffer as ArrayBuffer, textEncoder.encode(payload))
230
- }
231
-
232
- export async function signCanonicalPayloadHmac(payload: string, secret: string): Promise<string> {
233
- return hmacSign(payload, secret)
234
- }
235
-
236
- export async function verifyCanonicalPayloadHmac(payload: string, signature: string, secret: string): Promise<boolean> {
237
- return hmacVerify(payload, signature, secret)
238
- }
239
-
240
- export async function generateEd25519KeypairBase64Url(): Promise<{ publicKey: string; privateKey: string }> {
241
- const subtle = requireCryptoSubtle()
242
- const pair = await subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])
243
- const privateKeyRaw = await subtle.exportKey('pkcs8', pair.privateKey)
244
- const publicKeyRaw = await subtle.exportKey('spki', pair.publicKey)
245
- return {
246
- privateKey: toBase64Url(new Uint8Array(privateKeyRaw)),
247
- publicKey: toBase64Url(new Uint8Array(publicKeyRaw)),
248
- }
249
- }
250
-
251
- export async function signCanonicalPayloadEd25519(payload: string, privateKeyPkcs8Base64Url: string): Promise<string> {
252
- return ed25519Sign(payload, privateKeyPkcs8Base64Url)
253
- }
254
-
255
- export async function verifyCanonicalPayloadEd25519(
256
- payload: string,
257
- signature: string,
258
- publicKeySpkiBase64Url: string,
259
- ): Promise<boolean> {
260
- return ed25519Verify(payload, signature, publicKeySpkiBase64Url)
261
- }
262
-
263
- export async function signEnvelopeHmac(
264
- envelope: Omit<ProtocolEnvelope, 'signature'>,
265
- secret: string,
266
- keyId = 'local-dev-key',
267
- ): Promise<ProtocolEnvelope> {
268
- const payload = canonicalizeEnvelope(envelope)
269
- const signature = await hmacSign(payload, secret)
270
- return {
271
- ...envelope,
272
- signature: {
273
- alg: 'HS256',
274
- keyId,
275
- value: signature,
276
- },
277
- }
278
- }
279
-
280
- export async function verifyEnvelopeHmac(envelope: ProtocolEnvelope, secret: string): Promise<boolean> {
281
- if (!envelope.signature) return false
282
- if (envelope.signature.alg !== 'HS256') return false
283
-
284
- const unsigned: Omit<ProtocolEnvelope, 'signature'> = {
285
- header: envelope.header,
286
- body: envelope.body,
287
- }
288
- const payload = canonicalizeEnvelope(unsigned)
289
- return hmacVerify(payload, envelope.signature.value, secret)
290
- }
291
-
292
- export async function signEnvelopeEd25519(
293
- envelope: Omit<ProtocolEnvelope, 'signature'>,
294
- privateKeyPkcs8Base64Url: string,
295
- keyId = 'local-ed25519-key',
296
- ): Promise<ProtocolEnvelope> {
297
- const payload = canonicalizeEnvelope(envelope)
298
- const signature = await ed25519Sign(payload, privateKeyPkcs8Base64Url)
299
- return {
300
- ...envelope,
301
- signature: {
302
- alg: 'ED25519',
303
- keyId,
304
- value: signature,
305
- },
306
- }
307
- }
308
-
309
- export async function verifyEnvelopeEd25519(envelope: ProtocolEnvelope, publicKeySpkiBase64Url: string): Promise<boolean> {
310
- if (!envelope.signature) return false
311
- if (envelope.signature.alg !== 'ED25519') return false
312
-
313
- const unsigned: Omit<ProtocolEnvelope, 'signature'> = {
314
- header: envelope.header,
315
- body: envelope.body,
316
- }
317
- const payload = canonicalizeEnvelope(unsigned)
318
- return ed25519Verify(payload, envelope.signature.value, publicKeySpkiBase64Url)
319
- }
320
-
321
- export async function verifyEnvelopeSignature(
322
- envelope: ProtocolEnvelope,
323
- material: SignatureVerificationMaterial,
324
- ): Promise<boolean> {
325
- if (!envelope.signature) return false
326
- if (envelope.signature.alg !== material.alg) return false
327
- if (material.alg === 'HS256') {
328
- return verifyEnvelopeHmac(envelope, material.secret)
329
- }
330
- return verifyEnvelopeEd25519(envelope, material.publicKey)
331
- }
332
-
333
- export async function verifyCanonicalPayloadSignature(
334
- payload: string,
335
- signature: ProtocolSignature | undefined,
336
- material: SignatureVerificationMaterial,
337
- ): Promise<boolean> {
338
- if (!signature) return false
339
- if (signature.alg !== material.alg) return false
340
- if (material.alg === 'HS256') {
341
- return verifyCanonicalPayloadHmac(payload, signature.value, material.secret)
342
- }
343
- return verifyCanonicalPayloadEd25519(payload, signature.value, material.publicKey)
344
- }
345
-
346
- export function validateEnvelope(envelope: ProtocolEnvelope, nowMs = Date.now()): ProtocolDiagnostic[] {
347
- const diagnostics: ProtocolDiagnostic[] = []
348
- const header = (envelope as Partial<ProtocolEnvelope>).header ?? ({} as Partial<ProtocolHeader>)
349
- const body = (envelope as Partial<ProtocolEnvelope>).body ?? ({} as Partial<ProtocolBody>)
350
-
351
- const version = typeof header.version === 'string' ? header.version : ''
352
- const messageId = typeof header.messageId === 'string' ? header.messageId : ''
353
- const sender = typeof header.sender === 'string' ? header.sender : ''
354
- const nonce = typeof header.nonce === 'string' ? header.nonce : ''
355
- const timestampMs = typeof header.timestampMs === 'number' ? header.timestampMs : 0
356
- const ttlMs = typeof header.ttlMs === 'number' ? header.ttlMs : 0
357
- const content = typeof body.content === 'string' ? body.content : ''
358
-
359
- if (version !== '7h3/0.1') {
360
- diagnostics.push({ level: 'error', message: `Unsupported protocol version '${version}'` })
361
- }
362
- if (!messageId.trim()) {
363
- diagnostics.push({ level: 'error', message: 'Missing messageId' })
364
- }
365
- if (!sender.trim()) {
366
- diagnostics.push({ level: 'error', message: 'Missing sender identity' })
367
- }
368
- if (!nonce.trim()) {
369
- diagnostics.push({ level: 'error', message: 'Missing nonce — replay protection requires a unique nonce per message' })
370
- }
371
- if (ttlMs <= 0) {
372
- diagnostics.push({ level: 'error', message: 'ttlMs must be greater than zero' })
373
- }
374
- if (timestampMs + ttlMs < nowMs) {
375
- diagnostics.push({ level: 'error', message: 'Message TTL expired' })
376
- }
377
- if (!content.trim()) {
378
- diagnostics.push({ level: 'warning', message: 'Empty content payload' })
379
- }
380
-
381
- return diagnostics
382
- }
383
-
384
- export function createEnvelope(input: {
385
- sender: string
386
- recipient?: string
387
- intent: IntentKind
388
- content: string
389
- capability?: string
390
- correlationId?: string
391
- ttlMs?: number
392
- messageId?: string
393
- nonce?: string
394
- nowMs?: number
395
- }): Omit<ProtocolEnvelope, 'signature'> {
396
- const nowMs = input.nowMs ?? Date.now()
397
- return {
398
- header: {
399
- version: '7h3/0.1',
400
- messageId: input.messageId ?? `msg-${nowMs}-${Math.random().toString(36).slice(2, 10)}`,
401
- timestampMs: nowMs,
402
- ttlMs: input.ttlMs ?? 60_000,
403
- sender: input.sender,
404
- recipient: input.recipient,
405
- nonce: input.nonce ?? Math.random().toString(36).slice(2, 12),
406
- },
407
- body: {
408
- intent: input.intent,
409
- content: input.content,
410
- capability: input.capability,
411
- correlationId: input.correlationId,
412
- },
413
- }
414
- }
@@ -1,105 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
- import { AgentSession } from './protocolAgent'
3
- import { negotiateAipCapabilities, parseAipCapabilities } from './protocolCapabilities'
4
- import { encodeEnvelope, receiveEnvelope } from './protocolTransport'
5
-
6
- describe('AgentSession protocol loop', () => {
7
- const alpha = new AgentSession({
8
- agentId: 'agent.alpha',
9
- outboundSecret: 'alpha-secret',
10
- sharedSecrets: {
11
- 'agent.beta': 'beta-secret',
12
- },
13
- })
14
-
15
- const beta = new AgentSession({
16
- agentId: 'agent.beta',
17
- outboundSecret: 'beta-secret',
18
- capabilities: ['math.mul2', 'task.plan'],
19
- sharedSecrets: {
20
- 'agent.alpha': 'alpha-secret',
21
- },
22
- onTask: async (envelope) => ({
23
- intent: 'RESULT',
24
- content: `task accepted:${envelope.body.content}`,
25
- capability: envelope.body.capability,
26
- }),
27
- })
28
-
29
- it('responds to PING with signed PONG', async () => {
30
- const ping = await alpha.createSignedIntent({
31
- recipient: 'agent.beta',
32
- intent: 'PING',
33
- content: 'hello',
34
- messageId: 'p-1',
35
- nonce: 'n-1',
36
- nowMs: 1000,
37
- })
38
-
39
- const receivedByBeta = await beta.receiveAndRespond(encodeEnvelope(ping), 1000)
40
- expect(receivedByBeta.ok).toBe(true)
41
- expect(receivedByBeta.response?.body.intent).toBe('PONG')
42
-
43
- const receivedByAlpha = await receiveEnvelope(receivedByBeta.response!, {
44
- nowMs: 1001,
45
- secretResolver: async () => 'beta-secret',
46
- requireSignature: true,
47
- })
48
- expect(receivedByAlpha.ok).toBe(true)
49
- expect(receivedByAlpha.envelope?.body.correlationId).toBe('p-1')
50
- })
51
-
52
- it('responds to CAPS with capability payload', async () => {
53
- const capsReq = await alpha.createSignedIntent({
54
- recipient: 'agent.beta',
55
- intent: 'CAPS',
56
- content: 'what can you do?',
57
- messageId: 'c-1',
58
- nonce: 'n-2',
59
- nowMs: 1100,
60
- })
61
-
62
- const receivedByBeta = await beta.receiveAndRespond(capsReq, 1100)
63
- expect(receivedByBeta.ok).toBe(true)
64
- expect(receivedByBeta.response?.body.intent).toBe('RESULT')
65
-
66
- const parsed = JSON.parse(receivedByBeta.response?.body.content ?? '{}') as {
67
- agent?: string
68
- capabilities?: string[]
69
- wireFormats?: string[]
70
- batchMax?: number
71
- }
72
- expect(parsed.agent).toBe('agent.beta')
73
- expect(parsed.capabilities).toContain('math.mul2')
74
- expect(parsed.wireFormats).toContain('compact')
75
- expect(parsed.batchMax).toBe(1)
76
- })
77
-
78
- it('negotiates shared wire capabilities from CAPS payloads', () => {
79
- const local = parseAipCapabilities('{"agent":"local","capabilities":[],"wireFormats":["binary","compact"],"batchMax":16,"ackModes":["fast","receipt"]}')
80
- const remote = parseAipCapabilities('{"agent":"remote","capabilities":[],"wireFormats":["compact","json"],"batchMax":8,"ackModes":["receipt"]}')
81
- expect(local).not.toBeNull()
82
- expect(remote).not.toBeNull()
83
-
84
- const negotiated = negotiateAipCapabilities(local!, remote!)
85
- expect(negotiated).toEqual({ wireFormat: 'compact', batchMax: 8, ackMode: 'receipt' })
86
- })
87
-
88
- it('handles TASK with custom task handler', async () => {
89
- const task = await alpha.createSignedIntent({
90
- recipient: 'agent.beta',
91
- intent: 'TASK',
92
- content: 'plan route',
93
- capability: 'task.plan',
94
- messageId: 't-1',
95
- nonce: 'n-3',
96
- nowMs: 1200,
97
- })
98
-
99
- const receivedByBeta = await beta.receiveAndRespond(task, 1200)
100
- expect(receivedByBeta.ok).toBe(true)
101
- expect(receivedByBeta.response?.body.intent).toBe('RESULT')
102
- expect(receivedByBeta.response?.body.content).toContain('task accepted:plan route')
103
- expect(receivedByBeta.response?.body.correlationId).toBe('t-1')
104
- })
105
- })
@@ -1,169 +0,0 @@
1
- import { createEnvelope, signEnvelopeHmac, type IntentKind, type ProtocolDiagnostic, type ProtocolEnvelope } from './protocol'
2
- import { createAipCapabilities, encodeAipCapabilities, type AckMode } from './protocolCapabilities'
3
- import { InMemoryReplayCache } from './protocolReplay'
4
- import { receiveEnvelope, type WireEnvelope, type WireFormat } from './protocolTransport'
5
-
6
- export interface TaskHandlerResult {
7
- intent?: 'RESULT' | 'ERROR'
8
- content: string
9
- capability?: string
10
- }
11
-
12
- export interface AgentSessionConfig {
13
- agentId: string
14
- outboundSecret: string
15
- keyId?: string
16
- capabilities?: string[]
17
- supportedWireFormats?: WireFormat[]
18
- maxBatchSize?: number
19
- ackModes?: AckMode[]
20
- requireSignature?: boolean
21
- replayCache?: InMemoryReplayCache
22
- sharedSecrets?: Record<string, string>
23
- resolveInboundSecret?: (keyId: string, sender: string) => string | undefined | Promise<string | undefined>
24
- onTask?: (envelope: ProtocolEnvelope) => TaskHandlerResult | Promise<TaskHandlerResult>
25
- }
26
-
27
- export interface AgentReceiveResult {
28
- ok: boolean
29
- diagnostics: ProtocolDiagnostic[]
30
- received: ProtocolEnvelope | null
31
- response: ProtocolEnvelope | null
32
- }
33
-
34
- export class AgentSession {
35
- private readonly agentId: string
36
- private readonly outboundSecret: string
37
- private readonly keyId: string
38
- private readonly capabilities: string[]
39
- private readonly supportedWireFormats: WireFormat[]
40
- private readonly maxBatchSize: number
41
- private readonly ackModes: AckMode[]
42
- private readonly requireSignature: boolean
43
- private readonly replayCache: InMemoryReplayCache
44
- private readonly sharedSecrets: Record<string, string>
45
- private readonly resolveInboundSecret?: (keyId: string, sender: string) => string | undefined | Promise<string | undefined>
46
- private readonly onTask?: (envelope: ProtocolEnvelope) => TaskHandlerResult | Promise<TaskHandlerResult>
47
-
48
- constructor(config: AgentSessionConfig) {
49
- this.agentId = config.agentId
50
- this.outboundSecret = config.outboundSecret
51
- this.keyId = config.keyId ?? `${config.agentId}-k1`
52
- this.capabilities = config.capabilities ?? []
53
- this.supportedWireFormats = config.supportedWireFormats ?? ['compact', 'json']
54
- this.maxBatchSize = config.maxBatchSize ?? 1
55
- this.ackModes = config.ackModes ?? ['receipt']
56
- this.requireSignature = config.requireSignature ?? true
57
- this.replayCache = config.replayCache ?? new InMemoryReplayCache()
58
- this.sharedSecrets = config.sharedSecrets ?? {}
59
- this.resolveInboundSecret = config.resolveInboundSecret
60
- this.onTask = config.onTask
61
- }
62
-
63
- private async inboundSecretResolver(keyId: string, sender: string): Promise<string | undefined> {
64
- if (this.resolveInboundSecret) {
65
- return this.resolveInboundSecret(keyId, sender)
66
- }
67
- return this.sharedSecrets[sender]
68
- }
69
-
70
- async createSignedIntent(input: {
71
- recipient?: string
72
- intent: IntentKind
73
- content: string
74
- capability?: string
75
- correlationId?: string
76
- ttlMs?: number
77
- messageId?: string
78
- nonce?: string
79
- nowMs?: number
80
- }): Promise<ProtocolEnvelope> {
81
- const unsigned = createEnvelope({
82
- sender: this.agentId,
83
- recipient: input.recipient,
84
- intent: input.intent,
85
- content: input.content,
86
- capability: input.capability,
87
- correlationId: input.correlationId,
88
- ttlMs: input.ttlMs,
89
- messageId: input.messageId,
90
- nonce: input.nonce,
91
- nowMs: input.nowMs,
92
- })
93
- return signEnvelopeHmac(unsigned, this.outboundSecret, this.keyId)
94
- }
95
-
96
- async receiveAndRespond(input: WireEnvelope | ProtocolEnvelope, nowMs = Date.now()): Promise<AgentReceiveResult> {
97
- const received = await receiveEnvelope(input, {
98
- nowMs,
99
- requireSignature: this.requireSignature,
100
- replayCache: this.replayCache,
101
- secretResolver: (keyId, sender) => this.inboundSecretResolver(keyId, sender),
102
- })
103
-
104
- if (!received.ok || !received.envelope) {
105
- return {
106
- ok: false,
107
- diagnostics: received.diagnostics,
108
- received: received.envelope,
109
- response: null,
110
- }
111
- }
112
-
113
- const envelope = received.envelope
114
- const response = await this.buildAutoResponse(envelope, nowMs)
115
- return {
116
- ok: true,
117
- diagnostics: received.diagnostics,
118
- received: envelope,
119
- response,
120
- }
121
- }
122
-
123
- private async buildAutoResponse(envelope: ProtocolEnvelope, nowMs: number): Promise<ProtocolEnvelope | null> {
124
- if (envelope.body.intent === 'PING') {
125
- return this.createSignedIntent({
126
- recipient: envelope.header.sender,
127
- intent: 'PONG',
128
- content: 'pong',
129
- correlationId: envelope.header.messageId,
130
- nowMs,
131
- })
132
- }
133
-
134
- if (envelope.body.intent === 'CAPS') {
135
- return this.createSignedIntent({
136
- recipient: envelope.header.sender,
137
- intent: 'RESULT',
138
- content: encodeAipCapabilities(
139
- createAipCapabilities({
140
- agent: this.agentId,
141
- capabilities: this.capabilities,
142
- wireFormats: this.supportedWireFormats,
143
- batchMax: this.maxBatchSize,
144
- ackModes: this.ackModes,
145
- }),
146
- ),
147
- capability: 'caps',
148
- correlationId: envelope.header.messageId,
149
- nowMs,
150
- })
151
- }
152
-
153
- if (envelope.body.intent === 'TASK') {
154
- const taskResult = this.onTask
155
- ? await this.onTask(envelope)
156
- : { intent: 'RESULT' as const, content: 'ACK', capability: envelope.body.capability }
157
- return this.createSignedIntent({
158
- recipient: envelope.header.sender,
159
- intent: taskResult.intent ?? 'RESULT',
160
- content: taskResult.content,
161
- capability: taskResult.capability,
162
- correlationId: envelope.header.messageId,
163
- nowMs,
164
- })
165
- }
166
-
167
- return null
168
- }
169
- }