@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.
Files changed (230) hide show
  1. package/.dockerignore +19 -0
  2. package/.github/dependabot.yml +32 -0
  3. package/.github/workflows/ci.yml +31 -0
  4. package/.github/workflows/publish.yml +59 -0
  5. package/.github/workflows/scorecard.yml +37 -0
  6. package/7h3.example.yaml +125 -0
  7. package/CHANGELOG.md +92 -0
  8. package/CONTRIBUTING.md +82 -0
  9. package/Dockerfile +73 -0
  10. package/GOVERNANCE.md +62 -0
  11. package/README.md +323 -6
  12. package/SECURITY.md +70 -0
  13. package/bench-results/replay-cache-full-1777891033256.json +10 -0
  14. package/bench-results/replay-cache-full-1777896317488.json +10 -0
  15. package/bench-results/replay-cache-full-1777900993184.json +10 -0
  16. package/bench-results/replay-cache-full-1777901019285.json +10 -0
  17. package/bench-results/replay-cache-quick-1777870170126.json +10 -0
  18. package/bench-results/signature-profiles-quick-1775875160079.json +85 -0
  19. package/bench-results/signature-profiles-quick-1775983539716.json +85 -0
  20. package/bench-results/signature-profiles-quick-1776237913190.json +85 -0
  21. package/bench-results/wire-codecs-full-1777891019803.json +93 -0
  22. package/bench-results/wire-codecs-full-1777896260964.json +93 -0
  23. package/bench-results/wire-codecs-full-1777901004247.json +93 -0
  24. package/bench-results/wire-codecs-quick-1775972879056.json +93 -0
  25. package/bench-results/wire-codecs-quick-1775983541111.json +93 -0
  26. package/bench-results/wire-codecs-quick-1776237914299.json +93 -0
  27. package/bench-results/wire-codecs-quick-1777841285236.json +93 -0
  28. package/bench-results/wire-codecs-quick-1777841321772.json +93 -0
  29. package/bench-results/wire-codecs-quick-1777841330408.json +93 -0
  30. package/bench-results/wire-codecs-quick-1777852886082.json +93 -0
  31. package/bench-results/wire-codecs-quick-1777852988773.json +93 -0
  32. package/bench-results/wire-codecs-quick-1777870188095.json +93 -0
  33. package/bench-results/wire-codecs-quick-1777870263918.json +93 -0
  34. package/bench-results/wire-codecs-quick-1777870455034.json +93 -0
  35. package/bench-results/wire-codecs-quick-1778816163081.json +93 -0
  36. package/bench-results/wire-codecs-quick-1778843936130.json +93 -0
  37. package/bin/7h3.ts +385 -0
  38. package/conformance/7h3_v0_1.json +77 -0
  39. package/conformance/7h3_v0_1_binary.json +20 -0
  40. package/conformance/aip_v0_1_binary.json +20 -0
  41. package/docker-compose.yaml +77 -0
  42. package/docs/ADOPTION_PLAN.md +120 -0
  43. package/docs/AGENTS.md +77 -0
  44. package/docs/AIP_RFC_v0.1.md +97 -0
  45. package/docs/AI_DECISION_CARD.md +122 -0
  46. package/docs/AI_RUNTIME_POLICY.json +126 -0
  47. package/docs/AI_RUNTIME_POLICY.yaml +110 -0
  48. package/docs/BACKPRESSURE_TUNING.md +65 -0
  49. package/docs/BENCHMARK_CLAIM_MATRIX.md +42 -0
  50. package/docs/BENCHMARK_REPORT_TEMPLATE.md +169 -0
  51. package/docs/BINARY_CODEC_BENCH.md +23 -0
  52. package/docs/CLEAN_CLONE_RUNBOOK.md +36 -0
  53. package/docs/CLOCK_SKEW_POLICY.md +30 -0
  54. package/docs/DISTRIBUTED_REPLAY.md +142 -0
  55. package/docs/FUZZ_CAMPAIGN.md +121 -0
  56. package/docs/GATEWAY.md +195 -0
  57. package/docs/KEY_MANAGEMENT_POLICY.md +53 -0
  58. package/docs/KEY_REVOCATION.md +69 -0
  59. package/docs/MCP_WRAPPER.md +159 -0
  60. package/docs/MIGRATION_GUIDE.md +40 -0
  61. package/docs/OPERATORS.md +184 -0
  62. package/docs/PERF_REGRESSION_POLICY.md +34 -0
  63. package/docs/PROJECT_EXAMINATION_2026-05-31.md +219 -0
  64. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +135 -0
  65. package/docs/RELEASE_GATE.md +25 -0
  66. package/docs/RELEASE_NOTES_v0.1.0.md +54 -0
  67. package/docs/SECURITY_REVIEW_2026-06-05.md +165 -0
  68. package/docs/TELEMETRY.md +41 -0
  69. package/docs/THREAT_MODEL.md +89 -0
  70. package/docs/VERSIONING_POLICY.md +30 -0
  71. package/docs/assets/banner.png +0 -0
  72. package/eslint.config.js +15 -0
  73. package/fuzz/ts/harness-decode.ts +136 -0
  74. package/fuzz/ts/harness-verify.ts +121 -0
  75. package/fuzz/ts/run.ts +35 -0
  76. package/mcp-server/README.md +38 -0
  77. package/mcp-server/package-lock.json +1187 -0
  78. package/mcp-server/package.json +35 -0
  79. package/mcp-server/src/index.ts +236 -0
  80. package/mcp-server/tsconfig.json +14 -0
  81. package/package.json +79 -13
  82. package/scripts/aip-framework-quickstart.ts +110 -0
  83. package/scripts/aip-mcp-gateway.ts +38 -0
  84. package/scripts/aip-mcp-wrap-demo.ts +72 -0
  85. package/scripts/aip-quickstart.ts +60 -0
  86. package/scripts/bench-diff.ts +118 -0
  87. package/scripts/bench-protocol-e2e.ts +937 -0
  88. package/scripts/bench-protocol-openloop.ts +1397 -0
  89. package/scripts/bench-replay-cache.ts +76 -0
  90. package/scripts/bench-signature-profiles.ts +180 -0
  91. package/scripts/bench-wire-codecs.ts +161 -0
  92. package/scripts/build-binary-conformance.ts +36 -0
  93. package/scripts/build-release-dashboard.ts +175 -0
  94. package/scripts/canary-rollout.ts +38 -0
  95. package/scripts/mcpGatewayCli.test.ts +116 -0
  96. package/scripts/prepare-aip-package.ts +88 -0
  97. package/scripts/regen-conformance-sigs.ts +18 -0
  98. package/scripts/release-gate.ts +19 -0
  99. package/scripts/validate-runtime-policy.ts +18 -0
  100. package/sdk/browser/index.test.ts +162 -0
  101. package/sdk/browser/index.ts +257 -0
  102. package/sdk/browser/package.json +13 -0
  103. package/sdk/go/go.mod +3 -0
  104. package/sdk/go/http.go +135 -0
  105. package/sdk/go/protocol.go +324 -0
  106. package/sdk/go/protocol_test.go +334 -0
  107. package/sdk/go/webhook.go +136 -0
  108. package/sdk/python/README.md +18 -0
  109. package/sdk/python/protocol_7h3/__init__.py +46 -0
  110. package/sdk/python/protocol_7h3/http.py +212 -0
  111. package/sdk/python/protocol_7h3/keys.py +149 -0
  112. package/sdk/python/protocol_7h3/protocol.py +525 -0
  113. package/sdk/python/protocol_7h3/queue.py +118 -0
  114. package/sdk/python/protocol_7h3/webhook.py +116 -0
  115. package/sdk/python/pyproject.toml +40 -0
  116. package/sdk/python/tests/test_conformance.py +110 -0
  117. package/sdk/python/tests/test_http.py +305 -0
  118. package/sdk/python/tests/test_keys.py +417 -0
  119. package/sdk/python/tests/test_queue.py +120 -0
  120. package/sdk/python/tests/test_webhook.py +345 -0
  121. package/sdk/rust/Cargo.lock +371 -0
  122. package/sdk/rust/Cargo.toml +25 -0
  123. package/sdk/rust/README.md +31 -0
  124. package/sdk/rust/fuzz/Cargo.toml +29 -0
  125. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +46 -0
  126. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +11 -0
  127. package/sdk/rust/src/bin/aip_mcp_gateway.rs +59 -0
  128. package/sdk/rust/src/http.rs +145 -0
  129. package/sdk/rust/src/keys.rs +161 -0
  130. package/sdk/rust/src/lib.rs +688 -0
  131. package/sdk/rust/src/queue.rs +79 -0
  132. package/sdk/rust/src/webhook.rs +86 -0
  133. package/sdk/rust/tests/conformance.rs +148 -0
  134. package/sdk/rust/tests/gateway.rs +130 -0
  135. package/sdk/rust/tests/http_webhook_queue.rs +201 -0
  136. package/sdk/rust/tests/keys.rs +189 -0
  137. package/src/agentAdapter.test.ts +48 -0
  138. package/src/agentAdapter.ts +56 -0
  139. package/src/auditLog.test.ts +145 -0
  140. package/src/auditLog.ts +147 -0
  141. package/src/conformance.test.ts +136 -0
  142. package/src/conformanceVectors.ts +99 -0
  143. package/src/frameworkAdapters.test.ts +290 -0
  144. package/src/frameworkAdapters.ts +261 -0
  145. package/src/gateway.test.ts +343 -0
  146. package/src/gateway.ts +171 -0
  147. package/src/grpcBinding.test.ts +211 -0
  148. package/src/grpcBinding.ts +103 -0
  149. package/src/httpBinding.test.ts +376 -0
  150. package/src/httpBinding.ts +163 -0
  151. package/src/index.ts +32 -0
  152. package/src/keyInfra.test.ts +278 -0
  153. package/src/keyInfra.ts +228 -0
  154. package/src/keyRegistry.ts +59 -0
  155. package/src/keyRotation.test.ts +78 -0
  156. package/src/keyRotation.ts +72 -0
  157. package/src/mcpGateway.test.ts +129 -0
  158. package/src/mcpGateway.ts +250 -0
  159. package/src/mcpTransports.test.ts +92 -0
  160. package/src/mcpTransports.ts +169 -0
  161. package/src/mcpWrapper.test.ts +179 -0
  162. package/src/mcpWrapper.ts +206 -0
  163. package/src/policyEnforcer.test.ts +99 -0
  164. package/src/policyEnforcer.ts +169 -0
  165. package/src/policyTelemetryFeedback.test.ts +25 -0
  166. package/src/policyTelemetryFeedback.ts +38 -0
  167. package/src/protocol.bench.ts +37 -0
  168. package/src/protocol.test.ts +155 -0
  169. package/src/protocol.ts +413 -0
  170. package/src/protocolAgent.test.ts +105 -0
  171. package/src/protocolAgent.ts +169 -0
  172. package/src/protocolBinary.test.ts +165 -0
  173. package/src/protocolBinary.ts +312 -0
  174. package/src/protocolCapabilities.ts +70 -0
  175. package/src/protocolFuzz.advanced.test.ts +235 -0
  176. package/src/protocolFuzz.test.ts +111 -0
  177. package/src/protocolNegative.test.ts +97 -0
  178. package/src/protocolReplay.test.ts +71 -0
  179. package/src/protocolReplay.ts +194 -0
  180. package/src/protocolTransport.test.ts +556 -0
  181. package/src/protocolTransport.ts +483 -0
  182. package/src/queueBinding.test.ts +130 -0
  183. package/src/queueBinding.ts +102 -0
  184. package/src/rateLimiter.test.ts +96 -0
  185. package/src/rateLimiter.ts +46 -0
  186. package/src/redisClient.ts +140 -0
  187. package/src/redisIntegration.test.ts +134 -0
  188. package/src/replayStores.test.ts +141 -0
  189. package/src/replayStores.ts +82 -0
  190. package/src/revocation.test.ts +98 -0
  191. package/src/revocation.ts +0 -0
  192. package/src/routePolicy.test.ts +87 -0
  193. package/src/routePolicy.ts +72 -0
  194. package/src/runtimePolicy.test.ts +49 -0
  195. package/src/runtimePolicy.ts +81 -0
  196. package/src/runtimePolicyManager.test.ts +29 -0
  197. package/src/runtimePolicyManager.ts +50 -0
  198. package/src/runtimePolicyPresets.ts +43 -0
  199. package/src/signedResponse.test.ts +111 -0
  200. package/src/signedResponse.ts +83 -0
  201. package/src/webhookBinding.test.ts +144 -0
  202. package/src/webhookBinding.ts +115 -0
  203. package/src/wsBinding.test.ts +221 -0
  204. package/src/wsBinding.ts +100 -0
  205. package/tsconfig.json +15 -0
  206. package/tsconfig.lib.json +23 -0
  207. package/vite.lib.config.ts +16 -0
  208. package/agentAdapter.d.ts +0 -26
  209. package/conformanceVectors.d.ts +0 -20
  210. package/frameworkAdapters.d.ts +0 -72
  211. package/index.d.ts +0 -20
  212. package/index.js +0 -1702
  213. package/keyRotation.d.ts +0 -20
  214. package/mcpGateway.d.ts +0 -37
  215. package/mcpTransports.d.ts +0 -62
  216. package/mcpWrapper.d.ts +0 -83
  217. package/policyEnforcer.d.ts +0 -50
  218. package/policyTelemetryFeedback.d.ts +0 -11
  219. package/protocol.d.ts +0 -66
  220. package/protocolAgent.d.ts +0 -58
  221. package/protocolBinary.d.ts +0 -8
  222. package/protocolCapabilities.d.ts +0 -24
  223. package/protocolReplay.d.ts +0 -35
  224. package/protocolTransport.d.ts +0 -73
  225. package/redisClient.d.ts +0 -49
  226. package/replayStores.d.ts +0 -32
  227. package/revocation.d.ts +0 -71
  228. package/runtimePolicy.d.ts +0 -24
  229. package/runtimePolicyManager.d.ts +0 -15
  230. package/runtimePolicyPresets.d.ts +0 -11
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Property-based fuzz tests using fast-check.
3
+ *
4
+ * Area 1: Wire decoder resilience — decodeEnvelope must never throw on arbitrary
5
+ * string or Uint8Array input; it must always return {ok: false} on garbage.
6
+ *
7
+ * Area 2: Canonicalization determinism — canonicalizeEnvelope must be pure and
8
+ * stable: calling it twice on the same envelope returns the same string,
9
+ * and reordering the object's fields has no effect.
10
+ *
11
+ * Area 3: Replay cache idempotency — for any (sender, messageId, nonce) triple
12
+ * the first consume() is ok:true and a second is ok:false, provided the
13
+ * key is unique in the cache. Key collision via the "|" separator is
14
+ * handled explicitly (see comment below).
15
+ */
16
+
17
+ import * as fc from 'fast-check'
18
+ import { describe, expect, it } from 'vitest'
19
+ import { canonicalizeEnvelope } from './protocol'
20
+ import type { ProtocolBody, ProtocolHeader } from './protocol'
21
+ import { InMemoryReplayCache } from './protocolReplay'
22
+ import { decodeEnvelope } from './protocolTransport'
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // Area 1 — Wire decoder resilience
26
+ // ---------------------------------------------------------------------------
27
+
28
+ describe('decodeEnvelope resilience (property-based)', () => {
29
+ it('never throws on arbitrary string input — always returns {ok}', () => {
30
+ fc.assert(
31
+ fc.property(fc.string(), (raw) => {
32
+ let result: ReturnType<typeof decodeEnvelope>
33
+ expect(() => {
34
+ result = decodeEnvelope(raw)
35
+ }).not.toThrow()
36
+ // Must have an `ok` boolean — when the string is garbage it will be false.
37
+ expect(typeof result!.ok).toBe('boolean')
38
+ }),
39
+ )
40
+ })
41
+
42
+ it('never throws on arbitrary Uint8Array input — always returns {ok}', () => {
43
+ fc.assert(
44
+ fc.property(fc.uint8Array({ maxLength: 512 }), (bytes) => {
45
+ let result: ReturnType<typeof decodeEnvelope>
46
+ expect(() => {
47
+ result = decodeEnvelope(bytes)
48
+ }).not.toThrow()
49
+ expect(typeof result!.ok).toBe('boolean')
50
+ }),
51
+ )
52
+ })
53
+
54
+ it('returns ok:false (not throws) for partial JSON strings', () => {
55
+ // Strings that begin like JSON but are truncated or malformed.
56
+ fc.assert(
57
+ fc.property(
58
+ fc.oneof(
59
+ // Truncated JSON
60
+ fc.string({ maxLength: 20 }).map((s) => '{' + s),
61
+ // Random non-JSON
62
+ fc.string({ minLength: 1, maxLength: 64 }).filter((s) => {
63
+ try {
64
+ JSON.parse(s)
65
+ return false
66
+ } catch {
67
+ return true
68
+ }
69
+ }),
70
+ ),
71
+ (raw) => {
72
+ const result = decodeEnvelope(raw)
73
+ expect(result.ok).toBe(false)
74
+ },
75
+ ),
76
+ )
77
+ })
78
+ })
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Area 2 — Canonicalization determinism
82
+ // ---------------------------------------------------------------------------
83
+
84
+ /** Arbitraries for the valid types in headers and bodies. */
85
+ const intentKindArb = fc.constantFrom(
86
+ 'PING' as const,
87
+ 'PONG' as const,
88
+ 'CAPS' as const,
89
+ 'TASK' as const,
90
+ 'RESULT' as const,
91
+ 'ERROR' as const,
92
+ )
93
+
94
+ const headerArb: fc.Arbitrary<ProtocolHeader> = fc.record({
95
+ version: fc.constant('7h3/0.1' as const),
96
+ messageId: fc.string({ minLength: 1, maxLength: 64 }),
97
+ timestampMs: fc.integer({ min: 0, max: Number.MAX_SAFE_INTEGER }),
98
+ ttlMs: fc.integer({ min: 1, max: 86_400_000 }),
99
+ sender: fc.string({ minLength: 1, maxLength: 64 }),
100
+ nonce: fc.string({ minLength: 1, maxLength: 32 }),
101
+ // recipient is optional — generate it or leave it undefined
102
+ recipient: fc.option(fc.string({ minLength: 1, maxLength: 64 }), { nil: undefined }),
103
+ })
104
+
105
+ const bodyArb: fc.Arbitrary<ProtocolBody> = fc.record({
106
+ intent: intentKindArb,
107
+ content: fc.string({ maxLength: 256 }),
108
+ capability: fc.option(fc.string({ minLength: 1, maxLength: 64 }), { nil: undefined }),
109
+ correlationId: fc.option(fc.string({ minLength: 1, maxLength: 64 }), { nil: undefined }),
110
+ })
111
+
112
+ describe('canonicalizeEnvelope determinism (property-based)', () => {
113
+ it('returns the same string when called twice on the same envelope', () => {
114
+ fc.assert(
115
+ fc.property(headerArb, bodyArb, (header, body) => {
116
+ const envelope = { header, body }
117
+ expect(canonicalizeEnvelope(envelope)).toBe(canonicalizeEnvelope(envelope))
118
+ }),
119
+ )
120
+ })
121
+
122
+ it('is not affected by key insertion order in the header object', () => {
123
+ fc.assert(
124
+ fc.property(headerArb, bodyArb, (header, body) => {
125
+ // Build a structurally identical header whose keys are inserted in reverse
126
+ // order to the one produced by headerArb.
127
+ const reversedHeader: ProtocolHeader = Object.fromEntries(
128
+ Object.entries(header).reverse(),
129
+ ) as unknown as ProtocolHeader
130
+
131
+ const canonical = canonicalizeEnvelope({ header, body })
132
+ const canonicalReversed = canonicalizeEnvelope({ header: reversedHeader, body })
133
+ expect(canonical).toBe(canonicalReversed)
134
+ }),
135
+ )
136
+ })
137
+
138
+ it('is not affected by key insertion order in the body object', () => {
139
+ fc.assert(
140
+ fc.property(headerArb, bodyArb, (header, body) => {
141
+ const reversedBody: ProtocolBody = Object.fromEntries(
142
+ Object.entries(body).reverse(),
143
+ ) as unknown as ProtocolBody
144
+
145
+ const canonical = canonicalizeEnvelope({ header, body })
146
+ const canonicalReversed = canonicalizeEnvelope({ header, body: reversedBody })
147
+ expect(canonical).toBe(canonicalReversed)
148
+ }),
149
+ )
150
+ })
151
+ })
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // Area 3 — Replay cache properties
155
+ // ---------------------------------------------------------------------------
156
+
157
+ /**
158
+ * The InMemoryReplayCache key is built as `${sender}|${messageId}|${nonce}`.
159
+ * Because the separator is unescaped, two distinct (sender, messageId, nonce)
160
+ * triples can map to the same cache key — e.g. ("a|b", "c", "d") and
161
+ * ("a", "b|c", "d") both yield "a|b|c|d". We track seen keys ourselves
162
+ * using the same join rule so our assertions match what the cache actually does.
163
+ */
164
+ function replayCacheKey(sender: string, messageId: string, nonce: string): string {
165
+ return `${sender}|${messageId}|${nonce}`
166
+ }
167
+
168
+ const tripleArb = fc.record({
169
+ sender: fc.string({ maxLength: 32 }),
170
+ messageId: fc.string({ maxLength: 32 }),
171
+ nonce: fc.string({ maxLength: 32 }),
172
+ })
173
+
174
+ /** Build a minimal ProtocolEnvelope skeleton sufficient for InMemoryReplayCache.consume(). */
175
+ function makeEnvelope(sender: string, messageId: string, nonce: string, nowMs: number) {
176
+ return {
177
+ header: {
178
+ version: '7h3/0.1' as const,
179
+ sender,
180
+ messageId,
181
+ nonce,
182
+ timestampMs: nowMs,
183
+ ttlMs: 600_000, // 10 min — ensures entry lives well past both consume() calls
184
+ recipient: undefined,
185
+ },
186
+ body: {
187
+ intent: 'PING' as const,
188
+ content: '',
189
+ },
190
+ }
191
+ }
192
+
193
+ describe('InMemoryReplayCache properties (property-based)', () => {
194
+ it('first consume() ok:true, second consume() ok:false for any unique triple', () => {
195
+ fc.assert(
196
+ fc.property(tripleArb, ({ sender, messageId, nonce }) => {
197
+ const cache = new InMemoryReplayCache()
198
+ const nowMs = 1_700_000_000_000
199
+ const envelope = makeEnvelope(sender, messageId, nonce, nowMs)
200
+
201
+ const first = cache.consume(envelope, nowMs)
202
+ expect(first.ok).toBe(true)
203
+
204
+ const second = cache.consume(envelope, nowMs)
205
+ expect(second.ok).toBe(false)
206
+ }),
207
+ )
208
+ })
209
+
210
+ it('for a sequence of triples: first reserve for a key is ok:true, repeat is ok:false', () => {
211
+ fc.assert(
212
+ fc.property(fc.array(tripleArb, { minLength: 1, maxLength: 20 }), (triples) => {
213
+ const cache = new InMemoryReplayCache()
214
+ const nowMs = 1_700_000_000_000
215
+ // Track which keys the cache has already seen (mirrors makeKey internals).
216
+ const seenKeys = new Set<string>()
217
+
218
+ for (const { sender, messageId, nonce } of triples) {
219
+ const key = replayCacheKey(sender, messageId, nonce)
220
+ const envelope = makeEnvelope(sender, messageId, nonce, nowMs)
221
+ const result = cache.consume(envelope, nowMs)
222
+
223
+ if (seenKeys.has(key)) {
224
+ // Cache already has this key — must be rejected as replay.
225
+ expect(result.ok).toBe(false)
226
+ } else {
227
+ // First time this key is presented — must be accepted.
228
+ expect(result.ok).toBe(true)
229
+ seenKeys.add(key)
230
+ }
231
+ }
232
+ }),
233
+ )
234
+ })
235
+ })
@@ -0,0 +1,111 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { canonicalizeEnvelope, createEnvelope, signEnvelopeHmac, verifyEnvelopeHmac } from './protocol'
3
+ import { InMemoryReplayCache } from './protocolReplay'
4
+ import { decodeEnvelope, encodeEnvelope, receiveEnvelope } from './protocolTransport'
5
+
6
+ function seededRandom(seed: number): () => number {
7
+ let state = seed >>> 0
8
+ return () => {
9
+ state = (1664525 * state + 1013904223) >>> 0
10
+ return state / 0xffffffff
11
+ }
12
+ }
13
+
14
+ function randomText(rand: () => number, length: number): string {
15
+ const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789:-_/'
16
+ let out = ''
17
+ for (let i = 0; i < length; i += 1) {
18
+ out += alphabet[Math.floor(rand() * alphabet.length)]
19
+ }
20
+ return out
21
+ }
22
+
23
+ describe('AIP property and fuzz checks', () => {
24
+ it('keeps canonicalization and signed roundtrip stable for random envelopes', async () => {
25
+ const rand = seededRandom(0xdecafbad)
26
+
27
+ for (let i = 0; i < 200; i += 1) {
28
+ const nowMs = 1_700_000_000_000 + i
29
+ const envelope = createEnvelope({
30
+ sender: `agent.${randomText(rand, 6)}`,
31
+ recipient: rand() > 0.5 ? `agent.${randomText(rand, 5)}` : undefined,
32
+ intent: rand() > 0.5 ? 'TASK' : 'RESULT',
33
+ content: randomText(rand, 64),
34
+ capability: rand() > 0.6 ? `task.${randomText(rand, 5)}` : undefined,
35
+ correlationId: rand() > 0.4 ? `corr-${randomText(rand, 8)}` : undefined,
36
+ messageId: `fuzz-${i}-${randomText(rand, 8)}`,
37
+ nonce: `n-${i}-${randomText(rand, 8)}`,
38
+ nowMs,
39
+ ttlMs: 10_000 + Math.floor(rand() * 20_000),
40
+ })
41
+
42
+ const canonicalA = canonicalizeEnvelope(envelope)
43
+ const canonicalB = canonicalizeEnvelope({ header: envelope.header, body: envelope.body })
44
+ expect(canonicalA).toBe(canonicalB)
45
+
46
+ const signed = await signEnvelopeHmac(envelope, 'fuzz-shared-secret', 'fuzz-k1')
47
+ expect(await verifyEnvelopeHmac(signed, 'fuzz-shared-secret')).toBe(true)
48
+
49
+ const encoded = encodeEnvelope(signed, rand() > 0.5 ? 'compact' : 'json')
50
+ const decoded = decodeEnvelope(encoded)
51
+ expect(decoded.ok).toBe(true)
52
+ expect(decoded.envelope).toEqual(signed)
53
+
54
+ const received = await receiveEnvelope(encoded, {
55
+ nowMs: nowMs + 1,
56
+ replayCache: new InMemoryReplayCache(),
57
+ secretResolver: async () => 'fuzz-shared-secret',
58
+ })
59
+ expect(received.ok).toBe(true)
60
+ }
61
+ })
62
+
63
+ it('rejects fuzzed malformed or tampered payloads', async () => {
64
+ const rand = seededRandom(0xabad1dea)
65
+ const base = await signEnvelopeHmac(
66
+ createEnvelope({
67
+ sender: 'agent.fuzz',
68
+ recipient: 'agent.verify',
69
+ intent: 'TASK',
70
+ content: 'fuzz-base',
71
+ messageId: 'fuzz-base-1',
72
+ nonce: 'fuzz-base-n1',
73
+ nowMs: 1_700_000_001_000,
74
+ ttlMs: 60_000,
75
+ }),
76
+ 'fuzz-shared-secret',
77
+ 'fuzz-k1',
78
+ )
79
+
80
+ const malformedPayloads = ['{', '[]', '{"v":"7h3/0.1"}', '{"header":{},"body":{}}', '{"hello":"world"}']
81
+ for (const raw of malformedPayloads) {
82
+ const result = await receiveEnvelope(raw, {
83
+ nowMs: 1_700_000_001_001,
84
+ replayCache: new InMemoryReplayCache(),
85
+ secretResolver: async () => 'fuzz-shared-secret',
86
+ })
87
+ expect(result.ok).toBe(false)
88
+ }
89
+
90
+ for (let i = 0; i < 120; i += 1) {
91
+ const compact = JSON.parse(encodeEnvelope(base, 'compact')) as {
92
+ sig?: { a?: string; k: string; v: string }
93
+ }
94
+ if (!compact.sig) throw new Error('expected signature in compact envelope')
95
+
96
+ const index = Math.floor(rand() * compact.sig.v.length)
97
+ const current = compact.sig.v[index] ?? 'A'
98
+ const replacement = current === 'A' ? 'B' : 'A'
99
+ compact.sig.v = `${compact.sig.v.slice(0, index)}${replacement}${compact.sig.v.slice(index + 1)}`
100
+ const tampered = JSON.stringify(compact)
101
+
102
+ const result = await receiveEnvelope(tampered, {
103
+ nowMs: 1_700_000_001_001,
104
+ replayCache: new InMemoryReplayCache(),
105
+ secretResolver: async () => 'fuzz-shared-secret',
106
+ })
107
+ expect(result.ok).toBe(false)
108
+ expect(result.diagnostics.some((d) => d.message === 'Signature verification failed')).toBe(true)
109
+ }
110
+ })
111
+ })
@@ -0,0 +1,97 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { createEnvelope, generateEd25519KeypairBase64Url, signEnvelopeEd25519, signEnvelopeHmac } from './protocol'
3
+ import { InMemoryReplayCache } from './protocolReplay'
4
+ import { decodeEnvelope, decodeEnvelopeBatch, encodeEnvelope, receiveEnvelope } from './protocolTransport'
5
+
6
+ describe('AIP negative corpus', () => {
7
+ it('rejects invalid JSON envelopes', () => {
8
+ const decoded = decodeEnvelope('{invalid-json')
9
+ expect(decoded.ok).toBe(false)
10
+ expect(decoded.diagnostics.some((d) => d.message === 'Invalid JSON envelope')).toBe(true)
11
+ })
12
+
13
+ it('rejects unknown envelope shape', () => {
14
+ const decoded = decodeEnvelope(JSON.stringify({ hello: 'world' }))
15
+ expect(decoded.ok).toBe(false)
16
+ expect(decoded.diagnostics.some((d) => d.message.includes('shape is not recognized'))).toBe(true)
17
+ })
18
+
19
+ it('rejects batch payload that is not an array', () => {
20
+ const decoded = decodeEnvelopeBatch(JSON.stringify({ not: 'array' }))
21
+ expect(decoded).toHaveLength(1)
22
+ expect(decoded[0]?.ok).toBe(false)
23
+ expect(decoded[0]?.diagnostics.some((d) => d.message.includes('must be a JSON array'))).toBe(true)
24
+ })
25
+
26
+ it('rejects unsigned envelopes when signatures are required', async () => {
27
+ const unsigned = createEnvelope({
28
+ sender: 'agent.alpha',
29
+ intent: 'TASK',
30
+ content: 'unsigned',
31
+ messageId: 'neg-unsigned-1',
32
+ nonce: 'neg-unsigned-n1',
33
+ nowMs: 1000,
34
+ ttlMs: 60_000,
35
+ })
36
+
37
+ const result = await receiveEnvelope(encodeEnvelope(unsigned), {
38
+ nowMs: 1001,
39
+ replayCache: new InMemoryReplayCache(),
40
+ requireSignature: true,
41
+ })
42
+
43
+ expect(result.ok).toBe(false)
44
+ expect(result.diagnostics.some((d) => d.message === 'Missing signature')).toBe(true)
45
+ })
46
+
47
+ it('rejects signature when verification material algorithm mismatches', async () => {
48
+ const signed = await signEnvelopeHmac(
49
+ createEnvelope({
50
+ sender: 'agent.alpha',
51
+ intent: 'PING',
52
+ content: 'alg-mismatch',
53
+ messageId: 'neg-alg-1',
54
+ nonce: 'neg-alg-n1',
55
+ nowMs: 1000,
56
+ ttlMs: 60_000,
57
+ }),
58
+ 'shared-secret',
59
+ 'k1',
60
+ )
61
+
62
+ const result = await receiveEnvelope(encodeEnvelope(signed), {
63
+ nowMs: 1001,
64
+ replayCache: new InMemoryReplayCache(),
65
+ signatureResolver: async () => ({ alg: 'ED25519', publicKey: 'not-a-valid-ed25519-key' }),
66
+ })
67
+
68
+ expect(result.ok).toBe(false)
69
+ expect(result.diagnostics.some((d) => d.message === 'Signature verification failed')).toBe(true)
70
+ })
71
+
72
+ it('rejects ED25519 envelopes with missing verification material', async () => {
73
+ const keys = await generateEd25519KeypairBase64Url()
74
+ const signed = await signEnvelopeEd25519(
75
+ createEnvelope({
76
+ sender: 'agent.alpha',
77
+ intent: 'TASK',
78
+ content: 'needs-ed25519-material',
79
+ messageId: 'neg-ed-1',
80
+ nonce: 'neg-ed-n1',
81
+ nowMs: 1000,
82
+ ttlMs: 60_000,
83
+ }),
84
+ keys.privateKey,
85
+ 'ed-k1',
86
+ )
87
+
88
+ const result = await receiveEnvelope(encodeEnvelope(signed, 'compact'), {
89
+ nowMs: 1001,
90
+ replayCache: new InMemoryReplayCache(),
91
+ secretResolver: async () => 'shared-secret',
92
+ })
93
+
94
+ expect(result.ok).toBe(false)
95
+ expect(result.diagnostics.some((d) => d.message.includes('No signature verification material'))).toBe(true)
96
+ })
97
+ })
@@ -0,0 +1,71 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { createEnvelope } from './protocol'
3
+ import { InMemoryReplayCache } from './protocolReplay'
4
+
5
+ describe('InMemoryReplayCache', () => {
6
+ it('rejects replays until ttl expires', () => {
7
+ const cache = new InMemoryReplayCache(100)
8
+ const envelope = createEnvelope({
9
+ sender: 'agent.alpha',
10
+ intent: 'PING',
11
+ content: 'hello',
12
+ messageId: 'r1',
13
+ nonce: 'n1',
14
+ nowMs: 1000,
15
+ ttlMs: 100,
16
+ })
17
+
18
+ expect(cache.consume(envelope, 1001).ok).toBe(true)
19
+ expect(cache.consume(envelope, 1002).ok).toBe(false)
20
+ expect(cache.consume(envelope, 1101).ok).toBe(true)
21
+ })
22
+
23
+ it('evicts by expiry order when capacity is reached', () => {
24
+ const cache = new InMemoryReplayCache(2)
25
+ const first = createEnvelope({
26
+ sender: 'agent.alpha',
27
+ intent: 'PING',
28
+ content: 'one',
29
+ messageId: 'r2-1',
30
+ nonce: 'n1',
31
+ nowMs: 1000,
32
+ ttlMs: 10,
33
+ })
34
+ const second = createEnvelope({
35
+ sender: 'agent.alpha',
36
+ intent: 'PING',
37
+ content: 'two',
38
+ messageId: 'r2-2',
39
+ nonce: 'n2',
40
+ nowMs: 1000,
41
+ ttlMs: 1000,
42
+ })
43
+ const third = createEnvelope({
44
+ sender: 'agent.alpha',
45
+ intent: 'PING',
46
+ content: 'three',
47
+ messageId: 'r2-3',
48
+ nonce: 'n3',
49
+ nowMs: 1000,
50
+ ttlMs: 1000,
51
+ })
52
+
53
+ expect(cache.consume(first, 1001).ok).toBe(true)
54
+ expect(cache.consume(second, 1001).ok).toBe(true)
55
+ expect(cache.consume(third, 1001).ok).toBe(true)
56
+
57
+ // first key should be evicted or expired first; re-consuming at same window should be accepted
58
+ expect(cache.consume(first, 1002).ok).toBe(true)
59
+ })
60
+
61
+ it('bulk consumes envelopes and rejects duplicates in order', () => {
62
+ const cache = new InMemoryReplayCache(100)
63
+ const first = createEnvelope({ sender: 'agent.alpha', intent: 'PING', content: 'one', messageId: 'bulk-1', nonce: 'n1', nowMs: 1000, ttlMs: 1000 })
64
+ const duplicate = createEnvelope({ sender: 'agent.alpha', intent: 'PING', content: 'one-again', messageId: 'bulk-1', nonce: 'n1', nowMs: 1000, ttlMs: 1000 })
65
+ const second = createEnvelope({ sender: 'agent.alpha', intent: 'PING', content: 'two', messageId: 'bulk-2', nonce: 'n2', nowMs: 1000, ttlMs: 1000 })
66
+
67
+ const results = cache.consumeMany([first, duplicate, second], 1001)
68
+
69
+ expect(results.map((result) => result.ok)).toEqual([true, false, true])
70
+ })
71
+ })