@7h3/protocol 0.4.0 → 0.5.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 (63) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +1169 -175
  3. package/bin/7h3.ts +22 -1
  4. package/docs/assets/banner-github.png +0 -0
  5. package/docs/assets/banner.svg +123 -0
  6. package/package.json +55 -13
  7. package/sdk/browser/package.json +1 -1
  8. package/sdk/go/cbor.go +551 -0
  9. package/sdk/go/cbor_test.go +232 -0
  10. package/sdk/go/encryption.go +280 -0
  11. package/sdk/go/encryption_test.go +318 -0
  12. package/sdk/go/go.mod +5 -1
  13. package/sdk/go/go.sum +4 -0
  14. package/sdk/go/replay.go +121 -0
  15. package/sdk/go/replay_test.go +149 -0
  16. package/sdk/pq/package-lock.json +1358 -0
  17. package/sdk/pq/package.json +42 -0
  18. package/sdk/pq/src/index.test.ts +143 -0
  19. package/sdk/pq/src/index.ts +166 -0
  20. package/sdk/pq/tsconfig.json +14 -0
  21. package/sdk/pq/vitest.config.ts +7 -0
  22. package/sdk/python/protocol_7h3/encryption.py +252 -0
  23. package/sdk/python/protocol_7h3/pq.py +244 -0
  24. package/sdk/python/protocol_7h3/replay.py +98 -0
  25. package/sdk/python/pyproject.toml +1 -1
  26. package/sdk/python/tests/test_encryption.py +206 -0
  27. package/sdk/rust/Cargo.lock +1 -1
  28. package/sdk/rust/Cargo.toml +1 -1
  29. package/sdk/threshold/index.d.ts +68 -0
  30. package/sdk/threshold/index.d.ts.map +1 -0
  31. package/sdk/threshold/index.js +254 -0
  32. package/sdk/threshold/package-lock.json +1361 -0
  33. package/sdk/threshold/package.json +39 -0
  34. package/sdk/threshold/src/index.d.ts +68 -0
  35. package/sdk/threshold/src/index.d.ts.map +1 -0
  36. package/sdk/threshold/src/index.js +254 -0
  37. package/sdk/threshold/src/index.test.ts +238 -0
  38. package/sdk/threshold/src/index.ts +355 -0
  39. package/sdk/threshold/tsconfig.json +19 -0
  40. package/sdk/threshold/vitest.config.ts +12 -0
  41. package/src/capability.test.ts +504 -0
  42. package/src/capability.ts +380 -0
  43. package/src/cborCodec.test.ts +263 -0
  44. package/src/cborCodec.ts +339 -0
  45. package/src/encryption.test.ts +206 -0
  46. package/src/encryption.ts +245 -0
  47. package/src/envelopeCbor.ts +140 -0
  48. package/src/gateway.ts +75 -0
  49. package/src/httpBinding.ts +37 -11
  50. package/src/index.ts +7 -0
  51. package/src/otel.ts +136 -0
  52. package/src/protocol.d.ts +67 -0
  53. package/src/protocol.d.ts.map +1 -0
  54. package/src/protocol.js +294 -0
  55. package/src/protocol.ts +1 -0
  56. package/src/replayStores.test.ts +133 -1
  57. package/src/replayStores.ts +136 -3
  58. package/src/stream.test.ts +254 -0
  59. package/src/stream.ts +417 -0
  60. package/src/telemetry.test.ts +251 -0
  61. package/src/telemetry.ts +299 -0
  62. package/src/wsBinding.ts +100 -0
  63. package/vitest.config.ts +11 -0
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Minimal deterministic CBOR encoder/decoder — zero external dependencies.
3
+ * Follows RFC 8949 §4.2 deterministic encoding:
4
+ * - Shortest-length integers
5
+ * - Map keys sorted by lexicographic byte order of encoded key
6
+ */
7
+
8
+ const textEncoder = new TextEncoder()
9
+ const textDecoder = new TextDecoder()
10
+
11
+ // CBOR major types
12
+ const MT_UINT = 0 // major type 0: unsigned int
13
+ const MT_NINT = 1 // major type 1: negative int
14
+ const MT_BSTR = 2 // major type 2: byte string
15
+ const MT_TSTR = 3 // major type 3: text string
16
+ const MT_ARRAY = 4 // major type 4: array
17
+ const MT_MAP = 5 // major type 5: map
18
+ const MT_SIMPLE = 7 // major type 7: simple/float
19
+
20
+ const SIMPLE_FALSE = 0xf4
21
+ const SIMPLE_TRUE = 0xf5
22
+ const SIMPLE_NULL = 0xf6
23
+
24
+ // Additional info thresholds
25
+ const AI_1BYTE = 24
26
+ const AI_2BYTE = 25
27
+ const AI_4BYTE = 26
28
+ const AI_8BYTE = 27
29
+
30
+ // float64 additional info
31
+ const AI_FLOAT64 = 27
32
+
33
+ export class CborEncoder {
34
+ private chunks: Uint8Array[] = []
35
+
36
+ encode(value: unknown): Uint8Array {
37
+ this.chunks = []
38
+ this._encode(value)
39
+ return this._concat()
40
+ }
41
+
42
+ private _encode(value: unknown): void {
43
+ if (value === null || value === undefined) {
44
+ this.chunks.push(new Uint8Array([SIMPLE_NULL]))
45
+ return
46
+ }
47
+ if (typeof value === 'boolean') {
48
+ this.chunks.push(new Uint8Array([value ? SIMPLE_TRUE : SIMPLE_FALSE]))
49
+ return
50
+ }
51
+ if (typeof value === 'number') {
52
+ this._encodeNumber(value)
53
+ return
54
+ }
55
+ if (typeof value === 'string') {
56
+ this._encodeString(value)
57
+ return
58
+ }
59
+ if (value instanceof Uint8Array) {
60
+ this._encodeByteString(value)
61
+ return
62
+ }
63
+ if (Array.isArray(value)) {
64
+ this._encodeArray(value)
65
+ return
66
+ }
67
+ if (value instanceof Map) {
68
+ // Keys can be numbers or strings
69
+ const entries = [...value.entries()] as Array<[unknown, unknown]>
70
+ this._encodeMapFromAnyEntries(entries)
71
+ return
72
+ }
73
+ if (typeof value === 'object') {
74
+ // Plain object: treat keys as strings
75
+ const entries = Object.entries(value as Record<string, unknown>)
76
+ this._encodeMapFromEntries(entries)
77
+ return
78
+ }
79
+ throw new Error(`CborEncoder: unsupported type: ${typeof value}`)
80
+ }
81
+
82
+ private _encodeNumber(value: number): void {
83
+ if (!Number.isFinite(value) || !Number.isInteger(value)) {
84
+ // float64
85
+ this.chunks.push(this._float64Header())
86
+ const buf = new ArrayBuffer(8)
87
+ new DataView(buf).setFloat64(0, value, false)
88
+ this.chunks.push(new Uint8Array(buf))
89
+ return
90
+ }
91
+ if (value >= 0) {
92
+ this._encodeHead(MT_UINT, value)
93
+ } else {
94
+ // negative: -1 - n encoded as n
95
+ this._encodeHead(MT_NINT, -1 - value)
96
+ }
97
+ }
98
+
99
+ private _float64Header(): Uint8Array {
100
+ return new Uint8Array([(MT_SIMPLE << 5) | AI_FLOAT64])
101
+ }
102
+
103
+ private _encodeString(value: string): void {
104
+ const bytes = textEncoder.encode(value)
105
+ this._encodeHead(MT_TSTR, bytes.length)
106
+ this.chunks.push(bytes)
107
+ }
108
+
109
+ private _encodeByteString(value: Uint8Array): void {
110
+ this._encodeHead(MT_BSTR, value.length)
111
+ this.chunks.push(value)
112
+ }
113
+
114
+ private _encodeArray(value: unknown[]): void {
115
+ this._encodeHead(MT_ARRAY, value.length)
116
+ for (const item of value) {
117
+ this._encode(item)
118
+ }
119
+ }
120
+
121
+ private _encodeMapFromAnyEntries(entries: Array<[unknown, unknown]>): void {
122
+ // Encode each key to bytes, then sort by lexicographic byte order of encoded key
123
+ const encoded: Array<{ keyEncoded: Uint8Array; key: unknown; value: unknown }> = entries.map(([k, v]) => {
124
+ let keyEncoded: Uint8Array
125
+ if (typeof k === 'number' && Number.isInteger(k)) {
126
+ keyEncoded = this._encodeHeadBytes(MT_UINT, k)
127
+ } else {
128
+ const keyBytes = textEncoder.encode(String(k))
129
+ const keyLenEncoded = this._encodeHeadBytes(MT_TSTR, keyBytes.length)
130
+ keyEncoded = this._concatPair(keyLenEncoded, keyBytes)
131
+ }
132
+ return { keyEncoded, key: k, value: v }
133
+ })
134
+
135
+ encoded.sort((a, b) => this._compareBytes(a.keyEncoded, b.keyEncoded))
136
+
137
+ this._encodeHead(MT_MAP, encoded.length)
138
+ for (const { key, value } of encoded) {
139
+ // Write key
140
+ if (typeof key === 'number' && Number.isInteger(key)) {
141
+ this._encodeHead(MT_UINT, key as number)
142
+ } else {
143
+ const keyBytes = textEncoder.encode(String(key))
144
+ this._encodeHead(MT_TSTR, keyBytes.length)
145
+ this.chunks.push(keyBytes)
146
+ }
147
+ // Write value
148
+ this._encode(value)
149
+ }
150
+ }
151
+
152
+ private _encodeMapFromEntries(entries: Array<[string, unknown]>): void {
153
+ // Deterministic: sort keys by UTF-8 byte order of encoded key
154
+ const encoded: Array<{ keyBytes: Uint8Array; keyEncoded: Uint8Array; value: unknown }> = entries.map(([k, v]) => {
155
+ const keyBytes = textEncoder.encode(k)
156
+ const keyLenEncoded = this._encodeHeadBytes(MT_TSTR, keyBytes.length)
157
+ const keyEncoded = this._concatPair(keyLenEncoded, keyBytes)
158
+ return { keyBytes, keyEncoded, value: v }
159
+ })
160
+
161
+ encoded.sort((a, b) => this._compareBytes(a.keyEncoded, b.keyEncoded))
162
+
163
+ this._encodeHead(MT_MAP, encoded.length)
164
+ for (const { keyBytes, value } of encoded) {
165
+ // Write key
166
+ this._encodeHead(MT_TSTR, keyBytes.length)
167
+ this.chunks.push(keyBytes)
168
+ // Write value
169
+ this._encode(value)
170
+ }
171
+ }
172
+
173
+ private _compareBytes(a: Uint8Array, b: Uint8Array): number {
174
+ const len = Math.min(a.length, b.length)
175
+ for (let i = 0; i < len; i++) {
176
+ const diff = (a[i] ?? 0) - (b[i] ?? 0)
177
+ if (diff !== 0) return diff
178
+ }
179
+ return a.length - b.length
180
+ }
181
+
182
+ private _concatPair(a: Uint8Array, b: Uint8Array): Uint8Array {
183
+ const result = new Uint8Array(a.length + b.length)
184
+ result.set(a, 0)
185
+ result.set(b, a.length)
186
+ return result
187
+ }
188
+
189
+ private _encodeHead(majorType: number, value: number): void {
190
+ this.chunks.push(this._encodeHeadBytes(majorType, value))
191
+ }
192
+
193
+ private _encodeHeadBytes(majorType: number, value: number): Uint8Array {
194
+ const mt = majorType << 5
195
+ if (value <= 23) {
196
+ return new Uint8Array([mt | value])
197
+ }
198
+ if (value <= 0xff) {
199
+ return new Uint8Array([mt | AI_1BYTE, value])
200
+ }
201
+ if (value <= 0xffff) {
202
+ const buf = new ArrayBuffer(3)
203
+ const dv = new DataView(buf)
204
+ dv.setUint8(0, mt | AI_2BYTE)
205
+ dv.setUint16(1, value, false)
206
+ return new Uint8Array(buf)
207
+ }
208
+ if (value <= 0xffffffff) {
209
+ const buf = new ArrayBuffer(5)
210
+ const dv = new DataView(buf)
211
+ dv.setUint8(0, mt | AI_4BYTE)
212
+ dv.setUint32(1, value, false)
213
+ return new Uint8Array(buf)
214
+ }
215
+ // 8-byte (for large numbers)
216
+ const buf = new ArrayBuffer(9)
217
+ const dv = new DataView(buf)
218
+ dv.setUint8(0, mt | AI_8BYTE)
219
+ dv.setBigUint64(1, BigInt(value), false)
220
+ return new Uint8Array(buf)
221
+ }
222
+
223
+ private _concat(): Uint8Array {
224
+ const total = this.chunks.reduce((sum, c) => sum + c.length, 0)
225
+ const result = new Uint8Array(total)
226
+ let offset = 0
227
+ for (const chunk of this.chunks) {
228
+ result.set(chunk, offset)
229
+ offset += chunk.length
230
+ }
231
+ return result
232
+ }
233
+ }
234
+
235
+ export class CborDecoder {
236
+ private data!: Uint8Array
237
+ private offset = 0
238
+
239
+ decode(data: Uint8Array): unknown {
240
+ this.data = data
241
+ this.offset = 0
242
+ const result = this._decode()
243
+ return result
244
+ }
245
+
246
+ private _decode(): unknown {
247
+ const initialByte = this._readByte()
248
+ const majorType = (initialByte >> 5) & 0x7
249
+ const additionalInfo = initialByte & 0x1f
250
+
251
+ switch (majorType) {
252
+ case MT_UINT:
253
+ return this._decodeUint(additionalInfo)
254
+ case MT_NINT:
255
+ return -1 - this._decodeUint(additionalInfo)
256
+ case MT_BSTR: {
257
+ const len = this._decodeUint(additionalInfo)
258
+ return this._readBytes(len)
259
+ }
260
+ case MT_TSTR: {
261
+ const len = this._decodeUint(additionalInfo)
262
+ const bytes = this._readBytes(len)
263
+ return textDecoder.decode(bytes)
264
+ }
265
+ case MT_ARRAY: {
266
+ const count = this._decodeUint(additionalInfo)
267
+ const result: unknown[] = []
268
+ for (let i = 0; i < count; i++) {
269
+ result.push(this._decode())
270
+ }
271
+ return result
272
+ }
273
+ case MT_MAP: {
274
+ const count = this._decodeUint(additionalInfo)
275
+ const result: Record<string, unknown> = {}
276
+ for (let i = 0; i < count; i++) {
277
+ const key = this._decode()
278
+ const value = this._decode()
279
+ result[String(key)] = value
280
+ }
281
+ return result
282
+ }
283
+ case MT_SIMPLE: {
284
+ if (additionalInfo === 20) return false // 0xf4
285
+ if (additionalInfo === 21) return true // 0xf5
286
+ if (additionalInfo === 22) return null // 0xf6
287
+ if (additionalInfo === AI_FLOAT64) {
288
+ const bytes = this._readBytes(8)
289
+ return new DataView(bytes.buffer, bytes.byteOffset, 8).getFloat64(0, false)
290
+ }
291
+ throw new Error(`CborDecoder: unsupported simple value ${additionalInfo}`)
292
+ }
293
+ default:
294
+ throw new Error(`CborDecoder: unsupported major type ${majorType}`)
295
+ }
296
+ }
297
+
298
+ private _decodeUint(additionalInfo: number): number {
299
+ if (additionalInfo <= 23) return additionalInfo
300
+ if (additionalInfo === AI_1BYTE) return this._readByte()
301
+ if (additionalInfo === AI_2BYTE) {
302
+ const bytes = this._readBytes(2)
303
+ return new DataView(bytes.buffer, bytes.byteOffset, 2).getUint16(0, false)
304
+ }
305
+ if (additionalInfo === AI_4BYTE) {
306
+ const bytes = this._readBytes(4)
307
+ return new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0, false)
308
+ }
309
+ if (additionalInfo === AI_8BYTE) {
310
+ const bytes = this._readBytes(8)
311
+ return Number(new DataView(bytes.buffer, bytes.byteOffset, 8).getBigUint64(0, false))
312
+ }
313
+ throw new Error(`CborDecoder: unsupported additional info ${additionalInfo}`)
314
+ }
315
+
316
+ private _readByte(): number {
317
+ if (this.offset >= this.data.length) {
318
+ throw new Error('CborDecoder: unexpected end of data')
319
+ }
320
+ return this.data[this.offset++] ?? 0
321
+ }
322
+
323
+ private _readBytes(count: number): Uint8Array {
324
+ if (this.offset + count > this.data.length) {
325
+ throw new Error('CborDecoder: unexpected end of data')
326
+ }
327
+ const result = this.data.slice(this.offset, this.offset + count)
328
+ this.offset += count
329
+ return result
330
+ }
331
+ }
332
+
333
+ export function encodeCbor(value: unknown): Uint8Array {
334
+ return new CborEncoder().encode(value)
335
+ }
336
+
337
+ export function decodeCbor(data: Uint8Array): unknown {
338
+ return new CborDecoder().decode(data)
339
+ }
@@ -0,0 +1,206 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { createEnvelope, generateEd25519KeypairBase64Url, type ProtocolBody } from './protocol.js'
3
+ import {
4
+ decryptBody,
5
+ encryptBody,
6
+ generateX25519KeyPair,
7
+ openEnvelope,
8
+ sealEnvelope,
9
+ } from './encryption.js'
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Helpers
13
+ // ---------------------------------------------------------------------------
14
+
15
+ function makeEnvelope(body: ProtocolBody) {
16
+ return createEnvelope({
17
+ sender: 'agent-alice',
18
+ recipient: 'agent-bob',
19
+ intent: body.intent,
20
+ content: body.content,
21
+ capability: body.capability,
22
+ correlationId: body.correlationId,
23
+ ttlMs: 60_000,
24
+ })
25
+ }
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Tests
29
+ // ---------------------------------------------------------------------------
30
+
31
+ describe('generateX25519KeyPair', () => {
32
+ it('returns 32-byte base64url keys (~43 chars, no padding)', () => {
33
+ const kp = generateX25519KeyPair()
34
+ // base64url of 32 bytes = ceil(32 * 4/3) = 43 chars (no padding)
35
+ expect(kp.publicKey).toMatch(/^[A-Za-z0-9_-]{43}$/)
36
+ expect(kp.privateKey).toMatch(/^[A-Za-z0-9_-]{43}$/)
37
+ // Decoded must be exactly 32 bytes
38
+ expect(Buffer.from(kp.publicKey, 'base64url').length).toBe(32)
39
+ expect(Buffer.from(kp.privateKey, 'base64url').length).toBe(32)
40
+ })
41
+ })
42
+
43
+ describe('sealEnvelope + openEnvelope', () => {
44
+ it('round-trip recovers original body exactly', async () => {
45
+ const recipientKp = generateX25519KeyPair()
46
+ const senderEd = await generateEd25519KeypairBase64Url()
47
+
48
+ const originalBody: ProtocolBody = {
49
+ intent: 'TASK',
50
+ content: 'Hello encrypted world!',
51
+ capability: 'some-cap',
52
+ correlationId: 'corr-123',
53
+ }
54
+ const envelope = makeEnvelope(originalBody)
55
+
56
+ const sealed = await sealEnvelope(envelope, {
57
+ recipientX25519PublicKey: recipientKp.publicKey,
58
+ senderEd25519PrivateKey: senderEd.privateKey,
59
+ })
60
+
61
+ const { body } = await openEnvelope(sealed, {
62
+ recipientX25519PrivateKey: recipientKp.privateKey,
63
+ senderEd25519PublicKey: senderEd.publicKey,
64
+ })
65
+
66
+ expect(body.intent).toBe(originalBody.intent)
67
+ expect(body.content).toBe(originalBody.content)
68
+ expect(body.capability).toBe(originalBody.capability)
69
+ expect(body.correlationId).toBe(originalBody.correlationId)
70
+ })
71
+
72
+ it('fails with wrong recipient private key (AEAD tag mismatch)', async () => {
73
+ const recipientKp = generateX25519KeyPair()
74
+ const wrongKp = generateX25519KeyPair()
75
+ const senderEd = await generateEd25519KeypairBase64Url()
76
+
77
+ // Sign with correct recipient public key but try to open with wrong private key
78
+ // To bypass the signature check we need to seal with wrongKp pubkey too,
79
+ // but the spec says "wrong recipient key" meaning sealed to correct pub key but opened with wrong priv.
80
+ const envelope = makeEnvelope({ intent: 'PING', content: 'secret' })
81
+ const sealed = await sealEnvelope(envelope, {
82
+ recipientX25519PublicKey: recipientKp.publicKey,
83
+ senderEd25519PrivateKey: senderEd.privateKey,
84
+ })
85
+
86
+ // We must tamper with the encrypted content to force the wrong key path,
87
+ // but the signature would fail. Instead, bypass openEnvelope and call decryptBody directly
88
+ // with the wrong key — which is what the spec tests.
89
+ expect(() => decryptBody(sealed.body.content, wrongKp.privateKey)).toThrow()
90
+ })
91
+
92
+ it('fails if envelope signature is tampered', async () => {
93
+ const recipientKp = generateX25519KeyPair()
94
+ const senderEd = await generateEd25519KeypairBase64Url()
95
+
96
+ const envelope = makeEnvelope({ intent: 'PING', content: 'secret' })
97
+ const sealed = await sealEnvelope(envelope, {
98
+ recipientX25519PublicKey: recipientKp.publicKey,
99
+ senderEd25519PrivateKey: senderEd.privateKey,
100
+ })
101
+
102
+ // Tamper with the signature value
103
+ const tampered = {
104
+ ...sealed,
105
+ signature: {
106
+ ...sealed.signature!,
107
+ value: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
108
+ },
109
+ }
110
+
111
+ await expect(
112
+ openEnvelope(tampered, {
113
+ recipientX25519PrivateKey: recipientKp.privateKey,
114
+ senderEd25519PublicKey: senderEd.publicKey,
115
+ }),
116
+ ).rejects.toThrow('signature verification failed')
117
+ })
118
+
119
+ it('fails if ciphertext is tampered (AEAD auth tag fails)', async () => {
120
+ const recipientKp = generateX25519KeyPair()
121
+ const senderEd = await generateEd25519KeypairBase64Url()
122
+
123
+ const envelope = makeEnvelope({ intent: 'PING', content: 'secret' })
124
+ const sealed = await sealEnvelope(envelope, {
125
+ recipientX25519PublicKey: recipientKp.publicKey,
126
+ senderEd25519PrivateKey: senderEd.privateKey,
127
+ })
128
+
129
+ // Decode the encrypted payload, flip a bit in ciphertext, re-encode
130
+ const payloadJson = Buffer.from(sealed.body.content, 'base64url').toString('utf8')
131
+ const payload = JSON.parse(payloadJson) as { ephemeralPublic: string; nonce: string; ciphertext: string; tag: string }
132
+ const ctBuf = Buffer.from(payload.ciphertext, 'base64url')
133
+ ctBuf[0] ^= 0xff // flip bits in first byte
134
+ const tamperedPayload = { ...payload, ciphertext: ctBuf.toString('base64url') }
135
+ const tamperedContent = Buffer.from(JSON.stringify(tamperedPayload), 'utf8').toString('base64url')
136
+
137
+ // We need to re-sign with the same key for the tamper to get past sig verification
138
+ // Instead: call decryptBody directly with tampered content
139
+ expect(() => decryptBody(tamperedContent, recipientKp.privateKey)).toThrow()
140
+ })
141
+
142
+ it('two sealEnvelope calls on same body produce different ciphertexts (ephemeral randomness)', async () => {
143
+ const recipientKp = generateX25519KeyPair()
144
+ const senderEd = await generateEd25519KeypairBase64Url()
145
+
146
+ const envelope1 = makeEnvelope({ intent: 'PING', content: 'same content' })
147
+ const envelope2 = makeEnvelope({ intent: 'PING', content: 'same content' })
148
+
149
+ const sealed1 = await sealEnvelope(envelope1, {
150
+ recipientX25519PublicKey: recipientKp.publicKey,
151
+ senderEd25519PrivateKey: senderEd.privateKey,
152
+ })
153
+ const sealed2 = await sealEnvelope(envelope2, {
154
+ recipientX25519PublicKey: recipientKp.publicKey,
155
+ senderEd25519PrivateKey: senderEd.privateKey,
156
+ })
157
+
158
+ // Different ephemeral keys + different nonces → different ciphertexts
159
+ expect(sealed1.body.content).not.toBe(sealed2.body.content)
160
+ })
161
+
162
+ it('encrypted content is opaque (does not contain original body.content as plaintext)', async () => {
163
+ const recipientKp = generateX25519KeyPair()
164
+ const senderEd = await generateEd25519KeypairBase64Url()
165
+
166
+ const originalContent = 'super-secret-data-12345'
167
+ const envelope = makeEnvelope({ intent: 'TASK', content: originalContent })
168
+
169
+ const sealed = await sealEnvelope(envelope, {
170
+ recipientX25519PublicKey: recipientKp.publicKey,
171
+ senderEd25519PrivateKey: senderEd.privateKey,
172
+ })
173
+
174
+ // The encrypted content blob should not contain the original plaintext string
175
+ const encryptedContentDecoded = Buffer.from(sealed.body.content, 'base64url').toString('utf8')
176
+ expect(encryptedContentDecoded).not.toContain(originalContent)
177
+ // Also raw base64url should not contain it
178
+ expect(sealed.body.content).not.toContain(originalContent)
179
+ })
180
+
181
+ it('encrypted envelope body has correct structure', async () => {
182
+ const recipientKp = generateX25519KeyPair()
183
+ const senderEd = await generateEd25519KeypairBase64Url()
184
+
185
+ const envelope = makeEnvelope({ intent: 'PING', content: 'test' })
186
+ const sealed = await sealEnvelope(envelope, {
187
+ recipientX25519PublicKey: recipientKp.publicKey,
188
+ senderEd25519PrivateKey: senderEd.privateKey,
189
+ })
190
+
191
+ expect(sealed.body.intent).toBe('ENCRYPTED')
192
+ expect(sealed.body.capability).toBe('x25519-chacha20poly1305')
193
+ expect(sealed.signature).toBeDefined()
194
+ expect(sealed.signature?.alg).toBe('ED25519')
195
+ })
196
+ })
197
+
198
+ describe('encryptBody + decryptBody', () => {
199
+ it('round-trips a body with all optional fields', () => {
200
+ const kp = generateX25519KeyPair()
201
+ const body: ProtocolBody = { intent: 'RESULT', content: 'data', capability: 'cap', correlationId: 'cid-42' }
202
+ const { encryptedContent } = encryptBody(body, kp.publicKey)
203
+ const decrypted = decryptBody(encryptedContent, kp.privateKey)
204
+ expect(decrypted).toEqual(body)
205
+ })
206
+ })