@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,254 @@
1
+ import { bls12_381 } from '@noble/curves/bls12-381';
2
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
3
+ function toBase64Url(bytes) {
4
+ const base64 = Buffer.from(bytes).toString('base64');
5
+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
6
+ }
7
+ function fromBase64Url(value) {
8
+ const padded = value
9
+ .replace(/-/g, '+')
10
+ .replace(/_/g, '/')
11
+ .padEnd(Math.ceil(value.length / 4) * 4, '=');
12
+ return new Uint8Array(Buffer.from(padded, 'base64'));
13
+ }
14
+ async function sha256(data) {
15
+ const encoder = new TextEncoder();
16
+ const buf = await crypto.subtle.digest('SHA-256', encoder.encode(data));
17
+ return new Uint8Array(buf);
18
+ }
19
+ /**
20
+ * Canonical serialization of a protocol envelope for signing.
21
+ * Must match the canonical format in @7h3/protocol.
22
+ */
23
+ export function canonicalizeEnvelopeForBls(envelope) {
24
+ const h = envelope.header;
25
+ const b = envelope.body;
26
+ const headerParts = [
27
+ `"messageId":${JSON.stringify(h.messageId)}`,
28
+ `"nonce":${JSON.stringify(h.nonce)}`,
29
+ ];
30
+ if (h.recipient !== undefined) {
31
+ headerParts.push(`"recipient":${JSON.stringify(h.recipient)}`);
32
+ }
33
+ headerParts.push(`"sender":${JSON.stringify(h.sender)}`);
34
+ headerParts.push(`"timestampMs":${h.timestampMs}`);
35
+ headerParts.push(`"ttlMs":${h.ttlMs}`);
36
+ headerParts.push(`"version":${JSON.stringify(h.version)}`);
37
+ const headerStr = `{${headerParts.join(',')}}`;
38
+ const bodyParts = [];
39
+ if (b.capability !== undefined)
40
+ bodyParts.push(`"capability":${JSON.stringify(b.capability)}`);
41
+ bodyParts.push(`"content":${JSON.stringify(b.content)}`);
42
+ if (b.correlationId !== undefined)
43
+ bodyParts.push(`"correlationId":${JSON.stringify(b.correlationId)}`);
44
+ bodyParts.push(`"intent":${JSON.stringify(b.intent)}`);
45
+ const bodyStr = `{${bodyParts.join(',')}}`;
46
+ return `{"body":${bodyStr},"header":${headerStr}}`;
47
+ }
48
+ // ─── Key Generation ──────────────────────────────────────────────────────────
49
+ export function generateBlsKeyPair() {
50
+ const privateKeyBytes = bls12_381.utils.randomPrivateKey();
51
+ const publicKeyBytes = bls12_381.getPublicKey(privateKeyBytes);
52
+ return {
53
+ publicKey: toBase64Url(publicKeyBytes),
54
+ privateKey: toBase64Url(privateKeyBytes),
55
+ };
56
+ }
57
+ // ─── Partial Signing ─────────────────────────────────────────────────────────
58
+ export async function signEnvelopeBls(envelope, privateKeyBase64Url, signerId) {
59
+ const canonical = canonicalizeEnvelopeForBls(envelope);
60
+ const msgHash = await sha256(canonical);
61
+ const privateKeyBytes = fromBase64Url(privateKeyBase64Url);
62
+ // BLS sign: signature is a G2 point (96 bytes)
63
+ const sigBytes = bls12_381.sign(msgHash, privateKeyBytes);
64
+ return {
65
+ signerId,
66
+ partialSig: toBase64Url(sigBytes),
67
+ canonicalHash: toBase64Url(msgHash),
68
+ };
69
+ }
70
+ // ─── Aggregation ─────────────────────────────────────────────────────────────
71
+ export async function aggregateSignatures(partialSigs, publicKeys, // signerId → BLS public key (base64url)
72
+ envelope, config) {
73
+ if (partialSigs.length < config.m) {
74
+ throw new Error(`Threshold not met: need ${config.m} signatures, got ${partialSigs.length}`);
75
+ }
76
+ // Use exactly m signatures (first m)
77
+ const selected = partialSigs.slice(0, config.m);
78
+ const signerIds = selected.map((s) => s.signerId);
79
+ const sigBytesArr = selected.map((s) => fromBase64Url(s.partialSig));
80
+ const pubKeyBytesArr = signerIds.map((id) => {
81
+ const pk = publicKeys[id];
82
+ if (!pk)
83
+ throw new Error(`Missing public key for signer: ${id}`);
84
+ return fromBase64Url(pk);
85
+ });
86
+ const aggregatedSig = bls12_381.aggregateSignatures(sigBytesArr);
87
+ const aggregatedPubKey = bls12_381.aggregatePublicKeys(pubKeyBytesArr);
88
+ // Fingerprint: first 16 bytes of aggregated pubkey as base64url
89
+ const keyId = toBase64Url(aggregatedPubKey.slice(0, 16));
90
+ return {
91
+ ...envelope,
92
+ thresholdSignature: {
93
+ alg: 'BLS-G2-2',
94
+ keyId,
95
+ value: toBase64Url(aggregatedSig),
96
+ signerIds,
97
+ threshold: config,
98
+ },
99
+ };
100
+ }
101
+ // ─── Verification ────────────────────────────────────────────────────────────
102
+ export async function verifyThresholdEnvelope(envelope, participantPublicKeys, config) {
103
+ try {
104
+ const { thresholdSignature } = envelope;
105
+ if (!thresholdSignature)
106
+ return false;
107
+ if (thresholdSignature.alg !== 'BLS-G2-2')
108
+ return false;
109
+ if (thresholdSignature.signerIds.length < config.m)
110
+ return false;
111
+ const canonical = canonicalizeEnvelopeForBls({
112
+ header: envelope.header,
113
+ body: envelope.body,
114
+ });
115
+ const msgHash = await sha256(canonical);
116
+ const signerIds = thresholdSignature.signerIds;
117
+ const pubKeyBytesArr = signerIds.map((id) => {
118
+ const pk = participantPublicKeys[id];
119
+ if (!pk)
120
+ throw new Error(`Missing public key for signer: ${id}`);
121
+ return fromBase64Url(pk);
122
+ });
123
+ const aggregatedPubKey = bls12_381.aggregatePublicKeys(pubKeyBytesArr);
124
+ const sigBytes = fromBase64Url(thresholdSignature.value);
125
+ return bls12_381.verify(sigBytes, msgHash, aggregatedPubKey);
126
+ }
127
+ catch {
128
+ return false;
129
+ }
130
+ }
131
+ // ─── Shamir Secret Sharing ───────────────────────────────────────────────────
132
+ // Operates over the BLS12-381 scalar field (Fr), prime order r.
133
+ // BLS12-381 scalar field order r
134
+ const FIELD_ORDER = BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001');
135
+ function fieldMod(n) {
136
+ return ((n % FIELD_ORDER) + FIELD_ORDER) % FIELD_ORDER;
137
+ }
138
+ function fieldAdd(a, b) {
139
+ return fieldMod(a + b);
140
+ }
141
+ function fieldMul(a, b) {
142
+ return fieldMod(a * b);
143
+ }
144
+ // Modular inverse via Fermat's little theorem (field is prime order)
145
+ function fieldInv(a) {
146
+ if (a === 0n)
147
+ throw new Error('Cannot invert zero');
148
+ return fieldPow(a, FIELD_ORDER - 2n);
149
+ }
150
+ function fieldPow(base, exp) {
151
+ let result = 1n;
152
+ base = fieldMod(base);
153
+ while (exp > 0n) {
154
+ if (exp & 1n)
155
+ result = fieldMul(result, base);
156
+ base = fieldMul(base, base);
157
+ exp >>= 1n;
158
+ }
159
+ return result;
160
+ }
161
+ function bigintToBytes32(n) {
162
+ const hex = n.toString(16).padStart(64, '0');
163
+ const bytes = new Uint8Array(32);
164
+ for (let i = 0; i < 32; i++) {
165
+ bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
166
+ }
167
+ return bytes;
168
+ }
169
+ function bytes32ToBigint(bytes) {
170
+ let hex = '';
171
+ for (const b of bytes) {
172
+ hex += b.toString(16).padStart(2, '0');
173
+ }
174
+ return BigInt('0x' + hex);
175
+ }
176
+ // Generate a cryptographically random field element
177
+ function randomFieldElement() {
178
+ const bytes = new Uint8Array(32);
179
+ crypto.getRandomValues(bytes);
180
+ return fieldMod(bytes32ToBigint(bytes));
181
+ }
182
+ /**
183
+ * Split a BLS private key into N shares using Shamir's Secret Sharing.
184
+ * Any M shares can reconstruct the original key.
185
+ * Returns N shares as base64url strings.
186
+ * Share format: 1 byte index (1-based) || 32 bytes value
187
+ */
188
+ export function splitPrivateKey(privateKeyBase64Url, m, n) {
189
+ if (m < 2 || m > n)
190
+ throw new Error(`Invalid threshold: m=${m}, n=${n}`);
191
+ const secretBytes = fromBase64Url(privateKeyBase64Url);
192
+ const secret = fieldMod(bytes32ToBigint(secretBytes));
193
+ // Build polynomial: f(x) = secret + a1*x + a2*x^2 + ... + a_{m-1}*x^{m-1}
194
+ const coefficients = [secret];
195
+ for (let i = 1; i < m; i++) {
196
+ coefficients.push(randomFieldElement());
197
+ }
198
+ // Evaluate at x = 1..n
199
+ const shares = [];
200
+ for (let x = 1; x <= n; x++) {
201
+ let y = 0n;
202
+ let xPow = 1n;
203
+ for (const coeff of coefficients) {
204
+ y = fieldAdd(y, fieldMul(coeff, xPow));
205
+ xPow = fieldMul(xPow, BigInt(x));
206
+ }
207
+ // Encode share: index byte + 32-byte value
208
+ const shareBytes = new Uint8Array(33);
209
+ shareBytes[0] = x;
210
+ shareBytes.set(bigintToBytes32(y), 1);
211
+ shares.push(toBase64Url(shareBytes));
212
+ }
213
+ return shares;
214
+ }
215
+ /**
216
+ * Reconstruct a BLS private key from M or more shares using Lagrange interpolation.
217
+ * @param shares - array of share strings (base64url, at least m of them)
218
+ * @param m - minimum number of shares required (used for validation only)
219
+ */
220
+ export function reconstructPrivateKey(shares, m) {
221
+ if (shares.length < m) {
222
+ throw new Error(`Need at least ${m} shares, got ${shares.length}`);
223
+ }
224
+ // Decode shares — take exactly m
225
+ const decoded = shares.slice(0, m).map((s) => {
226
+ const bytes = fromBase64Url(s);
227
+ if (bytes.length !== 33)
228
+ throw new Error('Invalid share format');
229
+ const x = BigInt(bytes[0]);
230
+ const y = bytes32ToBigint(bytes.slice(1));
231
+ return { x, y };
232
+ });
233
+ // Lagrange interpolation at x=0 to recover secret
234
+ let secret = 0n;
235
+ for (let i = 0; i < decoded.length; i++) {
236
+ const xi = decoded[i].x;
237
+ const yi = decoded[i].y;
238
+ // Compute Lagrange basis polynomial l_i(0)
239
+ let num = 1n;
240
+ let den = 1n;
241
+ for (let j = 0; j < decoded.length; j++) {
242
+ if (i === j)
243
+ continue;
244
+ const xj = decoded[j].x;
245
+ // num *= (0 - xj) = -xj
246
+ num = fieldMul(num, fieldMod(-xj));
247
+ // den *= (xi - xj)
248
+ den = fieldMul(den, fieldMod(xi - xj));
249
+ }
250
+ const lagrangeBasis = fieldMul(num, fieldInv(den));
251
+ secret = fieldAdd(secret, fieldMul(yi, lagrangeBasis));
252
+ }
253
+ return toBase64Url(bigintToBytes32(secret));
254
+ }