@reclaimprotocol/attestor-core 5.0.3 → 5.0.4

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 (122) hide show
  1. package/LICENSE +660 -660
  2. package/browser/resources/attestor-browser.min.mjs +31 -31
  3. package/lib/avs/abis/avsDirectoryABI.js +340 -0
  4. package/lib/avs/abis/delegationABI.js +1 -0
  5. package/lib/avs/abis/registryABI.js +725 -0
  6. package/lib/avs/client/create-claim-on-avs.js +138 -0
  7. package/lib/avs/config.js +20 -0
  8. package/lib/avs/contracts/ReclaimServiceManager.js +1 -0
  9. package/lib/avs/contracts/common.js +1 -0
  10. package/lib/avs/contracts/factories/ReclaimServiceManager__factory.js +1169 -0
  11. package/lib/avs/contracts/factories/index.js +4 -0
  12. package/lib/avs/contracts/index.js +2 -0
  13. package/lib/avs/types/index.js +1 -0
  14. package/lib/avs/utils/contracts.js +33 -0
  15. package/lib/avs/utils/register.js +78 -0
  16. package/lib/avs/utils/tasks.js +40 -0
  17. package/lib/client/create-claim.js +433 -0
  18. package/lib/client/index.js +3 -0
  19. package/lib/client/tunnels/make-rpc-tcp-tunnel.js +51 -0
  20. package/lib/client/tunnels/make-rpc-tls-tunnel.js +131 -0
  21. package/lib/client/utils/attestor-pool.js +25 -0
  22. package/lib/client/utils/client-socket.js +98 -0
  23. package/lib/client/utils/message-handler.js +87 -0
  24. package/lib/config/index.d.ts +2 -2
  25. package/lib/config/index.js +44 -0
  26. package/lib/external-rpc/benchmark.js +69 -0
  27. package/lib/external-rpc/event-bus.js +14 -0
  28. package/lib/external-rpc/handle-incoming-msg.js +233 -0
  29. package/lib/external-rpc/index.js +101 -54
  30. package/lib/external-rpc/jsc-polyfills/1.js +82 -0
  31. package/lib/external-rpc/jsc-polyfills/2.js +20 -0
  32. package/lib/external-rpc/jsc-polyfills/event.js +14 -0
  33. package/lib/external-rpc/jsc-polyfills/index.js +2 -0
  34. package/lib/external-rpc/jsc-polyfills/ws.js +81 -0
  35. package/lib/external-rpc/setup-browser.js +33 -0
  36. package/lib/external-rpc/setup-jsc.js +22 -0
  37. package/lib/external-rpc/types.js +1 -0
  38. package/lib/external-rpc/utils.js +100 -0
  39. package/lib/external-rpc/zk.js +63 -0
  40. package/lib/index.js +121 -72
  41. package/lib/mechain/abis/governanceABI.js +458 -0
  42. package/lib/mechain/abis/taskABI.js +509 -0
  43. package/lib/mechain/client/create-claim-on-mechain.js +28 -0
  44. package/lib/mechain/client/index.js +1 -0
  45. package/lib/mechain/constants/index.js +3 -0
  46. package/lib/mechain/index.js +2 -0
  47. package/lib/mechain/types/index.js +1 -0
  48. package/lib/proto/api.d.ts +2 -0
  49. package/lib/proto/api.js +4273 -0
  50. package/lib/proto/tee-bundle.js +1316 -0
  51. package/lib/providers/http/index.js +658 -0
  52. package/lib/providers/http/patch-parse5-tree.js +33 -0
  53. package/lib/providers/http/utils.js +324 -0
  54. package/lib/providers/index.js +4 -0
  55. package/lib/scripts/fetch-ec2-metadata.d.ts +1 -0
  56. package/lib/server/create-server.js +103 -0
  57. package/lib/server/handlers/claimTeeBundle.js +252 -0
  58. package/lib/server/handlers/claimTunnel.js +73 -0
  59. package/lib/server/handlers/completeClaimOnChain.js +22 -0
  60. package/lib/server/handlers/createClaimOnChain.js +26 -0
  61. package/lib/server/handlers/createTaskOnMechain.js +47 -0
  62. package/lib/server/handlers/createTunnel.js +93 -0
  63. package/lib/server/handlers/disconnectTunnel.js +5 -0
  64. package/lib/server/handlers/fetchCertificateBytes.js +41 -0
  65. package/lib/server/handlers/index.js +22 -0
  66. package/lib/server/handlers/init.js +32 -0
  67. package/lib/server/handlers/toprf.js +16 -0
  68. package/lib/server/index.js +4 -0
  69. package/lib/server/socket.js +109 -0
  70. package/lib/server/tunnels/make-tcp-tunnel.js +177 -0
  71. package/lib/server/utils/apm.js +36 -0
  72. package/lib/server/utils/assert-valid-claim-request.d.ts +1 -1
  73. package/lib/server/utils/assert-valid-claim-request.js +204 -0
  74. package/lib/server/utils/config-env.js +4 -0
  75. package/lib/server/utils/dns.js +18 -0
  76. package/lib/server/utils/gcp-attestation.js +289 -0
  77. package/lib/server/utils/generics.d.ts +1 -0
  78. package/lib/server/utils/generics.js +51 -0
  79. package/lib/server/utils/iso.js +256 -0
  80. package/lib/server/utils/keep-alive.js +38 -0
  81. package/lib/server/utils/nitro-attestation.js +325 -0
  82. package/lib/server/utils/process-handshake.js +215 -0
  83. package/lib/server/utils/proxy-session.js +6 -0
  84. package/lib/server/utils/tee-oprf-mpc-verification.js +90 -0
  85. package/lib/server/utils/tee-oprf-verification.js +174 -0
  86. package/lib/server/utils/tee-transcript-reconstruction.js +187 -0
  87. package/lib/server/utils/tee-verification.js +421 -0
  88. package/lib/server/utils/validation.js +38 -0
  89. package/lib/types/bgp.js +1 -0
  90. package/lib/types/claims.js +1 -0
  91. package/lib/types/client.js +1 -0
  92. package/lib/types/general.js +1 -0
  93. package/lib/types/handlers.js +1 -0
  94. package/lib/types/index.js +10 -0
  95. package/lib/types/providers.d.ts +1 -0
  96. package/lib/types/providers.gen.js +10 -0
  97. package/lib/types/providers.js +1 -0
  98. package/lib/types/rpc.js +1 -0
  99. package/lib/types/signatures.js +1 -0
  100. package/lib/types/tunnel.js +1 -0
  101. package/lib/types/zk.js +1 -0
  102. package/lib/utils/auth.js +59 -0
  103. package/lib/utils/b64-json.js +17 -0
  104. package/lib/utils/bgp-listener.js +119 -0
  105. package/lib/utils/claims.js +99 -0
  106. package/lib/utils/env.js +15 -0
  107. package/lib/utils/error.js +50 -0
  108. package/lib/utils/generics.js +317 -0
  109. package/lib/utils/http-parser.d.ts +2 -1
  110. package/lib/utils/http-parser.js +246 -0
  111. package/lib/utils/index.js +13 -0
  112. package/lib/utils/logger.js +91 -0
  113. package/lib/utils/prepare-packets.js +62 -0
  114. package/lib/utils/redactions.js +148 -0
  115. package/lib/utils/retries.js +24 -0
  116. package/lib/utils/signatures/eth.js +29 -0
  117. package/lib/utils/signatures/index.js +7 -0
  118. package/lib/utils/socket-base.js +90 -0
  119. package/lib/utils/tls.js +58 -0
  120. package/lib/utils/ws.js +22 -0
  121. package/lib/utils/zk.js +577 -0
  122. package/package.json +3 -2
@@ -0,0 +1,325 @@
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
+ // eslint-disable-next-line max-depth
100
+ if (!isValid) {
101
+ errors.push(`Certificate ${i} signature verification failed`);
102
+ }
103
+ }
104
+ catch (error) {
105
+ errors.push(`Certificate ${i} verification failed: ${error.message}`);
106
+ }
107
+ }
108
+ }
109
+ return {
110
+ isValid: errors.length === 0,
111
+ errors,
112
+ chain
113
+ };
114
+ }
115
+ catch (error) {
116
+ errors.push(`Certificate chain validation error: ${error.message}`);
117
+ return { isValid: false, errors, chain: [] };
118
+ }
119
+ }
120
+ /**
121
+ * Extract public key from user_data field in attestation document
122
+ */
123
+ function extractPublicKeyFromUserData(userDataBuffer) {
124
+ try {
125
+ const userDataString = userDataBuffer.toString('utf-8');
126
+ // Parse new format: "tee_k_public_key:0xETH_ADDRESS" or "tee_t_public_key:0xETH_ADDRESS"
127
+ const teeKMatch = userDataString.match(/^tee_k_public_key:(0x[0-9a-fA-F]{40})$/);
128
+ const teeTMatch = userDataString.match(/^tee_t_public_key:(0x[0-9a-fA-F]{40})$/);
129
+ if (teeKMatch) {
130
+ return {
131
+ teeType: 'tee_k',
132
+ ethAddress: teeKMatch[1], // Store the full ETH address with 0x prefix
133
+ pcr0: ''
134
+ };
135
+ }
136
+ if (teeTMatch) {
137
+ return {
138
+ teeType: 'tee_t',
139
+ ethAddress: teeTMatch[1], // Store the full ETH address with 0x prefix
140
+ pcr0: ''
141
+ };
142
+ }
143
+ return null;
144
+ }
145
+ catch (error) {
146
+ return null;
147
+ }
148
+ }
149
+ /**
150
+ * Working validation function copied from nitroattestor
151
+ */
152
+ export async function validateNitroAttestationAndExtractKey(attestationBytes) {
153
+ const errors = [];
154
+ const warnings = [];
155
+ try {
156
+ // Set up WebCrypto
157
+ const crypto = new Crypto();
158
+ // Decode CBOR - use exact same approach as working nitroattestor
159
+ const decode = await getCborDecode();
160
+ let decoded;
161
+ try {
162
+ decoded = decode(Buffer.from(attestationBytes));
163
+ }
164
+ catch (error) {
165
+ errors.push(`CBOR decoding failed: ${error.message}`);
166
+ return { isValid: false, errors, warnings, pcr0: '' };
167
+ }
168
+ // Extract COSE_Sign1 structure
169
+ if (!Array.isArray(decoded) || decoded.length < 4) {
170
+ errors.push('Invalid COSE_Sign1 structure: expected array with 4 elements');
171
+ return { isValid: false, errors, warnings, pcr0: '' };
172
+ }
173
+ const [, , payload] = decoded;
174
+ // Validate payload exists and is not empty
175
+ if (!payload || payload.length === 0) {
176
+ errors.push('Empty or missing payload in COSE_Sign1 structure');
177
+ return { isValid: false, errors, warnings, pcr0: '' };
178
+ }
179
+ // Decode payload - use exact same approach as working code
180
+ let doc;
181
+ try {
182
+ doc = decode(payload);
183
+ }
184
+ catch (error) {
185
+ errors.push(`Payload decoding failed: ${error.message}`);
186
+ return { isValid: false, errors, warnings, pcr0: '' };
187
+ }
188
+ // Validate mandatory fields with strict type checking
189
+ if (doc.module_id.length === 0) {
190
+ errors.push('Missing or invalid module_id');
191
+ }
192
+ if (doc.digest.length === 0) {
193
+ errors.push('Missing or invalid digest');
194
+ }
195
+ if (!doc.pcrs || typeof doc.pcrs !== 'object') {
196
+ errors.push('Missing or invalid pcrs');
197
+ }
198
+ if (!Buffer.isBuffer(doc.certificate) || doc.certificate.length === 0) {
199
+ errors.push('Missing or invalid certificate');
200
+ }
201
+ if (!Array.isArray(doc.cabundle) || doc.cabundle.length === 0) {
202
+ errors.push('Missing or invalid cabundle');
203
+ }
204
+ // Early return if basic validation fails
205
+ if (errors.length > 0) {
206
+ return { isValid: false, errors, warnings, pcr0: '' };
207
+ }
208
+ const pcr0 = doc.pcrs[0].toString('hex');
209
+ // Validate PCRs with secure comparison
210
+ // for(const [index, expected] of Object.entries(EXPECTED_PCRS)) {
211
+ // const pcrIndex = parseInt(index)
212
+ // const actualPcr = doc.pcrs[pcrIndex]
213
+ //
214
+ // if(!Buffer.isBuffer(actualPcr)) {
215
+ // errors.push(`PCR${index} is not a Buffer`)
216
+ // continue
217
+ // }
218
+ //
219
+ // if(!secureBufferCompare(expected, actualPcr)) {
220
+ // errors.push(`PCR${index} mismatch`)
221
+ // }
222
+ // }
223
+ // Parse certificates with better error handling
224
+ const intermediateCerts = [];
225
+ for (let i = 0; i < doc.cabundle.length; i++) {
226
+ try {
227
+ const cert = new X509Certificate(doc.cabundle[i].toString('base64'));
228
+ intermediateCerts.push(cert);
229
+ }
230
+ catch (error) {
231
+ errors.push(`Failed to parse cabundle certificate ${i}: ${error.message}`);
232
+ }
233
+ }
234
+ // Parse target certificate
235
+ let targetCert;
236
+ try {
237
+ targetCert = new X509Certificate(doc.certificate.toString('base64'));
238
+ }
239
+ catch (error) {
240
+ errors.push(`Failed to parse target certificate: ${error.message}`);
241
+ return { isValid: false, errors, warnings, pcr0: '' };
242
+ }
243
+ // Parse root certificate
244
+ let rootCert;
245
+ try {
246
+ rootCert = new X509Certificate(AWS_NITRO_ROOT_CERT);
247
+ }
248
+ catch (error) {
249
+ errors.push(`Failed to parse AWS Nitro root certificate: ${error.message}`);
250
+ return { isValid: false, errors, warnings, pcr0: '' };
251
+ }
252
+ // Enhanced certificate chain validation
253
+ const chainResult = await validateCertificateChain(targetCert, intermediateCerts, rootCert, crypto);
254
+ if (!chainResult.isValid) {
255
+ errors.push(...chainResult.errors);
256
+ return { isValid: false, errors, warnings, pcr0: '' };
257
+ }
258
+ // Parse and validate public key
259
+ let publicKeyRaw;
260
+ try {
261
+ publicKeyRaw = Buffer.from(targetCert.publicKey.rawData);
262
+ }
263
+ catch (error) {
264
+ errors.push(`Failed to extract public key: ${error.message}`);
265
+ return { isValid: false, errors, warnings, pcr0: '' };
266
+ }
267
+ // Validate public key format (P-384 ECDSA)
268
+ if (publicKeyRaw.length !== 120 || publicKeyRaw[0] !== 0x30) {
269
+ errors.push(`Invalid public key format: expected 120-byte DER-encoded key, got ${publicKeyRaw.length} bytes`);
270
+ return { isValid: false, errors, warnings, pcr0: '' };
271
+ }
272
+ let spki;
273
+ try {
274
+ spki = AsnParser.parse(publicKeyRaw, SubjectPublicKeyInfo);
275
+ }
276
+ catch (error) {
277
+ errors.push(`Failed to parse SubjectPublicKeyInfo: ${error.message}`);
278
+ return { isValid: false, errors, warnings, pcr0: '' };
279
+ }
280
+ const ecPoint = Buffer.from(spki.subjectPublicKey);
281
+ if (ecPoint.length !== 97 || ecPoint[0] !== 0x04) {
282
+ errors.push('Invalid EC point: expected 97-byte uncompressed P-384 key');
283
+ return { isValid: false, errors, warnings, pcr0: '' };
284
+ }
285
+ const x = ecPoint.subarray(1, 49); // 48-byte x coordinate
286
+ const y = ecPoint.subarray(49, 97); // 48-byte y coordinate
287
+ // Validate ECDSA signature using cose-js
288
+ try {
289
+ const verifier = {
290
+ key: {
291
+ x: x,
292
+ y: y,
293
+ },
294
+ };
295
+ const options = { defaultType: 18 }; // cose.sign.Sign1Tag
296
+ await sign.verify(Buffer.from(attestationBytes), verifier, options);
297
+ }
298
+ catch (error) {
299
+ errors.push(`COSE signature verification failed: ${error.message}`);
300
+ return { isValid: false, errors, warnings, pcr0: '' };
301
+ }
302
+ // Extract public key from user_data if present
303
+ let userDataType;
304
+ let ethAddress;
305
+ if (doc.user_data) {
306
+ const keyInfo = extractPublicKeyFromUserData(doc.user_data);
307
+ if (keyInfo) {
308
+ userDataType = keyInfo.teeType;
309
+ ethAddress = keyInfo.ethAddress;
310
+ }
311
+ }
312
+ return {
313
+ isValid: errors.length === 0,
314
+ errors,
315
+ warnings,
316
+ userDataType,
317
+ ethAddress,
318
+ pcr0: pcr0
319
+ };
320
+ }
321
+ catch (error) {
322
+ errors.push(`Unexpected error during validation: ${error.message}`);
323
+ return { isValid: false, errors, warnings, pcr0: '' };
324
+ }
325
+ }
@@ -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
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * TEE OPRF MPC Verification
3
+ * Verifies OPRF MPC outputs from TEE_K and TEE_T match
4
+ *
5
+ * Unlike ZK OPRF which requires proof verification, OPRF MPC outputs
6
+ * are already trusted because they are included in TEE-signed payloads.
7
+ * This module verifies that both TEEs computed identical outputs.
8
+ */
9
+ import { AttestorError } from "../../utils/error.js";
10
+ /**
11
+ * Verifies OPRF MPC outputs from TEE_K and TEE_T match
12
+ * Returns verified outputs for transcript replacement (same format as ZK OPRF)
13
+ */
14
+ export function verifyOprfMpcOutputs(kPayload, tPayload, logger) {
15
+ const kOutputs = kPayload.oprfOutputs || [];
16
+ const tOutputs = tPayload.oprfOutputs || [];
17
+ // Empty is valid - no OPRF MPC was requested
18
+ if (kOutputs.length === 0 && tOutputs.length === 0) {
19
+ logger.debug('No OPRF MPC outputs to verify');
20
+ return [];
21
+ }
22
+ // Count must match between TEE_K and TEE_T
23
+ if (kOutputs.length !== tOutputs.length) {
24
+ throw new AttestorError('ERROR_INVALID_CLAIM', `OPRF MPC count mismatch: TEE_K has ${kOutputs.length}, TEE_T has ${tOutputs.length}`);
25
+ }
26
+ logger.info(`Verifying ${kOutputs.length} OPRF MPC outputs`);
27
+ const results = [];
28
+ for (const [i, kOut] of kOutputs.entries()) {
29
+ const tOut = tOutputs[i];
30
+ // Validate position bounds (must be non-negative)
31
+ if (kOut.tlsStart < 0 || tOut.tlsStart < 0) {
32
+ throw new AttestorError('ERROR_INVALID_CLAIM', `OPRF MPC invalid position at index ${i}: negative start position`);
33
+ }
34
+ // Validate length constraints (must be positive and <= 64 bytes, matching TEE validation)
35
+ if (kOut.tlsLength <= 0 || kOut.tlsLength > 64 || tOut.tlsLength <= 0 || tOut.tlsLength > 64) {
36
+ throw new AttestorError('ERROR_INVALID_CLAIM', `OPRF MPC invalid length at index ${i}: must be 1-64 bytes ` +
37
+ `(TEE_K: ${kOut.tlsLength}, TEE_T: ${tOut.tlsLength})`);
38
+ }
39
+ // Validate hash output size (must be exactly 32 bytes for SHA256)
40
+ if (kOut.hashOutput.length !== 32 || tOut.hashOutput.length !== 32) {
41
+ throw new AttestorError('ERROR_INVALID_CLAIM', `OPRF MPC invalid hash size at index ${i}: expected 32 bytes ` +
42
+ `(TEE_K: ${kOut.hashOutput.length}, TEE_T: ${tOut.hashOutput.length})`);
43
+ }
44
+ // Verify positions match
45
+ if (kOut.tlsStart !== tOut.tlsStart || kOut.tlsLength !== tOut.tlsLength) {
46
+ throw new AttestorError('ERROR_INVALID_CLAIM', `OPRF MPC position mismatch at index ${i}: ` +
47
+ `TEE_K [${kOut.tlsStart}:${kOut.tlsStart + kOut.tlsLength}] vs ` +
48
+ `TEE_T [${tOut.tlsStart}:${tOut.tlsStart + tOut.tlsLength}]`);
49
+ }
50
+ // Verify hash outputs match (hash = SHA256(CMAC), so this implies CMAC matched too)
51
+ if (!buffersEqual(kOut.hashOutput, tOut.hashOutput)) {
52
+ throw new AttestorError('ERROR_INVALID_CLAIM', `OPRF MPC hash mismatch at index ${i}: outputs differ between TEE_K and TEE_T`);
53
+ }
54
+ // Log the actual output data for debugging
55
+ const hashOutputHex = Buffer.from(kOut.hashOutput).toString('hex');
56
+ const hashOutputBase64 = Buffer.from(kOut.hashOutput).toString('base64');
57
+ logger.info({
58
+ index: i,
59
+ position: kOut.tlsStart,
60
+ length: kOut.tlsLength,
61
+ hashOutputLen: kOut.hashOutput.length,
62
+ hashOutputHex: hashOutputHex.substring(0, 32) + '...',
63
+ hashOutputBase64Preview: hashOutputBase64.substring(0, 20) + '...'
64
+ }, 'OPRF MPC output verified');
65
+ // Return in same format as ZK OPRF for unified replacement
66
+ // MPC OPRF uses full hash length (not truncated like TOPRF)
67
+ results.push({
68
+ position: kOut.tlsStart,
69
+ length: kOut.tlsLength,
70
+ output: new Uint8Array(kOut.hashOutput), // Use SHA256(CMAC) as the replacement value
71
+ isMPC: true
72
+ });
73
+ }
74
+ logger.info(`Successfully verified ${results.length} OPRF MPC outputs`);
75
+ return results;
76
+ }
77
+ /**
78
+ * Compare two Uint8Array buffers for equality
79
+ */
80
+ function buffersEqual(a, b) {
81
+ if (a.length !== b.length) {
82
+ return false;
83
+ }
84
+ for (const [i, element] of a.entries()) {
85
+ if (element !== b[i]) {
86
+ return false;
87
+ }
88
+ }
89
+ return true;
90
+ }