@haneullabs/seal 0.1.0

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 (109) hide show
  1. package/CHANGELOG.md +459 -0
  2. package/README.md +4 -0
  3. package/dist/cjs/bcs.d.ts +71 -0
  4. package/dist/cjs/bcs.js +74 -0
  5. package/dist/cjs/bcs.js.map +7 -0
  6. package/dist/cjs/bls12381.d.ts +44 -0
  7. package/dist/cjs/bls12381.js +151 -0
  8. package/dist/cjs/bls12381.js.map +7 -0
  9. package/dist/cjs/client.d.ts +84 -0
  10. package/dist/cjs/client.js +414 -0
  11. package/dist/cjs/client.js.map +7 -0
  12. package/dist/cjs/decrypt.d.ts +22 -0
  13. package/dist/cjs/decrypt.js +109 -0
  14. package/dist/cjs/decrypt.js.map +7 -0
  15. package/dist/cjs/dem.d.ts +38 -0
  16. package/dist/cjs/dem.js +185 -0
  17. package/dist/cjs/dem.js.map +7 -0
  18. package/dist/cjs/elgamal.d.ts +13 -0
  19. package/dist/cjs/elgamal.js +46 -0
  20. package/dist/cjs/elgamal.js.map +7 -0
  21. package/dist/cjs/encrypt.d.ts +32 -0
  22. package/dist/cjs/encrypt.js +104 -0
  23. package/dist/cjs/encrypt.js.map +7 -0
  24. package/dist/cjs/error.d.ts +86 -0
  25. package/dist/cjs/error.js +239 -0
  26. package/dist/cjs/error.js.map +7 -0
  27. package/dist/cjs/ibe.d.ts +98 -0
  28. package/dist/cjs/ibe.js +167 -0
  29. package/dist/cjs/ibe.js.map +7 -0
  30. package/dist/cjs/index.d.ts +6 -0
  31. package/dist/cjs/index.js +33 -0
  32. package/dist/cjs/index.js.map +7 -0
  33. package/dist/cjs/kdf.d.ts +30 -0
  34. package/dist/cjs/kdf.js +97 -0
  35. package/dist/cjs/kdf.js.map +7 -0
  36. package/dist/cjs/key-server.d.ts +98 -0
  37. package/dist/cjs/key-server.js +171 -0
  38. package/dist/cjs/key-server.js.map +7 -0
  39. package/dist/cjs/package.json +5 -0
  40. package/dist/cjs/session-key.d.ts +74 -0
  41. package/dist/cjs/session-key.js +245 -0
  42. package/dist/cjs/session-key.js.map +7 -0
  43. package/dist/cjs/shamir.d.ts +91 -0
  44. package/dist/cjs/shamir.js +770 -0
  45. package/dist/cjs/shamir.js.map +7 -0
  46. package/dist/cjs/types.d.ts +83 -0
  47. package/dist/cjs/types.js +17 -0
  48. package/dist/cjs/types.js.map +7 -0
  49. package/dist/cjs/utils.d.ts +47 -0
  50. package/dist/cjs/utils.js +106 -0
  51. package/dist/cjs/utils.js.map +7 -0
  52. package/dist/cjs/version.d.ts +1 -0
  53. package/dist/cjs/version.js +25 -0
  54. package/dist/cjs/version.js.map +7 -0
  55. package/dist/esm/bcs.d.ts +71 -0
  56. package/dist/esm/bcs.js +54 -0
  57. package/dist/esm/bcs.js.map +7 -0
  58. package/dist/esm/bls12381.d.ts +44 -0
  59. package/dist/esm/bls12381.js +131 -0
  60. package/dist/esm/bls12381.js.map +7 -0
  61. package/dist/esm/client.d.ts +84 -0
  62. package/dist/esm/client.js +407 -0
  63. package/dist/esm/client.js.map +7 -0
  64. package/dist/esm/decrypt.d.ts +22 -0
  65. package/dist/esm/decrypt.js +94 -0
  66. package/dist/esm/decrypt.js.map +7 -0
  67. package/dist/esm/dem.d.ts +38 -0
  68. package/dist/esm/dem.js +165 -0
  69. package/dist/esm/dem.js.map +7 -0
  70. package/dist/esm/elgamal.d.ts +13 -0
  71. package/dist/esm/elgamal.js +26 -0
  72. package/dist/esm/elgamal.js.map +7 -0
  73. package/dist/esm/encrypt.d.ts +32 -0
  74. package/dist/esm/encrypt.js +84 -0
  75. package/dist/esm/encrypt.js.map +7 -0
  76. package/dist/esm/error.d.ts +86 -0
  77. package/dist/esm/error.js +219 -0
  78. package/dist/esm/error.js.map +7 -0
  79. package/dist/esm/ibe.d.ts +98 -0
  80. package/dist/esm/ibe.js +147 -0
  81. package/dist/esm/ibe.js.map +7 -0
  82. package/dist/esm/index.d.ts +6 -0
  83. package/dist/esm/index.js +12 -0
  84. package/dist/esm/index.js.map +7 -0
  85. package/dist/esm/kdf.d.ts +30 -0
  86. package/dist/esm/kdf.js +83 -0
  87. package/dist/esm/kdf.js.map +7 -0
  88. package/dist/esm/key-server.d.ts +98 -0
  89. package/dist/esm/key-server.js +151 -0
  90. package/dist/esm/key-server.js.map +7 -0
  91. package/dist/esm/package.json +5 -0
  92. package/dist/esm/session-key.d.ts +74 -0
  93. package/dist/esm/session-key.js +230 -0
  94. package/dist/esm/session-key.js.map +7 -0
  95. package/dist/esm/shamir.d.ts +91 -0
  96. package/dist/esm/shamir.js +750 -0
  97. package/dist/esm/shamir.js.map +7 -0
  98. package/dist/esm/types.d.ts +83 -0
  99. package/dist/esm/types.js +1 -0
  100. package/dist/esm/types.js.map +7 -0
  101. package/dist/esm/utils.d.ts +47 -0
  102. package/dist/esm/utils.js +86 -0
  103. package/dist/esm/utils.js.map +7 -0
  104. package/dist/esm/version.d.ts +1 -0
  105. package/dist/esm/version.js +5 -0
  106. package/dist/esm/version.js.map +7 -0
  107. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  108. package/dist/tsconfig.tsbuildinfo +1 -0
  109. package/package.json +58 -0
@@ -0,0 +1,131 @@
1
+ import { bls12_381 } from "@noble/curves/bls12-381";
2
+ import { bytesToNumberBE, bytesToNumberLE, numberToBytesBE } from "@noble/curves/utils";
3
+ const _G1Element = class _G1Element {
4
+ constructor(point) {
5
+ this.point = point;
6
+ }
7
+ static generator() {
8
+ return new _G1Element(bls12_381.G1.Point.BASE);
9
+ }
10
+ static fromBytes(bytes) {
11
+ try {
12
+ return new _G1Element(bls12_381.G1.Point.fromBytes(bytes));
13
+ } catch {
14
+ throw new Error("Invalid G1 point");
15
+ }
16
+ }
17
+ toBytes() {
18
+ return this.point.toBytes();
19
+ }
20
+ multiply(scalar) {
21
+ return new _G1Element(this.point.multiply(scalar.scalar));
22
+ }
23
+ add(other) {
24
+ return new _G1Element(this.point.add(other.point));
25
+ }
26
+ subtract(other) {
27
+ return new _G1Element(this.point.subtract(other.point));
28
+ }
29
+ static hashToCurve(data) {
30
+ return new _G1Element(bls12_381.G1.Point.fromAffine(bls12_381.G1.hashToCurve(data).toAffine()));
31
+ }
32
+ pairing(other) {
33
+ return new GTElement(bls12_381.pairing(this.point, other.point));
34
+ }
35
+ };
36
+ _G1Element.SIZE = 48;
37
+ let G1Element = _G1Element;
38
+ const _G2Element = class _G2Element {
39
+ constructor(point) {
40
+ this.point = point;
41
+ }
42
+ static generator() {
43
+ return new _G2Element(bls12_381.G2.Point.BASE);
44
+ }
45
+ static fromBytes(bytes) {
46
+ try {
47
+ return new _G2Element(bls12_381.G2.Point.fromBytes(bytes));
48
+ } catch {
49
+ throw new Error("Invalid G2 point");
50
+ }
51
+ }
52
+ toBytes() {
53
+ return this.point.toBytes();
54
+ }
55
+ multiply(scalar) {
56
+ return new _G2Element(this.point.multiply(scalar.scalar));
57
+ }
58
+ add(other) {
59
+ return new _G2Element(this.point.add(other.point));
60
+ }
61
+ static hashToCurve(data) {
62
+ return new _G2Element(bls12_381.G2.Point.fromAffine(bls12_381.G2.hashToCurve(data).toAffine()));
63
+ }
64
+ equals(other) {
65
+ return this.point.equals(other.point);
66
+ }
67
+ };
68
+ _G2Element.SIZE = 96;
69
+ let G2Element = _G2Element;
70
+ const _GTElement = class _GTElement {
71
+ constructor(element) {
72
+ this.element = element;
73
+ }
74
+ toBytes() {
75
+ const P = [0, 3, 1, 4, 2, 5];
76
+ const PAIR_SIZE = _GTElement.SIZE / P.length;
77
+ const bytes = bls12_381.fields.Fp12.toBytes(this.element);
78
+ const result = new Uint8Array(_GTElement.SIZE);
79
+ for (let i = 0; i < P.length; i++) {
80
+ const sourceStart = P[i] * PAIR_SIZE;
81
+ const sourceEnd = sourceStart + PAIR_SIZE;
82
+ const targetStart = i * PAIR_SIZE;
83
+ result.set(bytes.subarray(sourceStart, sourceEnd), targetStart);
84
+ }
85
+ return result;
86
+ }
87
+ equals(other) {
88
+ return bls12_381.fields.Fp12.eql(this.element, other.element);
89
+ }
90
+ };
91
+ _GTElement.SIZE = 576;
92
+ let GTElement = _GTElement;
93
+ const _Scalar = class _Scalar {
94
+ constructor(scalar) {
95
+ this.scalar = scalar;
96
+ }
97
+ static fromBigint(scalar) {
98
+ if (scalar < 0n || scalar >= bls12_381.fields.Fr.ORDER) {
99
+ throw new Error("Scalar out of range");
100
+ }
101
+ return new _Scalar(scalar);
102
+ }
103
+ static random() {
104
+ const randomSecretKey = bls12_381.utils.randomSecretKey();
105
+ return _Scalar.fromBytes(randomSecretKey);
106
+ }
107
+ toBytes() {
108
+ return numberToBytesBE(this.scalar, _Scalar.SIZE);
109
+ }
110
+ static fromBytes(bytes) {
111
+ if (bytes.length !== _Scalar.SIZE) {
112
+ throw new Error("Invalid scalar length");
113
+ }
114
+ return this.fromBigint(bytesToNumberBE(bytes));
115
+ }
116
+ static fromBytesLE(bytes) {
117
+ if (bytes.length !== _Scalar.SIZE) {
118
+ throw new Error("Invalid scalar length");
119
+ }
120
+ return this.fromBigint(bytesToNumberLE(bytes));
121
+ }
122
+ };
123
+ _Scalar.SIZE = 32;
124
+ let Scalar = _Scalar;
125
+ export {
126
+ G1Element,
127
+ G2Element,
128
+ GTElement,
129
+ Scalar
130
+ };
131
+ //# sourceMappingURL=bls12381.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/bls12381.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Fp2, Fp12 } from '@noble/curves/abstract/tower';\nimport type { WeierstrassPoint } from '@noble/curves/abstract/weierstrass';\nimport { bls12_381 } from '@noble/curves/bls12-381';\nimport { bytesToNumberBE, bytesToNumberLE, numberToBytesBE } from '@noble/curves/utils';\n\nexport class G1Element {\n\tpoint: WeierstrassPoint<bigint>;\n\n\tpublic static readonly SIZE = 48;\n\n\tconstructor(point: WeierstrassPoint<bigint>) {\n\t\tthis.point = point;\n\t}\n\n\tstatic generator(): G1Element {\n\t\treturn new G1Element(bls12_381.G1.Point.BASE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): G1Element {\n\t\ttry {\n\t\t\treturn new G1Element(bls12_381.G1.Point.fromBytes(bytes));\n\t\t} catch {\n\t\t\tthrow new Error('Invalid G1 point');\n\t\t}\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\treturn this.point.toBytes() as Uint8Array<ArrayBuffer>;\n\t}\n\n\tmultiply(scalar: Scalar): G1Element {\n\t\treturn new G1Element(this.point.multiply(scalar.scalar));\n\t}\n\n\tadd(other: G1Element): G1Element {\n\t\treturn new G1Element(this.point.add(other.point));\n\t}\n\n\tsubtract(other: G1Element): G1Element {\n\t\treturn new G1Element(this.point.subtract(other.point));\n\t}\n\n\tstatic hashToCurve(data: Uint8Array): G1Element {\n\t\treturn new G1Element(bls12_381.G1.Point.fromAffine(bls12_381.G1.hashToCurve(data).toAffine()));\n\t}\n\n\tpairing(other: G2Element): GTElement {\n\t\treturn new GTElement(bls12_381.pairing(this.point, other.point));\n\t}\n}\n\nexport class G2Element {\n\tpoint: WeierstrassPoint<Fp2>;\n\n\tpublic static readonly SIZE = 96;\n\n\tconstructor(point: WeierstrassPoint<Fp2>) {\n\t\tthis.point = point;\n\t}\n\n\tstatic generator(): G2Element {\n\t\treturn new G2Element(bls12_381.G2.Point.BASE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): G2Element {\n\t\ttry {\n\t\t\treturn new G2Element(bls12_381.G2.Point.fromBytes(bytes));\n\t\t} catch {\n\t\t\tthrow new Error('Invalid G2 point');\n\t\t}\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\treturn this.point.toBytes() as Uint8Array<ArrayBuffer>;\n\t}\n\n\tmultiply(scalar: Scalar): G2Element {\n\t\treturn new G2Element(this.point.multiply(scalar.scalar));\n\t}\n\n\tadd(other: G2Element): G2Element {\n\t\treturn new G2Element(this.point.add(other.point));\n\t}\n\n\tstatic hashToCurve(data: Uint8Array): G2Element {\n\t\treturn new G2Element(bls12_381.G2.Point.fromAffine(bls12_381.G2.hashToCurve(data).toAffine()));\n\t}\n\n\tequals(other: G2Element): boolean {\n\t\treturn this.point.equals(other.point);\n\t}\n}\n\nexport class GTElement {\n\telement: Fp12;\n\n\tpublic static readonly SIZE = 576;\n\n\tconstructor(element: Fp12) {\n\t\tthis.element = element;\n\t}\n\n\ttoBytes(): Uint8Array<ArrayBuffer> {\n\t\t// This permutation reorders the 6 pairs of coefficients of the GT element for compatability with the Rust and Move implementations.\n\t\t//\n\t\t// The permutation P may be computed as:\n\t\t// for i in 0..3 {\n\t\t// for j in 0..2 {\n\t\t// P[2 * i + j] = i + 3 * j;\n\t\t// }\n\t\t// }\n\t\tconst P = [0, 3, 1, 4, 2, 5];\n\t\tconst PAIR_SIZE = GTElement.SIZE / P.length;\n\n\t\tconst bytes = bls12_381.fields.Fp12.toBytes(this.element);\n\t\tconst result = new Uint8Array(GTElement.SIZE);\n\n\t\tfor (let i = 0; i < P.length; i++) {\n\t\t\tconst sourceStart = P[i] * PAIR_SIZE;\n\t\t\tconst sourceEnd = sourceStart + PAIR_SIZE;\n\t\t\tconst targetStart = i * PAIR_SIZE;\n\t\t\tresult.set(bytes.subarray(sourceStart, sourceEnd), targetStart);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tequals(other: GTElement): boolean {\n\t\treturn bls12_381.fields.Fp12.eql(this.element, other.element);\n\t}\n}\n\nexport class Scalar {\n\tscalar: bigint;\n\n\tpublic static readonly SIZE = 32;\n\n\tconstructor(scalar: bigint) {\n\t\tthis.scalar = scalar;\n\t}\n\n\tstatic fromBigint(scalar: bigint): Scalar {\n\t\tif (scalar < 0n || scalar >= bls12_381.fields.Fr.ORDER) {\n\t\t\tthrow new Error('Scalar out of range');\n\t\t}\n\t\treturn new Scalar(scalar);\n\t}\n\n\tstatic random(): Scalar {\n\t\tconst randomSecretKey = bls12_381.utils.randomSecretKey();\n\t\treturn Scalar.fromBytes(randomSecretKey)!;\n\t}\n\n\ttoBytes(): Uint8Array {\n\t\treturn numberToBytesBE(this.scalar, Scalar.SIZE);\n\t}\n\n\tstatic fromBytes(bytes: Uint8Array): Scalar {\n\t\tif (bytes.length !== Scalar.SIZE) {\n\t\t\tthrow new Error('Invalid scalar length');\n\t\t}\n\t\treturn this.fromBigint(bytesToNumberBE(bytes));\n\t}\n\n\tstatic fromBytesLE(bytes: Uint8Array): Scalar {\n\t\tif (bytes.length !== Scalar.SIZE) {\n\t\t\tthrow new Error('Invalid scalar length');\n\t\t}\n\t\treturn this.fromBigint(bytesToNumberLE(bytes));\n\t}\n}\n"],
5
+ "mappings": "AAKA,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB,iBAAiB,uBAAuB;AAE3D,MAAM,aAAN,MAAM,WAAU;AAAA,EAKtB,YAAY,OAAiC;AAC5C,SAAK,QAAQ;AAAA,EACd;AAAA,EAEA,OAAO,YAAuB;AAC7B,WAAO,IAAI,WAAU,UAAU,GAAG,MAAM,IAAI;AAAA,EAC7C;AAAA,EAEA,OAAO,UAAU,OAA8B;AAC9C,QAAI;AACH,aAAO,IAAI,WAAU,UAAU,GAAG,MAAM,UAAU,KAAK,CAAC;AAAA,IACzD,QAAQ;AACP,YAAM,IAAI,MAAM,kBAAkB;AAAA,IACnC;AAAA,EACD;AAAA,EAEA,UAAmC;AAClC,WAAO,KAAK,MAAM,QAAQ;AAAA,EAC3B;AAAA,EAEA,SAAS,QAA2B;AACnC,WAAO,IAAI,WAAU,KAAK,MAAM,SAAS,OAAO,MAAM,CAAC;AAAA,EACxD;AAAA,EAEA,IAAI,OAA6B;AAChC,WAAO,IAAI,WAAU,KAAK,MAAM,IAAI,MAAM,KAAK,CAAC;AAAA,EACjD;AAAA,EAEA,SAAS,OAA6B;AACrC,WAAO,IAAI,WAAU,KAAK,MAAM,SAAS,MAAM,KAAK,CAAC;AAAA,EACtD;AAAA,EAEA,OAAO,YAAY,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C,QAAI,MAAM,WAAW,QAAO,MAAM;AACjC,YAAM,IAAI,MAAM,uBAAuB;AAAA,IACxC;AACA,WAAO,KAAK,WAAW,gBAAgB,KAAK,CAAC;AAAA,EAC9C;AACD;AAtCa,QAGW,OAAO;AAHxB,IAAM,SAAN;",
6
+ "names": []
7
+ }
@@ -0,0 +1,84 @@
1
+ import { G2Element } from './bls12381.js';
2
+ import type { DerivedKey, KeyServer } from './key-server.js';
3
+ import type { DecryptOptions, EncryptOptions, FetchKeysOptions, GetDerivedKeysOptions, SealClientExtensionOptions, SealClientOptions, SealCompatibleClient, SealOptions } from './types.js';
4
+ export declare function seal<Name = 'seal'>({ name, ...options }: SealOptions<Name>): {
5
+ name: Name;
6
+ register: (client: SealCompatibleClient) => SealClient;
7
+ };
8
+ export declare class SealClient {
9
+ #private;
10
+ constructor(options: SealClientOptions);
11
+ /** @deprecated Use `seal()` instead */
12
+ static asClientExtension(options: SealClientExtensionOptions): {
13
+ name: "seal";
14
+ register: (client: SealCompatibleClient) => SealClient;
15
+ };
16
+ /**
17
+ * Return an encrypted message under the identity.
18
+ *
19
+ * @param kemType - The type of KEM to use.
20
+ * @param demType - The type of DEM to use.
21
+ * @param threshold - The threshold for the TSS encryption.
22
+ * @param packageId - the packageId namespace.
23
+ * @param id - the identity to use.
24
+ * @param data - the data to encrypt.
25
+ * @param aad - optional additional authenticated data.
26
+ * @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.
27
+ * Since the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.
28
+ */
29
+ encrypt({ kemType, demType, threshold, packageId, id, data, aad, }: EncryptOptions): Promise<{
30
+ encryptedObject: Uint8Array<ArrayBuffer>;
31
+ key: Uint8Array<ArrayBuffer>;
32
+ }>;
33
+ /**
34
+ * Decrypt the given encrypted bytes using cached keys.
35
+ * Calls fetchKeys in case one or more of the required keys is not cached yet.
36
+ * The function throws an error if the client's key servers are not a subset of
37
+ * the encrypted object's key servers or if the threshold cannot be met.
38
+ *
39
+ * If checkShareConsistency is true, the decrypted shares are checked for consistency, meaning that
40
+ * any combination of at least threshold shares should either succesfully combine to the plaintext or fail.
41
+ * This is useful in case the encryptor is not trusted and the decryptor wants to ensure all decryptors
42
+ * receive the same output (e.g., for onchain encrypted voting).
43
+ *
44
+ * @param data - The encrypted bytes to decrypt.
45
+ * @param sessionKey - The session key to use.
46
+ * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
47
+ * @param checkShareConsistency - If true, the shares are checked for consistency.
48
+ * @param checkLEEncoding - If true, the encryption is also checked using an LE encoded nonce.
49
+ * @returns - The decrypted plaintext corresponding to ciphertext.
50
+ */
51
+ decrypt({ data, sessionKey, txBytes, checkShareConsistency, checkLEEncoding, }: DecryptOptions): Promise<Uint8Array<ArrayBufferLike>>;
52
+ getKeyServers(): Promise<Map<string, KeyServer>>;
53
+ /**
54
+ * Get the public keys for the given services.
55
+ * If all public keys are not in the cache, they are retrieved.
56
+ *
57
+ * @param services - The services to get the public keys for.
58
+ * @returns The public keys for the given services in the same order as the given services.
59
+ */
60
+ getPublicKeys(services: string[]): Promise<G2Element[]>;
61
+ /**
62
+ * Fetch keys from the key servers and update the cache.
63
+ *
64
+ * It is recommended to call this function once for all ids of all encrypted objects if
65
+ * there are multiple, then call decrypt for each object. This avoids calling fetchKey
66
+ * individually for each decrypt.
67
+ *
68
+ * @param ids - The ids of the encrypted objects.
69
+ * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
70
+ * @param sessionKey - The session key to use.
71
+ * @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.
72
+ */
73
+ fetchKeys({ ids, txBytes, sessionKey, threshold }: FetchKeysOptions): Promise<void>;
74
+ /**
75
+ * Get derived keys from the given services.
76
+ *
77
+ * @param id - The id of the encrypted object.
78
+ * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
79
+ * @param sessionKey - The session key to use.
80
+ * @param threshold - The threshold.
81
+ * @returns - Derived keys for the given services that are in the cache as a "service object ID" -> derived key map. If the call is succesful, exactly threshold keys will be returned.
82
+ */
83
+ getDerivedKeys({ kemType, id, txBytes, sessionKey, threshold, }: GetDerivedKeysOptions): Promise<Map<string, DerivedKey>>;
84
+ }
@@ -0,0 +1,407 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
+ var _haneulClient, _configs, _keyServers, _verifyKeyServers, _cachedKeys, _cachedPublicKeys, _timeout, _totalWeight, _SealClient_instances, createEncryptionInput_fn, weight_fn, validateEncryptionServices_fn, getWeightedKeyServers_fn, loadKeyServers_fn;
10
+ import { EncryptedObject } from "./bcs.js";
11
+ import { G1Element, G2Element } from "./bls12381.js";
12
+ import { decrypt } from "./decrypt.js";
13
+ import { AesGcm256, Hmac256Ctr } from "./dem.js";
14
+ import { DemType, encrypt, KemType } from "./encrypt.js";
15
+ import {
16
+ InconsistentKeyServersError,
17
+ InvalidClientOptionsError,
18
+ InvalidKeyServerError,
19
+ InvalidPackageError,
20
+ InvalidThresholdError,
21
+ toMajorityError,
22
+ TooManyFailedFetchKeyRequestsError
23
+ } from "./error.js";
24
+ import { BonehFranklinBLS12381Services } from "./ibe.js";
25
+ import {
26
+ BonehFranklinBLS12381DerivedKey,
27
+ retrieveKeyServers,
28
+ verifyKeyServer,
29
+ fetchKeysForAllIds
30
+ } from "./key-server.js";
31
+ import { createFullId, count } from "./utils.js";
32
+ function seal({ name = "seal", ...options }) {
33
+ return {
34
+ name,
35
+ register: (client) => {
36
+ return new SealClient({
37
+ haneulClient: client,
38
+ ...options
39
+ });
40
+ }
41
+ };
42
+ }
43
+ const _SealClient = class _SealClient {
44
+ constructor(options) {
45
+ __privateAdd(this, _SealClient_instances);
46
+ __privateAdd(this, _haneulClient);
47
+ __privateAdd(this, _configs);
48
+ __privateAdd(this, _keyServers, null);
49
+ __privateAdd(this, _verifyKeyServers);
50
+ // A caching map for: fullId:object_id -> partial key.
51
+ __privateAdd(this, _cachedKeys, /* @__PURE__ */ new Map());
52
+ __privateAdd(this, _cachedPublicKeys, /* @__PURE__ */ new Map());
53
+ __privateAdd(this, _timeout);
54
+ __privateAdd(this, _totalWeight);
55
+ __privateSet(this, _haneulClient, options.haneulClient);
56
+ if (new Set(options.serverConfigs.map((s) => s.objectId)).size !== options.serverConfigs.length) {
57
+ throw new InvalidClientOptionsError("Duplicate object IDs");
58
+ }
59
+ if (options.serverConfigs.some((s) => s.apiKeyName && !s.apiKey || !s.apiKeyName && s.apiKey)) {
60
+ throw new InvalidClientOptionsError(
61
+ "Both apiKeyName and apiKey must be provided or not provided for all key servers"
62
+ );
63
+ }
64
+ __privateSet(this, _configs, new Map(options.serverConfigs.map((server) => [server.objectId, server])));
65
+ __privateSet(this, _totalWeight, options.serverConfigs.map((server) => server.weight).reduce((sum, term) => sum + term, 0));
66
+ __privateSet(this, _verifyKeyServers, options.verifyKeyServers ?? true);
67
+ __privateSet(this, _timeout, options.timeout ?? 1e4);
68
+ }
69
+ /** @deprecated Use `seal()` instead */
70
+ static asClientExtension(options) {
71
+ return {
72
+ name: "seal",
73
+ register: (client) => {
74
+ return new _SealClient({
75
+ haneulClient: client,
76
+ ...options
77
+ });
78
+ }
79
+ };
80
+ }
81
+ /**
82
+ * Return an encrypted message under the identity.
83
+ *
84
+ * @param kemType - The type of KEM to use.
85
+ * @param demType - The type of DEM to use.
86
+ * @param threshold - The threshold for the TSS encryption.
87
+ * @param packageId - the packageId namespace.
88
+ * @param id - the identity to use.
89
+ * @param data - the data to encrypt.
90
+ * @param aad - optional additional authenticated data.
91
+ * @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.
92
+ * Since the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.
93
+ */
94
+ async encrypt({
95
+ kemType = KemType.BonehFranklinBLS12381DemCCA,
96
+ demType = DemType.AesGcm256,
97
+ threshold,
98
+ packageId,
99
+ id,
100
+ data,
101
+ aad = new Uint8Array()
102
+ }) {
103
+ const packageObj = await __privateGet(this, _haneulClient).core.getObject({ objectId: packageId });
104
+ if (String(packageObj.object.version) !== "1") {
105
+ throw new InvalidPackageError(`Package ${packageId} is not the first version`);
106
+ }
107
+ return encrypt({
108
+ keyServers: await __privateMethod(this, _SealClient_instances, getWeightedKeyServers_fn).call(this),
109
+ kemType,
110
+ threshold,
111
+ packageId,
112
+ id,
113
+ encryptionInput: __privateMethod(this, _SealClient_instances, createEncryptionInput_fn).call(this, demType, data, aad)
114
+ });
115
+ }
116
+ /**
117
+ * Decrypt the given encrypted bytes using cached keys.
118
+ * Calls fetchKeys in case one or more of the required keys is not cached yet.
119
+ * The function throws an error if the client's key servers are not a subset of
120
+ * the encrypted object's key servers or if the threshold cannot be met.
121
+ *
122
+ * If checkShareConsistency is true, the decrypted shares are checked for consistency, meaning that
123
+ * any combination of at least threshold shares should either succesfully combine to the plaintext or fail.
124
+ * This is useful in case the encryptor is not trusted and the decryptor wants to ensure all decryptors
125
+ * receive the same output (e.g., for onchain encrypted voting).
126
+ *
127
+ * @param data - The encrypted bytes to decrypt.
128
+ * @param sessionKey - The session key to use.
129
+ * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
130
+ * @param checkShareConsistency - If true, the shares are checked for consistency.
131
+ * @param checkLEEncoding - If true, the encryption is also checked using an LE encoded nonce.
132
+ * @returns - The decrypted plaintext corresponding to ciphertext.
133
+ */
134
+ async decrypt({
135
+ data,
136
+ sessionKey,
137
+ txBytes,
138
+ checkShareConsistency,
139
+ checkLEEncoding
140
+ }) {
141
+ const encryptedObject = EncryptedObject.parse(data);
142
+ __privateMethod(this, _SealClient_instances, validateEncryptionServices_fn).call(this, encryptedObject.services.map((s) => s[0]), encryptedObject.threshold);
143
+ await this.fetchKeys({
144
+ ids: [encryptedObject.id],
145
+ txBytes,
146
+ sessionKey,
147
+ threshold: encryptedObject.threshold
148
+ });
149
+ if (checkShareConsistency) {
150
+ const publicKeys = await this.getPublicKeys(
151
+ encryptedObject.services.map(([objectId, _]) => objectId)
152
+ );
153
+ return decrypt({
154
+ encryptedObject,
155
+ keys: __privateGet(this, _cachedKeys),
156
+ publicKeys,
157
+ checkLEEncoding: false
158
+ // We intentionally do not support other encodings here
159
+ });
160
+ }
161
+ return decrypt({ encryptedObject, keys: __privateGet(this, _cachedKeys), checkLEEncoding });
162
+ }
163
+ async getKeyServers() {
164
+ if (!__privateGet(this, _keyServers)) {
165
+ __privateSet(this, _keyServers, __privateMethod(this, _SealClient_instances, loadKeyServers_fn).call(this).catch((error) => {
166
+ __privateSet(this, _keyServers, null);
167
+ throw error;
168
+ }));
169
+ }
170
+ return __privateGet(this, _keyServers);
171
+ }
172
+ /**
173
+ * Get the public keys for the given services.
174
+ * If all public keys are not in the cache, they are retrieved.
175
+ *
176
+ * @param services - The services to get the public keys for.
177
+ * @returns The public keys for the given services in the same order as the given services.
178
+ */
179
+ async getPublicKeys(services) {
180
+ const keyServers = await this.getKeyServers();
181
+ const missingKeyServers = services.filter(
182
+ (objectId) => !keyServers.has(objectId) && !__privateGet(this, _cachedPublicKeys).has(objectId)
183
+ );
184
+ if (missingKeyServers.length > 0) {
185
+ (await retrieveKeyServers({
186
+ objectIds: missingKeyServers,
187
+ client: __privateGet(this, _haneulClient)
188
+ })).forEach(
189
+ (keyServer) => __privateGet(this, _cachedPublicKeys).set(keyServer.objectId, G2Element.fromBytes(keyServer.pk))
190
+ );
191
+ }
192
+ return services.map((objectId) => {
193
+ const keyServer = keyServers.get(objectId);
194
+ if (keyServer) {
195
+ return G2Element.fromBytes(keyServer.pk);
196
+ }
197
+ return __privateGet(this, _cachedPublicKeys).get(objectId);
198
+ });
199
+ }
200
+ /**
201
+ * Fetch keys from the key servers and update the cache.
202
+ *
203
+ * It is recommended to call this function once for all ids of all encrypted objects if
204
+ * there are multiple, then call decrypt for each object. This avoids calling fetchKey
205
+ * individually for each decrypt.
206
+ *
207
+ * @param ids - The ids of the encrypted objects.
208
+ * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
209
+ * @param sessionKey - The session key to use.
210
+ * @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.
211
+ */
212
+ async fetchKeys({ ids, txBytes, sessionKey, threshold }) {
213
+ if (threshold > __privateGet(this, _totalWeight) || threshold < 1) {
214
+ throw new InvalidThresholdError(
215
+ `Invalid threshold ${threshold} servers with weights ${JSON.stringify(__privateGet(this, _configs))}`
216
+ );
217
+ }
218
+ const keyServers = await this.getKeyServers();
219
+ const fullIds = ids.map((id) => createFullId(sessionKey.getPackageId(), id));
220
+ let completedWeight = 0;
221
+ const remainingKeyServers = [];
222
+ let remainingKeyServersWeight = 0;
223
+ for (const objectId of keyServers.keys()) {
224
+ if (fullIds.every((fullId) => __privateGet(this, _cachedKeys).has(`${fullId}:${objectId}`))) {
225
+ completedWeight += __privateMethod(this, _SealClient_instances, weight_fn).call(this, objectId);
226
+ } else {
227
+ remainingKeyServers.push(objectId);
228
+ remainingKeyServersWeight += __privateMethod(this, _SealClient_instances, weight_fn).call(this, objectId);
229
+ }
230
+ }
231
+ if (completedWeight >= threshold) {
232
+ return;
233
+ }
234
+ const certificate = await sessionKey.getCertificate();
235
+ const signedRequest = await sessionKey.createRequestParams(txBytes);
236
+ const controller = new AbortController();
237
+ const errors = [];
238
+ const keyFetches = remainingKeyServers.map(async (objectId) => {
239
+ const server = keyServers.get(objectId);
240
+ try {
241
+ const config = __privateGet(this, _configs).get(objectId);
242
+ const allKeys = await fetchKeysForAllIds({
243
+ url: server.url,
244
+ requestSignature: signedRequest.requestSignature,
245
+ transactionBytes: txBytes,
246
+ encKey: signedRequest.encKey,
247
+ encKeyPk: signedRequest.encKeyPk,
248
+ encVerificationKey: signedRequest.encVerificationKey,
249
+ certificate,
250
+ timeout: __privateGet(this, _timeout),
251
+ apiKeyName: config?.apiKeyName,
252
+ apiKey: config?.apiKey,
253
+ signal: controller.signal
254
+ });
255
+ for (const { fullId, key } of allKeys) {
256
+ const keyElement = G1Element.fromBytes(key);
257
+ if (!BonehFranklinBLS12381Services.verifyUserSecretKey(
258
+ keyElement,
259
+ fullId,
260
+ G2Element.fromBytes(server.pk)
261
+ )) {
262
+ console.warn("Received invalid key from key server " + server.objectId);
263
+ continue;
264
+ }
265
+ __privateGet(this, _cachedKeys).set(`${fullId}:${server.objectId}`, keyElement);
266
+ }
267
+ if (fullIds.every((fullId) => __privateGet(this, _cachedKeys).has(`${fullId}:${server.objectId}`))) {
268
+ completedWeight += __privateMethod(this, _SealClient_instances, weight_fn).call(this, objectId);
269
+ if (completedWeight >= threshold) {
270
+ controller.abort();
271
+ }
272
+ }
273
+ } catch (error) {
274
+ if (!controller.signal.aborted) {
275
+ errors.push(error);
276
+ }
277
+ } finally {
278
+ remainingKeyServersWeight -= __privateMethod(this, _SealClient_instances, weight_fn).call(this, objectId);
279
+ if (remainingKeyServersWeight < threshold - completedWeight) {
280
+ controller.abort(new TooManyFailedFetchKeyRequestsError());
281
+ }
282
+ }
283
+ });
284
+ await Promise.allSettled(keyFetches);
285
+ if (completedWeight < threshold) {
286
+ throw toMajorityError(errors);
287
+ }
288
+ }
289
+ /**
290
+ * Get derived keys from the given services.
291
+ *
292
+ * @param id - The id of the encrypted object.
293
+ * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
294
+ * @param sessionKey - The session key to use.
295
+ * @param threshold - The threshold.
296
+ * @returns - Derived keys for the given services that are in the cache as a "service object ID" -> derived key map. If the call is succesful, exactly threshold keys will be returned.
297
+ */
298
+ async getDerivedKeys({
299
+ kemType = KemType.BonehFranklinBLS12381DemCCA,
300
+ id,
301
+ txBytes,
302
+ sessionKey,
303
+ threshold
304
+ }) {
305
+ switch (kemType) {
306
+ case KemType.BonehFranklinBLS12381DemCCA:
307
+ const keyServers = await this.getKeyServers();
308
+ if (threshold > __privateGet(this, _totalWeight)) {
309
+ throw new InvalidThresholdError(
310
+ `Invalid threshold ${threshold} for ${__privateGet(this, _totalWeight)} servers`
311
+ );
312
+ }
313
+ await this.fetchKeys({
314
+ ids: [id],
315
+ txBytes,
316
+ sessionKey,
317
+ threshold
318
+ });
319
+ const fullId = createFullId(sessionKey.getPackageId(), id);
320
+ const derivedKeys = /* @__PURE__ */ new Map();
321
+ let weight = 0;
322
+ for (const objectId of keyServers.keys()) {
323
+ const cachedKey = __privateGet(this, _cachedKeys).get(`${fullId}:${objectId}`);
324
+ if (cachedKey) {
325
+ derivedKeys.set(objectId, new BonehFranklinBLS12381DerivedKey(cachedKey));
326
+ weight += __privateMethod(this, _SealClient_instances, weight_fn).call(this, objectId);
327
+ if (weight >= threshold) {
328
+ break;
329
+ }
330
+ }
331
+ }
332
+ return derivedKeys;
333
+ }
334
+ }
335
+ };
336
+ _haneulClient = new WeakMap();
337
+ _configs = new WeakMap();
338
+ _keyServers = new WeakMap();
339
+ _verifyKeyServers = new WeakMap();
340
+ _cachedKeys = new WeakMap();
341
+ _cachedPublicKeys = new WeakMap();
342
+ _timeout = new WeakMap();
343
+ _totalWeight = new WeakMap();
344
+ _SealClient_instances = new WeakSet();
345
+ createEncryptionInput_fn = function(type, data, aad) {
346
+ switch (type) {
347
+ case DemType.AesGcm256:
348
+ return new AesGcm256(data, aad);
349
+ case DemType.Hmac256Ctr:
350
+ return new Hmac256Ctr(data, aad);
351
+ }
352
+ };
353
+ weight_fn = function(objectId) {
354
+ return __privateGet(this, _configs).get(objectId)?.weight ?? 0;
355
+ };
356
+ validateEncryptionServices_fn = function(services, threshold) {
357
+ if (services.some((objectId) => {
358
+ const countInClient = __privateMethod(this, _SealClient_instances, weight_fn).call(this, objectId);
359
+ return countInClient > 0 && countInClient !== count(services, objectId);
360
+ })) {
361
+ throw new InconsistentKeyServersError(
362
+ `Client's key servers must be a subset of the encrypted object's key servers`
363
+ );
364
+ }
365
+ if (threshold > __privateGet(this, _totalWeight)) {
366
+ throw new InvalidThresholdError(
367
+ `Invalid threshold ${threshold} for ${__privateGet(this, _totalWeight)} servers`
368
+ );
369
+ }
370
+ };
371
+ getWeightedKeyServers_fn = async function() {
372
+ const keyServers = await this.getKeyServers();
373
+ const keyServersWithMultiplicity = [];
374
+ for (const [objectId, config] of __privateGet(this, _configs)) {
375
+ const keyServer = keyServers.get(objectId);
376
+ for (let i = 0; i < config.weight; i++) {
377
+ keyServersWithMultiplicity.push(keyServer);
378
+ }
379
+ }
380
+ return keyServersWithMultiplicity;
381
+ };
382
+ loadKeyServers_fn = async function() {
383
+ const keyServers = await retrieveKeyServers({
384
+ objectIds: [...__privateGet(this, _configs)].map(([objectId]) => objectId),
385
+ client: __privateGet(this, _haneulClient)
386
+ });
387
+ if (keyServers.length === 0) {
388
+ throw new InvalidKeyServerError("No key servers found");
389
+ }
390
+ if (__privateGet(this, _verifyKeyServers)) {
391
+ await Promise.all(
392
+ keyServers.map(async (server) => {
393
+ const config = __privateGet(this, _configs).get(server.objectId);
394
+ if (!await verifyKeyServer(server, __privateGet(this, _timeout), config?.apiKeyName, config?.apiKey)) {
395
+ throw new InvalidKeyServerError(`Key server ${server.objectId} is not valid`);
396
+ }
397
+ })
398
+ );
399
+ }
400
+ return new Map(keyServers.map((server) => [server.objectId, server]));
401
+ };
402
+ let SealClient = _SealClient;
403
+ export {
404
+ SealClient,
405
+ seal
406
+ };
407
+ //# sourceMappingURL=client.js.map