@reclaimprotocol/attestor-core 5.0.4 → 5.0.5

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/server/tee/acme-http-server.d.ts +13 -0
  4. package/lib/server/tee/attestation-generate.d.ts +29 -0
  5. package/lib/server/tee/bootstrap.d.ts +11 -0
  6. package/lib/server/tee/cert-manager.d.ts +24 -0
  7. package/lib/server/tee/cloud-logging.d.ts +23 -0
  8. package/lib/server/tee/secret-loader.d.ts +10 -0
  9. package/lib/server/tee/secret-manager.d.ts +3 -0
  10. package/lib/utils/gcp-attestation.d.ts +23 -0
  11. package/package.json +3 -3
  12. package/lib/avs/abis/avsDirectoryABI.js +0 -340
  13. package/lib/avs/abis/delegationABI.js +0 -1
  14. package/lib/avs/abis/registryABI.js +0 -725
  15. package/lib/avs/client/create-claim-on-avs.js +0 -138
  16. package/lib/avs/config.js +0 -20
  17. package/lib/avs/contracts/ReclaimServiceManager.js +0 -1
  18. package/lib/avs/contracts/common.js +0 -1
  19. package/lib/avs/contracts/factories/ReclaimServiceManager__factory.js +0 -1169
  20. package/lib/avs/contracts/factories/index.js +0 -4
  21. package/lib/avs/contracts/index.js +0 -2
  22. package/lib/avs/types/index.js +0 -1
  23. package/lib/avs/utils/contracts.js +0 -33
  24. package/lib/avs/utils/register.js +0 -78
  25. package/lib/avs/utils/tasks.js +0 -40
  26. package/lib/client/create-claim.js +0 -433
  27. package/lib/client/index.js +0 -3
  28. package/lib/client/tunnels/make-rpc-tcp-tunnel.js +0 -51
  29. package/lib/client/tunnels/make-rpc-tls-tunnel.js +0 -131
  30. package/lib/client/utils/attestor-pool.js +0 -25
  31. package/lib/client/utils/client-socket.js +0 -98
  32. package/lib/client/utils/message-handler.js +0 -87
  33. package/lib/config/index.js +0 -44
  34. package/lib/external-rpc/benchmark.js +0 -69
  35. package/lib/external-rpc/event-bus.js +0 -14
  36. package/lib/external-rpc/handle-incoming-msg.js +0 -233
  37. package/lib/external-rpc/jsc-polyfills/1.js +0 -82
  38. package/lib/external-rpc/jsc-polyfills/2.js +0 -20
  39. package/lib/external-rpc/jsc-polyfills/event.js +0 -14
  40. package/lib/external-rpc/jsc-polyfills/index.js +0 -2
  41. package/lib/external-rpc/jsc-polyfills/ws.js +0 -81
  42. package/lib/external-rpc/setup-browser.js +0 -33
  43. package/lib/external-rpc/setup-jsc.js +0 -22
  44. package/lib/external-rpc/types.js +0 -1
  45. package/lib/external-rpc/utils.js +0 -100
  46. package/lib/external-rpc/zk.js +0 -63
  47. package/lib/mechain/abis/governanceABI.js +0 -458
  48. package/lib/mechain/abis/taskABI.js +0 -509
  49. package/lib/mechain/client/create-claim-on-mechain.js +0 -28
  50. package/lib/mechain/client/index.js +0 -1
  51. package/lib/mechain/constants/index.js +0 -3
  52. package/lib/mechain/index.js +0 -2
  53. package/lib/mechain/types/index.js +0 -1
  54. package/lib/proto/api.js +0 -4273
  55. package/lib/proto/tee-bundle.js +0 -1316
  56. package/lib/providers/http/index.js +0 -658
  57. package/lib/providers/http/patch-parse5-tree.js +0 -33
  58. package/lib/providers/http/utils.js +0 -324
  59. package/lib/providers/index.js +0 -4
  60. package/lib/scripts/fetch-ec2-metadata.d.ts +0 -1
  61. package/lib/server/create-server.js +0 -103
  62. package/lib/server/handlers/claimTeeBundle.js +0 -252
  63. package/lib/server/handlers/claimTunnel.js +0 -73
  64. package/lib/server/handlers/completeClaimOnChain.js +0 -22
  65. package/lib/server/handlers/createClaimOnChain.js +0 -26
  66. package/lib/server/handlers/createTaskOnMechain.js +0 -47
  67. package/lib/server/handlers/createTunnel.js +0 -93
  68. package/lib/server/handlers/disconnectTunnel.js +0 -5
  69. package/lib/server/handlers/fetchCertificateBytes.js +0 -41
  70. package/lib/server/handlers/index.js +0 -22
  71. package/lib/server/handlers/init.js +0 -32
  72. package/lib/server/handlers/toprf.js +0 -16
  73. package/lib/server/index.js +0 -4
  74. package/lib/server/socket.js +0 -109
  75. package/lib/server/tunnels/make-tcp-tunnel.js +0 -177
  76. package/lib/server/utils/apm.js +0 -36
  77. package/lib/server/utils/assert-valid-claim-request.js +0 -204
  78. package/lib/server/utils/config-env.js +0 -4
  79. package/lib/server/utils/dns.js +0 -18
  80. package/lib/server/utils/gcp-attestation.js +0 -289
  81. package/lib/server/utils/generics.js +0 -51
  82. package/lib/server/utils/iso.js +0 -256
  83. package/lib/server/utils/keep-alive.js +0 -38
  84. package/lib/server/utils/nitro-attestation.js +0 -325
  85. package/lib/server/utils/process-handshake.js +0 -215
  86. package/lib/server/utils/proxy-session.js +0 -6
  87. package/lib/server/utils/tee-oprf-mpc-verification.js +0 -90
  88. package/lib/server/utils/tee-oprf-verification.js +0 -174
  89. package/lib/server/utils/tee-transcript-reconstruction.js +0 -187
  90. package/lib/server/utils/tee-verification.js +0 -421
  91. package/lib/server/utils/validation.js +0 -38
  92. package/lib/types/bgp.js +0 -1
  93. package/lib/types/claims.js +0 -1
  94. package/lib/types/client.js +0 -1
  95. package/lib/types/general.js +0 -1
  96. package/lib/types/handlers.js +0 -1
  97. package/lib/types/index.js +0 -10
  98. package/lib/types/providers.gen.js +0 -10
  99. package/lib/types/providers.js +0 -1
  100. package/lib/types/rpc.js +0 -1
  101. package/lib/types/signatures.js +0 -1
  102. package/lib/types/tunnel.js +0 -1
  103. package/lib/types/zk.js +0 -1
  104. package/lib/utils/auth.js +0 -59
  105. package/lib/utils/b64-json.js +0 -17
  106. package/lib/utils/bgp-listener.js +0 -119
  107. package/lib/utils/claims.js +0 -99
  108. package/lib/utils/env.js +0 -15
  109. package/lib/utils/error.js +0 -50
  110. package/lib/utils/generics.js +0 -317
  111. package/lib/utils/http-parser.js +0 -246
  112. package/lib/utils/index.js +0 -13
  113. package/lib/utils/logger.js +0 -91
  114. package/lib/utils/prepare-packets.js +0 -62
  115. package/lib/utils/redactions.js +0 -148
  116. package/lib/utils/retries.js +0 -24
  117. package/lib/utils/signatures/eth.js +0 -29
  118. package/lib/utils/signatures/index.js +0 -7
  119. package/lib/utils/socket-base.js +0 -90
  120. package/lib/utils/tls.js +0 -58
  121. package/lib/utils/ws.js +0 -22
  122. package/lib/utils/zk.js +0 -577
@@ -1,658 +0,0 @@
1
- import { areUint8ArraysEqual, concatenateUint8Arrays, uint8ArrayToBinaryStr } from '@reclaimprotocol/tls';
2
- import { utils } from 'ethers';
3
- import { DEFAULT_HTTPS_PORT, RECLAIM_USER_AGENT } from "../../config/index.js";
4
- import { AttestorVersion } from "../../proto/api.js";
5
- import { buildHeaders, convertResponsePosToAbsolutePos, extractHTMLElementsIndexes, extractJSONValueIndexes, getRedactionsForChunkHeaders, makeRegex, matchRedactedStrings, parseHttpResponse, } from "./utils.js";
6
- import { isValidProxySessionId } from "../../server/utils/proxy-session.js";
7
- import { findIndexInUint8Array, getHttpRequestDataFromTranscript, logger, REDACTION_CHAR_CODE, strToUint8Array, uint8ArrayToStr, } from "../../utils/index.js";
8
- const { base64 } = utils;
9
- const OK_HTTP_HEADER = 'HTTP/1.1 200';
10
- const dateHeaderRegex = '[dD]ate: ((?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (?:[0-3][0-9]) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (?:[0-9]{4}) (?:[01][0-9]|2[0-3])(?::[0-5][0-9]){2} GMT)';
11
- const dateDiff = 1000 * 60 * 10; // allow 10 min difference
12
- const HTTP_PROVIDER = {
13
- hostPort: getHostPort,
14
- writeRedactionMode(params) {
15
- return ('writeRedactionMode' in params)
16
- ? params.writeRedactionMode
17
- : undefined;
18
- },
19
- geoLocation(params, secretParams) {
20
- return ('geoLocation' in params)
21
- ? getGeoLocation(params, secretParams)
22
- : undefined;
23
- },
24
- proxySessionId(params, secretParams) {
25
- return ('proxySessionId' in params)
26
- ? getProxySessionId(params, secretParams)
27
- : undefined;
28
- },
29
- additionalClientOptions(params) {
30
- let defaultOptions = {
31
- applicationLayerProtocols: ['http/1.1']
32
- };
33
- if ('additionalClientOptions' in params) {
34
- defaultOptions = {
35
- ...defaultOptions,
36
- ...params.additionalClientOptions
37
- };
38
- }
39
- return defaultOptions;
40
- },
41
- createRequest(secretParams, params, logger) {
42
- if (!secretParams.cookieStr &&
43
- !secretParams.authorisationHeader &&
44
- !secretParams.headers) {
45
- throw new Error('auth parameters are not set');
46
- }
47
- const pubHeaders = params.headers || {};
48
- const secHeaders = { ...secretParams.headers };
49
- if (secretParams.cookieStr) {
50
- secHeaders['Cookie'] = secretParams.cookieStr;
51
- }
52
- if (secretParams.authorisationHeader) {
53
- secHeaders['Authorization'] = secretParams.authorisationHeader;
54
- }
55
- const hasUserAgent = Object.keys(pubHeaders)
56
- .some(k => k.toLowerCase() === 'user-agent') ||
57
- Object.keys(secHeaders)
58
- .some(k => k.toLowerCase() === 'user-agent');
59
- if (!hasUserAgent) {
60
- //only set user-agent if not set by provider
61
- pubHeaders['User-Agent'] = RECLAIM_USER_AGENT;
62
- }
63
- const newParams = substituteParamValues(params, secretParams);
64
- params = newParams.newParams;
65
- const url = new URL(params.url);
66
- const { pathname } = url;
67
- const searchParams = params.url.includes('?') ? params.url.split('?')[1] : '';
68
- logger.info({ url: params.url, path: pathname, query: searchParams.toString() });
69
- const body = params.body instanceof Uint8Array
70
- ? params.body
71
- : strToUint8Array(params.body || '');
72
- const contentLength = body.length;
73
- const reqLine = `${params.method} ${pathname}${searchParams?.length ? '?' + searchParams : ''} HTTP/1.1`;
74
- const secHeadersList = buildHeaders(secHeaders);
75
- logger.info({ requestLine: reqLine });
76
- const httpReqHeaderStr = [
77
- reqLine,
78
- `Host: ${getHostHeaderString(url)}`,
79
- `Content-Length: ${contentLength}`,
80
- 'Connection: close',
81
- //no compression
82
- 'Accept-Encoding: identity',
83
- ...buildHeaders(pubHeaders),
84
- ...secHeadersList,
85
- '\r\n',
86
- ].join('\r\n');
87
- const headerStr = strToUint8Array(httpReqHeaderStr);
88
- const data = concatenateUint8Arrays([headerStr, body]);
89
- // hide all secret headers
90
- const secHeadersStr = secHeadersList.join('\r\n');
91
- const tokenStartIndex = findIndexInUint8Array(data, strToUint8Array(secHeadersStr));
92
- const redactions = [
93
- {
94
- fromIndex: tokenStartIndex,
95
- toIndex: tokenStartIndex + secHeadersStr.length,
96
- }
97
- ];
98
- if (newParams.hiddenBodyParts?.length > 0) {
99
- for (const hiddenBodyPart of newParams.hiddenBodyParts) {
100
- if (hiddenBodyPart.length) {
101
- redactions.push({
102
- fromIndex: headerStr.length + hiddenBodyPart.index,
103
- toIndex: headerStr.length + hiddenBodyPart.index + hiddenBodyPart.length,
104
- });
105
- }
106
- }
107
- }
108
- if (newParams.hiddenURLParts?.length > 0) {
109
- for (const hiddenURLPart of newParams.hiddenURLParts) {
110
- if (hiddenURLPart.length) {
111
- redactions.push({
112
- fromIndex: hiddenURLPart.index,
113
- toIndex: hiddenURLPart.index + hiddenURLPart.length,
114
- });
115
- }
116
- }
117
- }
118
- redactions.sort((a, b) => a.toIndex - b.toIndex);
119
- return {
120
- data,
121
- redactions: redactions,
122
- };
123
- },
124
- getResponseRedactions({ response, params: rawParams, logger, ctx }) {
125
- logger.debug({ response: base64.encode(response), params: rawParams });
126
- const res = parseHttpResponse(response);
127
- if (!rawParams.responseRedactions?.length) {
128
- return [];
129
- }
130
- if (((res.statusCode / 100) >> 0) !== 2) {
131
- logger.error({ response: base64.encode(response), params: rawParams });
132
- throw new Error(`Expected status 2xx, got ${res.statusCode} (${res.statusMessage})`);
133
- }
134
- const newParams = substituteParamValues(rawParams, undefined, true);
135
- const params = newParams.newParams;
136
- const headerEndIndex = res.statusLineEndIndex;
137
- const bodyStartIdx = res.bodyStartIndex ?? 0;
138
- if (bodyStartIdx < 4) {
139
- logger.error({ response: base64.encode(response) });
140
- throw new Error('Failed to find response body');
141
- }
142
- const reveals = [
143
- { fromIndex: 0, toIndex: headerEndIndex }
144
- ];
145
- //reveal double CRLF which separates headers from body
146
- if (shouldRevealCrlf(ctx)) {
147
- const crlfs = response
148
- .slice(res.headerEndIdx, res.headerEndIdx + 4);
149
- if (!areUint8ArraysEqual(crlfs, strToUint8Array('\r\n\r\n'))) {
150
- logger.error({ response: base64.encode(response) });
151
- throw new Error(`Failed to find header/body separator at index ${res.headerEndIdx}`);
152
- }
153
- }
154
- reveals.push({ fromIndex: res.headerEndIdx, toIndex: res.headerEndIdx + 4 });
155
- //reveal date header
156
- if (res.headerIndices['date']) {
157
- reveals.push(res.headerIndices['date']);
158
- }
159
- const body = uint8ArrayToBinaryStr(res.body);
160
- const redactions = [];
161
- for (const rs of params.responseRedactions || []) {
162
- const processor = processRedactionRequest(body, rs, bodyStartIdx, res.chunks);
163
- for (const { reveal, redactions: reds } of processor) {
164
- reveals.push(reveal);
165
- redactions.push(...reds);
166
- }
167
- }
168
- reveals.sort((a, b) => a.toIndex - b.toIndex);
169
- if (reveals.length > 1) {
170
- let currentIndex = 0;
171
- for (const r of reveals) {
172
- if (currentIndex < r.fromIndex) {
173
- redactions.push({ fromIndex: currentIndex, toIndex: r.fromIndex });
174
- }
175
- currentIndex = r.toIndex;
176
- }
177
- redactions.push({ fromIndex: currentIndex, toIndex: response.length });
178
- }
179
- for (const r of reveals) {
180
- if (!r.hash) {
181
- continue;
182
- }
183
- redactions.push(r);
184
- }
185
- redactions.sort((a, b) => a.toIndex - b.toIndex);
186
- return redactions;
187
- },
188
- assertValidProviderReceipt({ receipt, params: paramsAny, logger, ctx }) {
189
- logTranscript();
190
- let extractedParams = {};
191
- const secretParams = ('secretParams' in paramsAny)
192
- ? paramsAny.secretParams
193
- : undefined;
194
- const newParams = substituteParamValues(paramsAny, secretParams, !secretParams);
195
- const params = newParams.newParams;
196
- extractedParams = { ...extractedParams, ...newParams.extractedValues };
197
- const req = getHttpRequestDataFromTranscript(receipt);
198
- if (req.method !== params.method.toLowerCase()) {
199
- throw new Error(`Invalid method: ${req.method}`);
200
- }
201
- const url = new URL(params.url);
202
- const { protocol, pathname } = url;
203
- if (protocol !== 'https:') {
204
- logger.error('params URL: %s', params.url);
205
- throw new Error(`Expected protocol: https, found: ${protocol}`);
206
- }
207
- const searchParams = params.url.includes('?') ? params.url.split('?')[1] : '';
208
- //brackets in URL path turn into %7B and %7D, so replace them back
209
- const expectedPath = pathname.replaceAll('%7B', '{').replaceAll('%7D', '}') + (searchParams?.length ? '?' + searchParams : '');
210
- if (!matchRedactedStrings(strToUint8Array(expectedPath), strToUint8Array(req.url))) {
211
- logger.error('params URL: %s', params.url);
212
- throw new Error(`Expected path: ${expectedPath}, found: ${req.url}`);
213
- }
214
- const expectedHostStr = getHostHeaderString(url);
215
- if (req.headers.host !== expectedHostStr) {
216
- throw new Error(`Expected host: ${expectedHostStr}, found: ${req.headers.host}`);
217
- }
218
- const connectionHeader = req.headers['connection'];
219
- if (connectionHeader !== 'close') {
220
- throw new Error(`Connection header must be "close", got "${connectionHeader}"`);
221
- }
222
- const serverBlocks = receipt
223
- .filter(s => s.sender === 'server')
224
- .map((r) => r.message)
225
- // filter out fully redacted blocks
226
- .filter(b => !b.every(b => b === REDACTION_CHAR_CODE));
227
- const response = concatArrays(...serverBlocks);
228
- let res;
229
- res = uint8ArrayToStr(response);
230
- const okRegex = makeRegex('^HTTP\\/1.1 2\\d{2}');
231
- const matchRes = okRegex.exec(res);
232
- if (!matchRes) {
233
- const statusRegex = makeRegex('^HTTP\\/1.1 (\\d{3})');
234
- const matchRes = statusRegex.exec(res);
235
- if (matchRes && matchRes.length > 1) {
236
- throw new Error(`Provider returned error ${matchRes[1]}`);
237
- }
238
- let lineEnd = res.indexOf('*');
239
- if (lineEnd === -1) {
240
- lineEnd = res.indexOf('\n');
241
- }
242
- if (lineEnd === -1) {
243
- lineEnd = OK_HTTP_HEADER.length;
244
- }
245
- throw new Error(`Response did not start with \"HTTP/1.1 2XX\" got "${res.slice(0, lineEnd)}"`);
246
- }
247
- let bodyStart;
248
- if (shouldRevealCrlf(ctx)) {
249
- bodyStart = res.indexOf('\r\n\r\n', OK_HTTP_HEADER.length) + 4;
250
- if (bodyStart < 4) {
251
- throw new Error('Response body start not found');
252
- }
253
- }
254
- else {
255
- bodyStart = OK_HTTP_HEADER.length;
256
- }
257
- //validate server Date header if present
258
- const dateHeader = makeRegex(dateHeaderRegex).exec(res);
259
- if (dateHeader && dateHeader.length > 1) {
260
- const serverDate = new Date(dateHeader[1]);
261
- if ((Date.now() - serverDate.getTime()) > dateDiff) {
262
- logger.info({ dateHeader: dateHeader[0], current: Date.now() }, 'date header is off');
263
- // too many false positives
264
- // throw new Error(
265
- // `Server date is off by "${(Date.now() - serverDate.getTime()) / 1000} s"`
266
- // )
267
- }
268
- }
269
- const paramBody = params.body instanceof Uint8Array
270
- ? params.body
271
- : strToUint8Array(params.body || '');
272
- if (paramBody.length > 0 && !matchRedactedStrings(paramBody, req.body)) {
273
- throw new Error('request body mismatch');
274
- }
275
- //remove asterisks to account for chunks in the middle of revealed strings
276
- if (!secretParams) {
277
- res = res.slice(bodyStart).replace(/(\*){3,}/g, '');
278
- }
279
- for (const { type, value, invert } of params.responseMatches || []) {
280
- const inv = Boolean(invert); // explicitly cast to boolean
281
- switch (type) {
282
- case 'regex':
283
- const regexRes = makeRegex(value).exec(res);
284
- const match = regexRes !== null;
285
- if (match === inv) { // if both true or both false then fail
286
- throw new Error('Invalid receipt.'
287
- + ` Regex "${value}" ${invert ? 'matched' : 'didn\'t match'}`);
288
- }
289
- if (!match) {
290
- continue;
291
- }
292
- const groups = regexRes?.groups;
293
- for (const paramName in groups || []) {
294
- if (paramName in extractedParams) {
295
- throw new Error(`Duplicate parameter ${paramName}`);
296
- }
297
- const value = groups?.[paramName];
298
- if (typeof value !== 'string') {
299
- continue;
300
- }
301
- extractedParams[paramName] = value;
302
- }
303
- break;
304
- case 'contains':
305
- const includes = res.includes(value);
306
- if (includes === inv) {
307
- throw new Error(`Invalid receipt. Response ${invert ? 'contains' : 'does not contain'} "${value}"`);
308
- }
309
- break;
310
- default:
311
- throw new Error(`Invalid response match type ${type}`);
312
- }
313
- }
314
- function concatArrays(...bufs) {
315
- const totalSize = bufs.reduce((acc, e) => acc + e.length, 0);
316
- const merged = new Uint8Array(totalSize);
317
- let lenDone = 0;
318
- for (const array of bufs) {
319
- merged.set(array, lenDone);
320
- lenDone += array.length;
321
- }
322
- return merged;
323
- }
324
- return { extractedParameters: extractedParams };
325
- function logTranscript() {
326
- const clientMsgs = receipt.filter(s => s.sender === 'client').map(m => m.message);
327
- const serverMsgs = receipt.filter(s => s.sender === 'server').map(m => m.message);
328
- const clientTranscript = base64.encode(concatenateUint8Arrays(clientMsgs));
329
- const serverTranscript = base64.encode(concatenateUint8Arrays(serverMsgs));
330
- logger.debug({ request: clientTranscript, response: serverTranscript, params: paramsAny });
331
- }
332
- },
333
- };
334
- // revealing CRLF is a breaking change -- and should only be done
335
- // if the client's version supports it
336
- function shouldRevealCrlf({ version }) {
337
- return version >= AttestorVersion.ATTESTOR_VERSION_2_0_1;
338
- }
339
- function getHostPort(params, secretParams) {
340
- const { host } = new URL(getURL(params, secretParams));
341
- if (!host) {
342
- throw new Error('url is incorrect');
343
- }
344
- return host;
345
- }
346
- /**
347
- * Obtain the host header string from the URL.
348
- * https://stackoverflow.com/a/3364396
349
- */
350
- function getHostHeaderString(url) {
351
- const host = url.hostname;
352
- const port = url.port;
353
- return port && +port !== DEFAULT_HTTPS_PORT
354
- ? `${host}:${port}`
355
- : host;
356
- }
357
- const paramsRegex = /{{([^{}]+)}}/sgi;
358
- function* processRedactionRequest(body, rs, bodyStartIdx, resChunks) {
359
- let element = body;
360
- let elementIdx = 0;
361
- let elementLength = -1;
362
- if (rs.xPath) {
363
- const indexes = extractHTMLElementsIndexes(body, rs.xPath, !!rs.jsonPath);
364
- for (const { start, end } of indexes) {
365
- element = body.slice(start, end);
366
- elementIdx = start;
367
- elementLength = end - start;
368
- if (rs.jsonPath) {
369
- yield* processJsonPath();
370
- }
371
- else if (rs.regex) {
372
- yield* processRegexp();
373
- }
374
- else {
375
- yield* addRedaction();
376
- }
377
- }
378
- }
379
- else if (rs.jsonPath) {
380
- yield* processJsonPath();
381
- }
382
- else if (rs.regex) {
383
- yield* processRegexp();
384
- }
385
- else {
386
- throw new Error('Expected either xPath, jsonPath or regex for redaction');
387
- }
388
- function* processJsonPath() {
389
- const jsonPathIndexes = extractJSONValueIndexes(element, rs.jsonPath);
390
- // eslint-disable-next-line max-depth
391
- const eIndex = elementIdx;
392
- for (const ji of jsonPathIndexes) {
393
- const jStart = ji.start;
394
- const jEnd = ji.end;
395
- element = body.slice(eIndex + jStart, eIndex + jEnd);
396
- elementIdx = eIndex + jStart;
397
- elementLength = jEnd - jStart;
398
- // eslint-disable-next-line max-depth
399
- if (rs.regex) {
400
- yield* processRegexp();
401
- }
402
- else {
403
- yield* addRedaction();
404
- }
405
- }
406
- }
407
- function* processRegexp() {
408
- logger.debug({
409
- element: base64.encode(strToUint8Array(element)),
410
- body: base64.encode(strToUint8Array(body))
411
- });
412
- const regexp = makeRegex(rs.regex);
413
- const elem = element || body;
414
- const match = regexp.exec(elem);
415
- // eslint-disable-next-line max-depth
416
- if (!match?.[0]) {
417
- throw new Error(`regexp ${rs.regex} does not match found element '${base64.encode(strToUint8Array(elem))}'`);
418
- }
419
- elementIdx += match.index;
420
- elementLength = regexp.lastIndex - match.index;
421
- element = match[0];
422
- if (rs.hash && (!match.groups || Object.keys(match.groups).length > 1)) {
423
- throw new Error('Exactly one named capture group is needed per hashed redaction');
424
- }
425
- // if there are groups in the regex,
426
- // we'll only hash the group values
427
- if (!rs.hash || !match.groups) {
428
- yield* addRedaction();
429
- return;
430
- }
431
- const fullStr = match[0];
432
- const grp = Object.values(match.groups)[0];
433
- const grpIdx = fullStr.indexOf(grp);
434
- // don't hash the entire regex, we'll hash the group values
435
- elementLength = grpIdx;
436
- element = fullStr.slice(0, grpIdx);
437
- yield* addRedaction(null);
438
- elementIdx += grpIdx;
439
- element = grp;
440
- elementLength = grp.length;
441
- const reveal = getReveal(elementIdx, elementLength, rs.hash);
442
- const chunkReds = getRedactionsForChunkHeaders(reveal.fromIndex, reveal.toIndex, resChunks);
443
- if (chunkReds.length) {
444
- throw new Error('Hash redactions cannot be performed if '
445
- + 'the redacted string is split between 2'
446
- + ' or more HTTP chunks');
447
- }
448
- yield { reveal, redactions: chunkReds };
449
- elementIdx += grp.length;
450
- element = fullStr.slice(grpIdx + grp.length);
451
- elementLength = element.length;
452
- yield* addRedaction(null);
453
- }
454
- // eslint-disable-next-line unicorn/consistent-function-scoping
455
- function* addRedaction(hash = rs.hash, _resChunks = resChunks) {
456
- if (elementIdx < 0 || !elementLength) {
457
- return;
458
- }
459
- const reveal = getReveal(elementIdx, elementLength, hash || undefined);
460
- yield {
461
- reveal,
462
- redactions: getRedactionsForChunkHeaders(reveal.fromIndex, reveal.toIndex, _resChunks)
463
- };
464
- }
465
- function getReveal(startIdx, len, hash) {
466
- const from = convertResponsePosToAbsolutePos(startIdx, bodyStartIdx, resChunks);
467
- const to = convertResponsePosToAbsolutePos(startIdx + len, bodyStartIdx, resChunks);
468
- return { fromIndex: from, toIndex: to, hash };
469
- }
470
- }
471
- export function substituteParamValues(currentParams, secretParams, ignoreMissingParams) {
472
- const params = JSON.parse(JSON.stringify(currentParams));
473
- let extractedValues = {};
474
- const hiddenURLParts = [];
475
- const urlParams = extractAndReplaceTemplateValues(params.url, ignoreMissingParams);
476
- if (urlParams) {
477
- params.url = urlParams.newParam;
478
- extractedValues = { ...urlParams.extractedValues };
479
- if (urlParams.hiddenParts.length) {
480
- const host = getHostHeaderString(new URL(params.url));
481
- const offset = `https://${host}`.length - currentParams.method.length - 1; //space between method and start of the path
482
- for (const hiddenURLPart of urlParams.hiddenParts) {
483
- hiddenURLParts.push({ index: hiddenURLPart.index - offset, length: hiddenURLPart.length });
484
- }
485
- }
486
- }
487
- let bodyParams;
488
- let hiddenBodyParts = [];
489
- if (params.body) {
490
- const strBody = typeof params.body === 'string' ? params.body : uint8ArrayToStr(params.body);
491
- bodyParams = extractAndReplaceTemplateValues(strBody, ignoreMissingParams);
492
- if (bodyParams) {
493
- params.body = bodyParams.newParam;
494
- extractedValues = { ...extractedValues, ...bodyParams.extractedValues };
495
- hiddenBodyParts = bodyParams.hiddenParts;
496
- }
497
- }
498
- const geoParams = extractAndReplaceTemplateValues(params.geoLocation);
499
- if (geoParams) {
500
- params.geoLocation = geoParams.newParam;
501
- extractedValues = { ...extractedValues, ...geoParams.extractedValues };
502
- }
503
- const proxySessionIdParams = extractAndReplaceTemplateValues(params.proxySessionId);
504
- if (proxySessionIdParams) {
505
- params.proxySessionId = proxySessionIdParams.newParam;
506
- extractedValues = { ...extractedValues, ...proxySessionIdParams.extractedValues };
507
- }
508
- if (params.responseRedactions) {
509
- for (const r of params.responseRedactions) {
510
- if (r.regex) {
511
- const regexParams = extractAndReplaceTemplateValues(r.regex);
512
- r.regex = regexParams?.newParam;
513
- }
514
- if (r.xPath) {
515
- const xpathParams = extractAndReplaceTemplateValues(r.xPath);
516
- r.xPath = xpathParams?.newParam;
517
- }
518
- if (r.jsonPath) {
519
- const jsonPathParams = extractAndReplaceTemplateValues(r.jsonPath);
520
- r.jsonPath = jsonPathParams?.newParam;
521
- }
522
- }
523
- }
524
- if (params.responseMatches) {
525
- for (const r of params.responseMatches) {
526
- if (r.value !== '') {
527
- const matchParam = extractAndReplaceTemplateValues(r.value);
528
- r.value = matchParam?.newParam;
529
- extractedValues = { ...extractedValues, ...matchParam?.extractedValues };
530
- }
531
- }
532
- }
533
- return {
534
- newParams: params,
535
- extractedValues: extractedValues,
536
- hiddenBodyParts: hiddenBodyParts,
537
- hiddenURLParts: hiddenURLParts
538
- };
539
- function extractAndReplaceTemplateValues(param, ignoreMissingParams) {
540
- if (!param) {
541
- return null;
542
- }
543
- //const paramNames: Set<string> = new Set()
544
- const extractedValues = {};
545
- const hiddenParts = [];
546
- let totalOffset = 0;
547
- param = param.replace(paramsRegex, (match, pn, offset) => {
548
- if (params.paramValues && pn in params.paramValues) {
549
- extractedValues[pn] = params.paramValues[pn];
550
- totalOffset += params.paramValues[pn].length - match.length;
551
- return params.paramValues[pn];
552
- }
553
- else if (secretParams) {
554
- if (secretParams?.paramValues && pn in secretParams?.paramValues) {
555
- hiddenParts.push({
556
- index: offset + totalOffset,
557
- length: secretParams.paramValues[pn].length,
558
- });
559
- totalOffset += secretParams.paramValues[pn].length - match.length;
560
- return secretParams.paramValues[pn];
561
- }
562
- else {
563
- throw new Error(`parameter's "${pn}" value not found in paramValues and secret parameter's paramValues`);
564
- }
565
- }
566
- else {
567
- if (!(!!ignoreMissingParams)) {
568
- throw new Error(`parameter's "${pn}" value not found in paramValues`);
569
- }
570
- else {
571
- return match;
572
- }
573
- }
574
- });
575
- return {
576
- newParam: param,
577
- extractedValues: extractedValues,
578
- hiddenParts: hiddenParts
579
- };
580
- }
581
- }
582
- function getGeoLocation(v2Params, secretParams) {
583
- if (v2Params?.geoLocation) {
584
- const paramNames = new Set();
585
- let geo = v2Params.geoLocation;
586
- //extract param names
587
- let match = null;
588
- while (match = paramsRegex.exec(geo)) {
589
- paramNames.add(match[1]);
590
- }
591
- for (const pn of paramNames) {
592
- if (v2Params.paramValues && pn in v2Params.paramValues) {
593
- geo = geo?.replaceAll(`{{${pn}}}`, v2Params.paramValues[pn].toString());
594
- }
595
- else if (secretParams?.paramValues && pn in secretParams.paramValues) {
596
- geo = geo?.replaceAll(`{{${pn}}}`, secretParams.paramValues[pn].toString());
597
- }
598
- else {
599
- throw new Error(`parameter "${pn}" value not found in templateParams`);
600
- }
601
- }
602
- const geoRegex = /^[A-Za-z]{2}$/sgiu;
603
- if (!geoRegex.test(geo)) {
604
- throw new Error(`Geolocation ${geo} is invalid`);
605
- }
606
- return geo;
607
- }
608
- return undefined;
609
- }
610
- function getProxySessionId(v2Params, secretParams) {
611
- if (v2Params?.proxySessionId) {
612
- const paramNames = new Set();
613
- let proxySessionIdValue = v2Params.proxySessionId;
614
- //extract param names
615
- let match = null;
616
- while (match = paramsRegex.exec(proxySessionIdValue)) {
617
- paramNames.add(match[1]);
618
- }
619
- for (const pn of paramNames) {
620
- if (v2Params.paramValues && pn in v2Params.paramValues) {
621
- proxySessionIdValue = proxySessionIdValue?.replaceAll(`{{${pn}}}`, v2Params.paramValues[pn].toString());
622
- }
623
- else if (secretParams?.paramValues && pn in secretParams.paramValues) {
624
- proxySessionIdValue = proxySessionIdValue?.replaceAll(`{{${pn}}}`, secretParams.paramValues[pn].toString());
625
- }
626
- else {
627
- throw new Error(`parameter "${pn}" value not found in templateParams`);
628
- }
629
- }
630
- if (!isValidProxySessionId(proxySessionIdValue)) {
631
- throw new Error(`proxySessionId ${proxySessionIdValue} is invalid`);
632
- }
633
- return proxySessionIdValue;
634
- }
635
- return undefined;
636
- }
637
- function getURL(v2Params, secretParams) {
638
- let hostPort = v2Params?.url;
639
- const paramNames = new Set();
640
- //extract param names
641
- let match = null;
642
- while (match = paramsRegex.exec(hostPort)) {
643
- paramNames.add(match[1]);
644
- }
645
- for (const pn of paramNames) {
646
- if (v2Params.paramValues && pn in v2Params.paramValues) {
647
- hostPort = hostPort?.replaceAll(`{{${pn}}}`, v2Params.paramValues[pn].toString());
648
- }
649
- else if (secretParams?.paramValues && pn in secretParams.paramValues) {
650
- hostPort = hostPort?.replaceAll(`{{${pn}}}`, secretParams.paramValues[pn].toString());
651
- }
652
- else {
653
- throw new Error(`parameter "${pn}" value not found in templateParams`);
654
- }
655
- }
656
- return hostPort;
657
- }
658
- export default HTTP_PROVIDER;
@@ -1,33 +0,0 @@
1
- // these patches are required to make "xpath" work with parse5
2
- import { Element, Node } from 'domhandler';
3
- Element.prototype.toString = function () {
4
- throw new Error('Element.toString() is not supported');
5
- // return ds(this)
6
- };
7
- Object.defineProperty(Node.prototype, 'nodeName', {
8
- get: function () {
9
- return this.name;
10
- },
11
- });
12
- Object.defineProperty(Node.prototype, 'localName', {
13
- get: function () {
14
- return this.name;
15
- },
16
- });
17
- const origAttributes = Object.getOwnPropertyDescriptor(Element.prototype, 'attributes')?.get;
18
- if (origAttributes) {
19
- Object.defineProperty(Element.prototype, 'attributes', {
20
- get: function (...args) {
21
- // eslint-disable-next-line prefer-rest-params
22
- const attrs = origAttributes.call(this, ...args);
23
- attrs.item = (idx) => {
24
- const el = attrs[idx];
25
- return { ...el, nodeType: 2, localName: el.name };
26
- };
27
- return attrs;
28
- },
29
- });
30
- }
31
- else {
32
- console.warn('[WARN] Unable to patch DOM: Element.attributes property descriptor not found');
33
- }