@reclaimprotocol/attestor-core 5.0.1-beta.13 → 5.0.1-beta.16

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 (134) hide show
  1. package/lib/external-rpc/index.js +17321 -3
  2. package/lib/index.d.ts +1 -0
  3. package/lib/index.js +15391 -11
  4. package/lib/scripts/build-browser-debug.d.ts +1 -0
  5. package/package.json +1 -1
  6. package/lib/avs/abis/avsDirectoryABI.js +0 -343
  7. package/lib/avs/abis/delegationABI.js +0 -4
  8. package/lib/avs/abis/registryABI.js +0 -728
  9. package/lib/avs/client/create-claim-on-avs.js +0 -168
  10. package/lib/avs/config.js +0 -26
  11. package/lib/avs/contracts/ReclaimServiceManager.js +0 -0
  12. package/lib/avs/contracts/common.js +0 -0
  13. package/lib/avs/contracts/factories/ReclaimServiceManager__factory.js +0 -1183
  14. package/lib/avs/contracts/factories/index.js +0 -4
  15. package/lib/avs/contracts/index.js +0 -6
  16. package/lib/avs/types/index.js +0 -0
  17. package/lib/avs/utils/contracts.js +0 -53
  18. package/lib/avs/utils/register.js +0 -74
  19. package/lib/avs/utils/tasks.js +0 -48
  20. package/lib/client/create-claim.js +0 -461
  21. package/lib/client/index.js +0 -3
  22. package/lib/client/tunnels/make-rpc-tcp-tunnel.js +0 -53
  23. package/lib/client/tunnels/make-rpc-tls-tunnel.js +0 -127
  24. package/lib/client/utils/attestor-pool.js +0 -24
  25. package/lib/client/utils/client-socket.js +0 -120
  26. package/lib/client/utils/message-handler.js +0 -97
  27. package/lib/config/index.js +0 -62
  28. package/lib/external-rpc/benchmark.js +0 -82
  29. package/lib/external-rpc/event-bus.js +0 -17
  30. package/lib/external-rpc/handle-incoming-msg.js +0 -241
  31. package/lib/external-rpc/jsc-polyfills/1.js +0 -80
  32. package/lib/external-rpc/jsc-polyfills/2.js +0 -15
  33. package/lib/external-rpc/jsc-polyfills/event.js +0 -19
  34. package/lib/external-rpc/jsc-polyfills/index.js +0 -2
  35. package/lib/external-rpc/jsc-polyfills/ws.js +0 -83
  36. package/lib/external-rpc/setup-browser.js +0 -33
  37. package/lib/external-rpc/setup-jsc.js +0 -22
  38. package/lib/external-rpc/types.js +0 -0
  39. package/lib/external-rpc/utils.js +0 -100
  40. package/lib/external-rpc/zk.js +0 -58
  41. package/lib/mechain/abis/governanceABI.js +0 -461
  42. package/lib/mechain/abis/taskABI.js +0 -512
  43. package/lib/mechain/client/create-claim-on-mechain.js +0 -33
  44. package/lib/mechain/client/index.js +0 -1
  45. package/lib/mechain/constants/index.js +0 -8
  46. package/lib/mechain/index.js +0 -2
  47. package/lib/mechain/types/index.js +0 -0
  48. package/lib/proto/api.js +0 -4250
  49. package/lib/proto/tee-bundle.js +0 -1296
  50. package/lib/providers/http/index.js +0 -640
  51. package/lib/providers/http/patch-parse5-tree.js +0 -34
  52. package/lib/providers/http/utils.js +0 -283
  53. package/lib/providers/index.js +0 -7
  54. package/lib/scripts/build-browser.js +0 -38
  55. package/lib/scripts/build-jsc.js +0 -47
  56. package/lib/scripts/build-lib.js +0 -47
  57. package/lib/scripts/check-avs-registration.js +0 -28
  58. package/lib/scripts/fallbacks/crypto.js +0 -4
  59. package/lib/scripts/fallbacks/empty.js +0 -4
  60. package/lib/scripts/fallbacks/re2.js +0 -7
  61. package/lib/scripts/fallbacks/snarkjs.js +0 -10
  62. package/lib/scripts/fallbacks/stwo.js +0 -159
  63. package/lib/scripts/generate-provider-types.js +0 -101
  64. package/lib/scripts/generate-receipt.js +0 -101
  65. package/lib/scripts/generate-toprf-keys.js +0 -24
  66. package/lib/scripts/jsc-cli-rpc.js +0 -35
  67. package/lib/scripts/register-avs-operator.js +0 -3
  68. package/lib/scripts/start-server.js +0 -11
  69. package/lib/scripts/update-avs-metadata.js +0 -20
  70. package/lib/scripts/utils.js +0 -10
  71. package/lib/scripts/whitelist-operator.js +0 -16
  72. package/lib/server/create-server.js +0 -105
  73. package/lib/server/handlers/claimTeeBundle.js +0 -232
  74. package/lib/server/handlers/claimTunnel.js +0 -80
  75. package/lib/server/handlers/completeClaimOnChain.js +0 -29
  76. package/lib/server/handlers/createClaimOnChain.js +0 -32
  77. package/lib/server/handlers/createTaskOnMechain.js +0 -57
  78. package/lib/server/handlers/createTunnel.js +0 -98
  79. package/lib/server/handlers/disconnectTunnel.js +0 -8
  80. package/lib/server/handlers/fetchCertificateBytes.js +0 -57
  81. package/lib/server/handlers/index.js +0 -25
  82. package/lib/server/handlers/init.js +0 -33
  83. package/lib/server/handlers/toprf.js +0 -19
  84. package/lib/server/index.js +0 -4
  85. package/lib/server/socket.js +0 -112
  86. package/lib/server/tunnels/make-tcp-tunnel.js +0 -202
  87. package/lib/server/utils/apm.js +0 -29
  88. package/lib/server/utils/assert-valid-claim-request.js +0 -354
  89. package/lib/server/utils/config-env.js +0 -4
  90. package/lib/server/utils/dns.js +0 -24
  91. package/lib/server/utils/gcp-attestation.js +0 -237
  92. package/lib/server/utils/generics.js +0 -45
  93. package/lib/server/utils/iso.js +0 -259
  94. package/lib/server/utils/keep-alive.js +0 -38
  95. package/lib/server/utils/nitro-attestation.js +0 -249
  96. package/lib/server/utils/oprf-raw.js +0 -61
  97. package/lib/server/utils/process-handshake.js +0 -233
  98. package/lib/server/utils/proxy-session.js +0 -6
  99. package/lib/server/utils/tee-oprf-mpc-verification.js +0 -86
  100. package/lib/server/utils/tee-oprf-verification.js +0 -151
  101. package/lib/server/utils/tee-transcript-reconstruction.js +0 -140
  102. package/lib/server/utils/tee-verification.js +0 -358
  103. package/lib/server/utils/validation.js +0 -45
  104. package/lib/types/bgp.js +0 -0
  105. package/lib/types/claims.js +0 -0
  106. package/lib/types/client.js +0 -0
  107. package/lib/types/general.js +0 -0
  108. package/lib/types/handlers.js +0 -0
  109. package/lib/types/index.js +0 -10
  110. package/lib/types/providers.gen.js +0 -16
  111. package/lib/types/providers.js +0 -0
  112. package/lib/types/rpc.js +0 -0
  113. package/lib/types/signatures.js +0 -0
  114. package/lib/types/tunnel.js +0 -0
  115. package/lib/types/zk.js +0 -0
  116. package/lib/utils/auth.js +0 -71
  117. package/lib/utils/b64-json.js +0 -17
  118. package/lib/utils/bgp-listener.js +0 -123
  119. package/lib/utils/claims.js +0 -89
  120. package/lib/utils/env.js +0 -19
  121. package/lib/utils/error.js +0 -54
  122. package/lib/utils/generics.js +0 -268
  123. package/lib/utils/http-parser.js +0 -201
  124. package/lib/utils/index.js +0 -13
  125. package/lib/utils/logger.js +0 -82
  126. package/lib/utils/prepare-packets.js +0 -69
  127. package/lib/utils/redactions.js +0 -135
  128. package/lib/utils/retries.js +0 -26
  129. package/lib/utils/signatures/eth.js +0 -31
  130. package/lib/utils/signatures/index.js +0 -12
  131. package/lib/utils/socket-base.js +0 -96
  132. package/lib/utils/tls.js +0 -58
  133. package/lib/utils/ws.js +0 -22
  134. package/lib/utils/zk.js +0 -625
@@ -1,80 +0,0 @@
1
- import { MAX_CLAIM_TIMESTAMP_DIFF_S } from "#src/config/index.js";
2
- import { ClaimTunnelResponse } from "#src/proto/api.js";
3
- import { getApm } from "#src/server/utils/apm.js";
4
- import { assertTranscriptsMatch, assertValidClaimRequest } from "#src/server/utils/assert-valid-claim-request.js";
5
- import { getAttestorAddress, signAsAttestor } from "#src/server/utils/generics.js";
6
- import { AttestorError, createSignDataForClaim, getIdentifierFromClaimInfo, unixTimestampSeconds } from "#src/utils/index.js";
7
- const claimTunnel = async (claimRequest, { tx, logger, client }) => {
8
- const {
9
- request,
10
- data: { timestampS } = {}
11
- } = claimRequest;
12
- const tunnel = client.getTunnel(request?.id);
13
- try {
14
- await tunnel.close();
15
- } catch (err) {
16
- logger.debug({ err }, "error closing tunnel");
17
- }
18
- if (tx) {
19
- const transcriptBytes = tunnel.transcript.reduce(
20
- (acc, { message }) => acc + message.length,
21
- 0
22
- );
23
- tx?.setLabel("transcriptBytes", transcriptBytes.toString());
24
- }
25
- if (tunnel.createRequest?.host !== request?.host || tunnel.createRequest?.port !== request?.port || tunnel.createRequest?.geoLocation !== request?.geoLocation || tunnel.createRequest?.proxySessionId !== request?.proxySessionId) {
26
- throw AttestorError.badRequest("Tunnel request does not match");
27
- }
28
- assertTranscriptsMatch(claimRequest.transcript, tunnel.transcript);
29
- const res = ClaimTunnelResponse.create({ request: claimRequest });
30
- try {
31
- const now = unixTimestampSeconds();
32
- if (Math.floor(timestampS - now) > MAX_CLAIM_TIMESTAMP_DIFF_S) {
33
- throw new AttestorError(
34
- "ERROR_INVALID_CLAIM",
35
- `Timestamp provided ${timestampS} is too far off. Current time is ${now}`
36
- );
37
- }
38
- const assertTx = getApm()?.startTransaction("assertValidClaimRequest", { childOf: tx });
39
- try {
40
- const claim = await assertValidClaimRequest(
41
- claimRequest,
42
- client.metadata,
43
- logger
44
- );
45
- res.claim = {
46
- ...claim,
47
- identifier: getIdentifierFromClaimInfo(claim),
48
- // hardcode for compatibility with V1 claims
49
- epoch: 1
50
- };
51
- } catch (err) {
52
- assertTx?.setOutcome("failure");
53
- throw err;
54
- } finally {
55
- assertTx?.end();
56
- }
57
- } catch (err) {
58
- logger.error({ err }, "invalid claim request");
59
- const attestorErr = AttestorError.fromError(err, "ERROR_INVALID_CLAIM");
60
- res.error = attestorErr.toProto();
61
- }
62
- res.signatures = {
63
- attestorAddress: getAttestorAddress(
64
- client.metadata.signatureType
65
- ),
66
- claimSignature: res.claim ? await signAsAttestor(
67
- createSignDataForClaim(res.claim),
68
- client.metadata.signatureType
69
- ) : new Uint8Array(),
70
- resultSignature: await signAsAttestor(
71
- ClaimTunnelResponse.encode(res).finish(),
72
- client.metadata.signatureType
73
- )
74
- };
75
- client.removeTunnel(request.id);
76
- return res;
77
- };
78
- export {
79
- claimTunnel
80
- };
@@ -1,29 +0,0 @@
1
- import { EventLog } from "ethers";
2
- import { getContracts } from "#src/avs/utils/contracts.js";
3
- import { getEnvVariable } from "#src/utils/env.js";
4
- import { AttestorError, ethersStructToPlainObject } from "#src/utils/index.js";
5
- const ACCEPT_CLAIM_PAYMENT_REQUESTS = getEnvVariable("ACCEPT_CLAIM_PAYMENT_REQUESTS") === "1";
6
- const completeClaimOnChain = async ({ chainId: chainIdNum, taskIndex, completedTaskJson }) => {
7
- if (!ACCEPT_CLAIM_PAYMENT_REQUESTS) {
8
- throw new AttestorError(
9
- "ERROR_PAYMENT_REFUSED",
10
- "Payment requests are not accepted at this time"
11
- );
12
- }
13
- const chainId = chainIdNum.toString();
14
- const { contract } = getContracts(chainId.toString());
15
- const task = JSON.parse(completedTaskJson);
16
- const tx = await contract.taskCompleted(task, taskIndex);
17
- const rslt = await tx.wait();
18
- const logs = rslt?.logs ?? [];
19
- const eventLogs = logs.filter((log) => log instanceof EventLog);
20
- const obj = eventLogs[0]?.args;
21
- const plainObj = ethersStructToPlainObject(obj);
22
- return {
23
- txHash: rslt?.hash ?? "",
24
- taskCompletedObjectJson: JSON.stringify(plainObj)
25
- };
26
- };
27
- export {
28
- completeClaimOnChain
29
- };
@@ -1,32 +0,0 @@
1
- import { getContracts } from "#src/avs/utils/contracts.js";
2
- import { createNewClaimRequestOnChain } from "#src/avs/utils/tasks.js";
3
- import { getEnvVariable } from "#src/utils/env.js";
4
- import { AttestorError, ethersStructToPlainObject } from "#src/utils/index.js";
5
- const ACCEPT_CLAIM_PAYMENT_REQUESTS = getEnvVariable("ACCEPT_CLAIM_PAYMENT_REQUESTS") === "1";
6
- const createClaimOnChain = async ({ chainId: chainIdNum, jsonCreateClaimRequest, requestSignature }) => {
7
- if (!ACCEPT_CLAIM_PAYMENT_REQUESTS) {
8
- throw new AttestorError(
9
- "ERROR_PAYMENT_REFUSED",
10
- "Payment requests are not accepted at this time"
11
- );
12
- }
13
- const chainId = chainIdNum.toString();
14
- const { wallet } = getContracts(chainId.toString());
15
- const request = JSON.parse(jsonCreateClaimRequest);
16
- const { task, tx } = await createNewClaimRequestOnChain({
17
- request,
18
- owner: request.owner,
19
- payer: wallet,
20
- chainId,
21
- requestSignature
22
- });
23
- const plainTask = ethersStructToPlainObject(task);
24
- return {
25
- txHash: tx?.hash ?? "",
26
- taskIndex: Number(task.taskIndex),
27
- jsonTask: JSON.stringify(plainTask)
28
- };
29
- };
30
- export {
31
- createClaimOnChain
32
- };
@@ -1,57 +0,0 @@
1
- import { Contract, JsonRpcProvider, randomBytes, Wallet } from "ethers";
2
- import { governanceABI } from "#src/mechain/abis/governanceABI.js";
3
- import { taskABI } from "#src/mechain/abis/taskABI.js";
4
- import { GOVERNANCE_CONTRACT_ADDRESS, RPC_URL, TASK_CONTRACT_ADDRESS } from "#src/mechain/constants/index.js";
5
- import { getEnvVariable } from "#src/utils/env.js";
6
- const createTaskOnMechain = async ({
7
- timestamp
8
- }) => {
9
- const { taskContract } = await getContracts();
10
- const seed = randomBytes(32);
11
- const result = await taskContract.createNewTaskRequest.staticCall(
12
- seed,
13
- timestamp
14
- );
15
- const taskId = result[0];
16
- const requiredAttestors = await taskContract.requiredAttestors();
17
- const hosts = [];
18
- for (let i = 0; i < requiredAttestors; i++) {
19
- hosts.push(result[1][i].host);
20
- }
21
- const tx = await taskContract.createNewTaskRequest(seed, timestamp);
22
- await tx.wait();
23
- return {
24
- taskId,
25
- requiredAttestors,
26
- hosts
27
- };
28
- };
29
- async function getContracts() {
30
- const privateKey = getEnvVariable("MECHAIN_PRIVATE_KEY");
31
- const taskContractAddress = getEnvVariable("TASK_CONTRACT_ADDRESS") || TASK_CONTRACT_ADDRESS;
32
- const governanceContractAddress = getEnvVariable("GOVERNANCE_CONTRACT_ADDRESS") || GOVERNANCE_CONTRACT_ADDRESS;
33
- if (!privateKey) {
34
- throw new Error("MECHAIN_PRIVATE_KEY environment variable is not set");
35
- }
36
- try {
37
- const provider = new JsonRpcProvider(RPC_URL);
38
- await provider.getNetwork();
39
- const signer = new Wallet(privateKey, provider);
40
- const taskContract = new Contract(
41
- taskContractAddress,
42
- taskABI,
43
- signer
44
- );
45
- const governanceContract = new Contract(
46
- governanceContractAddress,
47
- governanceABI,
48
- signer
49
- );
50
- return { taskContract, governanceContract };
51
- } catch (error) {
52
- throw new Error(`Failed to initialize contracts: ${error.message || error}`);
53
- }
54
- }
55
- export {
56
- createTaskOnMechain
57
- };
@@ -1,98 +0,0 @@
1
- import { makeTcpTunnel } from "#src/server/tunnels/make-tcp-tunnel.js";
2
- import { getApm } from "#src/server/utils/apm.js";
3
- import { resolveHostnames } from "#src/server/utils/dns.js";
4
- import { AttestorError } from "#src/utils/index.js";
5
- const createTunnel = async ({ id, ...opts }, { tx, logger, client }) => {
6
- if (client.tunnels[id]) {
7
- throw AttestorError.badRequest(`Tunnel "${id}" already exists`);
8
- }
9
- const allowedHosts = client.metadata?.auth?.data?.hostWhitelist;
10
- if (allowedHosts?.length && !allowedHosts.includes(opts.host)) {
11
- throw AttestorError.badRequest(
12
- `Host "${opts.host}" not allowed by auth request`
13
- );
14
- }
15
- let cancelBgp;
16
- const apm = getApm();
17
- const sessionTx = apm?.startTransaction("tunnelConnection", { childOf: tx });
18
- sessionTx?.setLabel("tunnelId", id.toString());
19
- sessionTx?.setLabel("hostPort", `${opts.host}:${opts.port}`);
20
- sessionTx?.setLabel("geoLocation", opts.geoLocation);
21
- sessionTx?.setLabel("proxySessionId", opts.proxySessionId);
22
- try {
23
- const tunnel = await makeTcpTunnel({
24
- ...opts,
25
- logger,
26
- onMessage(message) {
27
- if (!client.isOpen) {
28
- logger.warn("client is closed, dropping message");
29
- return;
30
- }
31
- return client.sendMessage({ tunnelMessage: { tunnelId: id, message } });
32
- },
33
- onClose(err) {
34
- cancelBgp?.();
35
- if (err) {
36
- apm?.captureError(err, { parent: sessionTx });
37
- sessionTx?.setOutcome("failure");
38
- } else {
39
- sessionTx?.setOutcome("success");
40
- }
41
- sessionTx?.end();
42
- if (!client.isOpen) {
43
- return;
44
- }
45
- client.sendMessage({
46
- tunnelDisconnectEvent: {
47
- tunnelId: id,
48
- error: err ? AttestorError.fromError(err).toProto() : void 0
49
- }
50
- }).catch((err2) => {
51
- logger.error(
52
- { err: err2 },
53
- "failed to send tunnel disconnect event"
54
- );
55
- });
56
- }
57
- });
58
- try {
59
- await checkForBgp(tunnel);
60
- } catch (err) {
61
- logger.warn(
62
- { err, host: opts.host },
63
- "failed to start BGP overlap check"
64
- );
65
- }
66
- client.tunnels[id] = tunnel;
67
- return {};
68
- } catch (err) {
69
- apm?.captureError(err, { parent: sessionTx });
70
- sessionTx?.setOutcome("failure");
71
- sessionTx?.end();
72
- cancelBgp?.();
73
- throw err;
74
- }
75
- async function checkForBgp(tunnel) {
76
- if (!client.bgpListener) {
77
- return;
78
- }
79
- const ips = await resolveHostnames(opts.host);
80
- cancelBgp = client.bgpListener.onOverlap(ips, (info) => {
81
- logger.warn(
82
- { info, host: opts.host },
83
- "BGP announcement overlap detected"
84
- );
85
- sessionTx?.addLabels({ bgpOverlap: true, ...info });
86
- void tunnel?.close(
87
- new AttestorError(
88
- "ERROR_BGP_ANNOUNCEMENT_OVERLAP",
89
- `BGP announcement overlap detected for ${opts.host}`
90
- )
91
- );
92
- });
93
- logger.debug({ ips }, "checking for BGP overlap");
94
- }
95
- };
96
- export {
97
- createTunnel
98
- };
@@ -1,8 +0,0 @@
1
- const disconnectTunnel = async ({ id }, { client }) => {
2
- const tunnel = client.getTunnel(id);
3
- await tunnel.close();
4
- return {};
5
- };
6
- export {
7
- disconnectTunnel
8
- };
@@ -1,57 +0,0 @@
1
- import { concatenateUint8Arrays, loadX509FromPem } from "@reclaimprotocol/tls";
2
- import { CERT_ALLOWED_MIMETYPES, MAX_CERT_SIZE_BYTES } from "#src/config/index.js";
3
- import { AttestorError } from "#src/utils/error.js";
4
- const fetchCertificateBytes = async ({ url }) => {
5
- const res = await fetch(url, {
6
- redirect: "follow",
7
- signal: AbortSignal.timeout(1e4)
8
- });
9
- if (!res.ok) {
10
- res.body?.cancel("Not ok");
11
- throw new AttestorError(
12
- "ERROR_CERTIFICATE_FETCH_FAILED",
13
- `Failed to fetch certificate from URL: ${url}, status: ${res.status}`
14
- );
15
- }
16
- const contentType = res.headers.get("content-type");
17
- if (!contentType || !CERT_ALLOWED_MIMETYPES.includes(contentType)) {
18
- res.body?.cancel("Mismatch");
19
- throw new AttestorError(
20
- "ERROR_CERTIFICATE_FETCH_FAILED",
21
- `Invalid content-type when fetching certificate from URL: ${url}, content-type: ${contentType}`
22
- );
23
- }
24
- if (!res.body) {
25
- throw new AttestorError(
26
- "ERROR_CERTIFICATE_FETCH_FAILED",
27
- `No body in response when fetching certificate from URL: ${url}`
28
- );
29
- }
30
- let total = 0;
31
- const byteArr = [];
32
- for await (const chunk of res.body) {
33
- total += chunk.length;
34
- if (total > MAX_CERT_SIZE_BYTES) {
35
- res.body.cancel("Too many bytes");
36
- throw new AttestorError(
37
- "ERROR_CERTIFICATE_FETCH_FAILED",
38
- `Certificate size exceeds maximum limit of ${MAX_CERT_SIZE_BYTES}b`
39
- );
40
- }
41
- byteArr.push(chunk);
42
- }
43
- const bytes = concatenateUint8Arrays(byteArr);
44
- try {
45
- const cert = loadX509FromPem(bytes);
46
- TLS_INTERMEDIATE_CA_CACHE[url] = cert;
47
- } catch (err) {
48
- throw new AttestorError(
49
- "ERROR_CERTIFICATE_FETCH_FAILED",
50
- `Failed to parse certificate, error: ${err.message}`
51
- );
52
- }
53
- return { bytes: concatenateUint8Arrays(byteArr) };
54
- };
55
- export {
56
- fetchCertificateBytes
57
- };
@@ -1,25 +0,0 @@
1
- import { claimTeeBundle } from "#src/server/handlers/claimTeeBundle.js";
2
- import { claimTunnel } from "#src/server/handlers/claimTunnel.js";
3
- import { completeClaimOnChain } from "#src/server/handlers/completeClaimOnChain.js";
4
- import { createClaimOnChain } from "#src/server/handlers/createClaimOnChain.js";
5
- import { createTaskOnMechain } from "#src/server/handlers/createTaskOnMechain.js";
6
- import { createTunnel } from "#src/server/handlers/createTunnel.js";
7
- import { disconnectTunnel } from "#src/server/handlers/disconnectTunnel.js";
8
- import { fetchCertificateBytes } from "#src/server/handlers/fetchCertificateBytes.js";
9
- import { init } from "#src/server/handlers/init.js";
10
- import { toprf } from "#src/server/handlers/toprf.js";
11
- const HANDLERS = {
12
- createTunnel,
13
- disconnectTunnel,
14
- claimTunnel,
15
- claimTeeBundle,
16
- init,
17
- createClaimOnChain,
18
- completeClaimOnChain,
19
- toprf,
20
- createTaskOnMechain,
21
- fetchCertificateBytes
22
- };
23
- export {
24
- HANDLERS
25
- };
@@ -1,33 +0,0 @@
1
- import { getBytes } from "ethers";
2
- import { getAttestorAddress } from "#src/server/utils/generics.js";
3
- import { assertValidAuthRequest } from "#src/utils/auth.js";
4
- import { getEnvVariable } from "#src/utils/env.js";
5
- import { AttestorError } from "#src/utils/index.js";
6
- import { SIGNATURES } from "#src/utils/signatures/index.js";
7
- const TOPRF_PUBLIC_KEY = getEnvVariable("TOPRF_PUBLIC_KEY");
8
- const init = async (initRequest, { client }) => {
9
- if (client.isInitialised) {
10
- throw AttestorError.badRequest("Client already initialised");
11
- }
12
- if (!SIGNATURES[initRequest.signatureType]) {
13
- throw AttestorError.badRequest("Unsupported signature type");
14
- }
15
- if (initRequest.clientVersion <= 0) {
16
- throw AttestorError.badRequest("Unsupported client version");
17
- }
18
- await assertValidAuthRequest(initRequest.auth, initRequest.signatureType);
19
- if (initRequest.auth?.data) {
20
- client.logger = client.logger.child({
21
- userId: initRequest.auth.data.id
22
- });
23
- }
24
- client.metadata = initRequest;
25
- client.isInitialised = true;
26
- return {
27
- toprfPublicKey: TOPRF_PUBLIC_KEY ? getBytes(TOPRF_PUBLIC_KEY) : new Uint8Array(),
28
- attestorAddress: getAttestorAddress(initRequest.signatureType)
29
- };
30
- };
31
- export {
32
- init
33
- };
@@ -1,19 +0,0 @@
1
- import { getBytes } from "ethers";
2
- import { getEnvVariable } from "#src/utils/env.js";
3
- import { getEngineString, makeDefaultOPRFOperator } from "#src/utils/index.js";
4
- const toprf = async ({ maskedData, engine }, { logger }) => {
5
- const PRIVATE_KEY_STR = getEnvVariable("TOPRF_SHARE_PRIVATE_KEY");
6
- const PUBLIC_KEY_STR = getEnvVariable("TOPRF_SHARE_PUBLIC_KEY");
7
- if (!PRIVATE_KEY_STR || !PUBLIC_KEY_STR) {
8
- throw new Error("private/public keys not set. Cannot execute OPRF");
9
- }
10
- const PRIVATE_KEY = getBytes(PRIVATE_KEY_STR);
11
- const PUBLIC_KEY = getBytes(PUBLIC_KEY_STR);
12
- const engineStr = getEngineString(engine);
13
- const operator = makeDefaultOPRFOperator("chacha20", engineStr, logger);
14
- const res = await operator.evaluateOPRF(PRIVATE_KEY, maskedData);
15
- return { ...res, publicKeyShare: PUBLIC_KEY };
16
- };
17
- export {
18
- toprf
19
- };
@@ -1,4 +0,0 @@
1
- export * from "./utils/config-env.js";
2
- export * from "./create-server.js";
3
- export * from "./tunnels/make-tcp-tunnel.js";
4
- export * from "./utils/assert-valid-claim-request.js";
@@ -1,112 +0,0 @@
1
- import { promisify } from "util";
2
- import { handleMessage } from "#src/client/utils/message-handler.js";
3
- import { DEFAULT_RPC_TIMEOUT_MS } from "#src/config/index.js";
4
- import { HANDLERS } from "#src/server/handlers/index.js";
5
- import { getApm } from "#src/server/utils/apm.js";
6
- import { getInitialMessagesFromQuery } from "#src/server/utils/generics.js";
7
- import { AttestorError, generateSessionId } from "#src/utils/index.js";
8
- import { AttestorSocket } from "#src/utils/socket-base.js";
9
- class AttestorServerSocket extends AttestorSocket {
10
- tunnels = {};
11
- sessionId;
12
- bgpListener;
13
- constructor(socket, sessionId, bgpListener, logger) {
14
- super(socket, {}, logger);
15
- this.sessionId = sessionId;
16
- this.bgpListener = bgpListener;
17
- this.addEventListener("rpc-request", handleRpcRequest.bind(this));
18
- this.addEventListener("tunnel-message", handleTunnelMessage.bind(this));
19
- this.addEventListener("connection-terminated", () => {
20
- for (const tunnelId in this.tunnels) {
21
- const tunnel = this.tunnels[tunnelId];
22
- void tunnel.close(new Error("WS session terminated"));
23
- }
24
- });
25
- }
26
- getTunnel(tunnelId) {
27
- const tunnel = this.tunnels[tunnelId];
28
- if (!tunnel) {
29
- throw new AttestorError(
30
- "ERROR_NOT_FOUND",
31
- `Tunnel "${tunnelId}" not found`
32
- );
33
- }
34
- return tunnel;
35
- }
36
- removeTunnel(tunnelId) {
37
- delete this.tunnels[tunnelId];
38
- }
39
- static async acceptConnection(socket, { req, logger, bgpListener }) {
40
- const bindSend = socket.send.bind(socket);
41
- socket.send = promisify(bindSend);
42
- const sessionId = generateSessionId();
43
- logger = logger.child({ sessionId });
44
- const client = new AttestorServerSocket(
45
- socket,
46
- sessionId,
47
- bgpListener,
48
- logger
49
- );
50
- try {
51
- const initMsgs = getInitialMessagesFromQuery(req);
52
- logger.trace(
53
- { initMsgs: initMsgs.length },
54
- "new connection, validating..."
55
- );
56
- for (const msg of initMsgs) {
57
- await handleMessage.call(client, msg);
58
- }
59
- logger.debug("connection accepted");
60
- } catch (err) {
61
- logger.error({ err }, "error in new connection");
62
- if (client.isOpen) {
63
- await client.terminateConnection(
64
- err instanceof AttestorError ? err : AttestorError.badRequest(err.message)
65
- );
66
- }
67
- return;
68
- }
69
- return client;
70
- }
71
- }
72
- async function handleTunnelMessage({ data: { tunnelId, message } }) {
73
- try {
74
- const tunnel = this.getTunnel(tunnelId);
75
- await tunnel.write(message);
76
- } catch (err) {
77
- this.logger?.error({ err, tunnelId }, "error writing to tunnel");
78
- }
79
- }
80
- async function handleRpcRequest({ data: { data, requestId, respond, type } }) {
81
- const logger = this.logger.child({ rpc: type, requestId });
82
- const apm = getApm();
83
- const tx = apm?.startTransaction(type);
84
- tx?.setLabel("requestId", requestId);
85
- tx?.setLabel("sessionId", this.sessionId.toString());
86
- const userId = this.metadata.auth?.data?.id;
87
- if (userId) {
88
- tx?.setLabel("authUserId", userId);
89
- }
90
- const timeout = setTimeout(() => {
91
- logger.warn({ type, requestId }, "RPC took too long to respond");
92
- }, DEFAULT_RPC_TIMEOUT_MS);
93
- try {
94
- logger.debug({ data }, "handling RPC request");
95
- const handler = HANDLERS[type];
96
- const res = await handler(data, { client: this, logger, tx });
97
- respond(res);
98
- logger.debug({ res }, "handled RPC request");
99
- tx?.setOutcome("success");
100
- } catch (err) {
101
- logger.error({ err }, "error in RPC request");
102
- respond(AttestorError.fromError(err));
103
- tx?.setOutcome("failure");
104
- apm?.captureError(err, { parent: tx });
105
- } finally {
106
- clearTimeout(timeout);
107
- tx?.end();
108
- }
109
- }
110
- export {
111
- AttestorServerSocket
112
- };