@reclaimprotocol/attestor-core 5.0.1-beta.2 → 5.0.1-beta.3

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 (169) hide show
  1. package/lib/browser/avs/abis/avsDirectoryABI.d.ts +60 -0
  2. package/lib/browser/avs/abis/avsDirectoryABI.js +343 -0
  3. package/lib/browser/avs/abis/delegationABI.d.ts +126 -0
  4. package/lib/browser/avs/abis/delegationABI.js +4 -0
  5. package/lib/browser/avs/abis/registryABI.d.ts +136 -0
  6. package/lib/browser/avs/abis/registryABI.js +728 -0
  7. package/lib/browser/avs/client/create-claim-on-avs.d.ts +12 -0
  8. package/lib/browser/avs/client/create-claim-on-avs.js +168 -0
  9. package/lib/browser/avs/config.d.ts +7 -0
  10. package/lib/browser/avs/config.js +26 -0
  11. package/lib/browser/avs/contracts/ReclaimServiceManager.d.ts +601 -0
  12. package/lib/browser/avs/contracts/ReclaimServiceManager.js +0 -0
  13. package/lib/browser/avs/contracts/common.d.ts +50 -0
  14. package/lib/browser/avs/contracts/common.js +0 -0
  15. package/lib/browser/avs/contracts/factories/ReclaimServiceManager__factory.d.ts +890 -0
  16. package/lib/browser/avs/contracts/factories/ReclaimServiceManager__factory.js +1183 -0
  17. package/lib/browser/avs/contracts/factories/index.d.ts +1 -0
  18. package/lib/browser/avs/contracts/factories/index.js +4 -0
  19. package/lib/browser/avs/contracts/index.d.ts +3 -0
  20. package/lib/browser/avs/contracts/index.js +6 -0
  21. package/lib/browser/avs/types/index.d.ts +55 -0
  22. package/lib/browser/avs/types/index.js +0 -0
  23. package/lib/browser/avs/utils/contracts.d.ts +21 -0
  24. package/lib/browser/avs/utils/contracts.js +53 -0
  25. package/lib/browser/avs/utils/register.d.ts +27 -0
  26. package/lib/browser/avs/utils/register.js +74 -0
  27. package/lib/browser/avs/utils/tasks.d.ts +22 -0
  28. package/lib/browser/avs/utils/tasks.js +48 -0
  29. package/lib/browser/client/create-claim.d.ts +5 -0
  30. package/lib/browser/client/create-claim.js +461 -0
  31. package/lib/browser/client/index.d.ts +3 -0
  32. package/lib/browser/client/index.js +3 -0
  33. package/lib/browser/client/tunnels/make-rpc-tcp-tunnel.d.ts +16 -0
  34. package/lib/browser/client/tunnels/make-rpc-tcp-tunnel.js +53 -0
  35. package/lib/browser/client/tunnels/make-rpc-tls-tunnel.d.ts +26 -0
  36. package/lib/browser/client/tunnels/make-rpc-tls-tunnel.js +127 -0
  37. package/lib/browser/client/utils/attestor-pool.d.ts +8 -0
  38. package/lib/browser/client/utils/attestor-pool.js +24 -0
  39. package/lib/browser/client/utils/client-socket.d.ts +11 -0
  40. package/lib/browser/client/utils/client-socket.js +120 -0
  41. package/lib/browser/client/utils/message-handler.d.ts +4 -0
  42. package/lib/browser/client/utils/message-handler.js +97 -0
  43. package/lib/browser/config/index.d.ts +31 -0
  44. package/lib/browser/config/index.js +62 -0
  45. package/lib/browser/external-rpc/benchmark.d.ts +1 -0
  46. package/lib/browser/external-rpc/benchmark.js +82 -0
  47. package/lib/browser/external-rpc/event-bus.d.ts +7 -0
  48. package/lib/browser/external-rpc/event-bus.js +17 -0
  49. package/lib/browser/external-rpc/global.d.js +0 -0
  50. package/lib/browser/external-rpc/handle-incoming-msg.d.ts +2 -0
  51. package/lib/browser/external-rpc/handle-incoming-msg.js +241 -0
  52. package/lib/browser/external-rpc/index.d.ts +3 -0
  53. package/lib/browser/external-rpc/index.js +3 -0
  54. package/lib/browser/external-rpc/jsc-polyfills/1.d.ts +14 -0
  55. package/lib/browser/external-rpc/jsc-polyfills/1.js +80 -0
  56. package/lib/browser/external-rpc/jsc-polyfills/2.d.ts +1 -0
  57. package/lib/browser/external-rpc/jsc-polyfills/2.js +15 -0
  58. package/lib/browser/external-rpc/jsc-polyfills/event.d.ts +10 -0
  59. package/lib/browser/external-rpc/jsc-polyfills/event.js +19 -0
  60. package/lib/browser/external-rpc/jsc-polyfills/index.d.ts +2 -0
  61. package/lib/browser/external-rpc/jsc-polyfills/index.js +2 -0
  62. package/lib/browser/external-rpc/jsc-polyfills/ws.d.ts +21 -0
  63. package/lib/browser/external-rpc/jsc-polyfills/ws.js +83 -0
  64. package/lib/browser/external-rpc/setup-browser.d.ts +6 -0
  65. package/lib/browser/external-rpc/setup-browser.js +33 -0
  66. package/lib/browser/external-rpc/setup-jsc.d.ts +24 -0
  67. package/lib/browser/external-rpc/setup-jsc.js +22 -0
  68. package/lib/browser/external-rpc/types.d.ts +213 -0
  69. package/lib/browser/external-rpc/types.js +0 -0
  70. package/lib/browser/external-rpc/utils.d.ts +20 -0
  71. package/lib/browser/external-rpc/utils.js +100 -0
  72. package/lib/browser/external-rpc/zk.d.ts +14 -0
  73. package/lib/browser/external-rpc/zk.js +58 -0
  74. package/lib/browser/index.browser.js +13 -0
  75. package/lib/browser/index.d.ts +9 -0
  76. package/lib/browser/index.js +13 -0
  77. package/lib/browser/mechain/abis/governanceABI.d.ts +50 -0
  78. package/lib/browser/mechain/abis/governanceABI.js +461 -0
  79. package/lib/browser/mechain/abis/taskABI.d.ts +157 -0
  80. package/lib/browser/mechain/abis/taskABI.js +512 -0
  81. package/lib/browser/mechain/client/create-claim-on-mechain.d.ts +10 -0
  82. package/lib/browser/mechain/client/create-claim-on-mechain.js +33 -0
  83. package/lib/browser/mechain/client/index.d.ts +1 -0
  84. package/lib/browser/mechain/client/index.js +1 -0
  85. package/lib/browser/mechain/constants/index.d.ts +3 -0
  86. package/lib/browser/mechain/constants/index.js +8 -0
  87. package/lib/browser/mechain/index.d.ts +2 -0
  88. package/lib/browser/mechain/index.js +2 -0
  89. package/lib/browser/mechain/types/index.d.ts +23 -0
  90. package/lib/browser/mechain/types/index.js +0 -0
  91. package/lib/browser/proto/api.d.ts +651 -0
  92. package/lib/browser/proto/api.js +4250 -0
  93. package/lib/browser/proto/tee-bundle.d.ts +156 -0
  94. package/lib/browser/proto/tee-bundle.js +1296 -0
  95. package/lib/browser/providers/http/index.d.ts +18 -0
  96. package/lib/browser/providers/http/index.js +640 -0
  97. package/lib/browser/providers/http/patch-parse5-tree.d.ts +6 -0
  98. package/lib/browser/providers/http/patch-parse5-tree.js +34 -0
  99. package/lib/browser/providers/http/utils.d.ts +77 -0
  100. package/lib/browser/providers/http/utils.js +283 -0
  101. package/lib/browser/providers/index.d.ts +4 -0
  102. package/lib/browser/providers/index.js +7 -0
  103. package/lib/browser/types/bgp.d.ts +11 -0
  104. package/lib/browser/types/bgp.js +0 -0
  105. package/lib/browser/types/claims.d.ts +70 -0
  106. package/lib/browser/types/claims.js +0 -0
  107. package/lib/browser/types/client.d.ts +163 -0
  108. package/lib/browser/types/client.js +0 -0
  109. package/lib/browser/types/general.d.ts +77 -0
  110. package/lib/browser/types/general.js +0 -0
  111. package/lib/browser/types/handlers.d.ts +10 -0
  112. package/lib/browser/types/handlers.js +0 -0
  113. package/lib/browser/types/index.d.ts +10 -0
  114. package/lib/browser/types/index.js +10 -0
  115. package/lib/browser/types/providers.d.ts +161 -0
  116. package/lib/browser/types/providers.gen.d.ts +443 -0
  117. package/lib/browser/types/providers.gen.js +16 -0
  118. package/lib/browser/types/providers.js +0 -0
  119. package/lib/browser/types/rpc.d.ts +35 -0
  120. package/lib/browser/types/rpc.js +0 -0
  121. package/lib/browser/types/signatures.d.ts +28 -0
  122. package/lib/browser/types/signatures.js +0 -0
  123. package/lib/browser/types/tunnel.d.ts +18 -0
  124. package/lib/browser/types/tunnel.js +0 -0
  125. package/lib/browser/types/zk.d.ts +38 -0
  126. package/lib/browser/types/zk.js +0 -0
  127. package/lib/browser/utils/auth.d.ts +8 -0
  128. package/lib/browser/utils/auth.js +71 -0
  129. package/lib/browser/utils/b64-json.d.ts +2 -0
  130. package/lib/browser/utils/b64-json.js +17 -0
  131. package/lib/browser/utils/claims.d.ts +33 -0
  132. package/lib/browser/utils/claims.js +89 -0
  133. package/lib/browser/utils/env.d.ts +3 -0
  134. package/lib/browser/utils/env.js +19 -0
  135. package/lib/browser/utils/error.d.ts +26 -0
  136. package/lib/browser/utils/error.js +54 -0
  137. package/lib/browser/utils/generics.d.ts +114 -0
  138. package/lib/browser/utils/generics.js +268 -0
  139. package/lib/browser/utils/http-parser.d.ts +59 -0
  140. package/lib/browser/utils/http-parser.js +201 -0
  141. package/lib/browser/utils/index.browser.js +12 -0
  142. package/lib/browser/utils/index.d.ts +12 -0
  143. package/lib/browser/utils/index.js +12 -0
  144. package/lib/browser/utils/logger.browser.js +88 -0
  145. package/lib/browser/utils/logger.d.ts +14 -0
  146. package/lib/browser/utils/logger.js +88 -0
  147. package/lib/browser/utils/prepare-packets.d.ts +16 -0
  148. package/lib/browser/utils/prepare-packets.js +69 -0
  149. package/lib/browser/utils/redactions.d.ts +73 -0
  150. package/lib/browser/utils/redactions.js +135 -0
  151. package/lib/browser/utils/retries.d.ts +12 -0
  152. package/lib/browser/utils/retries.js +26 -0
  153. package/lib/browser/utils/signatures/eth.d.ts +2 -0
  154. package/lib/browser/utils/signatures/eth.js +31 -0
  155. package/lib/browser/utils/signatures/index.d.ts +5 -0
  156. package/lib/browser/utils/signatures/index.js +12 -0
  157. package/lib/browser/utils/socket-base.d.ts +23 -0
  158. package/lib/browser/utils/socket-base.js +96 -0
  159. package/lib/browser/utils/tls.d.ts +2 -0
  160. package/lib/browser/utils/tls.js +58 -0
  161. package/lib/browser/utils/ws.d.ts +7 -0
  162. package/lib/browser/utils/ws.js +22 -0
  163. package/lib/browser/utils/zk.d.ts +71 -0
  164. package/lib/browser/utils/zk.js +625 -0
  165. package/lib/index.browser.d.ts +9 -0
  166. package/lib/types/general.d.ts +1 -0
  167. package/lib/utils/index.browser.d.ts +12 -0
  168. package/lib/utils/logger.browser.d.ts +14 -0
  169. package/package.json +18 -2
@@ -0,0 +1,2 @@
1
+ export declare const B64_JSON_REPLACER: (key: string, value: any) => any;
2
+ export declare const B64_JSON_REVIVER: (key: string, value: any) => any;
@@ -0,0 +1,17 @@
1
+ import { decodeBase64, encodeBase64 } from "ethers";
2
+ const B64_JSON_REPLACER = (key, value) => {
3
+ if (value instanceof Uint8Array || typeof value === "object" && value && "buffer" in value && value.buffer instanceof ArrayBuffer) {
4
+ return { type: "uint8array", value: encodeBase64(value) };
5
+ }
6
+ return value;
7
+ };
8
+ const B64_JSON_REVIVER = (key, value) => {
9
+ if (value?.type === "uint8array") {
10
+ return decodeBase64(value.value);
11
+ }
12
+ return value;
13
+ };
14
+ export {
15
+ B64_JSON_REPLACER,
16
+ B64_JSON_REVIVER
17
+ };
@@ -0,0 +1,33 @@
1
+ import { ClaimTunnelResponse } from '#src/proto/api.ts';
2
+ import type { ClaimID, ClaimInfo, CompleteClaimData, ProviderParams } from '#src/types/index.ts';
3
+ /**
4
+ * Creates the standard string to sign for a claim.
5
+ * This data is what the attestor will sign when it successfully
6
+ * verifies a claim.
7
+ */
8
+ export declare function createSignDataForClaim(data: CompleteClaimData): string;
9
+ /**
10
+ * Verify the claim tunnel response from a attestor.
11
+ *
12
+ * If you'd only like to verify the claim signature, you can
13
+ * optionally only pass "claim" & "signatures.claimSignature"
14
+ * to this function.
15
+ *
16
+ * The successful run of this function means that the claim
17
+ * is valid, and the attestor that signed the claim is valid.
18
+ */
19
+ export declare function assertValidClaimSignatures({ signatures, ...res }: Partial<ClaimTunnelResponse>, metadata?: import("#src/proto/api.ts").InitRequest): Promise<void>;
20
+ /**
21
+ * Generates a unique identifier for given claim info
22
+ * @param info
23
+ * @returns
24
+ */
25
+ export declare function getIdentifierFromClaimInfo(info: ClaimInfo): ClaimID;
26
+ /**
27
+ * Canonically stringifies an object, so that the same object will always
28
+ * produce the same string despite the order of keys
29
+ */
30
+ export declare function canonicalStringify(params: {
31
+ [key: string]: any;
32
+ } | undefined): string;
33
+ export declare function hashProviderParams(params: ProviderParams<'http'>): string;
@@ -0,0 +1,89 @@
1
+ import canonicalize from "canonicalize";
2
+ import { keccak256 } from "ethers";
3
+ import { DEFAULT_METADATA } from "../../config/index.js";
4
+ import { ClaimTunnelResponse } from "../../proto/api.js";
5
+ import { SIGNATURES, strToUint8Array } from "../../utils/index.js";
6
+ function createSignDataForClaim(data) {
7
+ const lines = [
8
+ getIdentifierFromClaimInfo(data),
9
+ // we lowercase the owner to ensure that the
10
+ // ETH addresses always serialize the same way
11
+ data.owner.toLowerCase(),
12
+ data.timestampS.toString(),
13
+ data.epoch.toString()
14
+ ];
15
+ return lines.join("\n");
16
+ }
17
+ async function assertValidClaimSignatures({
18
+ signatures,
19
+ ...res
20
+ }, metadata = DEFAULT_METADATA) {
21
+ if (!signatures) {
22
+ throw new Error("No signatures provided");
23
+ }
24
+ const {
25
+ resultSignature,
26
+ claimSignature,
27
+ attestorAddress
28
+ } = signatures;
29
+ const { verify } = SIGNATURES[metadata.signatureType];
30
+ if (signatures?.resultSignature) {
31
+ const resBytes = ClaimTunnelResponse.encode(ClaimTunnelResponse.create(res)).finish();
32
+ const verified = await verify(resBytes, resultSignature, attestorAddress);
33
+ if (!verified) {
34
+ throw new Error("Invalid result signature");
35
+ }
36
+ }
37
+ if (!res.claim) {
38
+ return;
39
+ }
40
+ const signData = createSignDataForClaim(res.claim);
41
+ const verifiedClaim = await verify(
42
+ strToUint8Array(signData),
43
+ claimSignature,
44
+ attestorAddress
45
+ );
46
+ if (!verifiedClaim) {
47
+ throw new Error("Invalid claim signature");
48
+ }
49
+ }
50
+ function getIdentifierFromClaimInfo(info) {
51
+ if (info.context?.length > 0) {
52
+ try {
53
+ const ctx = JSON.parse(info.context);
54
+ info.context = canonicalStringify(ctx);
55
+ } catch {
56
+ throw new Error("unable to parse non-empty context. Must be JSON");
57
+ }
58
+ }
59
+ const str = `${info.provider}
60
+ ${info.parameters}
61
+ ${info.context || ""}`;
62
+ return keccak256(strToUint8Array(str)).toLowerCase();
63
+ }
64
+ function canonicalStringify(params) {
65
+ if (!params) {
66
+ return "";
67
+ }
68
+ return canonicalize(params) || "";
69
+ }
70
+ function hashProviderParams(params) {
71
+ const filteredParams = {
72
+ url: params.url,
73
+ method: params.method,
74
+ body: params.body,
75
+ responseMatches: params.responseMatches,
76
+ responseRedactions: params.responseRedactions
77
+ };
78
+ const serializedParams = canonicalStringify(filteredParams);
79
+ return keccak256(
80
+ strToUint8Array(serializedParams)
81
+ ).toLowerCase();
82
+ }
83
+ export {
84
+ assertValidClaimSignatures,
85
+ canonicalStringify,
86
+ createSignDataForClaim,
87
+ getIdentifierFromClaimInfo,
88
+ hashProviderParams
89
+ };
@@ -0,0 +1,3 @@
1
+ export type TransportType = 'node' | 'react-native' | 'browser';
2
+ export declare function detectEnvironment(): TransportType;
3
+ export declare function getEnvVariable(name: string): string | undefined;
@@ -0,0 +1,19 @@
1
+ function detectEnvironment() {
2
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
3
+ return "react-native";
4
+ }
5
+ if (typeof window !== "undefined") {
6
+ return "browser";
7
+ }
8
+ return "node";
9
+ }
10
+ function getEnvVariable(name) {
11
+ if (typeof process === "undefined") {
12
+ return void 0;
13
+ }
14
+ return process?.env[name];
15
+ }
16
+ export {
17
+ detectEnvironment,
18
+ getEnvVariable
19
+ };
@@ -0,0 +1,26 @@
1
+ import { ErrorCode, ErrorData } from '#src/proto/api.ts';
2
+ /**
3
+ * Represents an error that can be thrown by the Attestor Core
4
+ * or server. Provides a code, and optional data
5
+ * to pass along with the error.
6
+ */
7
+ export declare class AttestorError extends Error {
8
+ readonly name = "AttestorError";
9
+ readonly code: keyof typeof ErrorCode;
10
+ readonly data: {
11
+ [_: string]: any;
12
+ } | undefined;
13
+ constructor(code: keyof typeof ErrorCode, message: string, data?: {
14
+ [_: string]: any;
15
+ });
16
+ /**
17
+ * Encodes the error as a ErrorData
18
+ * protobuf message
19
+ */
20
+ toProto(): ErrorData;
21
+ static fromProto(data?: ErrorData): AttestorError;
22
+ static fromError(err: Error, code?: keyof typeof ErrorCode): AttestorError;
23
+ static badRequest(message: string, data?: {
24
+ [_: string]: any;
25
+ }): AttestorError;
26
+ }
@@ -0,0 +1,54 @@
1
+ import { ErrorCode, ErrorData } from "../../proto/api.js";
2
+ const PROTO_ERROR = ErrorData.fromJSON({});
3
+ class AttestorError extends Error {
4
+ name = "AttestorError";
5
+ code;
6
+ data;
7
+ constructor(code, message, data) {
8
+ super(message);
9
+ this.code = code;
10
+ this.data = data;
11
+ }
12
+ /**
13
+ * Encodes the error as a ErrorData
14
+ * protobuf message
15
+ */
16
+ toProto() {
17
+ return ErrorData.create({
18
+ code: ErrorCode[this.code],
19
+ message: this.message,
20
+ data: JSON.stringify(this.data)
21
+ });
22
+ }
23
+ static fromProto(data = PROTO_ERROR) {
24
+ return new AttestorError(
25
+ typeof data.code === "number" ? getKeyForValue(ErrorCode, data.code) || "UNRECOGNIZED" : data.code,
26
+ data.message,
27
+ data.data ? JSON.parse(data.data) : void 0
28
+ );
29
+ }
30
+ static fromError(err, code = "ERROR_INTERNAL") {
31
+ if (err instanceof AttestorError) {
32
+ return err;
33
+ }
34
+ return new AttestorError(code, err.message);
35
+ }
36
+ static badRequest(message, data) {
37
+ return new AttestorError(
38
+ "ERROR_BAD_REQUEST",
39
+ message,
40
+ data
41
+ );
42
+ }
43
+ }
44
+ function getKeyForValue(obj, value) {
45
+ for (const key in obj) {
46
+ if (obj[key] === value) {
47
+ return key;
48
+ }
49
+ }
50
+ return void 0;
51
+ }
52
+ export {
53
+ AttestorError
54
+ };
@@ -0,0 +1,114 @@
1
+ import type { CipherSuite, TLSProtocolVersion } from '@reclaimprotocol/tls';
2
+ import { uint8ArrayToBinaryStr } from '@reclaimprotocol/tls';
3
+ import { RPCMessage, RPCMessages } from '#src/proto/api.ts';
4
+ import type { CompleteTLSPacket, IDecryptedTranscript, IDecryptedTranscriptMessage, ProviderField, RPCEvent, RPCEventMap, RPCEventType, RPCType, Transcript } from '#src/types/index.ts';
5
+ export { uint8ArrayToBinaryStr };
6
+ /**
7
+ * Decodes a Uint8Array to a UTF-8 string.
8
+ */
9
+ export declare function uint8ArrayToStr(arr: Uint8Array): string;
10
+ /**
11
+ * Encodes a UTF-8 string to a Uint8Array.
12
+ */
13
+ export declare function strToUint8Array(str: string): Uint8Array;
14
+ export declare function getTranscriptString(receipt: IDecryptedTranscript): string;
15
+ export declare const unixTimestampSeconds: () => number;
16
+ /**
17
+ * Find index of needle in haystack
18
+ */
19
+ export declare function findIndexInUint8Array(haystack: Uint8Array, needle: Uint8Array): number;
20
+ /**
21
+ * Fetch the ZK algorithm for the specified cipher suite
22
+ */
23
+ export declare function getZkAlgorithmForCipherSuite(cipherSuite: CipherSuite): "aes-256-ctr" | "aes-128-ctr" | "chacha20";
24
+ /**
25
+ * Get the pure ciphertext without any MAC,
26
+ * or authentication tag,
27
+ * @param content content w/o header
28
+ * @param cipherSuite
29
+ */
30
+ export declare function getPureCiphertext(content: Uint8Array, cipherSuite: CipherSuite): Uint8Array<ArrayBufferLike>;
31
+ /**
32
+ * Get the 8 byte IV part that's stored in the record for some cipher suites
33
+ * @param content content w/o header
34
+ * @param cipherSuite
35
+ */
36
+ export declare function getRecordIV(content: Uint8Array, cipherSuite: CipherSuite): Uint8Array<ArrayBuffer>;
37
+ export declare function getProviderValue<P, S, T>(params: P, fn: ProviderField<P, S, T>, secretParams?: S): T;
38
+ export declare function generateRpcMessageId(): number;
39
+ /**
40
+ * Random session ID for a WebSocket client.
41
+ */
42
+ export declare function generateSessionId(): number;
43
+ /**
44
+ * Random ID for a tunnel.
45
+ */
46
+ export declare function generateTunnelId(): number;
47
+ export declare function makeRpcEvent<T extends RPCEventType>(type: T, data: RPCEventMap[T]): RPCEvent<T>;
48
+ /**
49
+ * Get the RPC type from the key.
50
+ * For eg. "claimTunnelRequest" ->
51
+ * { type: 'claimTunnel', direction: 'request' }
52
+ */
53
+ export declare function getRpcTypeFromKey(key: string): {
54
+ type: RPCType;
55
+ direction: "request";
56
+ } | {
57
+ type: RPCType;
58
+ direction: "response";
59
+ } | undefined;
60
+ /**
61
+ * Get the RPC response type from the RPC type.
62
+ * For eg. "claimTunnel" -> "claimTunnelResponse"
63
+ */
64
+ export declare function getRpcResponseType<T extends RPCType>(type: T): `${T}Response`;
65
+ /**
66
+ * Get the RPC request type from the RPC type.
67
+ * For eg. "claimTunnel" -> "claimTunnelRequest"
68
+ */
69
+ export declare function getRpcRequestType<T extends RPCType>(type: T): `${T}Request`;
70
+ export declare function isApplicationData(packet: CompleteTLSPacket, tlsVersion: string | undefined): boolean;
71
+ /**
72
+ * Convert the received data from a WS to a Uint8Array
73
+ */
74
+ export declare function extractArrayBufferFromWsData(data: unknown): Promise<Uint8Array>;
75
+ /**
76
+ * Check if the RPC message is a request or a response.
77
+ */
78
+ export declare function getRpcRequest(msg: RPCMessage): {
79
+ type: RPCType;
80
+ direction: "request";
81
+ } | {
82
+ type: RPCType;
83
+ direction: "response";
84
+ } | {
85
+ direction: "response";
86
+ type: "error";
87
+ } | undefined;
88
+ /**
89
+ * Finds all application data messages in a transcript
90
+ * and returns them. Removes the "contentType" suffix from the message.
91
+ * in TLS 1.3
92
+ */
93
+ export declare function extractApplicationDataFromTranscript({ transcript, tlsVersion }: IDecryptedTranscript): Transcript<Uint8Array<ArrayBufferLike>>;
94
+ export type HandshakeTranscript<T> = {
95
+ sender: 'client' | 'server';
96
+ index: number;
97
+ message: T;
98
+ }[];
99
+ export declare function extractHandshakeFromTranscript({ transcript, tlsVersion }: {
100
+ transcript: IDecryptedTranscriptMessage[];
101
+ tlsVersion: TLSProtocolVersion;
102
+ }): HandshakeTranscript<Uint8Array<ArrayBufferLike>>;
103
+ export declare function decryptDirect(directReveal: any, cipherSuite: CipherSuite, recordHeader: Uint8Array, serverTlsVersion: TLSProtocolVersion, content: Uint8Array): Promise<{
104
+ plaintext: Uint8Array<ArrayBufferLike>;
105
+ iv: Uint8Array<ArrayBufferLike>;
106
+ }>;
107
+ export declare function packRpcMessages(...msgs: Partial<RPCMessage>[]): RPCMessages;
108
+ /**
109
+ * Converts an Ethers struct (an array w named keys) to
110
+ * a plain object. Recursively converts all structs inside.
111
+ * Required to correctly JSON.stringify the struct.
112
+ */
113
+ export declare function ethersStructToPlainObject<T>(struct: T): T;
114
+ export declare function isTls13Suite(suite: CipherSuite): suite is "TLS_CHACHA20_POLY1305_SHA256" | "TLS_AES_256_GCM_SHA384" | "TLS_AES_128_GCM_SHA256";
@@ -0,0 +1,268 @@
1
+ import {
2
+ areUint8ArraysEqual,
3
+ CONTENT_TYPE_MAP,
4
+ crypto,
5
+ decryptWrappedRecord,
6
+ PACKET_TYPE,
7
+ SUPPORTED_CIPHER_SUITE_MAP,
8
+ uint8ArrayToBinaryStr,
9
+ uint8ArrayToDataView
10
+ } from "@reclaimprotocol/tls";
11
+ import { REDACTION_CHAR_CODE } from "@reclaimprotocol/zk-symmetric-crypto";
12
+ import { RPCMessage, RPCMessages } from "../../proto/api.js";
13
+ const DEFAULT_REDACTION_DATA = new Uint8Array(4).fill(REDACTION_CHAR_CODE);
14
+ function uint8ArrayToStr(arr) {
15
+ return new TextDecoder().decode(arr);
16
+ }
17
+ function strToUint8Array(str) {
18
+ return new TextEncoder().encode(str);
19
+ }
20
+ function getTranscriptString(receipt) {
21
+ const applMsgs = extractApplicationDataFromTranscript(receipt);
22
+ const strList = [];
23
+ for (const { message, sender } of applMsgs) {
24
+ const content = uint8ArrayToStr(message);
25
+ if (strList[strList.length - 1]?.startsWith(sender)) {
26
+ strList[strList.length - 1] += content;
27
+ } else {
28
+ strList.push(`${sender}: ${content}`);
29
+ }
30
+ }
31
+ return strList.join("\n");
32
+ }
33
+ const unixTimestampSeconds = () => Math.floor(Date.now() / 1e3);
34
+ function findIndexInUint8Array(haystack, needle) {
35
+ for (let i = 0; i < haystack.length; i++) {
36
+ if (areUint8ArraysEqual(haystack.slice(i, i + needle.length), needle)) {
37
+ return i;
38
+ }
39
+ }
40
+ return -1;
41
+ }
42
+ function getZkAlgorithmForCipherSuite(cipherSuite) {
43
+ if (cipherSuite.includes("CHACHA20")) {
44
+ return "chacha20";
45
+ }
46
+ if (cipherSuite.includes("AES_256_GCM")) {
47
+ return "aes-256-ctr";
48
+ }
49
+ if (cipherSuite.includes("AES_128_GCM")) {
50
+ return "aes-128-ctr";
51
+ }
52
+ throw new Error(`${cipherSuite} not supported for ZK ops`);
53
+ }
54
+ function getPureCiphertext(content, cipherSuite) {
55
+ getZkAlgorithmForCipherSuite(cipherSuite);
56
+ content = content.slice(0, -16);
57
+ const {
58
+ ivLength: fixedIvLength
59
+ } = SUPPORTED_CIPHER_SUITE_MAP[cipherSuite];
60
+ const recordIvLength = 12 - fixedIvLength;
61
+ content = content.slice(recordIvLength);
62
+ return content;
63
+ }
64
+ function getRecordIV(content, cipherSuite) {
65
+ getZkAlgorithmForCipherSuite(cipherSuite);
66
+ const {
67
+ ivLength: fixedIvLength
68
+ } = SUPPORTED_CIPHER_SUITE_MAP[cipherSuite];
69
+ const recordIvLength = 12 - fixedIvLength;
70
+ return content.slice(0, recordIvLength);
71
+ }
72
+ function getProviderValue(params, fn, secretParams) {
73
+ return typeof fn === "function" ? fn(params, secretParams) : fn;
74
+ }
75
+ function generateRpcMessageId() {
76
+ return uint8ArrayToDataView(crypto.randomBytes(4)).getUint32(0);
77
+ }
78
+ function generateSessionId() {
79
+ return generateRpcMessageId();
80
+ }
81
+ function generateTunnelId() {
82
+ return generateRpcMessageId();
83
+ }
84
+ function makeRpcEvent(type, data) {
85
+ const ev = new Event(type);
86
+ ev.data = data;
87
+ return ev;
88
+ }
89
+ function getRpcTypeFromKey(key) {
90
+ if (key.endsWith("Request")) {
91
+ return {
92
+ type: key.slice(0, -7),
93
+ direction: "request"
94
+ };
95
+ }
96
+ if (key.endsWith("Response")) {
97
+ return {
98
+ type: key.slice(0, -8),
99
+ direction: "response"
100
+ };
101
+ }
102
+ }
103
+ function getRpcResponseType(type) {
104
+ return `${type}Response`;
105
+ }
106
+ function getRpcRequestType(type) {
107
+ return `${type}Request`;
108
+ }
109
+ function isApplicationData(packet, tlsVersion) {
110
+ return packet.type === "ciphertext" && (packet.contentType === "APPLICATION_DATA" || packet.data[0] === PACKET_TYPE.WRAPPED_RECORD && tlsVersion === "TLS1_2");
111
+ }
112
+ async function extractArrayBufferFromWsData(data) {
113
+ if (data instanceof ArrayBuffer) {
114
+ return new Uint8Array(data);
115
+ }
116
+ if (data instanceof Uint8Array || typeof data === "object" && data && "buffer" in data) {
117
+ return data;
118
+ }
119
+ if (typeof data === "string") {
120
+ return strToUint8Array(data);
121
+ }
122
+ if (typeof Blob !== "undefined" && data instanceof Blob) {
123
+ return new Uint8Array(await data.arrayBuffer());
124
+ }
125
+ throw new Error("unsupported data: " + String(data));
126
+ }
127
+ function getRpcRequest(msg) {
128
+ if (msg.requestError) {
129
+ return {
130
+ direction: "response",
131
+ type: "error"
132
+ };
133
+ }
134
+ for (const key in msg) {
135
+ if (!msg[key]) {
136
+ continue;
137
+ }
138
+ const rpcType = getRpcTypeFromKey(key);
139
+ if (!rpcType) {
140
+ continue;
141
+ }
142
+ return rpcType;
143
+ }
144
+ }
145
+ function extractApplicationDataFromTranscript({ transcript, tlsVersion }) {
146
+ const msgs = [];
147
+ for (const m of transcript) {
148
+ let message;
149
+ if (m.redacted) {
150
+ if (!m.plaintextLength) {
151
+ message = DEFAULT_REDACTION_DATA;
152
+ } else {
153
+ const len = tlsVersion === "TLS1_3" ? m.plaintextLength - 1 : m.plaintextLength;
154
+ message = new Uint8Array(len).fill(REDACTION_CHAR_CODE);
155
+ }
156
+ } else if (tlsVersion === "TLS1_3") {
157
+ const contentType = m.message[m.message.length - 1];
158
+ if (contentType !== CONTENT_TYPE_MAP["APPLICATION_DATA"]) {
159
+ continue;
160
+ }
161
+ message = m.message.slice(0, -1);
162
+ } else if (m.recordHeader[0] === PACKET_TYPE.WRAPPED_RECORD) {
163
+ message = m.message;
164
+ } else {
165
+ continue;
166
+ }
167
+ msgs.push({ message, sender: m.sender });
168
+ }
169
+ return msgs;
170
+ }
171
+ function extractHandshakeFromTranscript({ transcript, tlsVersion }) {
172
+ const msgs = [];
173
+ for (const [i, m] of transcript.entries()) {
174
+ if (m.redacted) {
175
+ break;
176
+ }
177
+ let message;
178
+ if (m.recordHeader[0] === PACKET_TYPE.HELLO) {
179
+ message = m.message;
180
+ } else if (m.recordHeader[0] === PACKET_TYPE.WRAPPED_RECORD) {
181
+ if (tlsVersion === "TLS1_3") {
182
+ const contentType = m.message[m.message.length - 1];
183
+ if (contentType !== CONTENT_TYPE_MAP["HANDSHAKE"]) {
184
+ break;
185
+ }
186
+ message = m.message.slice(0, -1);
187
+ } else {
188
+ break;
189
+ }
190
+ } else {
191
+ continue;
192
+ }
193
+ if (!message.length) {
194
+ throw new Error("unsupported handshake message");
195
+ }
196
+ msgs.push({ message, sender: m.sender, index: i });
197
+ }
198
+ return msgs;
199
+ }
200
+ async function decryptDirect(directReveal, cipherSuite, recordHeader, serverTlsVersion, content) {
201
+ const { key, iv, recordNumber } = directReveal;
202
+ const { cipher } = SUPPORTED_CIPHER_SUITE_MAP[cipherSuite];
203
+ const importedKey = await crypto.importKey(cipher, key);
204
+ return await decryptWrappedRecord(
205
+ content,
206
+ {
207
+ iv,
208
+ key: importedKey,
209
+ recordHeader,
210
+ recordNumber,
211
+ version: serverTlsVersion,
212
+ cipherSuite
213
+ }
214
+ );
215
+ }
216
+ function packRpcMessages(...msgs) {
217
+ return RPCMessages.create({
218
+ messages: msgs.map((msg) => RPCMessage.create({
219
+ ...msg,
220
+ id: msg.id || generateRpcMessageId()
221
+ }))
222
+ });
223
+ }
224
+ function ethersStructToPlainObject(struct) {
225
+ if (!Array.isArray(struct)) {
226
+ return struct;
227
+ }
228
+ const namedKeys = Object.keys(struct).filter((key) => isNaN(Number(key)));
229
+ if (!namedKeys.length) {
230
+ return struct.map(ethersStructToPlainObject);
231
+ }
232
+ const obj = {};
233
+ for (const key of namedKeys) {
234
+ obj[key] = ethersStructToPlainObject(struct[key]);
235
+ }
236
+ return obj;
237
+ }
238
+ function isTls13Suite(suite) {
239
+ return suite === "TLS_AES_128_GCM_SHA256" || suite === "TLS_AES_256_GCM_SHA384" || suite === "TLS_CHACHA20_POLY1305_SHA256";
240
+ }
241
+ export {
242
+ decryptDirect,
243
+ ethersStructToPlainObject,
244
+ extractApplicationDataFromTranscript,
245
+ extractArrayBufferFromWsData,
246
+ extractHandshakeFromTranscript,
247
+ findIndexInUint8Array,
248
+ generateRpcMessageId,
249
+ generateSessionId,
250
+ generateTunnelId,
251
+ getProviderValue,
252
+ getPureCiphertext,
253
+ getRecordIV,
254
+ getRpcRequest,
255
+ getRpcRequestType,
256
+ getRpcResponseType,
257
+ getRpcTypeFromKey,
258
+ getTranscriptString,
259
+ getZkAlgorithmForCipherSuite,
260
+ isApplicationData,
261
+ isTls13Suite,
262
+ makeRpcEvent,
263
+ packRpcMessages,
264
+ strToUint8Array,
265
+ uint8ArrayToBinaryStr,
266
+ uint8ArrayToStr,
267
+ unixTimestampSeconds
268
+ };
@@ -0,0 +1,59 @@
1
+ import type { IncomingHttpHeaders } from 'http';
2
+ import type { ArraySlice, Transcript } from '#src/types/index.ts';
3
+ export type HttpRequest = {
4
+ method: string;
5
+ url: string;
6
+ protocol: string;
7
+ headers: IncomingHttpHeaders;
8
+ body?: Uint8Array;
9
+ };
10
+ export type HttpResponse = {
11
+ statusCode: number;
12
+ statusMessage: string;
13
+ headers: IncomingHttpHeaders;
14
+ body: Uint8Array;
15
+ headersComplete: boolean;
16
+ complete: boolean;
17
+ /**
18
+ * Index of the first byte of the status line
19
+ */
20
+ statusLineEndIndex?: number;
21
+ /**
22
+ * Index of the first byte of the body
23
+ * in the complete response
24
+ */
25
+ bodyStartIndex?: number;
26
+ /**
27
+ * If using chunked transfer encoding,
28
+ * this will be set & contain indices of each
29
+ * chunk in the complete response
30
+ */
31
+ chunks?: ArraySlice[];
32
+ headerIndices: Map<string, ArraySlice>;
33
+ /**
34
+ * index of separator \r\n\r\n between headers and body
35
+ */
36
+ headerEndIdx: number;
37
+ };
38
+ /**
39
+ * parses http/1.1 responses
40
+ */
41
+ export declare function makeHttpResponseParser(): {
42
+ res: HttpResponse;
43
+ /**
44
+ * Parse the next chunk of data
45
+ * @param data the data to parse
46
+ */
47
+ onChunk(data: Uint8Array): void;
48
+ /**
49
+ * Call to prevent further parsing; indicating the end of the request
50
+ * Checks that the response is valid & complete, otherwise throws an error
51
+ */
52
+ streamEnded(): void;
53
+ };
54
+ /**
55
+ * Read the HTTP request from a TLS receipt transcript.
56
+ * @param receipt the transcript to read from or application messages if they were extracted beforehand
57
+ * @returns the parsed HTTP request
58
+ */
59
+ export declare function getHttpRequestDataFromTranscript(receipt: Transcript<Uint8Array>): HttpRequest;