@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,42 @@
1
+ {
2
+ "name": "@7h3/protocol-pq",
3
+ "version": "0.5.0",
4
+ "description": "7h3 Protocol — Post-quantum signatures (ML-DSA-65, ML-DSA-87) via @noble/post-quantum",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "import": "./index.js"
12
+ }
13
+ },
14
+ "dependencies": {
15
+ "@noble/post-quantum": "^0.2.0"
16
+ },
17
+ "peerDependencies": {
18
+ "@7h3/protocol": "^0.5.0"
19
+ },
20
+ "license": "MIT",
21
+ "keywords": [
22
+ "7h3",
23
+ "protocol",
24
+ "post-quantum",
25
+ "ml-dsa",
26
+ "dilithium",
27
+ "signing"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/IceMasterT/7h3-protocol.git"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc",
35
+ "test": "vitest run src/index.test.ts"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^26.1.0",
39
+ "typescript": "~6.0.3",
40
+ "vitest": "^4.1.8"
41
+ }
42
+ }
@@ -0,0 +1,143 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ generatePqKeyPair,
4
+ signEnvelopePq,
5
+ verifyEnvelopePq,
6
+ signEnvelopeMlDsa65,
7
+ signEnvelopeMlDsa87,
8
+ verifyEnvelopeMlDsa65,
9
+ verifyEnvelopeMlDsa87,
10
+ createEnvelope,
11
+ } from './index.js'
12
+
13
+ // Conformance vector envelope (deterministic for tests)
14
+ const baseEnvelope = {
15
+ header: {
16
+ version: '7h3/0.1' as const,
17
+ messageId: 'test-msg-001',
18
+ timestampMs: 1_700_000_000_000,
19
+ ttlMs: 60_000,
20
+ sender: 'agent-alpha',
21
+ recipient: 'agent-beta',
22
+ nonce: 'abc123xyz',
23
+ },
24
+ body: {
25
+ intent: 'TASK' as const,
26
+ content: 'Hello, post-quantum world!',
27
+ },
28
+ }
29
+
30
+ describe('generatePqKeyPair', () => {
31
+ it('1. ML-DSA-65 returns keypair with correct algorithm field', () => {
32
+ const kp = generatePqKeyPair('ML-DSA-65')
33
+ expect(kp.algorithm).toBe('ML-DSA-65')
34
+ expect(typeof kp.publicKey).toBe('string')
35
+ expect(typeof kp.privateKey).toBe('string')
36
+ expect(typeof kp.createdAt).toBe('number')
37
+ expect(kp.publicKey.length).toBeGreaterThan(0)
38
+ expect(kp.privateKey.length).toBeGreaterThan(0)
39
+ })
40
+
41
+ it('2. ML-DSA-87 returns keypair', () => {
42
+ const kp = generatePqKeyPair('ML-DSA-87')
43
+ expect(kp.algorithm).toBe('ML-DSA-87')
44
+ expect(typeof kp.publicKey).toBe('string')
45
+ expect(typeof kp.privateKey).toBe('string')
46
+ })
47
+
48
+ it('7. ML-DSA-65 public key is correct size (1952 bytes → ~2603 base64url chars)', () => {
49
+ const kp = generatePqKeyPair('ML-DSA-65')
50
+ // base64url: ceil(1952 / 3) * 4 = 2604 chars, minus up to 2 padding = 2603 or 2604
51
+ const decoded = Buffer.from(
52
+ kp.publicKey.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(kp.publicKey.length / 4) * 4, '='),
53
+ 'base64'
54
+ )
55
+ expect(decoded.length).toBe(1952)
56
+ })
57
+
58
+ it('8. ML-DSA-65 private key is correct size (4032 bytes secretKey)', () => {
59
+ const kp = generatePqKeyPair('ML-DSA-65')
60
+ const decoded = Buffer.from(
61
+ kp.privateKey.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(kp.privateKey.length / 4) * 4, '='),
62
+ 'base64'
63
+ )
64
+ expect(decoded.length).toBe(4032)
65
+ })
66
+ })
67
+
68
+ describe('ML-DSA-65 sign/verify', () => {
69
+ it('3. ML-DSA-65 sign + verify round trip', async () => {
70
+ const kp = generatePqKeyPair('ML-DSA-65')
71
+ const signed = await signEnvelopePq(baseEnvelope, kp.privateKey, 'ML-DSA-65')
72
+ expect(signed.signature?.alg).toBe('ML-DSA-65')
73
+ expect(typeof signed.signature?.value).toBe('string')
74
+ expect(signed.signature!.value.length).toBeGreaterThan(0)
75
+ const valid = await verifyEnvelopePq(signed, kp.publicKey)
76
+ expect(valid).toBe(true)
77
+ })
78
+
79
+ it('4. ML-DSA-65 verify fails on tampered envelope', async () => {
80
+ const kp = generatePqKeyPair('ML-DSA-65')
81
+ const signed = await signEnvelopePq(baseEnvelope, kp.privateKey, 'ML-DSA-65')
82
+ const tampered = {
83
+ ...signed,
84
+ body: { ...signed.body, content: 'TAMPERED content' },
85
+ }
86
+ const valid = await verifyEnvelopePq(tampered, kp.publicKey)
87
+ expect(valid).toBe(false)
88
+ })
89
+ })
90
+
91
+ describe('ML-DSA-87 sign/verify', () => {
92
+ it('5. ML-DSA-87 sign + verify round trip', async () => {
93
+ const kp = generatePqKeyPair('ML-DSA-87')
94
+ const signed = await signEnvelopePq(baseEnvelope, kp.privateKey, 'ML-DSA-87')
95
+ expect(signed.signature?.alg).toBe('ML-DSA-87')
96
+ const valid = await verifyEnvelopePq(signed, kp.publicKey)
97
+ expect(valid).toBe(true)
98
+ })
99
+
100
+ it('6. ML-DSA-87 verify fails with wrong public key', async () => {
101
+ const kp = generatePqKeyPair('ML-DSA-87')
102
+ const wrongKp = generatePqKeyPair('ML-DSA-87')
103
+ const signed = await signEnvelopePq(baseEnvelope, kp.privateKey, 'ML-DSA-87')
104
+ const valid = await verifyEnvelopePq(signed, wrongKp.publicKey)
105
+ expect(valid).toBe(false)
106
+ })
107
+ })
108
+
109
+ describe('algorithm-specific aliases', () => {
110
+ it('signEnvelopeMlDsa65 / verifyEnvelopeMlDsa65 round trip', async () => {
111
+ const kp = generatePqKeyPair('ML-DSA-65')
112
+ const envelope = createEnvelope({
113
+ sender: 'agent-a',
114
+ recipient: 'agent-b',
115
+ intent: 'PING',
116
+ content: 'alias test',
117
+ })
118
+ const signed = await signEnvelopeMlDsa65(envelope, kp.privateKey)
119
+ expect(signed.signature?.alg).toBe('ML-DSA-65')
120
+ const valid = await verifyEnvelopeMlDsa65(signed, kp.publicKey)
121
+ expect(valid).toBe(true)
122
+ })
123
+
124
+ it('signEnvelopeMlDsa87 / verifyEnvelopeMlDsa87 round trip', async () => {
125
+ const kp = generatePqKeyPair('ML-DSA-87')
126
+ const envelope = createEnvelope({
127
+ sender: 'agent-a',
128
+ recipient: 'agent-b',
129
+ intent: 'PONG',
130
+ content: 'ml-dsa-87 alias test',
131
+ })
132
+ const signed = await signEnvelopeMlDsa87(envelope, kp.privateKey)
133
+ expect(signed.signature?.alg).toBe('ML-DSA-87')
134
+ const valid = await verifyEnvelopeMlDsa87(signed, kp.publicKey)
135
+ expect(valid).toBe(true)
136
+ })
137
+
138
+ it('verifyEnvelopePq returns false when no signature', async () => {
139
+ const unsigned = { ...baseEnvelope }
140
+ const valid = await verifyEnvelopePq(unsigned, 'fakepublickey')
141
+ expect(valid).toBe(false)
142
+ })
143
+ })
@@ -0,0 +1,166 @@
1
+ import { ml_dsa65, ml_dsa87 } from '@noble/post-quantum/ml-dsa'
2
+
3
+ // Re-export from @7h3/protocol
4
+ export type { ProtocolEnvelope, ProtocolHeader, ProtocolBody } from '../../../src/protocol.js'
5
+ export { canonicalizeEnvelope, createEnvelope } from '../../../src/protocol.js'
6
+
7
+ import type { ProtocolEnvelope, ProtocolHeader, ProtocolBody } from '../../../src/protocol.js'
8
+ import { canonicalizeEnvelope } from '../../../src/protocol.js'
9
+
10
+ // ─── Types ──────────────────────────────────────────────────────────────────
11
+
12
+ export type PqAlgorithm = 'ML-DSA-65' | 'ML-DSA-87'
13
+
14
+ export interface PqKeyPair {
15
+ algorithm: PqAlgorithm
16
+ publicKey: string // base64url, no padding
17
+ privateKey: string // base64url, no padding (secretKey bytes from noble)
18
+ createdAt: number
19
+ }
20
+
21
+ /**
22
+ * Extended envelope type that carries a PQ signature.
23
+ * Structurally identical to ProtocolEnvelope but alg is widened.
24
+ */
25
+ export interface PqProtocolEnvelope {
26
+ header: ProtocolHeader
27
+ body: ProtocolBody
28
+ signature?: {
29
+ alg: PqAlgorithm
30
+ keyId: string
31
+ value: string
32
+ }
33
+ }
34
+
35
+ // ─── Base64url helpers ───────────────────────────────────────────────────────
36
+
37
+ function toBase64Url(bytes: Uint8Array): string {
38
+ const g = globalThis as unknown as {
39
+ Buffer?: { from: (b: Uint8Array) => { toString: (enc: string) => string } }
40
+ }
41
+ if (g.Buffer) {
42
+ return g.Buffer.from(bytes)
43
+ .toString('base64')
44
+ .replace(/\+/g, '-')
45
+ .replace(/\//g, '_')
46
+ .replace(/=+$/g, '')
47
+ }
48
+ let binary = ''
49
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i])
50
+ return btoa(binary)
51
+ .replace(/\+/g, '-')
52
+ .replace(/\//g, '_')
53
+ .replace(/=+$/g, '')
54
+ }
55
+
56
+ function fromBase64Url(value: string): Uint8Array {
57
+ const padded = value
58
+ .replace(/-/g, '+')
59
+ .replace(/_/g, '/')
60
+ .padEnd(Math.ceil(value.length / 4) * 4, '=')
61
+
62
+ const g = globalThis as unknown as {
63
+ Buffer?: { from: (s: string, enc: string) => Uint8Array }
64
+ }
65
+ if (g.Buffer) {
66
+ return new Uint8Array(g.Buffer.from(padded, 'base64'))
67
+ }
68
+ const binary = atob(padded)
69
+ const bytes = new Uint8Array(binary.length)
70
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
71
+ return bytes
72
+ }
73
+
74
+ // ─── Key generation ──────────────────────────────────────────────────────────
75
+
76
+ export function generatePqKeyPair(algorithm: PqAlgorithm = 'ML-DSA-65'): PqKeyPair {
77
+ const impl = algorithm === 'ML-DSA-65' ? ml_dsa65 : ml_dsa87
78
+ const seed = crypto.getRandomValues(new Uint8Array(32))
79
+ const { publicKey, secretKey } = impl.keygen(seed)
80
+ return {
81
+ algorithm,
82
+ publicKey: toBase64Url(publicKey),
83
+ privateKey: toBase64Url(secretKey),
84
+ createdAt: Date.now(),
85
+ }
86
+ }
87
+
88
+ // ─── Sign ────────────────────────────────────────────────────────────────────
89
+
90
+ export async function signEnvelopePq(
91
+ envelope: Omit<ProtocolEnvelope, 'signature'>,
92
+ privateKeyBase64Url: string,
93
+ algorithm: PqAlgorithm = 'ML-DSA-65',
94
+ ): Promise<PqProtocolEnvelope> {
95
+ const impl = algorithm === 'ML-DSA-65' ? ml_dsa65 : ml_dsa87
96
+ const canonical = canonicalizeEnvelope(envelope)
97
+ const message = new TextEncoder().encode(canonical)
98
+ const secretKey = fromBase64Url(privateKeyBase64Url)
99
+ const sigBytes = impl.sign(secretKey, message)
100
+ // keyId derived from first 16 chars of the secretKey base64url
101
+ const keyId = privateKeyBase64Url.slice(0, 16)
102
+
103
+ return {
104
+ header: envelope.header,
105
+ body: envelope.body,
106
+ signature: {
107
+ alg: algorithm,
108
+ keyId,
109
+ value: toBase64Url(sigBytes),
110
+ },
111
+ }
112
+ }
113
+
114
+ // ─── Verify ──────────────────────────────────────────────────────────────────
115
+
116
+ export async function verifyEnvelopePq(
117
+ envelope: PqProtocolEnvelope,
118
+ publicKeyBase64Url: string,
119
+ ): Promise<boolean> {
120
+ if (!envelope.signature) return false
121
+ const alg = envelope.signature.alg
122
+ if (alg !== 'ML-DSA-65' && alg !== 'ML-DSA-87') return false
123
+
124
+ const impl = alg === 'ML-DSA-65' ? ml_dsa65 : ml_dsa87
125
+ const unsigned = { header: envelope.header, body: envelope.body }
126
+ const canonical = canonicalizeEnvelope(unsigned)
127
+ const message = new TextEncoder().encode(canonical)
128
+ const publicKey = fromBase64Url(publicKeyBase64Url)
129
+ const sigBytes = fromBase64Url(envelope.signature.value)
130
+
131
+ try {
132
+ return impl.verify(publicKey, message, sigBytes)
133
+ } catch {
134
+ return false
135
+ }
136
+ }
137
+
138
+ // ─── Algorithm-specific aliases ──────────────────────────────────────────────
139
+
140
+ export async function signEnvelopeMlDsa65(
141
+ envelope: Omit<ProtocolEnvelope, 'signature'>,
142
+ privateKeyBase64Url: string,
143
+ ): Promise<PqProtocolEnvelope> {
144
+ return signEnvelopePq(envelope, privateKeyBase64Url, 'ML-DSA-65')
145
+ }
146
+
147
+ export async function signEnvelopeMlDsa87(
148
+ envelope: Omit<ProtocolEnvelope, 'signature'>,
149
+ privateKeyBase64Url: string,
150
+ ): Promise<PqProtocolEnvelope> {
151
+ return signEnvelopePq(envelope, privateKeyBase64Url, 'ML-DSA-87')
152
+ }
153
+
154
+ export async function verifyEnvelopeMlDsa65(
155
+ envelope: PqProtocolEnvelope,
156
+ publicKeyBase64Url: string,
157
+ ): Promise<boolean> {
158
+ return verifyEnvelopePq(envelope, publicKeyBase64Url)
159
+ }
160
+
161
+ export async function verifyEnvelopeMlDsa87(
162
+ envelope: PqProtocolEnvelope,
163
+ publicKeyBase64Url: string,
164
+ ): Promise<boolean> {
165
+ return verifyEnvelopePq(envelope, publicKeyBase64Url)
166
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "declaration": true,
7
+ "outDir": "./dist",
8
+ "rootDir": "../../../",
9
+ "strict": true,
10
+ "skipLibCheck": true,
11
+ "types": ["node"]
12
+ },
13
+ "include": ["src/index.ts", "../../../src/protocol.ts"]
14
+ }
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: false,
6
+ },
7
+ })
@@ -0,0 +1,252 @@
1
+ """
2
+ E2E Encryption for 7h3 Protocol — Python SDK
3
+
4
+ Uses X25519 Diffie-Hellman key exchange + ChaCha20-Poly1305 AEAD.
5
+ Requires: pip install cryptography
6
+
7
+ EncryptedEnvelope = SignedEnvelope where body['content'] is a base64url-encoded
8
+ EncryptedPayload JSON, body['intent'] = 'ENCRYPTED',
9
+ body['capability'] = 'x25519-chacha20poly1305'
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import json
16
+ import os
17
+ from typing import Any, Dict, Tuple
18
+
19
+ try:
20
+ from cryptography.hazmat.primitives.asymmetric.x25519 import (
21
+ X25519PrivateKey,
22
+ X25519PublicKey,
23
+ )
24
+ from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
25
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
26
+ from cryptography.hazmat.primitives import hashes
27
+ from cryptography.hazmat.primitives import serialization
28
+ except ImportError as exc:
29
+ raise ImportError(
30
+ "7h3/encryption requires the 'cryptography' package. "
31
+ "Install it with: pip install cryptography"
32
+ ) from exc
33
+
34
+ from .protocol import (
35
+ sign_envelope_ed25519,
36
+ verify_envelope_ed25519,
37
+ )
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Utility
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ def _b64url_encode(data: bytes) -> str:
46
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
47
+
48
+
49
+ def _b64url_decode(value: str) -> bytes:
50
+ padding = "=" * ((4 - (len(value) % 4)) % 4)
51
+ return base64.urlsafe_b64decode(value + padding)
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Types (documented shapes, not enforced at runtime)
56
+ # ---------------------------------------------------------------------------
57
+ # X25519KeyPair: tuple[str, str] = (publicKey_base64url, privateKey_base64url)
58
+ # EncryptedPayload dict keys: ephemeralPublic, nonce, ciphertext, tag
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Key generation
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ def generate_x25519_keypair() -> Tuple[str, str]:
67
+ """
68
+ Generate a fresh X25519 keypair.
69
+
70
+ Returns:
71
+ (public_base64url, private_base64url) — both are raw 32 bytes, base64url-encoded
72
+ """
73
+ private_key = X25519PrivateKey.generate()
74
+ public_key = private_key.public_key()
75
+
76
+ priv_raw = private_key.private_bytes(
77
+ serialization.Encoding.Raw,
78
+ serialization.PrivateFormat.Raw,
79
+ serialization.NoEncryption(),
80
+ )
81
+ pub_raw = public_key.public_bytes(
82
+ serialization.Encoding.Raw,
83
+ serialization.PublicFormat.Raw,
84
+ )
85
+ return _b64url_encode(pub_raw), _b64url_encode(priv_raw)
86
+
87
+
88
+ # ---------------------------------------------------------------------------
89
+ # HKDF key derivation
90
+ # ---------------------------------------------------------------------------
91
+
92
+
93
+ def _derive_encryption_key(
94
+ private_key_b64: str,
95
+ peer_public_key_b64: str,
96
+ nonce_b64: str,
97
+ ) -> bytes:
98
+ """
99
+ X25519 DH + HKDF-SHA256 → 32 bytes for ChaCha20-Poly1305.
100
+
101
+ nonce_b64: base64url-encoded 12-byte ChaCha nonce; used as HKDF salt.
102
+ """
103
+ priv_bytes = _b64url_decode(private_key_b64)
104
+ pub_bytes = _b64url_decode(peer_public_key_b64)
105
+ nonce_bytes = _b64url_decode(nonce_b64)
106
+
107
+ private_key = X25519PrivateKey.from_private_bytes(priv_bytes)
108
+ public_key = X25519PublicKey.from_public_bytes(pub_bytes)
109
+
110
+ shared_secret = private_key.exchange(public_key)
111
+
112
+ hkdf = HKDF(
113
+ algorithm=hashes.SHA256(),
114
+ length=32,
115
+ salt=nonce_bytes,
116
+ info=b"7h3-enc/1",
117
+ )
118
+ return hkdf.derive(shared_secret)
119
+
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # Body encryption / decryption
123
+ # ---------------------------------------------------------------------------
124
+
125
+
126
+ def _encrypt_body(
127
+ body: Dict[str, Any],
128
+ recipient_x25519_public_b64: str,
129
+ ) -> Dict[str, str]:
130
+ """
131
+ Encrypt a protocol body dict.
132
+
133
+ Returns EncryptedPayload dict with: ephemeralPublic, nonce, ciphertext, tag
134
+ """
135
+ # Generate ephemeral keypair for forward secrecy
136
+ ephemeral_pub_b64, ephemeral_priv_b64 = generate_x25519_keypair()
137
+
138
+ # Random 12-byte ChaCha nonce (also used as HKDF salt)
139
+ nonce12 = os.urandom(12)
140
+ nonce_b64 = _b64url_encode(nonce12)
141
+
142
+ # Derive encryption key
143
+ key = _derive_encryption_key(ephemeral_priv_b64, recipient_x25519_public_b64, nonce_b64)
144
+
145
+ # Encrypt body as JSON
146
+ plaintext = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
147
+ aead = ChaCha20Poly1305(key)
148
+ # ChaCha20Poly1305.encrypt returns ciphertext‖tag (tag is last 16 bytes)
149
+ ct_with_tag = aead.encrypt(nonce12, plaintext, None)
150
+ ciphertext = ct_with_tag[:-16]
151
+ tag = ct_with_tag[-16:]
152
+
153
+ return {
154
+ "ephemeralPublic": ephemeral_pub_b64,
155
+ "nonce": nonce_b64,
156
+ "ciphertext": _b64url_encode(ciphertext),
157
+ "tag": _b64url_encode(tag),
158
+ }
159
+
160
+
161
+ def _decrypt_body(
162
+ encrypted_content_b64: str,
163
+ recipient_x25519_private_b64: str,
164
+ ) -> Dict[str, Any]:
165
+ """
166
+ Decrypt an EncryptedPayload back to a protocol body dict.
167
+
168
+ Raises ValueError if AEAD tag verification fails.
169
+ """
170
+ payload_json = _b64url_decode(encrypted_content_b64).decode("utf-8")
171
+ payload = json.loads(payload_json)
172
+
173
+ ephemeral_pub_b64 = payload["ephemeralPublic"]
174
+ nonce_b64 = payload["nonce"]
175
+ ciphertext_b64 = payload["ciphertext"]
176
+ tag_b64 = payload["tag"]
177
+
178
+ key = _derive_encryption_key(recipient_x25519_private_b64, ephemeral_pub_b64, nonce_b64)
179
+
180
+ nonce12 = _b64url_decode(nonce_b64)
181
+ ciphertext = _b64url_decode(ciphertext_b64)
182
+ tag = _b64url_decode(tag_b64)
183
+
184
+ aead = ChaCha20Poly1305(key)
185
+ # Re-concatenate ciphertext‖tag for decryption
186
+ ct_with_tag = ciphertext + tag
187
+ plaintext = aead.decrypt(nonce12, ct_with_tag, None)
188
+ return json.loads(plaintext.decode("utf-8"))
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # Envelope-level seal / open
193
+ # ---------------------------------------------------------------------------
194
+
195
+
196
+ def seal_envelope(
197
+ envelope: Dict[str, Any],
198
+ recipient_x25519_public_b64: str,
199
+ sender_ed25519_private_b64: str,
200
+ ) -> Dict[str, Any]:
201
+ """
202
+ Encrypt the envelope body and sign the result with Ed25519.
203
+
204
+ The original body is encrypted; the envelope body is replaced with:
205
+ { intent: 'ENCRYPTED', content: <encrypted-payload>, capability: 'x25519-chacha20poly1305' }
206
+ The modified envelope is signed with Ed25519.
207
+ """
208
+ encrypted_payload = _encrypt_body(envelope["body"], recipient_x25519_public_b64)
209
+ encrypted_content = _b64url_encode(
210
+ json.dumps(encrypted_payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
211
+ )
212
+
213
+ encrypted_body: Dict[str, Any] = {
214
+ "intent": "ENCRYPTED",
215
+ "content": encrypted_content,
216
+ "capability": "x25519-chacha20poly1305",
217
+ }
218
+ # Preserve correlationId if present
219
+ if "correlationId" in envelope["body"] and envelope["body"]["correlationId"] is not None:
220
+ encrypted_body["correlationId"] = envelope["body"]["correlationId"]
221
+
222
+ unsigned = {
223
+ "header": envelope["header"],
224
+ "body": encrypted_body,
225
+ }
226
+
227
+ return sign_envelope_ed25519(unsigned, sender_ed25519_private_b64)
228
+
229
+
230
+ def open_envelope(
231
+ envelope: Dict[str, Any],
232
+ recipient_x25519_private_b64: str,
233
+ sender_ed25519_public_b64: str,
234
+ ) -> Dict[str, Any]:
235
+ """
236
+ Verify Ed25519 signature, then decrypt the body.
237
+
238
+ Signature is verified FIRST — decryption only proceeds if valid.
239
+
240
+ Returns a dict with:
241
+ 'envelope': the signed envelope (with encrypted body)
242
+ 'body': the decrypted original ProtocolBody dict
243
+
244
+ Raises ValueError if signature is invalid or AEAD tag fails.
245
+ """
246
+ # 1. Verify Ed25519 signature FIRST
247
+ if not verify_envelope_ed25519(envelope, sender_ed25519_public_b64):
248
+ raise ValueError("7h3/encryption: Ed25519 signature verification failed")
249
+
250
+ # 2. Decrypt
251
+ body = _decrypt_body(envelope["body"]["content"], recipient_x25519_private_b64)
252
+ return {"envelope": envelope, "body": body}