@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,355 @@
1
+ import { bls12_381 } from '@noble/curves/bls12-381'
2
+
3
+ // ─── Protocol Types (re-declared for standalone build; canonical source: @7h3/protocol) ──
4
+
5
+ export interface ProtocolHeader {
6
+ version: string
7
+ messageId: string
8
+ timestampMs: number
9
+ ttlMs: number
10
+ sender: string
11
+ recipient?: string
12
+ nonce: string
13
+ }
14
+
15
+ export interface ProtocolBody {
16
+ intent: string
17
+ content: string
18
+ capability?: string
19
+ correlationId?: string
20
+ }
21
+
22
+ export interface ProtocolEnvelope {
23
+ header: ProtocolHeader
24
+ body: ProtocolBody
25
+ }
26
+
27
+ // ─── BLS Types ───────────────────────────────────────────────────────────────
28
+
29
+ export interface BlsKeyPair {
30
+ publicKey: string // G1 point, 48 bytes, base64url
31
+ privateKey: string // scalar, 32 bytes, base64url
32
+ }
33
+
34
+ export interface ThresholdConfig {
35
+ m: number // minimum signers required
36
+ n: number // total participants
37
+ }
38
+
39
+ export interface ThresholdSignature {
40
+ alg: 'BLS-G2-2'
41
+ keyId: string // aggregated public key fingerprint (base64url of first 16 bytes)
42
+ value: string // aggregated signature (base64url, G2 point 96 bytes)
43
+ signerIds: string[] // which participants signed
44
+ threshold: ThresholdConfig
45
+ }
46
+
47
+ export interface ThresholdEnvelope extends ProtocolEnvelope {
48
+ thresholdSignature: ThresholdSignature
49
+ }
50
+
51
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
52
+
53
+ function toBase64Url(bytes: Uint8Array): string {
54
+ const base64 = Buffer.from(bytes).toString('base64')
55
+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
56
+ }
57
+
58
+ function fromBase64Url(value: string): Uint8Array {
59
+ const padded = value
60
+ .replace(/-/g, '+')
61
+ .replace(/_/g, '/')
62
+ .padEnd(Math.ceil(value.length / 4) * 4, '=')
63
+ return new Uint8Array(Buffer.from(padded, 'base64'))
64
+ }
65
+
66
+ async function sha256(data: string): Promise<Uint8Array> {
67
+ const encoder = new TextEncoder()
68
+ const buf = await crypto.subtle.digest('SHA-256', encoder.encode(data))
69
+ return new Uint8Array(buf)
70
+ }
71
+
72
+ /**
73
+ * Canonical serialization of a protocol envelope for signing.
74
+ * Must match the canonical format in @7h3/protocol.
75
+ */
76
+ export function canonicalizeEnvelopeForBls(envelope: ProtocolEnvelope): string {
77
+ const h = envelope.header
78
+ const b = envelope.body
79
+
80
+ const headerParts: string[] = [
81
+ `"messageId":${JSON.stringify(h.messageId)}`,
82
+ `"nonce":${JSON.stringify(h.nonce)}`,
83
+ ]
84
+ if (h.recipient !== undefined) {
85
+ headerParts.push(`"recipient":${JSON.stringify(h.recipient)}`)
86
+ }
87
+ headerParts.push(`"sender":${JSON.stringify(h.sender)}`)
88
+ headerParts.push(`"timestampMs":${h.timestampMs}`)
89
+ headerParts.push(`"ttlMs":${h.ttlMs}`)
90
+ headerParts.push(`"version":${JSON.stringify(h.version)}`)
91
+ const headerStr = `{${headerParts.join(',')}}`
92
+
93
+ const bodyParts: string[] = []
94
+ if (b.capability !== undefined) bodyParts.push(`"capability":${JSON.stringify(b.capability)}`)
95
+ bodyParts.push(`"content":${JSON.stringify(b.content)}`)
96
+ if (b.correlationId !== undefined) bodyParts.push(`"correlationId":${JSON.stringify(b.correlationId)}`)
97
+ bodyParts.push(`"intent":${JSON.stringify(b.intent)}`)
98
+ const bodyStr = `{${bodyParts.join(',')}}`
99
+
100
+ return `{"body":${bodyStr},"header":${headerStr}}`
101
+ }
102
+
103
+ // ─── Key Generation ──────────────────────────────────────────────────────────
104
+
105
+ export function generateBlsKeyPair(): BlsKeyPair {
106
+ const privateKeyBytes = bls12_381.utils.randomPrivateKey()
107
+ const publicKeyBytes = bls12_381.getPublicKey(privateKeyBytes)
108
+ return {
109
+ publicKey: toBase64Url(publicKeyBytes),
110
+ privateKey: toBase64Url(privateKeyBytes),
111
+ }
112
+ }
113
+
114
+ // ─── Partial Signing ─────────────────────────────────────────────────────────
115
+
116
+ export async function signEnvelopeBls(
117
+ envelope: ProtocolEnvelope,
118
+ privateKeyBase64Url: string,
119
+ signerId: string,
120
+ ): Promise<{ signerId: string; partialSig: string; canonicalHash: string }> {
121
+ const canonical = canonicalizeEnvelopeForBls(envelope)
122
+ const msgHash = await sha256(canonical)
123
+ const privateKeyBytes = fromBase64Url(privateKeyBase64Url)
124
+ // BLS sign: signature is a G2 point (96 bytes)
125
+ const sigBytes = bls12_381.sign(msgHash, privateKeyBytes)
126
+ return {
127
+ signerId,
128
+ partialSig: toBase64Url(sigBytes),
129
+ canonicalHash: toBase64Url(msgHash),
130
+ }
131
+ }
132
+
133
+ // ─── Aggregation ─────────────────────────────────────────────────────────────
134
+
135
+ export async function aggregateSignatures(
136
+ partialSigs: Array<{ signerId: string; partialSig: string }>,
137
+ publicKeys: Record<string, string>, // signerId → BLS public key (base64url)
138
+ envelope: ProtocolEnvelope,
139
+ config: ThresholdConfig,
140
+ ): Promise<ThresholdEnvelope> {
141
+ if (partialSigs.length < config.m) {
142
+ throw new Error(
143
+ `Threshold not met: need ${config.m} signatures, got ${partialSigs.length}`,
144
+ )
145
+ }
146
+
147
+ // Use exactly m signatures (first m)
148
+ const selected = partialSigs.slice(0, config.m)
149
+
150
+ const signerIds = selected.map((s) => s.signerId)
151
+ const sigBytesArr = selected.map((s) => fromBase64Url(s.partialSig))
152
+ const pubKeyBytesArr = signerIds.map((id) => {
153
+ const pk = publicKeys[id]
154
+ if (!pk) throw new Error(`Missing public key for signer: ${id}`)
155
+ return fromBase64Url(pk)
156
+ })
157
+
158
+ const aggregatedSig = bls12_381.aggregateSignatures(sigBytesArr)
159
+ const aggregatedPubKey = bls12_381.aggregatePublicKeys(pubKeyBytesArr)
160
+
161
+ // Fingerprint: first 16 bytes of aggregated pubkey as base64url
162
+ const keyId = toBase64Url(aggregatedPubKey.slice(0, 16))
163
+
164
+ return {
165
+ ...envelope,
166
+ thresholdSignature: {
167
+ alg: 'BLS-G2-2',
168
+ keyId,
169
+ value: toBase64Url(aggregatedSig),
170
+ signerIds,
171
+ threshold: config,
172
+ },
173
+ }
174
+ }
175
+
176
+ // ─── Verification ────────────────────────────────────────────────────────────
177
+
178
+ export async function verifyThresholdEnvelope(
179
+ envelope: ThresholdEnvelope,
180
+ participantPublicKeys: Record<string, string>,
181
+ config: ThresholdConfig,
182
+ ): Promise<boolean> {
183
+ try {
184
+ const { thresholdSignature } = envelope
185
+ if (!thresholdSignature) return false
186
+ if (thresholdSignature.alg !== 'BLS-G2-2') return false
187
+ if (thresholdSignature.signerIds.length < config.m) return false
188
+
189
+ const canonical = canonicalizeEnvelopeForBls({
190
+ header: envelope.header,
191
+ body: envelope.body,
192
+ })
193
+ const msgHash = await sha256(canonical)
194
+
195
+ const signerIds = thresholdSignature.signerIds
196
+ const pubKeyBytesArr = signerIds.map((id) => {
197
+ const pk = participantPublicKeys[id]
198
+ if (!pk) throw new Error(`Missing public key for signer: ${id}`)
199
+ return fromBase64Url(pk)
200
+ })
201
+
202
+ const aggregatedPubKey = bls12_381.aggregatePublicKeys(pubKeyBytesArr)
203
+ const sigBytes = fromBase64Url(thresholdSignature.value)
204
+
205
+ return bls12_381.verify(sigBytes, msgHash, aggregatedPubKey)
206
+ } catch {
207
+ return false
208
+ }
209
+ }
210
+
211
+ // ─── Shamir Secret Sharing ───────────────────────────────────────────────────
212
+ // Operates over the BLS12-381 scalar field (Fr), prime order r.
213
+
214
+ // BLS12-381 scalar field order r
215
+ const FIELD_ORDER = BigInt(
216
+ '0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001',
217
+ )
218
+
219
+ function fieldMod(n: bigint): bigint {
220
+ return ((n % FIELD_ORDER) + FIELD_ORDER) % FIELD_ORDER
221
+ }
222
+
223
+ function fieldAdd(a: bigint, b: bigint): bigint {
224
+ return fieldMod(a + b)
225
+ }
226
+
227
+ function fieldMul(a: bigint, b: bigint): bigint {
228
+ return fieldMod(a * b)
229
+ }
230
+
231
+ // Modular inverse via Fermat's little theorem (field is prime order)
232
+ function fieldInv(a: bigint): bigint {
233
+ if (a === 0n) throw new Error('Cannot invert zero')
234
+ return fieldPow(a, FIELD_ORDER - 2n)
235
+ }
236
+
237
+ function fieldPow(base: bigint, exp: bigint): bigint {
238
+ let result = 1n
239
+ base = fieldMod(base)
240
+ while (exp > 0n) {
241
+ if (exp & 1n) result = fieldMul(result, base)
242
+ base = fieldMul(base, base)
243
+ exp >>= 1n
244
+ }
245
+ return result
246
+ }
247
+
248
+ function bigintToBytes32(n: bigint): Uint8Array {
249
+ const hex = n.toString(16).padStart(64, '0')
250
+ const bytes = new Uint8Array(32)
251
+ for (let i = 0; i < 32; i++) {
252
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)
253
+ }
254
+ return bytes
255
+ }
256
+
257
+ function bytes32ToBigint(bytes: Uint8Array): bigint {
258
+ let hex = ''
259
+ for (const b of bytes) {
260
+ hex += b.toString(16).padStart(2, '0')
261
+ }
262
+ return BigInt('0x' + hex)
263
+ }
264
+
265
+ // Generate a cryptographically random field element
266
+ function randomFieldElement(): bigint {
267
+ const bytes = new Uint8Array(32)
268
+ crypto.getRandomValues(bytes)
269
+ return fieldMod(bytes32ToBigint(bytes))
270
+ }
271
+
272
+ /**
273
+ * Split a BLS private key into N shares using Shamir's Secret Sharing.
274
+ * Any M shares can reconstruct the original key.
275
+ * Returns N shares as base64url strings.
276
+ * Share format: 1 byte index (1-based) || 32 bytes value
277
+ */
278
+ export function splitPrivateKey(
279
+ privateKeyBase64Url: string,
280
+ m: number,
281
+ n: number,
282
+ ): string[] {
283
+ if (m < 2 || m > n) throw new Error(`Invalid threshold: m=${m}, n=${n}`)
284
+
285
+ const secretBytes = fromBase64Url(privateKeyBase64Url)
286
+ const secret = fieldMod(bytes32ToBigint(secretBytes))
287
+
288
+ // Build polynomial: f(x) = secret + a1*x + a2*x^2 + ... + a_{m-1}*x^{m-1}
289
+ const coefficients: bigint[] = [secret]
290
+ for (let i = 1; i < m; i++) {
291
+ coefficients.push(randomFieldElement())
292
+ }
293
+
294
+ // Evaluate at x = 1..n
295
+ const shares: string[] = []
296
+ for (let x = 1; x <= n; x++) {
297
+ let y = 0n
298
+ let xPow = 1n
299
+ for (const coeff of coefficients) {
300
+ y = fieldAdd(y, fieldMul(coeff, xPow))
301
+ xPow = fieldMul(xPow, BigInt(x))
302
+ }
303
+ // Encode share: index byte + 32-byte value
304
+ const shareBytes = new Uint8Array(33)
305
+ shareBytes[0] = x
306
+ shareBytes.set(bigintToBytes32(y), 1)
307
+ shares.push(toBase64Url(shareBytes))
308
+ }
309
+
310
+ return shares
311
+ }
312
+
313
+ /**
314
+ * Reconstruct a BLS private key from M or more shares using Lagrange interpolation.
315
+ * @param shares - array of share strings (base64url, at least m of them)
316
+ * @param m - minimum number of shares required (used for validation only)
317
+ */
318
+ export function reconstructPrivateKey(shares: string[], m: number): string {
319
+ if (shares.length < m) {
320
+ throw new Error(`Need at least ${m} shares, got ${shares.length}`)
321
+ }
322
+
323
+ // Decode shares — take exactly m
324
+ const decoded = shares.slice(0, m).map((s) => {
325
+ const bytes = fromBase64Url(s)
326
+ if (bytes.length !== 33) throw new Error('Invalid share format')
327
+ const x = BigInt(bytes[0])
328
+ const y = bytes32ToBigint(bytes.slice(1))
329
+ return { x, y }
330
+ })
331
+
332
+ // Lagrange interpolation at x=0 to recover secret
333
+ let secret = 0n
334
+ for (let i = 0; i < decoded.length; i++) {
335
+ const xi = decoded[i].x
336
+ const yi = decoded[i].y
337
+
338
+ // Compute Lagrange basis polynomial l_i(0)
339
+ let num = 1n
340
+ let den = 1n
341
+ for (let j = 0; j < decoded.length; j++) {
342
+ if (i === j) continue
343
+ const xj = decoded[j].x
344
+ // num *= (0 - xj) = -xj
345
+ num = fieldMul(num, fieldMod(-xj))
346
+ // den *= (xi - xj)
347
+ den = fieldMul(den, fieldMod(xi - xj))
348
+ }
349
+
350
+ const lagrangeBasis = fieldMul(num, fieldInv(den))
351
+ secret = fieldAdd(secret, fieldMul(yi, lagrangeBasis))
352
+ }
353
+
354
+ return toBase64Url(bigintToBytes32(secret))
355
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "lib": ["ES2023", "DOM"],
7
+ "types": ["node"],
8
+ "strict": true,
9
+ "skipLibCheck": true,
10
+ "declaration": true,
11
+ "declarationMap": true,
12
+ "outDir": ".",
13
+ "rootDir": "./src",
14
+ "esModuleInterop": true,
15
+ "verbatimModuleSyntax": false
16
+ },
17
+ "include": ["src/index.ts"],
18
+ "exclude": ["src/**/*.test.ts", "node_modules"]
19
+ }
@@ -0,0 +1,12 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: 'node',
6
+ },
7
+ resolve: {
8
+ alias: {
9
+ '@7h3/protocol': '/tmp/aip-work/src/protocol.ts',
10
+ },
11
+ },
12
+ })