@7h3/protocol 0.1.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dockerignore +19 -0
- package/.github/dependabot.yml +32 -0
- package/.github/workflows/ci.yml +31 -0
- package/.github/workflows/publish.yml +59 -0
- package/.github/workflows/scorecard.yml +37 -0
- package/7h3.example.yaml +125 -0
- package/CHANGELOG.md +92 -0
- package/CONTRIBUTING.md +82 -0
- package/Dockerfile +73 -0
- package/GOVERNANCE.md +62 -0
- package/README.md +323 -6
- package/SECURITY.md +70 -0
- package/bench-results/replay-cache-full-1777891033256.json +10 -0
- package/bench-results/replay-cache-full-1777896317488.json +10 -0
- package/bench-results/replay-cache-full-1777900993184.json +10 -0
- package/bench-results/replay-cache-full-1777901019285.json +10 -0
- package/bench-results/replay-cache-quick-1777870170126.json +10 -0
- package/bench-results/signature-profiles-quick-1775875160079.json +85 -0
- package/bench-results/signature-profiles-quick-1775983539716.json +85 -0
- package/bench-results/signature-profiles-quick-1776237913190.json +85 -0
- package/bench-results/wire-codecs-full-1777891019803.json +93 -0
- package/bench-results/wire-codecs-full-1777896260964.json +93 -0
- package/bench-results/wire-codecs-full-1777901004247.json +93 -0
- package/bench-results/wire-codecs-quick-1775972879056.json +93 -0
- package/bench-results/wire-codecs-quick-1775983541111.json +93 -0
- package/bench-results/wire-codecs-quick-1776237914299.json +93 -0
- package/bench-results/wire-codecs-quick-1777841285236.json +93 -0
- package/bench-results/wire-codecs-quick-1777841321772.json +93 -0
- package/bench-results/wire-codecs-quick-1777841330408.json +93 -0
- package/bench-results/wire-codecs-quick-1777852886082.json +93 -0
- package/bench-results/wire-codecs-quick-1777852988773.json +93 -0
- package/bench-results/wire-codecs-quick-1777870188095.json +93 -0
- package/bench-results/wire-codecs-quick-1777870263918.json +93 -0
- package/bench-results/wire-codecs-quick-1777870455034.json +93 -0
- package/bench-results/wire-codecs-quick-1778816163081.json +93 -0
- package/bench-results/wire-codecs-quick-1778843936130.json +93 -0
- package/bin/7h3.ts +385 -0
- package/conformance/7h3_v0_1.json +77 -0
- package/conformance/7h3_v0_1_binary.json +20 -0
- package/conformance/aip_v0_1_binary.json +20 -0
- package/docker-compose.yaml +77 -0
- package/docs/ADOPTION_PLAN.md +120 -0
- package/docs/AGENTS.md +77 -0
- package/docs/AIP_RFC_v0.1.md +97 -0
- package/docs/AI_DECISION_CARD.md +122 -0
- package/docs/AI_RUNTIME_POLICY.json +126 -0
- package/docs/AI_RUNTIME_POLICY.yaml +110 -0
- package/docs/BACKPRESSURE_TUNING.md +65 -0
- package/docs/BENCHMARK_CLAIM_MATRIX.md +42 -0
- package/docs/BENCHMARK_REPORT_TEMPLATE.md +169 -0
- package/docs/BINARY_CODEC_BENCH.md +23 -0
- package/docs/CLEAN_CLONE_RUNBOOK.md +36 -0
- package/docs/CLOCK_SKEW_POLICY.md +30 -0
- package/docs/DISTRIBUTED_REPLAY.md +142 -0
- package/docs/FUZZ_CAMPAIGN.md +121 -0
- package/docs/GATEWAY.md +195 -0
- package/docs/KEY_MANAGEMENT_POLICY.md +53 -0
- package/docs/KEY_REVOCATION.md +69 -0
- package/docs/MCP_WRAPPER.md +159 -0
- package/docs/MIGRATION_GUIDE.md +40 -0
- package/docs/OPERATORS.md +184 -0
- package/docs/PERF_REGRESSION_POLICY.md +34 -0
- package/docs/PROJECT_EXAMINATION_2026-05-31.md +219 -0
- package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +135 -0
- package/docs/RELEASE_GATE.md +25 -0
- package/docs/RELEASE_NOTES_v0.1.0.md +54 -0
- package/docs/SECURITY_REVIEW_2026-06-05.md +165 -0
- package/docs/TELEMETRY.md +41 -0
- package/docs/THREAT_MODEL.md +89 -0
- package/docs/VERSIONING_POLICY.md +30 -0
- package/docs/assets/banner.png +0 -0
- package/eslint.config.js +15 -0
- package/fuzz/ts/harness-decode.ts +136 -0
- package/fuzz/ts/harness-verify.ts +121 -0
- package/fuzz/ts/run.ts +35 -0
- package/mcp-server/README.md +38 -0
- package/mcp-server/package-lock.json +1187 -0
- package/mcp-server/package.json +35 -0
- package/mcp-server/src/index.ts +236 -0
- package/mcp-server/tsconfig.json +14 -0
- package/package.json +79 -13
- package/scripts/aip-framework-quickstart.ts +110 -0
- package/scripts/aip-mcp-gateway.ts +38 -0
- package/scripts/aip-mcp-wrap-demo.ts +72 -0
- package/scripts/aip-quickstart.ts +60 -0
- package/scripts/bench-diff.ts +118 -0
- package/scripts/bench-protocol-e2e.ts +937 -0
- package/scripts/bench-protocol-openloop.ts +1397 -0
- package/scripts/bench-replay-cache.ts +76 -0
- package/scripts/bench-signature-profiles.ts +180 -0
- package/scripts/bench-wire-codecs.ts +161 -0
- package/scripts/build-binary-conformance.ts +36 -0
- package/scripts/build-release-dashboard.ts +175 -0
- package/scripts/canary-rollout.ts +38 -0
- package/scripts/mcpGatewayCli.test.ts +116 -0
- package/scripts/prepare-aip-package.ts +88 -0
- package/scripts/regen-conformance-sigs.ts +18 -0
- package/scripts/release-gate.ts +19 -0
- package/scripts/validate-runtime-policy.ts +18 -0
- package/sdk/browser/index.test.ts +162 -0
- package/sdk/browser/index.ts +257 -0
- package/sdk/browser/package.json +13 -0
- package/sdk/go/go.mod +3 -0
- package/sdk/go/http.go +135 -0
- package/sdk/go/protocol.go +324 -0
- package/sdk/go/protocol_test.go +334 -0
- package/sdk/go/webhook.go +136 -0
- package/sdk/python/README.md +18 -0
- package/sdk/python/protocol_7h3/__init__.py +46 -0
- package/sdk/python/protocol_7h3/http.py +212 -0
- package/sdk/python/protocol_7h3/keys.py +149 -0
- package/sdk/python/protocol_7h3/protocol.py +525 -0
- package/sdk/python/protocol_7h3/queue.py +118 -0
- package/sdk/python/protocol_7h3/webhook.py +116 -0
- package/sdk/python/pyproject.toml +40 -0
- package/sdk/python/tests/test_conformance.py +110 -0
- package/sdk/python/tests/test_http.py +305 -0
- package/sdk/python/tests/test_keys.py +417 -0
- package/sdk/python/tests/test_queue.py +120 -0
- package/sdk/python/tests/test_webhook.py +345 -0
- package/sdk/rust/Cargo.lock +371 -0
- package/sdk/rust/Cargo.toml +25 -0
- package/sdk/rust/README.md +31 -0
- package/sdk/rust/fuzz/Cargo.toml +29 -0
- package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +46 -0
- package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +11 -0
- package/sdk/rust/src/bin/aip_mcp_gateway.rs +59 -0
- package/sdk/rust/src/http.rs +145 -0
- package/sdk/rust/src/keys.rs +161 -0
- package/sdk/rust/src/lib.rs +688 -0
- package/sdk/rust/src/queue.rs +79 -0
- package/sdk/rust/src/webhook.rs +86 -0
- package/sdk/rust/tests/conformance.rs +148 -0
- package/sdk/rust/tests/gateway.rs +130 -0
- package/sdk/rust/tests/http_webhook_queue.rs +201 -0
- package/sdk/rust/tests/keys.rs +189 -0
- package/src/agentAdapter.test.ts +48 -0
- package/src/agentAdapter.ts +56 -0
- package/src/auditLog.test.ts +145 -0
- package/src/auditLog.ts +147 -0
- package/src/conformance.test.ts +136 -0
- package/src/conformanceVectors.ts +99 -0
- package/src/frameworkAdapters.test.ts +290 -0
- package/src/frameworkAdapters.ts +261 -0
- package/src/gateway.test.ts +343 -0
- package/src/gateway.ts +171 -0
- package/src/grpcBinding.test.ts +211 -0
- package/src/grpcBinding.ts +103 -0
- package/src/httpBinding.test.ts +376 -0
- package/src/httpBinding.ts +163 -0
- package/src/index.ts +32 -0
- package/src/keyInfra.test.ts +278 -0
- package/src/keyInfra.ts +228 -0
- package/src/keyRegistry.ts +59 -0
- package/src/keyRotation.test.ts +78 -0
- package/src/keyRotation.ts +72 -0
- package/src/mcpGateway.test.ts +129 -0
- package/src/mcpGateway.ts +250 -0
- package/src/mcpTransports.test.ts +92 -0
- package/src/mcpTransports.ts +169 -0
- package/src/mcpWrapper.test.ts +179 -0
- package/src/mcpWrapper.ts +206 -0
- package/src/policyEnforcer.test.ts +99 -0
- package/src/policyEnforcer.ts +169 -0
- package/src/policyTelemetryFeedback.test.ts +25 -0
- package/src/policyTelemetryFeedback.ts +38 -0
- package/src/protocol.bench.ts +37 -0
- package/src/protocol.test.ts +155 -0
- package/src/protocol.ts +413 -0
- package/src/protocolAgent.test.ts +105 -0
- package/src/protocolAgent.ts +169 -0
- package/src/protocolBinary.test.ts +165 -0
- package/src/protocolBinary.ts +312 -0
- package/src/protocolCapabilities.ts +70 -0
- package/src/protocolFuzz.advanced.test.ts +235 -0
- package/src/protocolFuzz.test.ts +111 -0
- package/src/protocolNegative.test.ts +97 -0
- package/src/protocolReplay.test.ts +71 -0
- package/src/protocolReplay.ts +194 -0
- package/src/protocolTransport.test.ts +556 -0
- package/src/protocolTransport.ts +483 -0
- package/src/queueBinding.test.ts +130 -0
- package/src/queueBinding.ts +102 -0
- package/src/rateLimiter.test.ts +96 -0
- package/src/rateLimiter.ts +46 -0
- package/src/redisClient.ts +140 -0
- package/src/redisIntegration.test.ts +134 -0
- package/src/replayStores.test.ts +141 -0
- package/src/replayStores.ts +82 -0
- package/src/revocation.test.ts +98 -0
- package/src/revocation.ts +0 -0
- package/src/routePolicy.test.ts +87 -0
- package/src/routePolicy.ts +72 -0
- package/src/runtimePolicy.test.ts +49 -0
- package/src/runtimePolicy.ts +81 -0
- package/src/runtimePolicyManager.test.ts +29 -0
- package/src/runtimePolicyManager.ts +50 -0
- package/src/runtimePolicyPresets.ts +43 -0
- package/src/signedResponse.test.ts +111 -0
- package/src/signedResponse.ts +83 -0
- package/src/webhookBinding.test.ts +144 -0
- package/src/webhookBinding.ts +115 -0
- package/src/wsBinding.test.ts +221 -0
- package/src/wsBinding.ts +100 -0
- package/tsconfig.json +15 -0
- package/tsconfig.lib.json +23 -0
- package/vite.lib.config.ts +16 -0
- package/agentAdapter.d.ts +0 -26
- package/conformanceVectors.d.ts +0 -20
- package/frameworkAdapters.d.ts +0 -72
- package/index.d.ts +0 -20
- package/index.js +0 -1702
- package/keyRotation.d.ts +0 -20
- package/mcpGateway.d.ts +0 -37
- package/mcpTransports.d.ts +0 -62
- package/mcpWrapper.d.ts +0 -83
- package/policyEnforcer.d.ts +0 -50
- package/policyTelemetryFeedback.d.ts +0 -11
- package/protocol.d.ts +0 -66
- package/protocolAgent.d.ts +0 -58
- package/protocolBinary.d.ts +0 -8
- package/protocolCapabilities.d.ts +0 -24
- package/protocolReplay.d.ts +0 -35
- package/protocolTransport.d.ts +0 -73
- package/redisClient.d.ts +0 -49
- package/replayStores.d.ts +0 -32
- package/revocation.d.ts +0 -71
- package/runtimePolicy.d.ts +0 -24
- package/runtimePolicyManager.d.ts +0 -15
- package/runtimePolicyPresets.d.ts +0 -11
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { describe, it, expect, beforeAll } from 'vitest'
|
|
2
|
+
import { signResponse, verifyResponse, RESPONSE_HEADER } from './signedResponse'
|
|
3
|
+
import { generateEd25519KeypairBase64Url } from './protocol'
|
|
4
|
+
|
|
5
|
+
let keys: { publicKey: string; privateKey: string }
|
|
6
|
+
let wrongKeys: { publicKey: string; privateKey: string }
|
|
7
|
+
|
|
8
|
+
beforeAll(async () => {
|
|
9
|
+
keys = await generateEd25519KeypairBase64Url()
|
|
10
|
+
wrongKeys = await generateEd25519KeypairBase64Url()
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
describe('signedResponse', () => {
|
|
14
|
+
it('round-trip: signs and verifies correctly', async () => {
|
|
15
|
+
const body = 'hello world'
|
|
16
|
+
const { headers } = await signResponse(body, {
|
|
17
|
+
privateKey: keys.privateKey,
|
|
18
|
+
sender: 'gateway-agent',
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
const result = await verifyResponse(body, headers, { publicKey: keys.publicKey })
|
|
22
|
+
expect(result.ok).toBe(true)
|
|
23
|
+
expect(result.envelope?.body.intent).toBe('RESULT')
|
|
24
|
+
expect(result.envelope?.body.content).toBe(body)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('fails when body does not match envelope content', async () => {
|
|
28
|
+
const body = 'original body'
|
|
29
|
+
const { headers } = await signResponse(body, {
|
|
30
|
+
privateKey: keys.privateKey,
|
|
31
|
+
sender: 'gateway-agent',
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
const result = await verifyResponse('tampered body', headers, { publicKey: keys.publicKey })
|
|
35
|
+
expect(result.ok).toBe(false)
|
|
36
|
+
expect(result.reason).toBe('content-mismatch')
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('fails with wrong public key', async () => {
|
|
40
|
+
const body = 'some content'
|
|
41
|
+
const { headers } = await signResponse(body, {
|
|
42
|
+
privateKey: keys.privateKey,
|
|
43
|
+
sender: 'gateway-agent',
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
const result = await verifyResponse(body, headers, { publicKey: wrongKeys.publicKey })
|
|
47
|
+
expect(result.ok).toBe(false)
|
|
48
|
+
expect(result.reason).toBe('invalid-signature')
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('fails when header is missing', async () => {
|
|
52
|
+
const result = await verifyResponse('body', {}, { publicKey: keys.publicKey })
|
|
53
|
+
expect(result.ok).toBe(false)
|
|
54
|
+
expect(result.reason).toBe('missing-header')
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('fails when envelope TTL is expired', async () => {
|
|
58
|
+
// Sign with 1ms ttl — immediately expired
|
|
59
|
+
const body = 'ttl-test'
|
|
60
|
+
const { headers } = await signResponse(body, {
|
|
61
|
+
privateKey: keys.privateKey,
|
|
62
|
+
sender: 'gateway-agent',
|
|
63
|
+
ttlMs: 1,
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
// Wait a tick to ensure expiry
|
|
67
|
+
await new Promise(r => setTimeout(r, 10))
|
|
68
|
+
|
|
69
|
+
const result = await verifyResponse(body, headers, { publicKey: keys.publicKey })
|
|
70
|
+
expect(result.ok).toBe(false)
|
|
71
|
+
expect(result.reason).toBe('ttl-expired')
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('fails when maxAgeMs exceeded', async () => {
|
|
75
|
+
const body = 'max-age-test'
|
|
76
|
+
const { headers } = await signResponse(body, {
|
|
77
|
+
privateKey: keys.privateKey,
|
|
78
|
+
sender: 'gateway-agent',
|
|
79
|
+
ttlMs: 60_000, // long ttl
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
// Wait to ensure age exceeds maxAgeMs
|
|
83
|
+
await new Promise(r => setTimeout(r, 10))
|
|
84
|
+
|
|
85
|
+
const result = await verifyResponse(body, headers, {
|
|
86
|
+
publicKey: keys.publicKey,
|
|
87
|
+
maxAgeMs: 1, // tiny window
|
|
88
|
+
})
|
|
89
|
+
expect(result.ok).toBe(false)
|
|
90
|
+
expect(result.reason).toBe('ttl-expired')
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it('passes correlationId and recipient through envelope', async () => {
|
|
94
|
+
const body = 'corr-test'
|
|
95
|
+
const { headers } = await signResponse(body, {
|
|
96
|
+
privateKey: keys.privateKey,
|
|
97
|
+
sender: 'gateway-agent',
|
|
98
|
+
recipient: 'client-agent',
|
|
99
|
+
correlationId: 'req-123',
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
const result = await verifyResponse(body, headers, { publicKey: keys.publicKey })
|
|
103
|
+
expect(result.ok).toBe(true)
|
|
104
|
+
expect(result.envelope?.body.correlationId).toBe('req-123')
|
|
105
|
+
expect(result.envelope?.header.recipient).toBe('client-agent')
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it('RESPONSE_HEADER constant is x-7h3-response', () => {
|
|
109
|
+
expect(RESPONSE_HEADER).toBe('x-7h3-response')
|
|
110
|
+
})
|
|
111
|
+
})
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createEnvelope,
|
|
3
|
+
signEnvelopeEd25519,
|
|
4
|
+
verifyEnvelopeEd25519,
|
|
5
|
+
type ProtocolEnvelope,
|
|
6
|
+
} from './protocol'
|
|
7
|
+
|
|
8
|
+
export const RESPONSE_HEADER = 'x-7h3-response'
|
|
9
|
+
|
|
10
|
+
export async function signResponse(
|
|
11
|
+
body: string,
|
|
12
|
+
opts: {
|
|
13
|
+
privateKey: string
|
|
14
|
+
sender: string
|
|
15
|
+
recipient?: string
|
|
16
|
+
correlationId?: string
|
|
17
|
+
ttlMs?: number
|
|
18
|
+
},
|
|
19
|
+
): Promise<{ headers: { 'x-7h3-response': string } }> {
|
|
20
|
+
const envelope = createEnvelope({
|
|
21
|
+
sender: opts.sender,
|
|
22
|
+
recipient: opts.recipient,
|
|
23
|
+
intent: 'RESULT',
|
|
24
|
+
content: body,
|
|
25
|
+
correlationId: opts.correlationId,
|
|
26
|
+
ttlMs: opts.ttlMs ?? 60_000,
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
const signed = await signEnvelopeEd25519(envelope, opts.privateKey)
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
headers: {
|
|
33
|
+
[RESPONSE_HEADER]: JSON.stringify(signed),
|
|
34
|
+
},
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function verifyResponse(
|
|
39
|
+
body: string,
|
|
40
|
+
headers: Record<string, string | string[] | undefined>,
|
|
41
|
+
opts: {
|
|
42
|
+
publicKey: string
|
|
43
|
+
maxAgeMs?: number
|
|
44
|
+
},
|
|
45
|
+
): Promise<{ ok: boolean; envelope?: ProtocolEnvelope; reason?: string }> {
|
|
46
|
+
const raw = headers[RESPONSE_HEADER]
|
|
47
|
+
const rawStr = Array.isArray(raw) ? raw[0] : raw
|
|
48
|
+
if (!rawStr) {
|
|
49
|
+
return { ok: false, reason: 'missing-header' }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let envelope: ProtocolEnvelope
|
|
53
|
+
try {
|
|
54
|
+
envelope = JSON.parse(rawStr) as ProtocolEnvelope
|
|
55
|
+
} catch {
|
|
56
|
+
return { ok: false, reason: 'malformed-envelope' }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Check TTL from envelope
|
|
60
|
+
const nowMs = Date.now()
|
|
61
|
+
const { timestampMs, ttlMs } = envelope.header
|
|
62
|
+
if (timestampMs + ttlMs < nowMs) {
|
|
63
|
+
return { ok: false, reason: 'ttl-expired', envelope }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Check maxAgeMs if provided
|
|
67
|
+
if (opts.maxAgeMs !== undefined && nowMs - timestampMs > opts.maxAgeMs) {
|
|
68
|
+
return { ok: false, reason: 'ttl-expired', envelope }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Verify signature
|
|
72
|
+
const valid = await verifyEnvelopeEd25519(envelope, opts.publicKey)
|
|
73
|
+
if (!valid) {
|
|
74
|
+
return { ok: false, reason: 'invalid-signature', envelope }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Verify body matches envelope content
|
|
78
|
+
if (envelope.body.content !== body) {
|
|
79
|
+
return { ok: false, reason: 'content-mismatch', envelope }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { ok: true, envelope }
|
|
83
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
signWebhook,
|
|
4
|
+
verifyWebhook,
|
|
5
|
+
signWebhookHmac,
|
|
6
|
+
verifyWebhookHmac,
|
|
7
|
+
consumeWebhook,
|
|
8
|
+
generateEd25519KeypairBase64Url,
|
|
9
|
+
WEBHOOK_SIG_HEADER,
|
|
10
|
+
WEBHOOK_TS_HEADER,
|
|
11
|
+
} from './webhookBinding'
|
|
12
|
+
|
|
13
|
+
describe('webhookBinding', () => {
|
|
14
|
+
// 1. Ed25519 sign + verify round trip
|
|
15
|
+
it('signWebhook + verifyWebhook round trip (Ed25519)', async () => {
|
|
16
|
+
const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
|
|
17
|
+
const payload = JSON.stringify({ event: 'user.created', userId: '123' })
|
|
18
|
+
const headers = await signWebhook(payload, { privateKey })
|
|
19
|
+
const valid = await verifyWebhook(payload, headers, { publicKey })
|
|
20
|
+
expect(valid).toBe(true)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
// 2. HMAC sign + verify round trip
|
|
24
|
+
it('signWebhookHmac + verifyWebhookHmac round trip', async () => {
|
|
25
|
+
const secret = 'super-secret-webhook-key'
|
|
26
|
+
const payload = JSON.stringify({ event: 'order.paid', orderId: 'abc' })
|
|
27
|
+
const headers = await signWebhookHmac(payload, { secret })
|
|
28
|
+
const valid = await verifyWebhookHmac(payload, headers, { secret })
|
|
29
|
+
expect(valid).toBe(true)
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
// 3. Tampered payload returns false (Ed25519)
|
|
33
|
+
it('tampered payload returns false (Ed25519)', async () => {
|
|
34
|
+
const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
|
|
35
|
+
const payload = JSON.stringify({ event: 'user.created', userId: '123' })
|
|
36
|
+
const headers = await signWebhook(payload, { privateKey })
|
|
37
|
+
const tamperedPayload = JSON.stringify({ event: 'user.created', userId: '999' })
|
|
38
|
+
const valid = await verifyWebhook(tamperedPayload, headers, { publicKey })
|
|
39
|
+
expect(valid).toBe(false)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
// 3b. Tampered payload returns false (HMAC)
|
|
43
|
+
it('tampered payload returns false (HMAC)', async () => {
|
|
44
|
+
const secret = 'super-secret-webhook-key'
|
|
45
|
+
const payload = JSON.stringify({ event: 'order.paid', orderId: 'abc' })
|
|
46
|
+
const headers = await signWebhookHmac(payload, { secret })
|
|
47
|
+
const tamperedPayload = JSON.stringify({ event: 'order.paid', orderId: 'TAMPERED' })
|
|
48
|
+
const valid = await verifyWebhookHmac(tamperedPayload, headers, { secret })
|
|
49
|
+
expect(valid).toBe(false)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
// 4. Expired timestamp returns false
|
|
53
|
+
it('expired timestamp returns false', async () => {
|
|
54
|
+
const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
|
|
55
|
+
const payload = JSON.stringify({ event: 'ping' })
|
|
56
|
+
const headers = await signWebhook(payload, { privateKey })
|
|
57
|
+
// Backdate the timestamp to be 10 minutes ago
|
|
58
|
+
const expiredHeaders = {
|
|
59
|
+
...headers,
|
|
60
|
+
[WEBHOOK_TS_HEADER]: String(Date.now() - 10 * 60 * 1000),
|
|
61
|
+
}
|
|
62
|
+
const valid = await verifyWebhook(payload, expiredHeaders, { publicKey, maxAgeMs: 300_000 })
|
|
63
|
+
expect(valid).toBe(false)
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
// 5. Wrong key returns false
|
|
67
|
+
it('wrong public key returns false', async () => {
|
|
68
|
+
const { privateKey } = await generateEd25519KeypairBase64Url()
|
|
69
|
+
const { publicKey: wrongPublicKey } = await generateEd25519KeypairBase64Url()
|
|
70
|
+
const payload = JSON.stringify({ event: 'test' })
|
|
71
|
+
const headers = await signWebhook(payload, { privateKey })
|
|
72
|
+
const valid = await verifyWebhook(payload, headers, { publicKey: wrongPublicKey })
|
|
73
|
+
expect(valid).toBe(false)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
// 5b. Wrong HMAC secret returns false
|
|
77
|
+
it('wrong HMAC secret returns false', async () => {
|
|
78
|
+
const secret = 'correct-secret'
|
|
79
|
+
const payload = JSON.stringify({ event: 'test' })
|
|
80
|
+
const headers = await signWebhookHmac(payload, { secret })
|
|
81
|
+
const valid = await verifyWebhookHmac(payload, headers, { secret: 'wrong-secret' })
|
|
82
|
+
expect(valid).toBe(false)
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
// 6. consumeWebhook parses valid payload
|
|
86
|
+
it('consumeWebhook parses valid payload and returns parsed object', async () => {
|
|
87
|
+
const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
|
|
88
|
+
const data = { event: 'invoice.paid', amount: 9900, currency: 'usd' }
|
|
89
|
+
const payload = JSON.stringify(data)
|
|
90
|
+
const headers = await signWebhook(payload, { privateKey })
|
|
91
|
+
const result = await consumeWebhook<typeof data>(payload, headers as Record<string, string>, { publicKey })
|
|
92
|
+
expect(result).toEqual(data)
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
// 7. consumeWebhook throws on invalid signature
|
|
96
|
+
it('consumeWebhook throws on invalid signature', async () => {
|
|
97
|
+
const { privateKey } = await generateEd25519KeypairBase64Url()
|
|
98
|
+
const { publicKey: wrongPublicKey } = await generateEd25519KeypairBase64Url()
|
|
99
|
+
const payload = JSON.stringify({ event: 'invoice.paid' })
|
|
100
|
+
const headers = await signWebhook(payload, { privateKey })
|
|
101
|
+
await expect(
|
|
102
|
+
consumeWebhook(payload, headers as Record<string, string>, { publicKey: wrongPublicKey })
|
|
103
|
+
).rejects.toThrow('7h3: webhook signature verification failed')
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
// 7b. consumeWebhook throws on expired timestamp
|
|
107
|
+
it('consumeWebhook throws on expired timestamp', async () => {
|
|
108
|
+
const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
|
|
109
|
+
const payload = JSON.stringify({ event: 'test' })
|
|
110
|
+
const headers = await signWebhook(payload, { privateKey })
|
|
111
|
+
const expiredHeaders = {
|
|
112
|
+
...headers,
|
|
113
|
+
[WEBHOOK_TS_HEADER]: String(Date.now() - 10 * 60 * 1000),
|
|
114
|
+
}
|
|
115
|
+
await expect(
|
|
116
|
+
consumeWebhook(payload, expiredHeaders as Record<string, string>, { publicKey, maxAgeMs: 300_000 })
|
|
117
|
+
).rejects.toThrow('7h3: webhook signature verification failed')
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
// Edge: missing headers return false
|
|
121
|
+
it('missing sig header returns false', async () => {
|
|
122
|
+
const { publicKey } = await generateEd25519KeypairBase64Url()
|
|
123
|
+
const payload = 'hello'
|
|
124
|
+
const valid = await verifyWebhook(payload, { [WEBHOOK_TS_HEADER]: String(Date.now()) } as Record<string, string>, { publicKey })
|
|
125
|
+
expect(valid).toBe(false)
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
it('missing ts header returns false', async () => {
|
|
129
|
+
const { publicKey } = await generateEd25519KeypairBase64Url()
|
|
130
|
+
const payload = 'hello'
|
|
131
|
+
const valid = await verifyWebhook(payload, { [WEBHOOK_SIG_HEADER]: 'fakesig' } as Record<string, string>, { publicKey })
|
|
132
|
+
expect(valid).toBe(false)
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
// Uint8Array payload works (Ed25519)
|
|
136
|
+
it('Uint8Array payload signs and verifies (Ed25519)', async () => {
|
|
137
|
+
const { privateKey, publicKey } = await generateEd25519KeypairBase64Url()
|
|
138
|
+
const payloadStr = JSON.stringify({ binary: true })
|
|
139
|
+
const payloadBytes = new TextEncoder().encode(payloadStr)
|
|
140
|
+
const headers = await signWebhook(payloadBytes, { privateKey })
|
|
141
|
+
const valid = await verifyWebhook(payloadBytes, headers, { publicKey })
|
|
142
|
+
expect(valid).toBe(true)
|
|
143
|
+
})
|
|
144
|
+
})
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import {
|
|
2
|
+
signCanonicalPayloadEd25519,
|
|
3
|
+
verifyCanonicalPayloadEd25519,
|
|
4
|
+
signCanonicalPayloadHmac,
|
|
5
|
+
verifyCanonicalPayloadHmac,
|
|
6
|
+
generateEd25519KeypairBase64Url,
|
|
7
|
+
} from './protocol'
|
|
8
|
+
|
|
9
|
+
export const WEBHOOK_SIG_HEADER = 'x-7h3-sig'
|
|
10
|
+
export const WEBHOOK_TS_HEADER = 'x-7h3-ts'
|
|
11
|
+
export const WEBHOOK_DEFAULT_TTL_MS = 300_000 // 5 minutes
|
|
12
|
+
|
|
13
|
+
// What gets signed: "${timestampMs}.${rawBody}" — binds time AND content
|
|
14
|
+
function webhookSigningPayload(timestampMs: number, body: string): string {
|
|
15
|
+
return `${timestampMs}.${body}`
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface WebhookSignOptions {
|
|
19
|
+
privateKey: string // Ed25519 PKCS8 base64url
|
|
20
|
+
ttlMs?: number // default 5 min
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface WebhookSignHmacOptions {
|
|
24
|
+
secret: string
|
|
25
|
+
ttlMs?: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface WebhookVerifyOptions {
|
|
29
|
+
publicKey: string // Ed25519 SPKI base64url
|
|
30
|
+
maxAgeMs?: number // default 5 min
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface WebhookVerifyHmacOptions {
|
|
34
|
+
secret: string
|
|
35
|
+
maxAgeMs?: number
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface WebhookHeaders {
|
|
39
|
+
[WEBHOOK_SIG_HEADER]: string
|
|
40
|
+
[WEBHOOK_TS_HEADER]: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Sign a webhook payload with Ed25519
|
|
44
|
+
export async function signWebhook(
|
|
45
|
+
payload: string | Uint8Array,
|
|
46
|
+
opts: WebhookSignOptions
|
|
47
|
+
): Promise<WebhookHeaders> {
|
|
48
|
+
const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload)
|
|
49
|
+
const timestampMs = Date.now()
|
|
50
|
+
const signingPayload = webhookSigningPayload(timestampMs, body)
|
|
51
|
+
const sig = await signCanonicalPayloadEd25519(signingPayload, opts.privateKey)
|
|
52
|
+
return { [WEBHOOK_SIG_HEADER]: sig, [WEBHOOK_TS_HEADER]: String(timestampMs) }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Sign with HMAC shared secret
|
|
56
|
+
export async function signWebhookHmac(
|
|
57
|
+
payload: string | Uint8Array,
|
|
58
|
+
opts: WebhookSignHmacOptions
|
|
59
|
+
): Promise<WebhookHeaders> {
|
|
60
|
+
const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload)
|
|
61
|
+
const timestampMs = Date.now()
|
|
62
|
+
const signingPayload = webhookSigningPayload(timestampMs, body)
|
|
63
|
+
const sig = await signCanonicalPayloadHmac(signingPayload, opts.secret)
|
|
64
|
+
return { [WEBHOOK_SIG_HEADER]: sig, [WEBHOOK_TS_HEADER]: String(timestampMs) }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Verify Ed25519 webhook signature
|
|
68
|
+
export async function verifyWebhook(
|
|
69
|
+
payload: string | Uint8Array,
|
|
70
|
+
headers: WebhookHeaders | Record<string, string>,
|
|
71
|
+
opts: WebhookVerifyOptions
|
|
72
|
+
): Promise<boolean> {
|
|
73
|
+
const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload)
|
|
74
|
+
const sig = headers[WEBHOOK_SIG_HEADER]
|
|
75
|
+
const tsStr = headers[WEBHOOK_TS_HEADER]
|
|
76
|
+
if (!sig || !tsStr) return false
|
|
77
|
+
const ts = Number(tsStr)
|
|
78
|
+
if (!Number.isFinite(ts)) return false
|
|
79
|
+
const maxAge = opts.maxAgeMs ?? WEBHOOK_DEFAULT_TTL_MS
|
|
80
|
+
if (Date.now() - ts > maxAge) return false
|
|
81
|
+
const signingPayload = webhookSigningPayload(ts, body)
|
|
82
|
+
return verifyCanonicalPayloadEd25519(signingPayload, sig, opts.publicKey)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Verify HMAC webhook signature
|
|
86
|
+
export async function verifyWebhookHmac(
|
|
87
|
+
payload: string | Uint8Array,
|
|
88
|
+
headers: WebhookHeaders | Record<string, string>,
|
|
89
|
+
opts: WebhookVerifyHmacOptions
|
|
90
|
+
): Promise<boolean> {
|
|
91
|
+
const body = typeof payload === 'string' ? payload : new TextDecoder().decode(payload)
|
|
92
|
+
const sig = headers[WEBHOOK_SIG_HEADER]
|
|
93
|
+
const tsStr = headers[WEBHOOK_TS_HEADER]
|
|
94
|
+
if (!sig || !tsStr) return false
|
|
95
|
+
const ts = Number(tsStr)
|
|
96
|
+
if (!Number.isFinite(ts)) return false
|
|
97
|
+
const maxAge = opts.maxAgeMs ?? WEBHOOK_DEFAULT_TTL_MS
|
|
98
|
+
if (Date.now() - ts > maxAge) return false
|
|
99
|
+
const signingPayload = webhookSigningPayload(ts, body)
|
|
100
|
+
return verifyCanonicalPayloadHmac(signingPayload, sig, opts.secret)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Parse and verify in one call, throws on failure
|
|
104
|
+
export async function consumeWebhook<T = unknown>(
|
|
105
|
+
payload: string,
|
|
106
|
+
headers: Record<string, string>,
|
|
107
|
+
opts: WebhookVerifyOptions
|
|
108
|
+
): Promise<T> {
|
|
109
|
+
const valid = await verifyWebhook(payload, headers, opts)
|
|
110
|
+
if (!valid) throw new Error('7h3: webhook signature verification failed')
|
|
111
|
+
return JSON.parse(payload) as T
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Re-export key generation for convenience
|
|
115
|
+
export { generateEd25519KeypairBase64Url }
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { wrapWebSocket, generateEd25519KeypairBase64Url, type WebSocketLike } from './wsBinding'
|
|
3
|
+
import { signEnvelopeEd25519, createEnvelope, type ProtocolEnvelope } from './protocol'
|
|
4
|
+
import { createStaticKeyRegistry } from './keyRegistry'
|
|
5
|
+
|
|
6
|
+
// Mock WebSocket class that buffers sent messages and lets you inject received messages
|
|
7
|
+
class MockWebSocket implements WebSocketLike {
|
|
8
|
+
public sent: string[] = []
|
|
9
|
+
private messageHandlers: Array<(e: { data: string }) => void> = []
|
|
10
|
+
private closeHandlers: Array<() => void> = []
|
|
11
|
+
readyState = 1
|
|
12
|
+
|
|
13
|
+
send(data: string): void {
|
|
14
|
+
this.sent.push(data)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
addEventListener(event: string, handler: (...args: any[]) => void): void {
|
|
18
|
+
if (event === 'message') {
|
|
19
|
+
this.messageHandlers.push(handler as (e: { data: string }) => void)
|
|
20
|
+
} else if (event === 'close') {
|
|
21
|
+
this.closeHandlers.push(handler as () => void)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
removeEventListener(event: string, handler: (...args: unknown[]) => void): void {
|
|
26
|
+
if (event === 'message') {
|
|
27
|
+
const idx = this.messageHandlers.indexOf(handler as any)
|
|
28
|
+
if (idx !== -1) this.messageHandlers.splice(idx, 1)
|
|
29
|
+
} else if (event === 'close') {
|
|
30
|
+
const idx = this.closeHandlers.indexOf(handler as any)
|
|
31
|
+
if (idx !== -1) this.closeHandlers.splice(idx, 1)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Inject a received message
|
|
36
|
+
receive(data: string): void {
|
|
37
|
+
for (const h of this.messageHandlers) h({ data })
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
close(): void {
|
|
41
|
+
for (const h of this.closeHandlers) h()
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
describe('wrapWebSocket', () => {
|
|
46
|
+
it('send() produces a signed JSON frame', async () => {
|
|
47
|
+
const keypair = await generateEd25519KeypairBase64Url()
|
|
48
|
+
const ws = new MockWebSocket()
|
|
49
|
+
const registry = createStaticKeyRegistry({ 'agent-A': keypair.publicKey })
|
|
50
|
+
|
|
51
|
+
const pws = wrapWebSocket(ws, {
|
|
52
|
+
privateKey: keypair.privateKey,
|
|
53
|
+
sender: 'agent-A',
|
|
54
|
+
keyRegistry: registry,
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
await pws.send({ hello: 'world' })
|
|
58
|
+
|
|
59
|
+
expect(ws.sent).toHaveLength(1)
|
|
60
|
+
const frame = JSON.parse(ws.sent[0]) as ProtocolEnvelope
|
|
61
|
+
expect(frame.header.sender).toBe('agent-A')
|
|
62
|
+
expect(frame.signature).toBeDefined()
|
|
63
|
+
expect(frame.signature?.alg).toBe('ED25519')
|
|
64
|
+
expect(frame.body.intent).toBe('TASK')
|
|
65
|
+
expect(frame.body.content).toBe(JSON.stringify({ hello: 'world' }))
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('incoming signed frame calls onMessage handler', async () => {
|
|
69
|
+
const keypair = await generateEd25519KeypairBase64Url()
|
|
70
|
+
const ws = new MockWebSocket()
|
|
71
|
+
const registry = createStaticKeyRegistry({ 'agent-B': keypair.publicKey })
|
|
72
|
+
|
|
73
|
+
const pws = wrapWebSocket(ws, {
|
|
74
|
+
privateKey: keypair.privateKey,
|
|
75
|
+
sender: 'agent-A',
|
|
76
|
+
keyRegistry: registry,
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
const received: Array<{ payload: unknown; envelope: ProtocolEnvelope }> = []
|
|
80
|
+
pws.onMessage((payload, envelope) => received.push({ payload, envelope }))
|
|
81
|
+
|
|
82
|
+
// Create a valid signed frame from agent-B
|
|
83
|
+
const envelope = createEnvelope({
|
|
84
|
+
sender: 'agent-B',
|
|
85
|
+
intent: 'TASK',
|
|
86
|
+
content: JSON.stringify({ ping: true }),
|
|
87
|
+
ttlMs: 30_000,
|
|
88
|
+
})
|
|
89
|
+
const signed = await signEnvelopeEd25519(envelope, keypair.privateKey)
|
|
90
|
+
|
|
91
|
+
// Wait for async message processing
|
|
92
|
+
await new Promise<void>(resolve => {
|
|
93
|
+
pws.onMessage(() => resolve())
|
|
94
|
+
ws.receive(JSON.stringify(signed))
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
expect(received).toHaveLength(1)
|
|
98
|
+
expect(received[0].payload).toEqual({ ping: true })
|
|
99
|
+
expect(received[0].envelope.header.sender).toBe('agent-B')
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it('tampered frame calls onVerifyFail', async () => {
|
|
103
|
+
const keypair = await generateEd25519KeypairBase64Url()
|
|
104
|
+
const ws = new MockWebSocket()
|
|
105
|
+
const registry = createStaticKeyRegistry({ 'agent-B': keypair.publicKey })
|
|
106
|
+
|
|
107
|
+
const pws = wrapWebSocket(ws, {
|
|
108
|
+
privateKey: keypair.privateKey,
|
|
109
|
+
sender: 'agent-A',
|
|
110
|
+
keyRegistry: registry,
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
const errors: Error[] = []
|
|
114
|
+
pws.onVerifyFail((err) => errors.push(err))
|
|
115
|
+
|
|
116
|
+
// Create a valid signed frame, then tamper with body content
|
|
117
|
+
const envelope = createEnvelope({
|
|
118
|
+
sender: 'agent-B',
|
|
119
|
+
intent: 'TASK',
|
|
120
|
+
content: 'original content',
|
|
121
|
+
ttlMs: 30_000,
|
|
122
|
+
})
|
|
123
|
+
const signed = await signEnvelopeEd25519(envelope, keypair.privateKey)
|
|
124
|
+
// Tamper with content after signing
|
|
125
|
+
const tampered = { ...signed, body: { ...signed.body, content: 'tampered content' } }
|
|
126
|
+
|
|
127
|
+
await new Promise<void>(resolve => {
|
|
128
|
+
pws.onVerifyFail(() => resolve())
|
|
129
|
+
ws.receive(JSON.stringify(tampered))
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
expect(errors).toHaveLength(1)
|
|
133
|
+
expect(errors[0].message).toContain('invalid signature')
|
|
134
|
+
})
|
|
135
|
+
|
|
136
|
+
it('unknown sender calls onVerifyFail', async () => {
|
|
137
|
+
const keypair = await generateEd25519KeypairBase64Url()
|
|
138
|
+
const ws = new MockWebSocket()
|
|
139
|
+
// Registry has no entry for 'unknown-agent'
|
|
140
|
+
const registry = createStaticKeyRegistry({})
|
|
141
|
+
|
|
142
|
+
const pws = wrapWebSocket(ws, {
|
|
143
|
+
privateKey: keypair.privateKey,
|
|
144
|
+
sender: 'agent-A',
|
|
145
|
+
keyRegistry: registry,
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
const errors: Error[] = []
|
|
149
|
+
pws.onVerifyFail((err) => errors.push(err))
|
|
150
|
+
|
|
151
|
+
const envelope = createEnvelope({
|
|
152
|
+
sender: 'unknown-agent',
|
|
153
|
+
intent: 'TASK',
|
|
154
|
+
content: 'hello',
|
|
155
|
+
ttlMs: 30_000,
|
|
156
|
+
})
|
|
157
|
+
const signed = await signEnvelopeEd25519(envelope, keypair.privateKey)
|
|
158
|
+
|
|
159
|
+
await new Promise<void>(resolve => {
|
|
160
|
+
pws.onVerifyFail(() => resolve())
|
|
161
|
+
ws.receive(JSON.stringify(signed))
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
expect(errors).toHaveLength(1)
|
|
165
|
+
expect(errors[0].message).toContain('unknown sender')
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
it('malformed JSON calls onVerifyFail', async () => {
|
|
169
|
+
const keypair = await generateEd25519KeypairBase64Url()
|
|
170
|
+
const ws = new MockWebSocket()
|
|
171
|
+
const registry = createStaticKeyRegistry({})
|
|
172
|
+
|
|
173
|
+
const pws = wrapWebSocket(ws, {
|
|
174
|
+
privateKey: keypair.privateKey,
|
|
175
|
+
sender: 'agent-A',
|
|
176
|
+
keyRegistry: registry,
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
const errors: Error[] = []
|
|
180
|
+
pws.onVerifyFail((err) => errors.push(err))
|
|
181
|
+
|
|
182
|
+
await new Promise<void>(resolve => {
|
|
183
|
+
pws.onVerifyFail(() => resolve())
|
|
184
|
+
ws.receive('this is not valid JSON {{{')
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
expect(errors).toHaveLength(1)
|
|
188
|
+
expect(errors[0].message).toContain('malformed frame')
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
it('seq increments on each send', async () => {
|
|
192
|
+
const keypair = await generateEd25519KeypairBase64Url()
|
|
193
|
+
const ws = new MockWebSocket()
|
|
194
|
+
const registry = createStaticKeyRegistry({ 'agent-A': keypair.publicKey })
|
|
195
|
+
|
|
196
|
+
const pws = wrapWebSocket(ws, {
|
|
197
|
+
privateKey: keypair.privateKey,
|
|
198
|
+
sender: 'agent-A',
|
|
199
|
+
keyRegistry: registry,
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
expect(pws.seq).toBe(0)
|
|
203
|
+
|
|
204
|
+
await pws.send('first')
|
|
205
|
+
expect(pws.seq).toBe(1)
|
|
206
|
+
|
|
207
|
+
await pws.send('second')
|
|
208
|
+
expect(pws.seq).toBe(2)
|
|
209
|
+
|
|
210
|
+
await pws.send('third')
|
|
211
|
+
expect(pws.seq).toBe(3)
|
|
212
|
+
|
|
213
|
+
// Verify correlationId carries the seq number
|
|
214
|
+
const frame1 = JSON.parse(ws.sent[0]) as ProtocolEnvelope
|
|
215
|
+
const frame2 = JSON.parse(ws.sent[1]) as ProtocolEnvelope
|
|
216
|
+
const frame3 = JSON.parse(ws.sent[2]) as ProtocolEnvelope
|
|
217
|
+
expect(frame1.body.correlationId).toBe('1')
|
|
218
|
+
expect(frame2.body.correlationId).toBe('2')
|
|
219
|
+
expect(frame3.body.correlationId).toBe('3')
|
|
220
|
+
})
|
|
221
|
+
})
|