@reclaimprotocol/attestor-core 5.0.1-beta.21 → 5.0.1-beta.22

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 (132) hide show
  1. package/browser/resources/attestor-browser.min.mjs +9 -9
  2. package/lib/avs/abis/avsDirectoryABI.js +340 -0
  3. package/lib/avs/abis/delegationABI.js +1 -0
  4. package/lib/avs/abis/registryABI.js +725 -0
  5. package/lib/avs/client/create-claim-on-avs.js +140 -0
  6. package/lib/avs/config.js +20 -0
  7. package/lib/avs/contracts/factories/ReclaimServiceManager__factory.js +1166 -0
  8. package/lib/avs/contracts/factories/index.js +4 -0
  9. package/lib/avs/contracts/index.js +2 -0
  10. package/lib/avs/utils/contracts.js +33 -0
  11. package/lib/avs/utils/register.js +79 -0
  12. package/lib/avs/utils/tasks.js +41 -0
  13. package/lib/client/create-claim.js +432 -0
  14. package/lib/client/index.js +3 -0
  15. package/lib/client/tunnels/make-rpc-tcp-tunnel.js +51 -0
  16. package/lib/client/tunnels/make-rpc-tls-tunnel.js +131 -0
  17. package/lib/client/utils/attestor-pool.js +25 -0
  18. package/lib/client/utils/client-socket.js +97 -0
  19. package/lib/client/utils/message-handler.js +87 -0
  20. package/lib/config/index.js +44 -0
  21. package/lib/external-rpc/benchmark.js +69 -0
  22. package/lib/external-rpc/event-bus.js +14 -0
  23. package/lib/external-rpc/handle-incoming-msg.js +232 -0
  24. package/lib/external-rpc/index.js +3 -10399
  25. package/lib/external-rpc/jsc-polyfills/1.js +82 -0
  26. package/lib/external-rpc/jsc-polyfills/2.js +20 -0
  27. package/lib/external-rpc/jsc-polyfills/event.js +14 -0
  28. package/lib/external-rpc/jsc-polyfills/index.js +2 -0
  29. package/lib/external-rpc/jsc-polyfills/ws.js +81 -0
  30. package/lib/external-rpc/setup-browser.js +33 -0
  31. package/lib/external-rpc/setup-jsc.js +22 -0
  32. package/lib/external-rpc/types.js +1 -0
  33. package/lib/external-rpc/utils.js +100 -0
  34. package/lib/external-rpc/zk.js +63 -0
  35. package/lib/index.js +9 -8326
  36. package/lib/mechain/abis/governanceABI.js +458 -0
  37. package/lib/mechain/abis/taskABI.js +509 -0
  38. package/lib/mechain/client/create-claim-on-mechain.js +28 -0
  39. package/lib/mechain/client/index.js +1 -0
  40. package/lib/mechain/constants/index.js +3 -0
  41. package/lib/mechain/index.js +2 -0
  42. package/lib/proto/api.js +4363 -0
  43. package/lib/proto/tee-bundle.js +1316 -0
  44. package/lib/providers/http/index.js +653 -0
  45. package/lib/providers/http/patch-parse5-tree.js +32 -0
  46. package/lib/providers/http/utils.js +324 -0
  47. package/lib/providers/index.js +4 -0
  48. package/lib/server/create-server.js +103 -0
  49. package/lib/server/handlers/claimTeeBundle.js +252 -0
  50. package/lib/server/handlers/claimTunnel.js +73 -0
  51. package/lib/server/handlers/completeClaimOnChain.js +24 -0
  52. package/lib/server/handlers/createClaimOnChain.js +26 -0
  53. package/lib/server/handlers/createTaskOnMechain.js +47 -0
  54. package/lib/server/handlers/createTunnel.js +93 -0
  55. package/lib/server/handlers/disconnectTunnel.js +5 -0
  56. package/lib/server/handlers/fetchCertificateBytes.js +41 -0
  57. package/lib/server/handlers/index.js +22 -0
  58. package/lib/server/handlers/init.js +32 -0
  59. package/lib/server/handlers/toprf.js +16 -0
  60. package/lib/server/index.js +4 -0
  61. package/lib/server/socket.js +109 -0
  62. package/lib/server/tunnels/make-tcp-tunnel.js +177 -0
  63. package/lib/server/utils/apm.js +36 -0
  64. package/lib/server/utils/assert-valid-claim-request.js +325 -0
  65. package/lib/server/utils/config-env.js +4 -0
  66. package/lib/server/utils/dns.js +18 -0
  67. package/lib/server/utils/gcp-attestation.js +289 -0
  68. package/lib/server/utils/generics.d.ts +1 -1
  69. package/lib/server/utils/generics.js +51 -0
  70. package/lib/server/utils/iso.js +256 -0
  71. package/lib/server/utils/keep-alive.js +38 -0
  72. package/lib/server/utils/nitro-attestation.js +324 -0
  73. package/lib/server/utils/oprf-raw.js +54 -0
  74. package/lib/server/utils/process-handshake.js +215 -0
  75. package/lib/server/utils/proxy-session.js +6 -0
  76. package/lib/server/utils/tee-oprf-mpc-verification.js +90 -0
  77. package/lib/server/utils/tee-oprf-verification.js +174 -0
  78. package/lib/server/utils/tee-transcript-reconstruction.js +187 -0
  79. package/lib/server/utils/tee-verification.js +421 -0
  80. package/lib/server/utils/validation.js +38 -0
  81. package/lib/types/bgp.js +1 -0
  82. package/lib/types/claims.js +1 -0
  83. package/lib/types/client.js +1 -0
  84. package/lib/types/general.js +1 -0
  85. package/lib/types/handlers.js +1 -0
  86. package/lib/types/index.js +10 -0
  87. package/lib/types/providers.d.ts +3 -2
  88. package/lib/types/providers.gen.js +10 -0
  89. package/lib/types/providers.js +1 -0
  90. package/lib/types/rpc.js +1 -0
  91. package/lib/types/signatures.d.ts +1 -2
  92. package/lib/types/signatures.js +1 -0
  93. package/lib/types/tunnel.js +1 -0
  94. package/lib/types/zk.js +1 -0
  95. package/lib/utils/auth.js +59 -0
  96. package/lib/utils/b64-json.js +17 -0
  97. package/lib/utils/bgp-listener.js +119 -0
  98. package/lib/utils/claims.js +98 -0
  99. package/lib/utils/env.js +15 -0
  100. package/lib/utils/error.js +50 -0
  101. package/lib/utils/generics.js +317 -0
  102. package/lib/utils/http-parser.js +246 -0
  103. package/lib/utils/index.js +13 -0
  104. package/lib/utils/logger.js +91 -0
  105. package/lib/utils/prepare-packets.js +71 -0
  106. package/lib/utils/redactions.js +177 -0
  107. package/lib/utils/retries.js +24 -0
  108. package/lib/utils/signatures/eth.js +32 -0
  109. package/lib/utils/signatures/index.js +7 -0
  110. package/lib/utils/socket-base.js +92 -0
  111. package/lib/utils/tls.js +58 -0
  112. package/lib/utils/ws.js +22 -0
  113. package/lib/utils/zk.js +585 -0
  114. package/package.json +5 -3
  115. package/lib/scripts/check-avs-registration.d.ts +0 -1
  116. package/lib/scripts/fallbacks/crypto.d.ts +0 -1
  117. package/lib/scripts/fallbacks/empty.d.ts +0 -3
  118. package/lib/scripts/fallbacks/re2.d.ts +0 -1
  119. package/lib/scripts/fallbacks/snarkjs.d.ts +0 -1
  120. package/lib/scripts/fallbacks/stwo.d.ts +0 -6
  121. package/lib/scripts/generate-provider-types.d.ts +0 -5
  122. package/lib/scripts/generate-receipt.d.ts +0 -9
  123. package/lib/scripts/jsc-cli-rpc.d.ts +0 -1
  124. package/lib/scripts/register-avs-operator.d.ts +0 -1
  125. package/lib/scripts/start-server.d.ts +0 -1
  126. package/lib/scripts/update-avs-metadata.d.ts +0 -1
  127. package/lib/scripts/utils.d.ts +0 -1
  128. package/lib/scripts/whitelist-operator.d.ts +0 -1
  129. /package/lib/{scripts/build-browser.d.ts → avs/contracts/ReclaimServiceManager.js} +0 -0
  130. /package/lib/{scripts/build-jsc.d.ts → avs/contracts/common.js} +0 -0
  131. /package/lib/{scripts/build-lib.d.ts → avs/types/index.js} +0 -0
  132. /package/lib/{scripts/generate-toprf-keys.d.ts → mechain/types/index.js} +0 -0
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Working Nitro Attestation validation utilities
3
+ */
4
+ import { AsnParser } from '@peculiar/asn1-schema';
5
+ import { SubjectPublicKeyInfo } from '@peculiar/asn1-x509';
6
+ import { Crypto } from '@peculiar/webcrypto';
7
+ import { X509Certificate, X509ChainBuilder } from '@peculiar/x509';
8
+ import { sign } from 'cose-js';
9
+ // Helper function to dynamically import cbor-x
10
+ async function getCborDecode() {
11
+ const { decode } = await import('cbor-x');
12
+ return decode;
13
+ }
14
+ // AWS Nitro root certificate (from nitrite)
15
+ const AWS_NITRO_ROOT_CERT = `-----BEGIN CERTIFICATE-----
16
+ MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTEL
17
+ MAkGA1UEBhMCVVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYD
18
+ VQQDDBJhd3Mubml0cm8tZW5jbGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4
19
+ MTQyODA1WjBJMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMQwwCgYDVQQL
20
+ DANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2MBAGByqGSM49AgEG
21
+ BSuBBAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSksfbb
22
+ 48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ3BABIeTPYwEoCWZE
23
+ h8l5YoQwTcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkF
24
+ R+eWw5b6cp3PmanfS5YwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYC
25
+ MQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5W2OpYow9OYCVRaEevL8uO1XYru5xtMPW
26
+ rfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/nNr12UO8Yfwr6wPLb+6N
27
+ IwLz3/Y=
28
+ -----END CERTIFICATE-----`;
29
+ // Expected PCR values (replace with actual values)
30
+ // const EXPECTED_PCRS = {
31
+ // //0: Buffer.from('000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', 'hex'),
32
+ // }
33
+ //
34
+ // // Secure buffer comparison to prevent timing attacks
35
+ // function secureBufferCompare(a: Buffer, b: Buffer): boolean {
36
+ // if(a.length !== b.length) {
37
+ // return false
38
+ // }
39
+ //
40
+ // let result = 0
41
+ // for(const [i, element] of a.entries()) {
42
+ // result |= element ^ b[i]
43
+ // }
44
+ //
45
+ // return result === 0
46
+ // }
47
+ // Enhanced certificate chain validation
48
+ async function validateCertificateChain(targetCert, intermediateCerts, rootCert, crypto) {
49
+ const errors = [];
50
+ try {
51
+ // Validate root certificate is self-signed and trusted
52
+ const rootSubject = rootCert.subject;
53
+ const rootIssuer = rootCert.issuer;
54
+ if (rootSubject !== rootIssuer) {
55
+ errors.push('Root certificate is not self-signed');
56
+ }
57
+ // Verify root certificate signature (self-verification)
58
+ try {
59
+ const isRootValid = await rootCert.verify(undefined, crypto);
60
+ if (!isRootValid) {
61
+ errors.push('Root certificate signature verification failed');
62
+ }
63
+ }
64
+ catch (error) {
65
+ errors.push(`Root certificate verification failed: ${error.message}`);
66
+ }
67
+ // Build the certificate chain
68
+ const chainBuilder = new X509ChainBuilder({
69
+ certificates: [rootCert, ...intermediateCerts]
70
+ });
71
+ let chain;
72
+ try {
73
+ chain = await chainBuilder.build(targetCert, crypto);
74
+ }
75
+ catch (error) {
76
+ errors.push(`Certificate chain building failed: ${error.message}`);
77
+ return { isValid: false, errors, chain: [] };
78
+ }
79
+ if (!chain || chain.length === 0) {
80
+ errors.push('No valid certificate chain could be built');
81
+ return { isValid: false, errors, chain: [] };
82
+ }
83
+ // Validate each certificate in the chain
84
+ const now = new Date();
85
+ for (let i = 0; i < chain.length; i++) {
86
+ const cert = chain[i];
87
+ // Check expiration dates
88
+ if (now < cert.notBefore) {
89
+ errors.push(`Certificate ${i} (${cert.subject}) is not yet valid`);
90
+ }
91
+ if (now > cert.notAfter) {
92
+ errors.push(`Certificate ${i} (${cert.subject}) has expired`);
93
+ }
94
+ // Verify each certificate's signature (except root which is self-signed)
95
+ if (i < chain.length - 1) {
96
+ try {
97
+ const issuer = chain[i + 1];
98
+ const isValid = await cert.verify(issuer, crypto);
99
+ if (!isValid) {
100
+ errors.push(`Certificate ${i} signature verification failed`);
101
+ }
102
+ }
103
+ catch (error) {
104
+ errors.push(`Certificate ${i} verification failed: ${error.message}`);
105
+ }
106
+ }
107
+ }
108
+ return {
109
+ isValid: errors.length === 0,
110
+ errors,
111
+ chain
112
+ };
113
+ }
114
+ catch (error) {
115
+ errors.push(`Certificate chain validation error: ${error.message}`);
116
+ return { isValid: false, errors, chain: [] };
117
+ }
118
+ }
119
+ /**
120
+ * Extract public key from user_data field in attestation document
121
+ */
122
+ function extractPublicKeyFromUserData(userDataBuffer) {
123
+ try {
124
+ const userDataString = userDataBuffer.toString('utf-8');
125
+ // Parse new format: "tee_k_public_key:0xETH_ADDRESS" or "tee_t_public_key:0xETH_ADDRESS"
126
+ const teeKMatch = userDataString.match(/^tee_k_public_key:(0x[0-9a-fA-F]{40})$/);
127
+ const teeTMatch = userDataString.match(/^tee_t_public_key:(0x[0-9a-fA-F]{40})$/);
128
+ if (teeKMatch) {
129
+ return {
130
+ teeType: 'tee_k',
131
+ ethAddress: teeKMatch[1], // Store the full ETH address with 0x prefix
132
+ pcr0: ''
133
+ };
134
+ }
135
+ if (teeTMatch) {
136
+ return {
137
+ teeType: 'tee_t',
138
+ ethAddress: teeTMatch[1], // Store the full ETH address with 0x prefix
139
+ pcr0: ''
140
+ };
141
+ }
142
+ return null;
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ }
148
+ /**
149
+ * Working validation function copied from nitroattestor
150
+ */
151
+ export async function validateNitroAttestationAndExtractKey(attestationBytes) {
152
+ const errors = [];
153
+ const warnings = [];
154
+ try {
155
+ // Set up WebCrypto
156
+ const crypto = new Crypto();
157
+ // Decode CBOR - use exact same approach as working nitroattestor
158
+ const decode = await getCborDecode();
159
+ let decoded;
160
+ try {
161
+ decoded = decode(Buffer.from(attestationBytes));
162
+ }
163
+ catch (error) {
164
+ errors.push(`CBOR decoding failed: ${error.message}`);
165
+ return { isValid: false, errors, warnings, pcr0: '' };
166
+ }
167
+ // Extract COSE_Sign1 structure
168
+ if (!Array.isArray(decoded) || decoded.length < 4) {
169
+ errors.push('Invalid COSE_Sign1 structure: expected array with 4 elements');
170
+ return { isValid: false, errors, warnings, pcr0: '' };
171
+ }
172
+ const [, , payload] = decoded;
173
+ // Validate payload exists and is not empty
174
+ if (!payload || payload.length === 0) {
175
+ errors.push('Empty or missing payload in COSE_Sign1 structure');
176
+ return { isValid: false, errors, warnings, pcr0: '' };
177
+ }
178
+ // Decode payload - use exact same approach as working code
179
+ let doc;
180
+ try {
181
+ doc = decode(payload);
182
+ }
183
+ catch (error) {
184
+ errors.push(`Payload decoding failed: ${error.message}`);
185
+ return { isValid: false, errors, warnings, pcr0: '' };
186
+ }
187
+ // Validate mandatory fields with strict type checking
188
+ if (doc.module_id.length === 0) {
189
+ errors.push('Missing or invalid module_id');
190
+ }
191
+ if (doc.digest.length === 0) {
192
+ errors.push('Missing or invalid digest');
193
+ }
194
+ if (!doc.pcrs || typeof doc.pcrs !== 'object') {
195
+ errors.push('Missing or invalid pcrs');
196
+ }
197
+ if (!Buffer.isBuffer(doc.certificate) || doc.certificate.length === 0) {
198
+ errors.push('Missing or invalid certificate');
199
+ }
200
+ if (!Array.isArray(doc.cabundle) || doc.cabundle.length === 0) {
201
+ errors.push('Missing or invalid cabundle');
202
+ }
203
+ // Early return if basic validation fails
204
+ if (errors.length > 0) {
205
+ return { isValid: false, errors, warnings, pcr0: '' };
206
+ }
207
+ const pcr0 = doc.pcrs[0].toString('hex');
208
+ // Validate PCRs with secure comparison
209
+ // for(const [index, expected] of Object.entries(EXPECTED_PCRS)) {
210
+ // const pcrIndex = parseInt(index)
211
+ // const actualPcr = doc.pcrs[pcrIndex]
212
+ //
213
+ // if(!Buffer.isBuffer(actualPcr)) {
214
+ // errors.push(`PCR${index} is not a Buffer`)
215
+ // continue
216
+ // }
217
+ //
218
+ // if(!secureBufferCompare(expected, actualPcr)) {
219
+ // errors.push(`PCR${index} mismatch`)
220
+ // }
221
+ // }
222
+ // Parse certificates with better error handling
223
+ const intermediateCerts = [];
224
+ for (let i = 0; i < doc.cabundle.length; i++) {
225
+ try {
226
+ const cert = new X509Certificate(doc.cabundle[i].toString('base64'));
227
+ intermediateCerts.push(cert);
228
+ }
229
+ catch (error) {
230
+ errors.push(`Failed to parse cabundle certificate ${i}: ${error.message}`);
231
+ }
232
+ }
233
+ // Parse target certificate
234
+ let targetCert;
235
+ try {
236
+ targetCert = new X509Certificate(doc.certificate.toString('base64'));
237
+ }
238
+ catch (error) {
239
+ errors.push(`Failed to parse target certificate: ${error.message}`);
240
+ return { isValid: false, errors, warnings, pcr0: '' };
241
+ }
242
+ // Parse root certificate
243
+ let rootCert;
244
+ try {
245
+ rootCert = new X509Certificate(AWS_NITRO_ROOT_CERT);
246
+ }
247
+ catch (error) {
248
+ errors.push(`Failed to parse AWS Nitro root certificate: ${error.message}`);
249
+ return { isValid: false, errors, warnings, pcr0: '' };
250
+ }
251
+ // Enhanced certificate chain validation
252
+ const chainResult = await validateCertificateChain(targetCert, intermediateCerts, rootCert, crypto);
253
+ if (!chainResult.isValid) {
254
+ errors.push(...chainResult.errors);
255
+ return { isValid: false, errors, warnings, pcr0: '' };
256
+ }
257
+ // Parse and validate public key
258
+ let publicKeyRaw;
259
+ try {
260
+ publicKeyRaw = Buffer.from(targetCert.publicKey.rawData);
261
+ }
262
+ catch (error) {
263
+ errors.push(`Failed to extract public key: ${error.message}`);
264
+ return { isValid: false, errors, warnings, pcr0: '' };
265
+ }
266
+ // Validate public key format (P-384 ECDSA)
267
+ if (publicKeyRaw.length !== 120 || publicKeyRaw[0] !== 0x30) {
268
+ errors.push(`Invalid public key format: expected 120-byte DER-encoded key, got ${publicKeyRaw.length} bytes`);
269
+ return { isValid: false, errors, warnings, pcr0: '' };
270
+ }
271
+ let spki;
272
+ try {
273
+ spki = AsnParser.parse(publicKeyRaw, SubjectPublicKeyInfo);
274
+ }
275
+ catch (error) {
276
+ errors.push(`Failed to parse SubjectPublicKeyInfo: ${error.message}`);
277
+ return { isValid: false, errors, warnings, pcr0: '' };
278
+ }
279
+ const ecPoint = Buffer.from(spki.subjectPublicKey);
280
+ if (ecPoint.length !== 97 || ecPoint[0] !== 0x04) {
281
+ errors.push('Invalid EC point: expected 97-byte uncompressed P-384 key');
282
+ return { isValid: false, errors, warnings, pcr0: '' };
283
+ }
284
+ const x = ecPoint.subarray(1, 49); // 48-byte x coordinate
285
+ const y = ecPoint.subarray(49, 97); // 48-byte y coordinate
286
+ // Validate ECDSA signature using cose-js
287
+ try {
288
+ const verifier = {
289
+ key: {
290
+ x: x,
291
+ y: y,
292
+ },
293
+ };
294
+ const options = { defaultType: 18 }; // cose.sign.Sign1Tag
295
+ await sign.verify(Buffer.from(attestationBytes), verifier, options);
296
+ }
297
+ catch (error) {
298
+ errors.push(`COSE signature verification failed: ${error.message}`);
299
+ return { isValid: false, errors, warnings, pcr0: '' };
300
+ }
301
+ // Extract public key from user_data if present
302
+ let userDataType;
303
+ let ethAddress;
304
+ if (doc.user_data) {
305
+ const keyInfo = extractPublicKeyFromUserData(doc.user_data);
306
+ if (keyInfo) {
307
+ userDataType = keyInfo.teeType;
308
+ ethAddress = keyInfo.ethAddress;
309
+ }
310
+ }
311
+ return {
312
+ isValid: errors.length === 0,
313
+ errors,
314
+ warnings,
315
+ userDataType,
316
+ ethAddress,
317
+ pcr0: pcr0
318
+ };
319
+ }
320
+ catch (error) {
321
+ errors.push(`Unexpected error during validation: ${error.message}`);
322
+ return { isValid: false, errors, warnings, pcr0: '' };
323
+ }
324
+ }
@@ -0,0 +1,54 @@
1
+ import { getBytes } from 'ethers';
2
+ import { TOPRF_DOMAIN_SEPARATOR } from "../../config/index.js";
3
+ import { getEnvVariable } from "../../utils/env.js";
4
+ import { makeDefaultOPRFOperator } from "../../utils/zk.js";
5
+ /**
6
+ * Compute OPRF for plaintext data marked with oprf-raw.
7
+ * This runs server-side since the attestor has access to the revealed plaintext.
8
+ *
9
+ * @param plaintext - The revealed plaintext from the TLS transcript
10
+ * @param markers - Positions in the plaintext to compute OPRF for
11
+ * @param logger - Logger instance
12
+ * @returns Array of OPRF results with nullifiers
13
+ */
14
+ export async function computeOPRFRaw(plaintext, markers, logger) {
15
+ if (!markers.length) {
16
+ return [];
17
+ }
18
+ const PRIVATE_KEY_STR = getEnvVariable('TOPRF_SHARE_PRIVATE_KEY');
19
+ const PUBLIC_KEY_STR = getEnvVariable('TOPRF_SHARE_PUBLIC_KEY');
20
+ if (!PRIVATE_KEY_STR || !PUBLIC_KEY_STR) {
21
+ throw new Error('TOPRF keys not configured. Cannot compute oprf-raw.');
22
+ }
23
+ const privateKey = getBytes(PRIVATE_KEY_STR);
24
+ const publicKey = getBytes(PUBLIC_KEY_STR);
25
+ // Use gnark engine for server-side OPRF (same as TOPRF handler)
26
+ const operator = makeDefaultOPRFOperator('chacha20', 'gnark', logger);
27
+ const results = [];
28
+ for (const marker of markers) {
29
+ const { dataLocation } = marker;
30
+ if (!dataLocation) {
31
+ logger.warn('oprf-raw marker missing dataLocation, skipping');
32
+ continue;
33
+ }
34
+ const { fromIndex, length } = dataLocation;
35
+ const endIndex = fromIndex + length;
36
+ if (endIndex > plaintext.length) {
37
+ throw new Error(`oprf-raw marker out of bounds: fromIndex=${fromIndex}, length=${length}, plaintextLength=${plaintext.length}`);
38
+ }
39
+ // Extract the data to OPRF
40
+ const data = plaintext.slice(fromIndex, endIndex);
41
+ // Generate OPRF request (server-side, we do the full flow)
42
+ const request = await operator.generateOPRFRequestData(data, TOPRF_DOMAIN_SEPARATOR, logger);
43
+ // Evaluate OPRF with server's private key
44
+ const response = await operator.evaluateOPRF(privateKey, request.maskedData, logger);
45
+ // Finalize to get the nullifier
46
+ const nullifier = await operator.finaliseOPRF(publicKey, request, [{ ...response, publicKeyShare: publicKey }], logger);
47
+ results.push({
48
+ dataLocation: { fromIndex, length },
49
+ nullifier
50
+ });
51
+ logger.debug({ fromIndex, length, nullifierHex: Buffer.from(nullifier).toString('hex').slice(0, 16) + '...' }, 'computed oprf-raw nullifier');
52
+ }
53
+ return results;
54
+ }
@@ -0,0 +1,215 @@
1
+ import { concatenateUint8Arrays, getSignatureDataTls12, getSignatureDataTls13, PACKET_TYPE, parseCertificates, parseClientHello, parseServerCertificateVerify, parseServerHello, processServerKeyShare, SUPPORTED_RECORD_TYPE_MAP, uint8ArrayToDataView, verifyCertificateChain, verifyCertificateSignature } from '@reclaimprotocol/tls';
2
+ import { TranscriptMessageSenderType } from "../../proto/api.js";
3
+ import { decryptDirect } from "../../utils/index.js";
4
+ const RECORD_LENGTH_BYTES = 3;
5
+ /**
6
+ * Verifies server cert chain and removes handshake messages from transcript
7
+ * @param receipt
8
+ * @param logger
9
+ */
10
+ export async function processHandshake(receipt, logger) {
11
+ const certificates = [];
12
+ const handshakeRawMessages = [];
13
+ let currentPacketIdx = 0;
14
+ let cipherSuite = undefined;
15
+ let tlsVersion = undefined;
16
+ let serverRandom = undefined;
17
+ let clientRandom = undefined;
18
+ let serverFinishedIdx = -1;
19
+ let clientFinishedIdx = -1;
20
+ let certVerified = false;
21
+ let certVerifyHandled = false;
22
+ let hostname = undefined;
23
+ let clientChangeCipherSpecMsgIdx = -1;
24
+ let serverChangeCipherSpecMsgIdx = -1;
25
+ let incompletePkt = undefined;
26
+ while (serverFinishedIdx < 0 || clientFinishedIdx < 0) {
27
+ const packetIdx = currentPacketIdx++;
28
+ if (packetIdx >= receipt.length) {
29
+ throw new Error('Receipt over but server finish: ' + serverFinishedIdx
30
+ + ', client finish: ' + clientFinishedIdx);
31
+ }
32
+ const { message, reveal, sender } = receipt[packetIdx];
33
+ // skip change cipher spec message
34
+ if (message[0] === PACKET_TYPE['CHANGE_CIPHER_SPEC']) {
35
+ if (sender === TranscriptMessageSenderType
36
+ .TRANSCRIPT_MESSAGE_SENDER_TYPE_CLIENT) {
37
+ clientChangeCipherSpecMsgIdx = packetIdx;
38
+ logger.trace('found client change cipher spec message');
39
+ }
40
+ else {
41
+ serverChangeCipherSpecMsgIdx = packetIdx;
42
+ logger.trace('found server change cipher spec message');
43
+ }
44
+ continue;
45
+ }
46
+ let plaintext = getWithoutHeader(message);
47
+ if (!plaintext) {
48
+ throw new Error('incomplete TLS record encountered');
49
+ }
50
+ if (
51
+ // decrypt if wrapped record or after change cipher spec message,
52
+ // after which records are encrypted
53
+ message[0] === PACKET_TYPE['WRAPPED_RECORD']
54
+ || (serverChangeCipherSpecMsgIdx > 0
55
+ && sender === TranscriptMessageSenderType
56
+ .TRANSCRIPT_MESSAGE_SENDER_TYPE_SERVER)
57
+ || (clientChangeCipherSpecMsgIdx > 0
58
+ && sender === TranscriptMessageSenderType
59
+ .TRANSCRIPT_MESSAGE_SENDER_TYPE_CLIENT)) { // encrypted
60
+ if (!tlsVersion || !cipherSuite) {
61
+ throw new Error('Could not find cipherSuite to use & got enc record');
62
+ }
63
+ if (!reveal?.directReveal?.key) {
64
+ throw new Error('no direct reveal for handshake packet: ' + packetIdx);
65
+ }
66
+ const recordHeader = message.slice(0, 5);
67
+ ({ plaintext } = await decryptDirect(reveal?.directReveal, cipherSuite, recordHeader, tlsVersion, plaintext));
68
+ if (tlsVersion === 'TLS1_3') {
69
+ plaintext = plaintext.slice(0, -1);
70
+ }
71
+ }
72
+ if (incompletePkt) {
73
+ const incSender = receipt[incompletePkt.packetIdx].sender;
74
+ if (incSender !== sender) {
75
+ throw new Error('Missing follow up to incomplete packet at idx: '
76
+ + incompletePkt.packetIdx);
77
+ }
78
+ plaintext = concatenateUint8Arrays([
79
+ incompletePkt.remainingBytes,
80
+ plaintext
81
+ ]);
82
+ incompletePkt = undefined;
83
+ }
84
+ const handshakeMessages = [];
85
+ // each handshake packet may contain multiple handshake messages
86
+ for (let offset = 0; offset < plaintext.length;) {
87
+ const type = plaintext[offset];
88
+ // +1 for the record type byte
89
+ const content = readWithLength(plaintext.slice(offset + 1), RECORD_LENGTH_BYTES);
90
+ if (!content) {
91
+ incompletePkt = {
92
+ remainingBytes: plaintext.slice(offset),
93
+ packetIdx,
94
+ };
95
+ break;
96
+ }
97
+ handshakeMessages.push({
98
+ type,
99
+ content,
100
+ contentWithHeader: plaintext.slice(offset, offset + 1 + RECORD_LENGTH_BYTES + content.length),
101
+ packetIdx,
102
+ });
103
+ offset += 1 + RECORD_LENGTH_BYTES + content.length;
104
+ }
105
+ for (const msg of handshakeMessages) {
106
+ await processHandshakeMessage(msg);
107
+ handshakeRawMessages.push(msg.contentWithHeader);
108
+ }
109
+ }
110
+ if (!certVerified) {
111
+ throw new Error('No provider certificates received');
112
+ }
113
+ if (tlsVersion === 'TLS1_3' && serverFinishedIdx < 0) {
114
+ throw new Error('server finished message not found');
115
+ }
116
+ if (tlsVersion === 'TLS1_3' && !certVerifyHandled) {
117
+ throw new Error('TLS1.3 cert verify packet not received');
118
+ }
119
+ if (tlsVersion === 'TLS1_2' && (serverChangeCipherSpecMsgIdx < 0 || clientChangeCipherSpecMsgIdx < 0)) {
120
+ throw new Error('change cipher spec message not found');
121
+ }
122
+ const nextMsgIndex = Math.max(serverFinishedIdx, clientFinishedIdx) + 1;
123
+ return {
124
+ tlsVersion: tlsVersion,
125
+ cipherSuite: cipherSuite,
126
+ hostname: hostname,
127
+ nextMsgIndex,
128
+ };
129
+ async function processHandshakeMessage({ type, content, contentWithHeader, packetIdx }) {
130
+ switch (type) {
131
+ case SUPPORTED_RECORD_TYPE_MAP.CLIENT_HELLO:
132
+ const clientHello = parseClientHello(contentWithHeader);
133
+ clientRandom = clientHello.serverRandom;
134
+ const { SERVER_NAME: sni } = clientHello.extensions;
135
+ hostname = sni?.serverName;
136
+ if (!hostname) {
137
+ throw new Error('client hello has no SNI');
138
+ }
139
+ break;
140
+ case SUPPORTED_RECORD_TYPE_MAP.SERVER_HELLO:
141
+ const serverHello = await parseServerHello(content);
142
+ cipherSuite = serverHello.cipherSuite;
143
+ tlsVersion = serverHello.serverTlsVersion;
144
+ serverRandom = serverHello.serverRandom;
145
+ logger.info({ serverTLSVersion: tlsVersion, cipherSuite }, 'extracted server hello params');
146
+ break;
147
+ case SUPPORTED_RECORD_TYPE_MAP.CERTIFICATE:
148
+ const parseResult = parseCertificates(content, { version: tlsVersion });
149
+ certificates.push(...parseResult.certificates);
150
+ await verifyCertificateChain(certificates, hostname, logger);
151
+ logger.info({ hostname }, 'verified provider certificate chain');
152
+ certVerified = true;
153
+ break;
154
+ case SUPPORTED_RECORD_TYPE_MAP.CERTIFICATE_VERIFY:
155
+ const signature = parseServerCertificateVerify(content);
156
+ if (!certificates?.length) {
157
+ throw new Error('No provider certificates received');
158
+ }
159
+ const signatureData = await getSignatureDataTls13(handshakeRawMessages, cipherSuite);
160
+ await verifyCertificateSignature({
161
+ ...signature,
162
+ publicKey: certificates[0].getPublicKey(),
163
+ signatureData,
164
+ });
165
+ certVerifyHandled = true;
166
+ break;
167
+ case SUPPORTED_RECORD_TYPE_MAP.SERVER_KEY_SHARE:
168
+ if (!certificates?.length) {
169
+ throw new Error('No provider certificates received');
170
+ }
171
+ const keyShare = await processServerKeyShare(content);
172
+ const signatureData12 = await getSignatureDataTls12({
173
+ clientRandom: clientRandom,
174
+ serverRandom: serverRandom,
175
+ curveType: keyShare.publicKeyType,
176
+ publicKey: keyShare.publicKey,
177
+ });
178
+ // verify signature
179
+ await verifyCertificateSignature({
180
+ signature: keyShare.signatureBytes,
181
+ algorithm: keyShare.signatureAlgorithm,
182
+ publicKey: certificates[0].getPublicKey(),
183
+ signatureData: signatureData12,
184
+ publicKeyType: keyShare.publicKeyType
185
+ });
186
+ await verifyCertificateChain(certificates, hostname, logger);
187
+ logger.info({ hostname }, 'verified provider certificate chain');
188
+ certVerified = true;
189
+ break;
190
+ case SUPPORTED_RECORD_TYPE_MAP.FINISHED:
191
+ const packet = receipt[packetIdx];
192
+ if (packet.sender === TranscriptMessageSenderType.TRANSCRIPT_MESSAGE_SENDER_TYPE_CLIENT) {
193
+ clientFinishedIdx = packetIdx;
194
+ }
195
+ else {
196
+ serverFinishedIdx = packetIdx;
197
+ }
198
+ break;
199
+ }
200
+ }
201
+ }
202
+ function getWithoutHeader(message) {
203
+ // strip the record header (xx 03 03 xx xx)
204
+ return readWithLength(message.slice(3), 2);
205
+ }
206
+ function readWithLength(data, lengthBytes = 2) {
207
+ const dataView = uint8ArrayToDataView(data);
208
+ const length = lengthBytes === 1
209
+ ? dataView.getUint8(0)
210
+ : dataView.getUint16(lengthBytes === 3 ? 1 : 0);
211
+ if (data.length < lengthBytes + length) {
212
+ return undefined;
213
+ }
214
+ return data.slice(lengthBytes, lengthBytes + length);
215
+ }
@@ -0,0 +1,6 @@
1
+ export function isValidProxySessionId(sessionId) {
2
+ return typeof sessionId === 'string'
3
+ && sessionId.length >= 8
4
+ && sessionId.length < 15
5
+ && /^[a-z0-9]+$/.test(sessionId);
6
+ }