@reclaimprotocol/attestor-core 5.0.1-beta.28 → 5.0.1-beta.29

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 (117) hide show
  1. package/lib/external-rpc/index.js +10400 -3
  2. package/lib/external-rpc/index.js.map +7 -0
  3. package/lib/index.js +8331 -11
  4. package/lib/index.js.map +7 -0
  5. package/package.json +2 -2
  6. package/lib/avs/abis/avsDirectoryABI.js +0 -340
  7. package/lib/avs/abis/delegationABI.js +0 -1
  8. package/lib/avs/abis/registryABI.js +0 -725
  9. package/lib/avs/client/create-claim-on-avs.js +0 -140
  10. package/lib/avs/config.js +0 -20
  11. package/lib/avs/contracts/ReclaimServiceManager.js +0 -1
  12. package/lib/avs/contracts/common.js +0 -1
  13. package/lib/avs/contracts/factories/ReclaimServiceManager__factory.js +0 -1166
  14. package/lib/avs/contracts/factories/index.js +0 -4
  15. package/lib/avs/contracts/index.js +0 -2
  16. package/lib/avs/types/index.js +0 -1
  17. package/lib/avs/utils/contracts.js +0 -33
  18. package/lib/avs/utils/register.js +0 -79
  19. package/lib/avs/utils/tasks.js +0 -41
  20. package/lib/client/create-claim.js +0 -432
  21. package/lib/client/index.js +0 -3
  22. package/lib/client/tunnels/make-rpc-tcp-tunnel.js +0 -51
  23. package/lib/client/tunnels/make-rpc-tls-tunnel.js +0 -131
  24. package/lib/client/utils/attestor-pool.js +0 -25
  25. package/lib/client/utils/client-socket.js +0 -97
  26. package/lib/client/utils/message-handler.js +0 -87
  27. package/lib/config/index.js +0 -44
  28. package/lib/external-rpc/benchmark.js +0 -69
  29. package/lib/external-rpc/event-bus.js +0 -14
  30. package/lib/external-rpc/handle-incoming-msg.js +0 -232
  31. package/lib/external-rpc/jsc-polyfills/1.js +0 -82
  32. package/lib/external-rpc/jsc-polyfills/2.js +0 -20
  33. package/lib/external-rpc/jsc-polyfills/event.js +0 -14
  34. package/lib/external-rpc/jsc-polyfills/index.js +0 -2
  35. package/lib/external-rpc/jsc-polyfills/ws.js +0 -81
  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 -1
  39. package/lib/external-rpc/utils.js +0 -100
  40. package/lib/external-rpc/zk.js +0 -63
  41. package/lib/mechain/abis/governanceABI.js +0 -458
  42. package/lib/mechain/abis/taskABI.js +0 -509
  43. package/lib/mechain/client/create-claim-on-mechain.js +0 -28
  44. package/lib/mechain/client/index.js +0 -1
  45. package/lib/mechain/constants/index.js +0 -3
  46. package/lib/mechain/index.js +0 -2
  47. package/lib/mechain/types/index.js +0 -1
  48. package/lib/proto/api.js +0 -4363
  49. package/lib/proto/tee-bundle.js +0 -1316
  50. package/lib/providers/http/index.js +0 -653
  51. package/lib/providers/http/patch-parse5-tree.js +0 -32
  52. package/lib/providers/http/utils.js +0 -324
  53. package/lib/providers/index.js +0 -4
  54. package/lib/server/create-server.js +0 -103
  55. package/lib/server/handlers/claimTeeBundle.js +0 -252
  56. package/lib/server/handlers/claimTunnel.js +0 -73
  57. package/lib/server/handlers/completeClaimOnChain.js +0 -24
  58. package/lib/server/handlers/createClaimOnChain.js +0 -26
  59. package/lib/server/handlers/createTaskOnMechain.js +0 -47
  60. package/lib/server/handlers/createTunnel.js +0 -93
  61. package/lib/server/handlers/disconnectTunnel.js +0 -5
  62. package/lib/server/handlers/fetchCertificateBytes.js +0 -41
  63. package/lib/server/handlers/index.js +0 -22
  64. package/lib/server/handlers/init.js +0 -32
  65. package/lib/server/handlers/toprf.js +0 -16
  66. package/lib/server/index.js +0 -4
  67. package/lib/server/socket.js +0 -109
  68. package/lib/server/tunnels/make-tcp-tunnel.js +0 -177
  69. package/lib/server/utils/apm.js +0 -36
  70. package/lib/server/utils/assert-valid-claim-request.js +0 -325
  71. package/lib/server/utils/config-env.js +0 -4
  72. package/lib/server/utils/dns.js +0 -18
  73. package/lib/server/utils/gcp-attestation.js +0 -289
  74. package/lib/server/utils/generics.js +0 -51
  75. package/lib/server/utils/iso.js +0 -256
  76. package/lib/server/utils/keep-alive.js +0 -38
  77. package/lib/server/utils/nitro-attestation.js +0 -324
  78. package/lib/server/utils/oprf-raw.js +0 -54
  79. package/lib/server/utils/process-handshake.js +0 -215
  80. package/lib/server/utils/proxy-session.js +0 -6
  81. package/lib/server/utils/tee-oprf-mpc-verification.js +0 -90
  82. package/lib/server/utils/tee-oprf-verification.js +0 -174
  83. package/lib/server/utils/tee-transcript-reconstruction.js +0 -187
  84. package/lib/server/utils/tee-verification.js +0 -421
  85. package/lib/server/utils/validation.js +0 -38
  86. package/lib/tls-exports.js +0 -5
  87. package/lib/types/bgp.js +0 -1
  88. package/lib/types/claims.js +0 -1
  89. package/lib/types/client.js +0 -1
  90. package/lib/types/general.js +0 -1
  91. package/lib/types/handlers.js +0 -1
  92. package/lib/types/index.js +0 -10
  93. package/lib/types/providers.gen.js +0 -10
  94. package/lib/types/providers.js +0 -1
  95. package/lib/types/rpc.js +0 -1
  96. package/lib/types/signatures.js +0 -1
  97. package/lib/types/tunnel.js +0 -1
  98. package/lib/types/zk.js +0 -1
  99. package/lib/utils/auth.js +0 -59
  100. package/lib/utils/b64-json.js +0 -17
  101. package/lib/utils/bgp-listener.js +0 -119
  102. package/lib/utils/claims.js +0 -98
  103. package/lib/utils/env.js +0 -15
  104. package/lib/utils/error.js +0 -50
  105. package/lib/utils/generics.js +0 -317
  106. package/lib/utils/http-parser.js +0 -246
  107. package/lib/utils/index.js +0 -13
  108. package/lib/utils/logger.js +0 -91
  109. package/lib/utils/prepare-packets.js +0 -71
  110. package/lib/utils/redactions.js +0 -177
  111. package/lib/utils/retries.js +0 -24
  112. package/lib/utils/signatures/eth.js +0 -32
  113. package/lib/utils/signatures/index.js +0 -7
  114. package/lib/utils/socket-base.js +0 -92
  115. package/lib/utils/tls.js +0 -58
  116. package/lib/utils/ws.js +0 -22
  117. package/lib/utils/zk.js +0 -585
@@ -1,232 +0,0 @@
1
- import { hexlify } from 'ethers';
2
- import { createClaimOnAvs } from "../avs/client/create-claim-on-avs.js";
3
- import { createClaimOnAttestor } from "../client/index.js";
4
- import { benchmark } from "./benchmark.js";
5
- import { generateRpcRequestId, getCurrentMemoryUsage, getWsApiUrlFromBaseUrl, RPC_MSG_BRIDGE, sendMessageToApp, waitForResponse } from "./utils.js";
6
- import { ALL_ENC_ALGORITHMS, makeExternalRpcOprfOperator, makeExternalRpcZkOperator } from "./zk.js";
7
- import { createClaimOnMechain } from "../mechain/client/create-claim-on-mechain.js";
8
- import { extractHTMLElement, extractJSONValueIndex, generateRequstAndResponseFromTranscript } from "../providers/http/utils.js";
9
- import { B64_JSON_REVIVER } from "../utils/b64-json.js";
10
- import { AttestorError, getIdentifierFromClaimInfo, logger, makeLogger, uint8ArrayToStr } from "../utils/index.js";
11
- export async function handleIncomingMessage(data) {
12
- let id = '';
13
- try {
14
- const req = (typeof data === 'string'
15
- ? JSON.parse(data, B64_JSON_REVIVER)
16
- : data);
17
- id = req.id || '';
18
- const rslt = await _handleIncomingMessage(req);
19
- if (!rslt) {
20
- return;
21
- }
22
- respond(rslt);
23
- }
24
- catch (err) {
25
- console.error('Error in RPC', { id, error: err });
26
- respond({
27
- type: 'error',
28
- data: {
29
- message: err.message,
30
- stack: err.stack,
31
- }
32
- });
33
- }
34
- function respond(data) {
35
- const res = {
36
- ...data,
37
- id,
38
- isResponse: true
39
- };
40
- return sendMessageToApp(res);
41
- }
42
- }
43
- async function _handleIncomingMessage(req) {
44
- const { id: reqId, type: reqType } = req;
45
- // ignore any messages not for us
46
- if (!reqId || !reqType) {
47
- return;
48
- }
49
- RPC_MSG_BRIDGE.dispatch(req);
50
- // ignore response messages
51
- if (('isResponse' in req && req.isResponse)) {
52
- return;
53
- }
54
- if (!reqId) {
55
- logger.warn({ req }, 'Window RPC request missing ID');
56
- return;
57
- }
58
- logger.info({ req }, 'processing RPC request');
59
- switch (req.type) {
60
- case 'createClaim':
61
- const claimTunnelRes = await createClaimOnAttestor({
62
- ...req.request,
63
- context: req.request.context
64
- ? JSON.parse(req.request.context)
65
- : undefined,
66
- zkOperators: getZkOperators(req.request.zkOperatorMode, req.request.zkEngine),
67
- oprfOperators: getOprfOperators(req.request.zkOperatorMode, req.request.zkEngine),
68
- client: {
69
- url: getWsApiUrlFromBaseUrl(),
70
- authRequest: req.request.authRequest
71
- },
72
- logger,
73
- onStep(step) {
74
- sendMessageToApp({
75
- type: 'createClaimStep',
76
- step: { name: 'attestor-progress', step },
77
- id: req.id,
78
- });
79
- },
80
- updateProviderParams: req.request.updateProviderParams
81
- ? updateProviderParams
82
- : undefined,
83
- });
84
- const response = mapToCreateClaimResponse(claimTunnelRes);
85
- return { type: 'createClaimDone', response };
86
- case 'createClaimOnAvs':
87
- const avsRes = await createClaimOnAvs({
88
- ...req.request,
89
- payer: req.request.payer === 'attestor'
90
- ? { attestor: getWsApiUrlFromBaseUrl() }
91
- : undefined,
92
- context: req.request.context
93
- ? JSON.parse(req.request.context)
94
- : undefined,
95
- zkOperators: getZkOperators(req.request.zkOperatorMode, req.request.zkEngine),
96
- oprfOperators: getOprfOperators(req.request.zkOperatorMode, req.request.zkEngine),
97
- logger,
98
- onStep(step) {
99
- sendMessageToApp({
100
- type: 'createClaimOnAvsStep',
101
- step,
102
- id: req.id,
103
- });
104
- },
105
- });
106
- return {
107
- type: 'createClaimOnAvsDone',
108
- response: avsRes,
109
- };
110
- case 'createClaimOnMechain':
111
- const mechainRes = await createClaimOnMechain({
112
- ...req.request,
113
- context: req.request.context
114
- ? JSON.parse(req.request.context)
115
- : undefined,
116
- zkOperators: getZkOperators(req.request.zkOperatorMode, req.request.zkEngine),
117
- oprfOperators: getOprfOperators(req.request.zkOperatorMode, req.request.zkEngine),
118
- client: { url: getWsApiUrlFromBaseUrl() },
119
- logger,
120
- onStep(step) {
121
- sendMessageToApp({
122
- type: 'createClaimOnMechainStep',
123
- step,
124
- id: req.id,
125
- });
126
- },
127
- });
128
- const claimResponses = [];
129
- for (let i = 0; i < mechainRes.responses.length; i++) {
130
- claimResponses[i] = mapToCreateClaimResponse(mechainRes.responses[i]);
131
- }
132
- return {
133
- type: 'createClaimOnMechainDone',
134
- response: { taskId: mechainRes.taskId, data: claimResponses },
135
- };
136
- case 'extractHtmlElement':
137
- return {
138
- type: 'extractHtmlElementDone',
139
- response: extractHTMLElement(req.request.html, req.request.xpathExpression, req.request.contentsOnly),
140
- };
141
- case 'extractJSONValueIndex':
142
- return {
143
- type: 'extractJSONValueIndexDone',
144
- response: extractJSONValueIndex(req.request.json, req.request.jsonPath),
145
- };
146
- case 'getCurrentMemoryUsage':
147
- return {
148
- type: 'getCurrentMemoryUsageDone',
149
- response: await getCurrentMemoryUsage(),
150
- };
151
- case 'setLogLevel':
152
- makeLogger(true, req.request.logLevel, req.request.sendLogsToApp
153
- ? (level, message) => (sendMessageToApp({
154
- type: 'log',
155
- level,
156
- message,
157
- id: req.id,
158
- }))
159
- : undefined);
160
- return { type: 'setLogLevelDone', response: undefined };
161
- case 'benchmarkZK':
162
- return { type: 'benchmarkZKDone', response: await benchmark() };
163
- case 'ping':
164
- return { type: 'pingDone', response: { pong: new Date().toJSON() } };
165
- default:
166
- break;
167
- }
168
- }
169
- function getZkOperators(mode = 'default', zkEngine = 'snarkjs') {
170
- // use default snarkJS ops
171
- if (mode === 'default') {
172
- return;
173
- }
174
- // the native app/window calling implements
175
- // a ZK operator & wants to use it
176
- const operators = {};
177
- for (const alg of ALL_ENC_ALGORITHMS) {
178
- operators[alg] = makeExternalRpcZkOperator(alg, zkEngine);
179
- }
180
- return operators;
181
- }
182
- function getOprfOperators(mode = 'default', zkEngine = 'snarkjs') {
183
- // use default webview ops
184
- if (mode === 'default') {
185
- return;
186
- }
187
- // the native app/window calling implements
188
- // a ZK operator & wants to use it
189
- const operators = {};
190
- for (const alg of ALL_ENC_ALGORITHMS) {
191
- operators[alg] = makeExternalRpcOprfOperator(alg, zkEngine);
192
- }
193
- return operators;
194
- }
195
- async function updateProviderParams(transcript, tlsVersion) {
196
- const { req, res } = generateRequstAndResponseFromTranscript(transcript, tlsVersion);
197
- const id = generateRpcRequestId();
198
- const waitForRes = waitForResponse('updateProviderParams', id);
199
- sendMessageToApp({
200
- type: 'updateProviderParams',
201
- id,
202
- request: {
203
- request: {
204
- ...req,
205
- body: req.body
206
- ? uint8ArrayToStr(req.body)
207
- : undefined
208
- },
209
- response: { ...res, body: uint8ArrayToStr(res.body) },
210
- }
211
- });
212
- return waitForRes;
213
- }
214
- function mapToCreateClaimResponse(res) {
215
- if (!res.claim) {
216
- throw AttestorError.fromProto(res.error);
217
- }
218
- return {
219
- identifier: getIdentifierFromClaimInfo(res.claim),
220
- claimData: res.claim,
221
- witnesses: [
222
- {
223
- id: res.signatures.attestorAddress,
224
- url: getWsApiUrlFromBaseUrl()
225
- }
226
- ],
227
- signatures: [
228
- hexlify(res.signatures.claimSignature)
229
- .toLowerCase()
230
- ]
231
- };
232
- }
@@ -1,82 +0,0 @@
1
- import { TextDecoder, TextEncoder } from '@kayahr/text-encoding';
2
- import { crypto, uint8ArrayToBinaryStr } from '@reclaimprotocol/tls';
3
- import { fromByteArray, toByteArray } from 'base64-js';
4
- import { EventTarget } from 'event-target-shim';
5
- if (typeof global === 'undefined') {
6
- globalThis.global = globalThis;
7
- }
8
- if (typeof console === 'undefined') {
9
- // @ts-expect-error
10
- globalThis.console = {
11
- log: print,
12
- error: print,
13
- warn: print,
14
- info: print,
15
- debug: print,
16
- };
17
- }
18
- if (typeof globalThis.crypto === 'undefined') {
19
- globalThis.crypto = {
20
- // @ts-expect-error
21
- getRandomValues(arr) {
22
- const randVals = crypto.randomBytes(arr.length);
23
- for (let i = 0; i < arr.length; i++) {
24
- arr[i] = randVals[i];
25
- }
26
- return arr;
27
- },
28
- randomBytes(length) {
29
- return crypto.randomBytes(length);
30
- }
31
- };
32
- }
33
- if (typeof globalThis.TextEncoder === 'undefined') {
34
- globalThis.TextEncoder = TextEncoder;
35
- }
36
- if (typeof globalThis.TextDecoder === 'undefined') {
37
- globalThis.TextDecoder = TextDecoder;
38
- }
39
- if (typeof globalThis.EventTarget === 'undefined') {
40
- globalThis.EventTarget = EventTarget;
41
- }
42
- if (typeof globalThis.atob === 'undefined') {
43
- globalThis.atob = a => uint8ArrayToBinaryStr(toByteArray(a));
44
- }
45
- if (typeof globalThis.btoa === 'undefined') {
46
- function binaryStringToUint8Array(binaryString) {
47
- const uint8Array = new Uint8Array(binaryString.length);
48
- for (let i = 0; i < binaryString.length; i++) {
49
- uint8Array[i] = binaryString.charCodeAt(i);
50
- }
51
- return uint8Array;
52
- }
53
- globalThis.btoa = b => fromByteArray(binaryStringToUint8Array(b));
54
- }
55
- if (typeof globalThis.clearTimeout === 'undefined') {
56
- const ogSettimeout = globalThis.setTimeout;
57
- if (!ogSettimeout) {
58
- throw new Error('setTimeout is not defined, no polyfill yet');
59
- }
60
- // @ts-expect-error
61
- globalThis.setTimeout = (fn, delayMs, ...args) => {
62
- let aborted = false;
63
- const abortableFn = (...args) => {
64
- if (aborted) {
65
- return;
66
- }
67
- return fn(...args);
68
- };
69
- const val = ogSettimeout(abortableFn, delayMs, ...args);
70
- return {
71
- original: val,
72
- abort() {
73
- aborted = true;
74
- }
75
- };
76
- };
77
- globalThis.clearTimeout = (id) => {
78
- if (typeof id === 'object' && !!id && 'abort' in id) {
79
- id.abort();
80
- }
81
- };
82
- }
@@ -1,20 +0,0 @@
1
- import { URL as WHATWG_URL } from 'whatwg-url';
2
- import { CloseEventPolyfill, ErrorEventPolyfill, EventPolyfill, MessageEventPolyfill } from "./event.js";
3
- import { RPCWebSocket } from "./ws.js";
4
- if (typeof globalThis.URL === 'undefined') {
5
- globalThis.URL = WHATWG_URL;
6
- }
7
- if (typeof globalThis.Event === 'undefined') {
8
- // @ts-expect-error
9
- globalThis.Event = EventPolyfill;
10
- // @ts-expect-error
11
- globalThis.ErrorEvent = ErrorEventPolyfill;
12
- // @ts-expect-error
13
- globalThis.CloseEvent = CloseEventPolyfill;
14
- // @ts-expect-error
15
- globalThis.MessageEvent = MessageEventPolyfill;
16
- }
17
- if (typeof globalThis.WebSocket === 'undefined') {
18
- // @ts-expect-error
19
- globalThis.WebSocket = RPCWebSocket;
20
- }
@@ -1,14 +0,0 @@
1
- // @ts-expect-error
2
- export class EventPolyfill {
3
- type;
4
- constructor(type, eventInitDict) {
5
- this.type = type;
6
- Object.assign(this, eventInitDict);
7
- }
8
- }
9
- export class ErrorEventPolyfill extends EventPolyfill {
10
- }
11
- export class CloseEventPolyfill extends EventPolyfill {
12
- }
13
- export class MessageEventPolyfill extends EventPolyfill {
14
- }
@@ -1,2 +0,0 @@
1
- import "./1.js";
2
- import "./2.js";
@@ -1,81 +0,0 @@
1
- import { RPC_MSG_BRIDGE, rpcRequest } from "../utils.js";
2
- export class RPCWebSocket extends EventTarget {
3
- CONNECTING = 0;
4
- OPEN = 1;
5
- CLOSING = 2;
6
- CLOSED = 3;
7
- id = `ws_${Date.now()}`;
8
- binaryType = 'arraybuffer';
9
- bufferedAmount = 0;
10
- extensions = '';
11
- url;
12
- protocol;
13
- readyState = this.CONNECTING;
14
- onopen;
15
- onerror;
16
- onclose;
17
- onmessage;
18
- #cancelRpcBridge;
19
- constructor(url) {
20
- super();
21
- this.url = url;
22
- this.protocol = '';
23
- this.#onMessage = this.#onMessage.bind(this);
24
- rpcRequest({
25
- type: 'connectWs',
26
- request: { id: this.id, url }
27
- })
28
- .then(() => this.#callOpen(new Event('open')))
29
- .catch(error => this.#callError(new ErrorEvent('error', { error })));
30
- }
31
- send(data) {
32
- if (typeof data !== 'string'
33
- && !ArrayBuffer.isView(data)) {
34
- throw new TypeError('Data must be a string, Uint8Array or ArrayBuffer');
35
- }
36
- rpcRequest({ type: 'sendWsMessage', request: { id: this.id, data: data } });
37
- }
38
- close(code, reason) {
39
- this.readyState = this.CLOSING;
40
- rpcRequest({
41
- type: 'disconnectWs',
42
- request: { id: this.id, code, reason }
43
- })
44
- .then(() => this.#callClose(new CloseEvent('close', { code, reason })))
45
- .catch(error => this.#callError(new ErrorEvent('error', { error })));
46
- }
47
- #callOpen(ev) {
48
- this.readyState = this.OPEN;
49
- this.onopen?.call(this, ev);
50
- this.dispatchEvent(ev);
51
- this.#cancelRpcBridge?.();
52
- this.#cancelRpcBridge = RPC_MSG_BRIDGE.addListener(this.#onMessage);
53
- }
54
- #callError(ev) {
55
- this.readyState = this.CLOSED;
56
- this.onerror?.call(this, ev);
57
- this.dispatchEvent(ev);
58
- }
59
- #callClose(ev) {
60
- this.readyState = this.CLOSED;
61
- this.onclose?.call(this, ev);
62
- this.dispatchEvent(ev);
63
- }
64
- #onMessage = (msg) => {
65
- if (msg.type === 'sendWsMessage' && msg.request.id === this.id) {
66
- const data = msg.request.data;
67
- const event = new MessageEvent('message', { data });
68
- this.onmessage?.call(this, event);
69
- this.dispatchEvent(event);
70
- return;
71
- }
72
- if (msg.type === 'disconnectWs' && msg.request.id === this.id) {
73
- if (!msg.request.err) {
74
- this.#callClose(new CloseEvent('close', { code: 1000, reason: 'Normal Closure' }));
75
- return;
76
- }
77
- this.#callError(new ErrorEvent('error', { error: new Error(msg.request.err) }));
78
- return;
79
- }
80
- };
81
- }
@@ -1,33 +0,0 @@
1
- import { setCryptoImplementation } from '@reclaimprotocol/tls';
2
- import { webcryptoCrypto } from '@reclaimprotocol/tls/webcrypto';
3
- import { handleIncomingMessage } from "./handle-incoming-msg.js";
4
- import { getWsApiUrlFromBaseUrl } from "./utils.js";
5
- import { logger, makeLogger } from "../utils/index.js";
6
- makeLogger(true);
7
- setCryptoImplementation(webcryptoCrypto);
8
- /**
9
- * For browsers only. Sets up the current window to listen for RPC requests
10
- * from React Native or other windows
11
- */
12
- export function setupWindowRpc(baseUrl, channel = 'attestor-core') {
13
- if (baseUrl) {
14
- globalThis.ATTESTOR_BASE_URL = baseUrl;
15
- }
16
- else if (typeof window !== 'undefined' && window.location) {
17
- globalThis.ATTESTOR_BASE_URL = window.location.toString();
18
- }
19
- else {
20
- throw new Error('No base URL provided and window.location unavailable');
21
- }
22
- if (channel) {
23
- globalThis.RPC_CHANNEL_NAME = channel;
24
- }
25
- else if (!globalThis.RPC_CHANNEL_NAME) {
26
- throw new Error('No channel name provided and globalThis.RPC_CHANNEL_NAME unavailable');
27
- }
28
- if (typeof window !== 'undefined') {
29
- window.addEventListener('message', ev => handleIncomingMessage(ev.data), false);
30
- }
31
- logger.info({ defaultUrl: getWsApiUrlFromBaseUrl() }, 'window RPC setup');
32
- }
33
- export * from "../index.js";
@@ -1,22 +0,0 @@
1
- import "./jsc-polyfills/index.js";
2
- 1; // done to avoid eslint rule
3
- import { setCryptoImplementation } from '@reclaimprotocol/tls';
4
- import { pureJsCrypto } from '@reclaimprotocol/tls/purejs-crypto';
5
- import * as AttestorRPCImport from "./index.js";
6
- import { makeLogger } from "../utils/logger.js";
7
- setCryptoImplementation(pureJsCrypto);
8
- makeLogger(true);
9
- /**
10
- * Sets up the library to run in JS environments like QuickJS or JavascriptCore.
11
- */
12
- export function setupJsRpc(baseUrl, channel = 'attestor-core') {
13
- globalThis.ATTESTOR_BASE_URL = baseUrl;
14
- globalThis.RPC_CHANNEL_NAME = channel;
15
- const rpcChannel = {
16
- postMessage(message) {
17
- return globalThis.sendMessage(channel, message);
18
- }
19
- };
20
- globalThis[channel] = rpcChannel;
21
- }
22
- globalThis.AttestorRPC = { ...AttestorRPCImport, setupJsRpc };
@@ -1 +0,0 @@
1
- export {};
@@ -1,100 +0,0 @@
1
- import { WS_PATHNAME } from "../config/index.js";
2
- import { EventBus } from "./event-bus.js";
3
- import { B64_JSON_REPLACER } from "../utils/b64-json.js";
4
- import { AttestorError } from "../utils/error.js";
5
- export const RPC_MSG_BRIDGE = new EventBus();
6
- // track memory usage
7
- export async function getCurrentMemoryUsage() {
8
- if (!window.crossOriginIsolated) {
9
- return {
10
- available: false,
11
- content: 'N/A (page not cross-origin-isolated)'
12
- };
13
- }
14
- else if (!performance.measureUserAgentSpecificMemory) {
15
- return {
16
- available: false,
17
- content: 'N/A (performance.measureUserAgentSpecificMemory() is not available)',
18
- };
19
- }
20
- else {
21
- try {
22
- const result = performance.measureUserAgentSpecificMemory();
23
- const totalmb = Math.round(result.bytes / 1024 / 1024);
24
- return { available: true, content: `${totalmb}mb` };
25
- }
26
- catch (error) {
27
- if (error instanceof DOMException && error.name === 'SecurityError') {
28
- return { available: false, content: `N/A (${error.message})` };
29
- }
30
- throw error;
31
- }
32
- }
33
- }
34
- export function generateRpcRequestId() {
35
- return Math.random().toString(36).slice(2);
36
- }
37
- /**
38
- * The window RPC will be served from the same origin as the API server.
39
- * so we can get the API server's origin from the location.
40
- */
41
- export function getWsApiUrlFromBaseUrl() {
42
- if (typeof ATTESTOR_BASE_URL !== 'string') {
43
- throw new Error('ATTESTOR_BASE_URL is not set');
44
- }
45
- const parsed = new URL(ATTESTOR_BASE_URL);
46
- const { host, protocol } = parsed;
47
- const wsProtocol = protocol === 'https:' ? 'wss:' : 'ws:';
48
- return `${wsProtocol}//${host}${WS_PATHNAME}`;
49
- }
50
- export function rpcRequest(opts) {
51
- const id = generateRpcRequestId();
52
- const waitForRes = waitForResponse(opts.type, id);
53
- // @ts-expect-error
54
- sendMessageToApp({
55
- id,
56
- type: opts.type,
57
- request: opts.request,
58
- });
59
- return waitForRes;
60
- }
61
- export function waitForResponse(type, requestId, timeoutMs = 60_000) {
62
- const returnType = `${type}Done`;
63
- return new Promise((resolve, reject) => {
64
- const timeout = setTimeout(() => {
65
- reject(new AttestorError('ERROR_INTERNAL', `Timeout waiting for response: ${type}`, { requestId }));
66
- cancel();
67
- }, timeoutMs);
68
- const cancel = RPC_MSG_BRIDGE.addListener(msg => {
69
- if (msg.id !== requestId) {
70
- return;
71
- }
72
- if (msg.type === 'error') {
73
- reject(new Error(msg.data.message));
74
- }
75
- else if (msg.type === returnType) {
76
- resolve(msg.response);
77
- }
78
- else {
79
- return;
80
- }
81
- clearTimeout(timeout);
82
- cancel();
83
- });
84
- });
85
- }
86
- /**
87
- * Sends a message back to the host app
88
- * @param data
89
- */
90
- export function sendMessageToApp(data) {
91
- const str = JSON.stringify(data, B64_JSON_REPLACER);
92
- if (!RPC_CHANNEL_NAME) {
93
- throw new Error('global RPC_CHANNEL_NAME is not set');
94
- }
95
- const channel = globalThis[RPC_CHANNEL_NAME];
96
- if (!channel) {
97
- throw new Error(`RPC channel ${RPC_CHANNEL_NAME} not set on globalThis`);
98
- }
99
- channel.postMessage(str);
100
- }
@@ -1,63 +0,0 @@
1
- import { rpcRequest } from "./utils.js";
2
- import { logger, makeDefaultZkOperator } from "../utils/index.js";
3
- export const ALL_ENC_ALGORITHMS = [
4
- 'aes-256-ctr',
5
- 'aes-128-ctr',
6
- 'chacha20',
7
- ];
8
- /**
9
- * The goal of this RPC operator is if the attestor client
10
- * is running in a WebView, it can call the native
11
- * application to perform the ZK operations
12
- */
13
- export function makeExternalRpcZkOperator(algorithm, zkEngine = 'snarkjs') {
14
- return {
15
- async generateWitness(input) {
16
- const operator = await makeDefaultZkOperator(algorithm, zkEngine, logger);
17
- return operator.generateWitness(input);
18
- },
19
- groth16Prove(input) {
20
- return callFnZk({ fn: 'groth16Prove', args: [input] });
21
- },
22
- groth16Verify(publicSignals, proof) {
23
- return callFnZk({ fn: 'groth16Verify', args: [publicSignals, proof] });
24
- },
25
- };
26
- }
27
- function callFnZk(request) {
28
- return rpcRequest({ type: 'executeZkFunctionV3', request });
29
- }
30
- /**
31
- * The goal of this RPC operator is if the attestor client
32
- * is running in a WebView, it can call the native
33
- * application to perform the OPRF operations
34
- */
35
- export function makeExternalRpcOprfOperator(algorithm, zkEngine = 'snarkjs') {
36
- return {
37
- async generateWitness(input) {
38
- const operator = await makeDefaultZkOperator(algorithm, zkEngine, logger);
39
- return operator.generateWitness(input);
40
- },
41
- groth16Prove(input) {
42
- return callFnOprf({ fn: 'groth16Prove', args: [input] });
43
- },
44
- groth16Verify(publicSignals, proof) {
45
- return callFnOprf({ fn: 'groth16Verify', args: [publicSignals, proof] });
46
- },
47
- generateThresholdKeys(total, threshold) {
48
- return callFnOprf({ fn: 'generateThresholdKeys', args: [total, threshold] });
49
- },
50
- generateOPRFRequestData(data, domainSeparator) {
51
- return callFnOprf({ fn: 'generateOPRFRequestData', args: [data, domainSeparator] });
52
- },
53
- finaliseOPRF(serverPublicKey, request, responses) {
54
- return callFnOprf({ fn: 'finaliseOPRF', args: [serverPublicKey, request, responses] });
55
- },
56
- evaluateOPRF(serverPrivateKey, request) {
57
- return callFnOprf({ fn: 'evaluateOPRF', args: [serverPrivateKey, request] });
58
- },
59
- };
60
- }
61
- function callFnOprf(request) {
62
- return rpcRequest({ type: 'executeOprfFunctionV3', request });
63
- }