@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,131 @@
1
+ import { concatenateUint8Arrays, makeTLSClient } from '@reclaimprotocol/tls';
2
+ import { makeRpcTcpTunnel } from "./make-rpc-tcp-tunnel.js";
3
+ import { DEFAULT_HTTPS_PORT } from "../../config/index.js";
4
+ import { generateRpcMessageId, generateTunnelId } from "../../utils/index.js";
5
+ /**
6
+ * Makes a TLS tunnel that connects to the server via RPC protocol
7
+ */
8
+ export const makeRpcTlsTunnel = async ({ onMessage, onClose, tlsOpts, request, connect, logger }) => {
9
+ const transcript = [];
10
+ const tunnelId = request.id || generateTunnelId();
11
+ let tunnel;
12
+ let client;
13
+ let handshakeResolve;
14
+ let handshakeReject;
15
+ const waitForHandshake = new Promise((resolve, reject) => {
16
+ handshakeResolve = resolve;
17
+ handshakeReject = reject;
18
+ });
19
+ const tls = makeTLSClient({
20
+ host: request.host,
21
+ ...tlsOpts,
22
+ logger,
23
+ onHandshake() {
24
+ handshakeResolve?.();
25
+ },
26
+ onApplicationData(plaintext) {
27
+ return onMessage?.(plaintext);
28
+ },
29
+ onTlsEnd: onConnectionClose,
30
+ async write(packet, ctx) {
31
+ const message = concatenateUint8Arrays([
32
+ packet.header,
33
+ packet.content
34
+ ]);
35
+ transcript.push({
36
+ sender: 'client',
37
+ message: { ...ctx, data: message }
38
+ });
39
+ if (!tunnel) {
40
+ // sends the packet as the initial message
41
+ // to the plaintext tunnel. Prevents another
42
+ // round trip to the server as we send the packet
43
+ // in the same message as the tunnel creation.
44
+ const createTunnelReqId = generateRpcMessageId();
45
+ client = connect([
46
+ {
47
+ id: createTunnelReqId,
48
+ createTunnelRequest: {
49
+ host: request.host || '',
50
+ port: request.port || DEFAULT_HTTPS_PORT,
51
+ geoLocation: request.geoLocation || '',
52
+ proxySessionId: request.proxySessionId || '',
53
+ id: tunnelId
54
+ },
55
+ },
56
+ { tunnelMessage: { tunnelId, message } }
57
+ ]);
58
+ try {
59
+ await makeTunnel();
60
+ // wait for tunnel to be successfully created
61
+ await client.waitForResponse(createTunnelReqId);
62
+ }
63
+ catch (err) {
64
+ onConnectionClose(err);
65
+ }
66
+ return;
67
+ }
68
+ return tunnel.write(message);
69
+ },
70
+ onRead(packet, ctx) {
71
+ transcript.push({
72
+ sender: 'server',
73
+ message: {
74
+ ...ctx,
75
+ data: concatenateUint8Arrays([
76
+ packet.header,
77
+ // the TLS package sends us the decrypted
78
+ // content, so we need to get the orginal
79
+ // ciphertext received from the server
80
+ // as that's part of the true transcript.
81
+ ctx.type === 'ciphertext'
82
+ ? ctx.ciphertext
83
+ : packet.content
84
+ ])
85
+ }
86
+ });
87
+ },
88
+ });
89
+ await tls.startHandshake();
90
+ // wait for handshake completion
91
+ await waitForHandshake;
92
+ handshakeResolve = handshakeReject = undefined;
93
+ return {
94
+ transcript,
95
+ tls,
96
+ write(data) {
97
+ return tls.write(data);
98
+ },
99
+ async close(err) {
100
+ onConnectionClose(err);
101
+ try {
102
+ await tunnel.close(err);
103
+ }
104
+ catch (err) {
105
+ logger?.error({ err }, 'err in close tunnel');
106
+ }
107
+ },
108
+ };
109
+ function onConnectionClose(err) {
110
+ onClose?.(err);
111
+ // once the TLS connection is closed, we no longer
112
+ // want to send `onClose` events back to the caller
113
+ // of this function.
114
+ onClose = undefined;
115
+ handshakeReject?.(err || new Error('TLS connection closed'));
116
+ }
117
+ async function makeTunnel() {
118
+ tunnel = await makeRpcTcpTunnel({
119
+ tunnelId,
120
+ client: client,
121
+ onMessage(data) {
122
+ tls.handleReceivedBytes(data);
123
+ },
124
+ onClose(err) {
125
+ tls.end(err);
126
+ },
127
+ });
128
+ logger?.debug('plaintext tunnel created');
129
+ return tunnel;
130
+ }
131
+ };
@@ -0,0 +1,25 @@
1
+ import { AttestorClient } from "./client-socket.js";
2
+ const POOL = {};
3
+ /**
4
+ * Get a attestor client from the pool,
5
+ * if it doesn't exist, create one.
6
+ * @param [getCreateOpts] - Function to get the options for creating a new client.
7
+ * called synchronously, in the same tick as this function.
8
+ */
9
+ export function getAttestorClientFromPool(url, getCreateOpts = () => ({})) {
10
+ const key = url.toString();
11
+ let client = POOL[key];
12
+ let createReason;
13
+ if (client?.isClosed) {
14
+ createReason = 'closed';
15
+ }
16
+ else if (!client) {
17
+ createReason = 'non-existent';
18
+ }
19
+ if (createReason) {
20
+ const createOpts = getCreateOpts();
21
+ createOpts?.logger?.info({ key, createReason }, 'creating new client');
22
+ client = (POOL[key] = new AttestorClient({ ...createOpts, url }));
23
+ }
24
+ return client;
25
+ }
@@ -0,0 +1,98 @@
1
+ import { utils } from 'ethers';
2
+ import { DEFAULT_METADATA, DEFAULT_RPC_TIMEOUT_MS } from "../../config/index.js";
3
+ import { RPCMessages } from "../../proto/api.js";
4
+ import { AttestorError, generateRpcMessageId, getRpcRequestType, logger as LOGGER, packRpcMessages } from "../../utils/index.js";
5
+ import { AttestorSocket } from "../../utils/socket-base.js";
6
+ import { makeWebSocket as defaultMakeWebSocket } from "../../utils/ws.js";
7
+ const { base64 } = utils;
8
+ export class AttestorClient extends AttestorSocket {
9
+ waitForInitPromise;
10
+ initResponse;
11
+ constructor({ url, initMessages = [], signatureType = DEFAULT_METADATA.signatureType, logger = LOGGER, authRequest, makeWebSocket = defaultMakeWebSocket }) {
12
+ const initRequest = {
13
+ ...DEFAULT_METADATA,
14
+ signatureType,
15
+ auth: authRequest
16
+ };
17
+ const msg = packRpcMessages({ initRequest }, ...initMessages);
18
+ const initRequestBytes = RPCMessages.encode(msg).finish();
19
+ const initRequestB64 = base64.encode(initRequestBytes);
20
+ url = new URL(url.toString());
21
+ url.searchParams.set('messages', initRequestB64);
22
+ super(makeWebSocket(url), initRequest, logger);
23
+ const initReqId = msg.messages[0].id;
24
+ this.waitForInitPromise = this
25
+ .waitForResponse(initReqId, DEFAULT_RPC_TIMEOUT_MS)
26
+ .then(res => {
27
+ logger.info('client initialised');
28
+ this.isInitialised = true;
29
+ this.initResponse = res;
30
+ });
31
+ // swallow the error if anything bad happens, and we've no
32
+ // catch block to handle it
33
+ this.waitForInitPromise
34
+ .catch(() => { });
35
+ this.addEventListener('connection-terminated', ev => (logger.info({ err: ev.data }, 'connection terminated')));
36
+ }
37
+ async rpc(type, request, timeoutMs = DEFAULT_RPC_TIMEOUT_MS) {
38
+ const msgId = generateRpcMessageId();
39
+ this.logger.debug({ type, id: msgId }, 'sending rpc request');
40
+ const now = Date.now();
41
+ try {
42
+ const rslt = this.waitForResponse(msgId, timeoutMs);
43
+ await this.sendMessage({ id: msgId, [getRpcRequestType(type)]: request });
44
+ return await rslt;
45
+ }
46
+ finally {
47
+ const timeTakenMs = Date.now() - now;
48
+ this.logger.debug({ type, timeTakenMs }, 'received rpc response');
49
+ }
50
+ }
51
+ waitForResponse(id, timeoutMs = DEFAULT_RPC_TIMEOUT_MS) {
52
+ if (this.isClosed) {
53
+ throw new AttestorError('ERROR_NETWORK_ERROR', 'Client connection already closed');
54
+ }
55
+ // setup a promise to wait for the response
56
+ return new Promise((resolve, reject) => {
57
+ const handler = (event) => {
58
+ if (event.data.id !== id) {
59
+ return;
60
+ }
61
+ removeHandlers();
62
+ if ('error' in event.data) {
63
+ reject(event.data.error);
64
+ return;
65
+ }
66
+ // @ts-expect-error
67
+ resolve(event.data.data);
68
+ };
69
+ const terminateHandler = (event) => {
70
+ removeHandlers();
71
+ // if the connection was terminated, reject the promise
72
+ // but update the error code to reflect the network error
73
+ if (event.data.code === 'ERROR_NO_ERROR') {
74
+ reject(new AttestorError('ERROR_NETWORK_ERROR', event.data.message, event.data.data));
75
+ return;
76
+ }
77
+ reject(event.data);
78
+ };
79
+ const timeout = setTimeout(() => {
80
+ removeHandlers();
81
+ reject(new AttestorError('ERROR_TIMEOUT', `RPC request timed out after ${timeoutMs}ms`, { id }));
82
+ }, timeoutMs);
83
+ const removeHandlers = () => {
84
+ clearTimeout(timeout);
85
+ this.removeEventListener('rpc-response', handler);
86
+ this.removeEventListener('connection-terminated', terminateHandler);
87
+ };
88
+ this.addEventListener('rpc-response', handler);
89
+ this.addEventListener('connection-terminated', terminateHandler);
90
+ });
91
+ }
92
+ waitForInit = () => {
93
+ if (this.isClosed) {
94
+ throw new AttestorError('ERROR_NETWORK_ERROR', 'Client connection already closed');
95
+ }
96
+ return this.waitForInitPromise;
97
+ };
98
+ }
@@ -0,0 +1,87 @@
1
+ import { RPCMessages } from "../../proto/api.js";
2
+ import { AttestorError, extractArrayBufferFromWsData, getRpcRequest, getRpcRequestType, getRpcResponseType } from "../../utils/index.js";
3
+ export async function wsMessageHandler(data) {
4
+ // extract array buffer from WS data & decode proto
5
+ const buff = await extractArrayBufferFromWsData(data);
6
+ const { messages } = RPCMessages.decode(buff);
7
+ for (const msg of messages) {
8
+ await handleMessage.call(this, msg);
9
+ }
10
+ }
11
+ export function handleMessage(msg) {
12
+ this.logger?.trace({ msg }, 'received message');
13
+ // handle connection termination alert
14
+ if (msg.connectionTerminationAlert) {
15
+ const err = AttestorError.fromProto(msg.connectionTerminationAlert);
16
+ this.logger?.warn({
17
+ err: err.code !== 'ERROR_NO_ERROR'
18
+ ? err
19
+ : undefined
20
+ }, 'received connection termination alert');
21
+ this.dispatchRPCEvent('connection-terminated', err);
22
+ return;
23
+ }
24
+ const rpcRequest = getRpcRequest(msg);
25
+ if (rpcRequest) {
26
+ if (rpcRequest.direction === 'response'
27
+ && rpcRequest.type === 'error') {
28
+ this.dispatchRPCEvent('rpc-response', {
29
+ id: msg.id,
30
+ error: AttestorError.fromProto(msg.requestError)
31
+ });
32
+ return;
33
+ }
34
+ const resType = getRpcResponseType(rpcRequest.type);
35
+ if (rpcRequest.direction === 'response') {
36
+ this.dispatchRPCEvent('rpc-response', {
37
+ id: msg.id,
38
+ type: rpcRequest.type,
39
+ data: msg[resType]
40
+ });
41
+ return;
42
+ }
43
+ if (!this.isInitialised && rpcRequest.type !== 'init') {
44
+ this.logger.warn({ type: rpcRequest.type }, 'RPC request received before initialisation');
45
+ void this.sendMessage({
46
+ id: msg.id,
47
+ requestError: AttestorError
48
+ .badRequest('Initialise connection first')
49
+ .toProto()
50
+ });
51
+ return;
52
+ }
53
+ return new Promise((resolve, reject) => {
54
+ this.dispatchRPCEvent('rpc-request', {
55
+ requestId: msg.id,
56
+ type: rpcRequest.type,
57
+ data: msg[getRpcRequestType(rpcRequest.type)],
58
+ respond: (res) => {
59
+ if (!this.isOpen) {
60
+ this.logger?.debug({ type: rpcRequest.type, res }, 'connection closed before responding');
61
+ reject(new Error('connection closed'));
62
+ return;
63
+ }
64
+ if ('code' in res) {
65
+ reject(res);
66
+ return this.sendMessage({
67
+ id: msg.id,
68
+ requestError: res.toProto()
69
+ });
70
+ }
71
+ resolve();
72
+ return this
73
+ .sendMessage({ id: msg.id, [resType]: res });
74
+ },
75
+ });
76
+ });
77
+ }
78
+ if (msg.tunnelMessage) {
79
+ this.dispatchRPCEvent('tunnel-message', msg.tunnelMessage);
80
+ return;
81
+ }
82
+ if (msg.tunnelDisconnectEvent) {
83
+ this.dispatchRPCEvent('tunnel-disconnect-event', msg.tunnelDisconnectEvent);
84
+ return;
85
+ }
86
+ this.logger.warn({ msg }, 'unhandled message');
87
+ }
@@ -10,10 +10,10 @@ export declare const API_SERVER_PORT = 8001;
10
10
  export declare const CONNECTION_TIMEOUT_MS = 10000;
11
11
  export declare const DNS_SERVERS: string[];
12
12
  export declare const MAX_CLAIM_TIMESTAMP_DIFF_S: number;
13
- export declare const CURRENT_ATTESTOR_VERSION: 5;
13
+ export declare const CURRENT_ATTESTOR_VERSION: 6;
14
14
  export declare const DEFAULT_METADATA: InitRequest;
15
15
  export declare const PROVIDER_CTX: {
16
- version: 5;
16
+ version: 6;
17
17
  };
18
18
  export declare const PING_INTERVAL_MS = 10000;
19
19
  /**
@@ -0,0 +1,44 @@
1
+ import { AttestorVersion, ServiceSignatureType } from "../proto/api.js";
2
+ export const DEFAULT_ZK_CONCURRENCY = 10;
3
+ export const RECLAIM_USER_AGENT = 'reclaim/0.0.1';
4
+ export const DEFAULT_HTTPS_PORT = 443;
5
+ export const WS_PATHNAME = '/ws';
6
+ export const BROWSER_RPC_PATHNAME = '/browser-rpc';
7
+ export const ATTESTOR_ADDRESS_PATHNAME = '/address';
8
+ export const DEFAULT_REMOTE_FILE_FETCH_BASE_URL = `${BROWSER_RPC_PATHNAME}/resources`;
9
+ export const API_SERVER_PORT = 8001;
10
+ // 10s
11
+ export const CONNECTION_TIMEOUT_MS = 10_000;
12
+ export const DNS_SERVERS = [
13
+ '8.8.8.8',
14
+ '8.8.4.4'
15
+ ];
16
+ // 10m
17
+ export const MAX_CLAIM_TIMESTAMP_DIFF_S = 10 * 60;
18
+ export const CURRENT_ATTESTOR_VERSION = AttestorVersion.ATTESTOR_VERSION_3_0_0;
19
+ export const DEFAULT_METADATA = {
20
+ signatureType: ServiceSignatureType.SERVICE_SIGNATURE_TYPE_ETH,
21
+ clientVersion: CURRENT_ATTESTOR_VERSION,
22
+ auth: undefined
23
+ };
24
+ export const PROVIDER_CTX = { version: CURRENT_ATTESTOR_VERSION };
25
+ export const PING_INTERVAL_MS = 10_000;
26
+ /**
27
+ * Maximum interval in seconds to wait for before assuming
28
+ * the connection is dead
29
+ * @default 30s
30
+ */
31
+ export const MAX_NO_DATA_INTERVAL_MS = 30_000;
32
+ export const MAX_PAYLOAD_SIZE = 512 * 1024 * 1024; // 512MB
33
+ export const DEFAULT_AUTH_EXPIRY_S = 15 * 60; // 15m
34
+ export const DEFAULT_RPC_TIMEOUT_MS = 90_000;
35
+ export const TOPRF_DOMAIN_SEPARATOR = 'reclaim-toprf';
36
+ export const MAX_CERT_SIZE_BYTES = 10 * 1024 * 1024 * 1024; // 10MB
37
+ export const CERT_ALLOWED_MIMETYPES = [
38
+ 'application/x-x509-ca-cert',
39
+ 'application/x-x509-user-cert',
40
+ 'application/pkix-cert',
41
+ 'application/pkcs7-mime',
42
+ 'application/octet-stream'
43
+ ];
44
+ export const BGP_WS_URL = 'wss://ris-live.ripe.net/v1/ws/?client=reclaim-hijack-detector';
@@ -0,0 +1,69 @@
1
+ import { crypto, encryptWrappedRecord, SUPPORTED_CIPHER_SUITE_MAP } from '@reclaimprotocol/tls';
2
+ import { strToUint8Array } from "../utils/generics.js";
3
+ import { logger } from "../utils/logger.js";
4
+ import { makeZkProofGenerator } from "../utils/zk.js";
5
+ const ZK_CIPHER_SUITES = [
6
+ 'TLS_CHACHA20_POLY1305_SHA256',
7
+ 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384',
8
+ 'TLS_AES_128_GCM_SHA256'
9
+ ];
10
+ export async function benchmark() {
11
+ let benchmarkRes = '';
12
+ for (const cipherSuite of ZK_CIPHER_SUITES) {
13
+ const now = Date.now();
14
+ const alg = cipherSuite.includes('CHACHA20')
15
+ ? 'CHACHA20-POLY1305'
16
+ : (cipherSuite.includes('AES_256_GCM')
17
+ ? 'AES-256-GCM'
18
+ : 'AES-128-GCM');
19
+ const keylength = alg === 'AES-128-GCM' ? 16 : 32;
20
+ const key = Buffer.alloc(keylength, 0);
21
+ const { ivLength: fixedIvLength, } = SUPPORTED_CIPHER_SUITE_MAP[cipherSuite];
22
+ const fixedIv = Buffer.alloc(fixedIvLength, 0);
23
+ const encKey = await crypto.importKey(alg, key);
24
+ const vectors = [
25
+ {
26
+ plaintext: 'My cool API secret is "my name jeff". Please don\'t reveal it'
27
+ }
28
+ ];
29
+ const proofGenerator = await makeZkProofGenerator({
30
+ logger,
31
+ cipherSuite,
32
+ });
33
+ for (const { plaintext } of vectors) {
34
+ const plaintextArr = strToUint8Array(plaintext);
35
+ const { ciphertext, iv } = await encryptWrappedRecord(plaintextArr, {
36
+ key: encKey,
37
+ iv: fixedIv,
38
+ recordNumber: 0,
39
+ recordHeaderOpts: {
40
+ type: 'WRAPPED_RECORD'
41
+ },
42
+ cipherSuite,
43
+ version: cipherSuite.includes('ECDHE_')
44
+ ? 'TLS1_2'
45
+ : 'TLS1_3',
46
+ });
47
+ const packet = {
48
+ type: 'ciphertext',
49
+ encKey,
50
+ iv,
51
+ recordNumber: 0,
52
+ plaintext: plaintextArr,
53
+ ciphertext,
54
+ fixedIv: new Uint8Array(0),
55
+ data: ciphertext
56
+ };
57
+ await proofGenerator.addPacketToProve(packet, {
58
+ type: 'zk',
59
+ redactedPlaintext: plaintextArr,
60
+ }, () => { }, () => {
61
+ throw new Error('should not be called in benchmark');
62
+ });
63
+ await proofGenerator.generateProofs();
64
+ }
65
+ benchmarkRes = benchmarkRes + `Benchmark ${alg} ok. Took ${Date.now() - now} ms \n`;
66
+ }
67
+ logger.info(benchmarkRes);
68
+ return benchmarkRes;
69
+ }
@@ -0,0 +1,14 @@
1
+ export class EventBus {
2
+ #listeners = [];
3
+ addListener(fn) {
4
+ this.#listeners.push(fn);
5
+ return () => {
6
+ this.#listeners = this.#listeners.filter(l => l !== fn);
7
+ };
8
+ }
9
+ dispatch(data) {
10
+ for (const listener of this.#listeners) {
11
+ listener(data);
12
+ }
13
+ }
14
+ }