@mysten/seal 0.2.0 → 0.3.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 (108) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/cjs/bcs.d.ts +132 -0
  3. package/dist/cjs/bcs.js +67 -0
  4. package/dist/cjs/bcs.js.map +7 -0
  5. package/dist/cjs/client.d.ts +83 -0
  6. package/dist/cjs/client.js +283 -0
  7. package/dist/cjs/client.js.map +7 -0
  8. package/dist/cjs/decrypt.d.ts +15 -0
  9. package/dist/cjs/decrypt.js +93 -0
  10. package/dist/cjs/decrypt.js.map +7 -0
  11. package/dist/cjs/dem.d.ts +36 -0
  12. package/dist/cjs/dem.js +173 -0
  13. package/dist/cjs/dem.js.map +7 -0
  14. package/dist/cjs/elgamal.js.map +2 -2
  15. package/dist/cjs/encrypt.d.ts +14 -5
  16. package/dist/cjs/encrypt.js +51 -21
  17. package/dist/cjs/encrypt.js.map +3 -3
  18. package/dist/cjs/error.d.ts +58 -0
  19. package/dist/cjs/error.js +175 -0
  20. package/dist/cjs/error.js.map +7 -0
  21. package/dist/cjs/ibe.d.ts +10 -14
  22. package/dist/cjs/ibe.js +23 -26
  23. package/dist/cjs/ibe.js.map +2 -2
  24. package/dist/cjs/index.d.ts +2 -5
  25. package/dist/cjs/index.js +3 -11
  26. package/dist/cjs/index.js.map +2 -2
  27. package/dist/cjs/kdf.d.ts +5 -0
  28. package/dist/cjs/kdf.js +28 -1
  29. package/dist/cjs/kdf.js.map +3 -3
  30. package/dist/cjs/key-server.d.ts +5 -5
  31. package/dist/cjs/key-server.js +24 -21
  32. package/dist/cjs/key-server.js.map +2 -2
  33. package/dist/cjs/keys.d.ts +17 -0
  34. package/dist/cjs/keys.js +61 -0
  35. package/dist/cjs/keys.js.map +7 -0
  36. package/dist/cjs/session-key.d.ts +20 -14
  37. package/dist/cjs/session-key.js +90 -23
  38. package/dist/cjs/session-key.js.map +2 -2
  39. package/dist/cjs/types.d.ts +1 -86
  40. package/dist/cjs/types.js +0 -32
  41. package/dist/cjs/types.js.map +2 -2
  42. package/dist/cjs/utils.d.ts +2 -1
  43. package/dist/cjs/utils.js +17 -5
  44. package/dist/cjs/utils.js.map +2 -2
  45. package/dist/cjs/version.d.ts +1 -0
  46. package/dist/cjs/version.js +25 -0
  47. package/dist/cjs/version.js.map +7 -0
  48. package/dist/esm/bcs.d.ts +132 -0
  49. package/dist/esm/bcs.js +47 -0
  50. package/dist/esm/bcs.js.map +7 -0
  51. package/dist/esm/client.d.ts +83 -0
  52. package/dist/esm/client.js +268 -0
  53. package/dist/esm/client.js.map +7 -0
  54. package/dist/esm/decrypt.d.ts +15 -0
  55. package/dist/esm/decrypt.js +73 -0
  56. package/dist/esm/decrypt.js.map +7 -0
  57. package/dist/esm/dem.d.ts +36 -0
  58. package/dist/esm/dem.js +153 -0
  59. package/dist/esm/dem.js.map +7 -0
  60. package/dist/esm/elgamal.js.map +2 -2
  61. package/dist/esm/encrypt.d.ts +14 -5
  62. package/dist/esm/encrypt.js +48 -18
  63. package/dist/esm/encrypt.js.map +3 -3
  64. package/dist/esm/error.d.ts +58 -0
  65. package/dist/esm/error.js +155 -0
  66. package/dist/esm/error.js.map +7 -0
  67. package/dist/esm/ibe.d.ts +10 -14
  68. package/dist/esm/ibe.js +23 -26
  69. package/dist/esm/ibe.js.map +2 -2
  70. package/dist/esm/index.d.ts +2 -5
  71. package/dist/esm/index.js +4 -16
  72. package/dist/esm/index.js.map +2 -2
  73. package/dist/esm/kdf.d.ts +5 -0
  74. package/dist/esm/kdf.js +28 -1
  75. package/dist/esm/kdf.js.map +3 -3
  76. package/dist/esm/key-server.d.ts +5 -5
  77. package/dist/esm/key-server.js +29 -21
  78. package/dist/esm/key-server.js.map +2 -2
  79. package/dist/esm/keys.d.ts +17 -0
  80. package/dist/esm/keys.js +41 -0
  81. package/dist/esm/keys.js.map +7 -0
  82. package/dist/esm/session-key.d.ts +20 -14
  83. package/dist/esm/session-key.js +95 -24
  84. package/dist/esm/session-key.js.map +2 -2
  85. package/dist/esm/types.d.ts +1 -86
  86. package/dist/esm/types.js +0 -28
  87. package/dist/esm/types.js.map +3 -3
  88. package/dist/esm/utils.d.ts +2 -1
  89. package/dist/esm/utils.js +17 -5
  90. package/dist/esm/utils.js.map +2 -2
  91. package/dist/esm/version.d.ts +1 -0
  92. package/dist/esm/version.js +5 -0
  93. package/dist/esm/version.js.map +7 -0
  94. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  95. package/dist/tsconfig.tsbuildinfo +1 -1
  96. package/package.json +6 -5
  97. package/dist/cjs/aes.d.ts +0 -18
  98. package/dist/cjs/aes.js +0 -111
  99. package/dist/cjs/aes.js.map +0 -7
  100. package/dist/cjs/key-store.d.ts +0 -49
  101. package/dist/cjs/key-store.js +0 -203
  102. package/dist/cjs/key-store.js.map +0 -7
  103. package/dist/esm/aes.d.ts +0 -18
  104. package/dist/esm/aes.js +0 -91
  105. package/dist/esm/aes.js.map +0 -7
  106. package/dist/esm/key-store.d.ts +0 -49
  107. package/dist/esm/key-store.js +0 -183
  108. package/dist/esm/key-store.js.map +0 -7
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/error.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nexport class SealError extends Error {}\n\nexport class UserError extends SealError {}\n\n// Errors returned by the Seal server\nexport class SealAPIError extends SealError {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic requestId?: string,\n\t\tpublic status?: number,\n\t) {\n\t\tsuper(message);\n\t}\n\n\tstatic #generate(message: string, requestId: string, status?: number) {\n\t\tswitch (message) {\n\t\t\tcase 'InvalidPTB':\n\t\t\t\treturn new InvalidPTBError(requestId);\n\t\t\tcase 'InvalidPackage':\n\t\t\t\treturn new InvalidPackageError(requestId);\n\t\t\tcase 'NoAccess':\n\t\t\t\treturn new NoAccessError(requestId);\n\t\t\tcase 'InvalidCertificate':\n\t\t\t\treturn new ExpiredSessionKeyError(requestId);\n\t\t\tcase 'OldPackageVersion':\n\t\t\t\treturn new OldPackageError(requestId);\n\t\t\tcase 'InvalidSignature':\n\t\t\t\treturn new InvalidUserSignatureError(requestId);\n\t\t\tcase 'InvalidSessionSignature':\n\t\t\t\treturn new InvalidSessionKeySignatureError(requestId);\n\t\t\tcase 'Failure':\n\t\t\t\treturn new InternalError(requestId);\n\t\t\tdefault:\n\t\t\t\treturn new GeneralError(message, requestId, status);\n\t\t}\n\t}\n\n\tstatic async assertResponse(response: Response, requestId: string) {\n\t\tif (response.ok) {\n\t\t\treturn;\n\t\t}\n\t\tlet errorInstance: SealAPIError;\n\t\ttry {\n\t\t\tconst text = await response.text();\n\t\t\tconst error = JSON.parse(text)['error'];\n\t\t\terrorInstance = SealAPIError.#generate(error, requestId);\n\t\t} catch (e) {\n\t\t\t// If we can't parse the response as JSON or if it doesn't have the expected format,\n\t\t\t// fall back to using the status text\n\t\t\terrorInstance = new GeneralError(response.statusText, requestId, response.status);\n\t\t}\n\t\tthrow errorInstance;\n\t}\n}\n\n// Errors returned by the Seal server that indicate that the PTB is invalid\n\nexport class InvalidPTBError extends SealAPIError {\n\tconstructor(requestId?: string) {\n\t\tsuper('PTB does not conform to the expected format', requestId);\n\t}\n}\n\nexport class InvalidPackageError extends SealAPIError {\n\tconstructor(requestId?: string) {\n\t\tsuper('Package ID used in PTB is invalid', requestId);\n\t}\n}\n\nexport class OldPackageError extends SealAPIError {\n\tconstructor(requestId?: string) {\n\t\tsuper('PTB must call the latest version of the package', requestId);\n\t}\n}\n\n// Errors returned by the Seal server that indicate that the user's signature is invalid\n\nexport class InvalidUserSignatureError extends SealAPIError {\n\tconstructor(requestId?: string) {\n\t\tsuper('User signature on the session key is invalid', requestId);\n\t}\n}\n\nexport class InvalidSessionKeySignatureError extends SealAPIError {\n\tconstructor(requestId?: string) {\n\t\tsuper('Session key signature is invalid', requestId);\n\t}\n}\n\n/** Server error indicating that the user does not have access to one or more of the requested keys */\nexport class NoAccessError extends SealAPIError {\n\tconstructor(requestId?: string) {\n\t\tsuper('User does not have access to one or more of the requested keys', requestId);\n\t}\n}\n\n/** Server error indicating that the session key has expired */\nexport class ExpiredSessionKeyError extends SealAPIError {\n\tconstructor(requestId?: string) {\n\t\tsuper('Session key has expired', requestId);\n\t}\n}\n\n/** Internal server error, caller should retry */\nexport class InternalError extends SealAPIError {\n\tconstructor(requestId?: string) {\n\t\tsuper('Internal server error, caller should retry', requestId);\n\t}\n}\n\n/** General server errors that are not specific to the Seal API (e.g., 404 \"Not Found\") */\nexport class GeneralError extends SealAPIError {}\n\n// Errors returned by the SDK\nexport class InvalidPersonalMessageSignatureError extends UserError {}\nexport class InvalidGetObjectError extends UserError {}\nexport class UnsupportedFeatureError extends UserError {}\nexport class UnsupportedNetworkError extends UserError {}\nexport class InvalidKeyServerError extends UserError {}\nexport class InvalidCiphertextError extends UserError {}\nexport class InvalidThresholdError extends UserError {}\nexport class InconsistentKeyServersError extends UserError {}\n\nexport function toMajorityError(errors: Error[]): Error {\n\tlet maxCount = 0;\n\tlet majorityError = errors[0];\n\tconst counts = new Map<string, number>();\n\tfor (const error of errors) {\n\t\tconst errorName = error.constructor.name;\n\t\tconst newCount = (counts.get(errorName) || 0) + 1;\n\t\tcounts.set(errorName, newCount);\n\n\t\tif (newCount > maxCount) {\n\t\t\tmaxCount = newCount;\n\t\t\tmajorityError = error;\n\t\t}\n\t}\n\n\treturn majorityError;\n}\n"],
5
+ "mappings": ";;;;;;AAAA;AAGO,MAAM,kBAAkB,MAAM;AAAC;AAE/B,MAAM,kBAAkB,UAAU;AAAC;AAGnC,MAAM,gBAAN,MAAM,sBAAqB,UAAU;AAAA,EAC3C,YACC,SACO,WACA,QACN;AACD,UAAM,OAAO;AAHN;AACA;AAAA,EAGR;AAAA,EAyBA,aAAa,eAAe,UAAoB,WAAmB;AAxCpE;AAyCE,QAAI,SAAS,IAAI;AAChB;AAAA,IACD;A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AEO,MAAM,wCAAwC,aAAa;AAAA,EACjE,YAAY,WAAoB;AAC/B,UAAM,oCAAoC,SAAS;AAAA,EACpD;AACD;AAGO,MAAM,sBAAsB,aAAa;AAAA,EAC/C,YAAY,WAAoB;AAC/B,UAAM,kEAAkE,SAAS;AAAA,EAClF;AACD;AAGO,MAAM,+BAA+B,aAAa;AAAA,EACxD,YAAY,WAAoB;AAC/B,UAAM,2BAA2B,SAAS;AAAA,EAC3C;AACD;AAGO,MAAM,sBAAsB,aAAa;AAAA,EAC/C,YAAY,WAAoB;AAC/B,UAAM,8CAA8C,SAAS;AAAA,EAC9D;AACD;AAGO,MAAM,qBAAqB,aAAa;AAAC;AAGzC,MAAM,6CAA6C,UAAU;AAAC;AAC9D,MAAM,8BAA8B,UAAU;AAAC;AAC/C,MAAM,gCAAgC,UAAU;AAAC;AACjD,MAAM,gCAAgC,UAAU;AAAC;AACjD,MAAM,8BAA8B,UAAU;AAAC;AAC/C,MAAM,+BAA+B,UAAU;AAAC;AAChD,MAAM,8BAA8B,UAAU;AAAC;AAC/C,MAAM,oCAAoC,UAAU;AAAC;AAErD,SAAS,gBAAgB,QAAwB;AACvD,MAAI,WAAW;AACf,MAAI,gBAAgB,OAAO,CAAC;AAC5B,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,SAAS,QAAQ;AAC3B,UAAM,YAAY,MAAM,YAAY;AACpC,UAAM,YAAY,OAAO,IAAI,SAAS,KAAK,KAAK;AAChD,WAAO,IAAI,WAAW,QAAQ;AAE9B,QAAI,WAAW,UAAU;AACxB,iBAAW;AACX,sBAAgB;AAAA,IACjB;AAAA,EACD;AAEA,SAAO;AACR;",
6
+ "names": []
7
+ }
package/dist/esm/ibe.d.ts CHANGED
@@ -1,6 +1,6 @@
1
+ import type { IBEEncryptions } from './bcs.js';
1
2
  import { G1Element, G2Element } from './bls12381.js';
2
3
  import type { KeyServer } from './key-server.js';
3
- import type { IBEEncryptionsType } from './types.js';
4
4
  /**
5
5
  * The domain separation tag for the hash-to-group function.
6
6
  */
@@ -13,12 +13,8 @@ export declare const DST_POP: Uint8Array;
13
13
  * The interface for the key servers.
14
14
  */
15
15
  export declare abstract class IBEServers {
16
- protected readonly object_ids: Uint8Array[];
17
- protected constructor(object_ids: Uint8Array[]);
18
- /**
19
- * The object IDs of the key servers.
20
- */
21
- getObjectIds(): Uint8Array[];
16
+ objectIds: string[];
17
+ constructor(objectIds: string[]);
22
18
  /**
23
19
  * The number of key servers.
24
20
  */
@@ -27,25 +23,25 @@ export declare abstract class IBEServers {
27
23
  * Encrypt a batch of messages for the given identity.
28
24
  *
29
25
  * @param id The identity.
30
- * @param msg_and_infos The messages and an additional info parameter which will be included in the KDF.
26
+ * @param msgAndInfos The messages and an additional info parameter which will be included in the KDF.
31
27
  * @returns The encrypted messages.
32
28
  */
33
- abstract encryptBatched(id: Uint8Array, msg_and_infos: {
29
+ abstract encryptBatched(id: Uint8Array, msgAndInfos: {
34
30
  msg: Uint8Array;
35
31
  info: Uint8Array;
36
- }[]): IBEEncryptionsType;
32
+ }[], randomnessKey: Uint8Array): typeof IBEEncryptions.$inferType;
37
33
  }
38
34
  /**
39
35
  * Identity-based encryption based on the Boneh-Franklin IBE scheme.
40
36
  * This object represents a set of key servers that can be used to encrypt messages for a given identity.
41
37
  */
42
38
  export declare class BonehFranklinBLS12381Services extends IBEServers {
43
- readonly public_keys: G2Element[];
39
+ readonly publicKeys: G2Element[];
44
40
  constructor(services: KeyServer[]);
45
- encryptBatched(id: Uint8Array, msg_and_infos: {
41
+ encryptBatched(id: Uint8Array, msgAndInfos: {
46
42
  msg: Uint8Array;
47
43
  info: Uint8Array;
48
- }[]): IBEEncryptionsType;
44
+ }[], randomnessKey: Uint8Array): typeof IBEEncryptions.$inferType;
49
45
  /**
50
46
  * Returns true if the user secret key is valid for the given public key and id.
51
47
  * @param user_secret_key - The user secret key.
@@ -53,7 +49,7 @@ export declare class BonehFranklinBLS12381Services extends IBEServers {
53
49
  * @param public_key - The public key.
54
50
  * @returns True if the user secret key is valid for the given public key and id.
55
51
  */
56
- static verifyUserSecretKey(user_secret_key: G1Element, id: Uint8Array, public_key: G2Element): boolean;
52
+ static verifyUserSecretKey(userSecretKey: G1Element, id: string, publicKey: G2Element): boolean;
57
53
  /**
58
54
  * Identity-based decryption.
59
55
  *
package/dist/esm/ibe.js CHANGED
@@ -1,42 +1,39 @@
1
+ import { fromHex } from "@mysten/bcs";
1
2
  import { G1Element, G2Element, Scalar } from "./bls12381.js";
2
3
  import { kdf } from "./kdf.js";
3
4
  import { xor } from "./utils.js";
4
5
  const DST = new TextEncoder().encode("SUI-SEAL-IBE-BLS12381-00");
5
- const DST_POP = new TextEncoder().encode("SUI-SEAL-IBE-BLS12381-00-POP");
6
+ const DST_POP = new TextEncoder().encode("SUI-SEAL-IBE-BLS12381-POP-00");
6
7
  class IBEServers {
7
- constructor(object_ids) {
8
- this.object_ids = object_ids;
9
- }
10
- /**
11
- * The object IDs of the key servers.
12
- */
13
- getObjectIds() {
14
- return this.object_ids;
8
+ constructor(objectIds) {
9
+ this.objectIds = objectIds;
15
10
  }
16
11
  /**
17
12
  * The number of key servers.
18
13
  */
19
14
  size() {
20
- return this.object_ids.length;
15
+ return this.objectIds.length;
21
16
  }
22
17
  }
23
18
  class BonehFranklinBLS12381Services extends IBEServers {
24
19
  constructor(services) {
25
20
  super(services.map((service) => service.objectId));
26
- this.public_keys = services.map((service) => G2Element.fromBytes(service.pk));
21
+ this.publicKeys = services.map((service) => G2Element.fromBytes(service.pk));
27
22
  }
28
- encryptBatched(id, msg_and_infos) {
29
- if (this.public_keys.length === 0 || this.public_keys.length !== msg_and_infos.length) {
30
- throw new Error("Invalid input");
23
+ encryptBatched(id, msgAndInfos, randomnessKey) {
24
+ if (this.publicKeys.length === 0 || this.publicKeys.length !== msgAndInfos.length) {
25
+ throw new Error("Invalid public keys");
31
26
  }
32
- const [nonce, keys] = encapBatched(this.public_keys, id);
33
- const encrypted_msgs = msg_and_infos.map(
34
- (msg_and_info, i) => xor(msg_and_info.msg, kdf(keys[i], msg_and_info.info))
27
+ const [r, nonce, keys] = encapBatched(this.publicKeys, id);
28
+ const encryptedShares = msgAndInfos.map(
29
+ (msgAndInfo, i) => xor(msgAndInfo.msg, kdf(keys[i], msgAndInfo.info))
35
30
  );
31
+ const encryptedRandomness = xor(randomnessKey, r.toBytes());
36
32
  return {
37
33
  BonehFranklinBLS12381: {
38
- encapsulation: nonce.toBytes(),
39
- shares: encrypted_msgs
34
+ nonce: nonce.toBytes(),
35
+ encryptedShares,
36
+ encryptedRandomness
40
37
  },
41
38
  $kind: "BonehFranklinBLS12381"
42
39
  };
@@ -48,9 +45,9 @@ class BonehFranklinBLS12381Services extends IBEServers {
48
45
  * @param public_key - The public key.
49
46
  * @returns True if the user secret key is valid for the given public key and id.
50
47
  */
51
- static verifyUserSecretKey(user_secret_key, id, public_key) {
52
- const lhs = user_secret_key.pairing(G2Element.generator()).toBytes();
53
- const rhs = G1Element.hashToCurve(id).pairing(public_key).toBytes();
48
+ static verifyUserSecretKey(userSecretKey, id, publicKey) {
49
+ const lhs = userSecretKey.pairing(G2Element.generator()).toBytes();
50
+ const rhs = G1Element.hashToCurve(fromHex(id)).pairing(publicKey).toBytes();
54
51
  return lhs.length === rhs.length && lhs.every((value, index) => value === rhs[index]);
55
52
  }
56
53
  /**
@@ -66,14 +63,14 @@ class BonehFranklinBLS12381Services extends IBEServers {
66
63
  return xor(ciphertext, kdf(decap(nonce, sk), info));
67
64
  }
68
65
  }
69
- function encapBatched(public_keys, id) {
70
- if (public_keys.length === 0) {
71
- throw new Error("Invalid input");
66
+ function encapBatched(publicKeys, id) {
67
+ if (publicKeys.length === 0) {
68
+ throw new Error("No public keys provided");
72
69
  }
73
70
  const r = Scalar.random();
74
71
  const nonce = G2Element.generator().multiply(r);
75
72
  const gid = G1Element.hashToCurve(id).multiply(r);
76
- return [nonce, public_keys.map((public_key) => gid.pairing(public_key))];
73
+ return [r, nonce, publicKeys.map((public_key) => gid.pairing(public_key))];
77
74
  }
78
75
  function decap(nonce, usk) {
79
76
  return usk.pairing(nonce);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/ibe.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { GTElement } from './bls12381.js';\nimport { G1Element, G2Element, Scalar } from './bls12381.js';\nimport { kdf } from './kdf.js';\nimport type { KeyServer } from './key-server.js';\nimport type { IBEEncryptionsType } from './types.js';\nimport { xor } from './utils.js';\n\n/**\n * The domain separation tag for the hash-to-group function.\n */\nexport const DST: Uint8Array = new TextEncoder().encode('SUI-SEAL-IBE-BLS12381-00');\n\n/**\n * The domain separation tag for the signing proof of possession.\n */\nexport const DST_POP: Uint8Array = new TextEncoder().encode('SUI-SEAL-IBE-BLS12381-00-POP');\n\n/**\n * The interface for the key servers.\n */\nexport abstract class IBEServers {\n\tprotected readonly object_ids: Uint8Array[];\n\n\tprotected constructor(object_ids: Uint8Array[]) {\n\t\tthis.object_ids = object_ids;\n\t}\n\n\t/**\n\t * The object IDs of the key servers.\n\t */\n\tgetObjectIds(): Uint8Array[] {\n\t\treturn this.object_ids;\n\t}\n\n\t/**\n\t * The number of key servers.\n\t */\n\tsize(): number {\n\t\treturn this.object_ids.length;\n\t}\n\n\t/**\n\t * Encrypt a batch of messages for the given identity.\n\t *\n\t * @param id The identity.\n\t * @param msg_and_infos The messages and an additional info parameter which will be included in the KDF.\n\t * @returns The encrypted messages.\n\t */\n\tabstract encryptBatched(\n\t\tid: Uint8Array,\n\t\tmsg_and_infos: { msg: Uint8Array; info: Uint8Array }[],\n\t): IBEEncryptionsType;\n}\n\n/**\n * Identity-based encryption based on the Boneh-Franklin IBE scheme.\n * This object represents a set of key servers that can be used to encrypt messages for a given identity.\n */\nexport class BonehFranklinBLS12381Services extends IBEServers {\n\treadonly public_keys: G2Element[];\n\n\tconstructor(services: KeyServer[]) {\n\t\tsuper(services.map((service) => service.objectId));\n\t\tthis.public_keys = services.map((service) => G2Element.fromBytes(service.pk));\n\t}\n\n\tencryptBatched(\n\t\tid: Uint8Array,\n\t\tmsg_and_infos: { msg: Uint8Array; info: Uint8Array }[],\n\t): IBEEncryptionsType {\n\t\tif (this.public_keys.length === 0 || this.public_keys.length !== msg_and_infos.length) {\n\t\t\tthrow new Error('Invalid input');\n\t\t}\n\t\tconst [nonce, keys] = encapBatched(this.public_keys, id);\n\t\tconst encrypted_msgs = msg_and_infos.map((msg_and_info, i) =>\n\t\t\txor(msg_and_info.msg, kdf(keys[i], msg_and_info.info)),\n\t\t);\n\n\t\treturn {\n\t\t\tBonehFranklinBLS12381: {\n\t\t\t\tencapsulation: nonce.toBytes(),\n\t\t\t\tshares: encrypted_msgs,\n\t\t\t},\n\t\t\t$kind: 'BonehFranklinBLS12381',\n\t\t};\n\t}\n\n\t/**\n\t * Returns true if the user secret key is valid for the given public key and id.\n\t * @param user_secret_key - The user secret key.\n\t * @param id - The identity.\n\t * @param public_key - The public key.\n\t * @returns True if the user secret key is valid for the given public key and id.\n\t */\n\tstatic verifyUserSecretKey(\n\t\tuser_secret_key: G1Element,\n\t\tid: Uint8Array,\n\t\tpublic_key: G2Element,\n\t): boolean {\n\t\tconst lhs = user_secret_key.pairing(G2Element.generator()).toBytes();\n\t\tconst rhs = G1Element.hashToCurve(id).pairing(public_key).toBytes();\n\t\treturn lhs.length === rhs.length && lhs.every((value, index) => value === rhs[index]);\n\t}\n\n\t/**\n\t * Identity-based decryption.\n\t *\n\t * @param nonce The encryption nonce.\n\t * @param sk The user secret key.\n\t * @param ciphertext The encrypted message.\n\t * @param info An info parameter also included in the KDF.\n\t * @returns The decrypted message.\n\t */\n\tstatic decrypt(\n\t\tnonce: G2Element,\n\t\tsk: G1Element,\n\t\tciphertext: Uint8Array,\n\t\tinfo: Uint8Array,\n\t): Uint8Array {\n\t\treturn xor(ciphertext, kdf(decap(nonce, sk), info));\n\t}\n}\n\n/**\n * Batched identity-based key-encapsulation mechanism: encapsulate multiple keys for given identity using different key servers.\n *\n * @param public_keys Public keys for a set of key servers.\n * @param id The identity used to encapsulate the keys.\n * @returns A common nonce of the keys and a list of keys, 32 bytes each.\n */\nfunction encapBatched(public_keys: G2Element[], id: Uint8Array): [G2Element, GTElement[]] {\n\tif (public_keys.length === 0) {\n\t\tthrow new Error('Invalid input');\n\t}\n\tconst r = Scalar.random();\n\tconst nonce = G2Element.generator().multiply(r);\n\tconst gid = G1Element.hashToCurve(id).multiply(r);\n\treturn [nonce, public_keys.map((public_key) => gid.pairing(public_key))];\n}\n\n/**\n * Decapsulate a key using a user secret key and the nonce.\n *\n * @param usk The user secret key.\n * @param nonce The nonce.\n * @returns The encapsulated key.\n */\nfunction decap(nonce: G2Element, usk: G1Element): GTElement {\n\treturn usk.pairing(nonce);\n}\n"],
5
- "mappings": "AAIA,SAAS,WAAW,WAAW,cAAc;AAC7C,SAAS,WAAW;AAGpB,SAAS,WAAW;AAKb,MAAM,MAAkB,IAAI,YAAY,EAAE,OAAO,0BAA0B;AAK3E,MAAM,UAAsB,IAAI,YAAY,EAAE,OAAO,8BAA8B;AAKnF,MAAe,WAAW;AAAA,EAGtB,YAAY,YAA0B;AAC/C,SAAK,aAAa;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA,EAKA,eAA6B;AAC5B,WAAO,KAAK;AAAA,EACb;AAAA;AAAA;AAAA;AAAA,EAKA,OAAe;AACd,WAAO,KAAK,WAAW;AAAA,EACxB;AAaD;AAMO,MAAM,sCAAsC,WAAW;AAAA,EAG7D,YAAY,UAAuB;AAClC,UAAM,SAAS,IAAI,CAAC,YAAY,QAAQ,QAAQ,CAAC;AACjD,SAAK,cAAc,SAAS,IAAI,CAAC,YAAY,UAAU,UAAU,QAAQ,EAAE,CAAC;AAAA,EAC7E;AAAA,EAEA,eACC,IACA,eACqB;AACrB,QAAI,KAAK,YAAY,WAAW,KAAK,KAAK,YAAY,WAAW,cAAc,QAAQ;AACtF,YAAM,IAAI,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
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex } from '@mysten/bcs';\n\nimport type { IBEEncryptions } from './bcs.js';\nimport type { GTElement } from './bls12381.js';\nimport { G1Element, G2Element, Scalar } from './bls12381.js';\nimport { kdf } from './kdf.js';\nimport type { KeyServer } from './key-server.js';\nimport { xor } from './utils.js';\n\n/**\n * The domain separation tag for the hash-to-group function.\n */\nexport const DST: Uint8Array = new TextEncoder().encode('SUI-SEAL-IBE-BLS12381-00');\n\n/**\n * The domain separation tag for the signing proof of possession.\n */\nexport const DST_POP: Uint8Array = new TextEncoder().encode('SUI-SEAL-IBE-BLS12381-POP-00');\n\n/**\n * The interface for the key servers.\n */\nexport abstract class IBEServers {\n\tobjectIds: string[];\n\n\tconstructor(objectIds: string[]) {\n\t\tthis.objectIds = objectIds;\n\t}\n\n\t/**\n\t * The number of key servers.\n\t */\n\tsize(): number {\n\t\treturn this.objectIds.length;\n\t}\n\n\t/**\n\t * Encrypt a batch of messages for the given identity.\n\t *\n\t * @param id The identity.\n\t * @param msgAndInfos The messages and an additional info parameter which will be included in the KDF.\n\t * @returns The encrypted messages.\n\t */\n\tabstract encryptBatched(\n\t\tid: Uint8Array,\n\t\tmsgAndInfos: { msg: Uint8Array; info: Uint8Array }[],\n\t\trandomnessKey: Uint8Array,\n\t): typeof IBEEncryptions.$inferType;\n}\n\n/**\n * Identity-based encryption based on the Boneh-Franklin IBE scheme.\n * This object represents a set of key servers that can be used to encrypt messages for a given identity.\n */\nexport class BonehFranklinBLS12381Services extends IBEServers {\n\treadonly publicKeys: G2Element[];\n\n\tconstructor(services: KeyServer[]) {\n\t\tsuper(services.map((service) => service.objectId));\n\t\tthis.publicKeys = services.map((service) => G2Element.fromBytes(service.pk));\n\t}\n\n\tencryptBatched(\n\t\tid: Uint8Array,\n\t\tmsgAndInfos: { msg: Uint8Array; info: Uint8Array }[],\n\t\trandomnessKey: Uint8Array,\n\t): typeof IBEEncryptions.$inferType {\n\t\tif (this.publicKeys.length === 0 || this.publicKeys.length !== msgAndInfos.length) {\n\t\t\tthrow new Error('Invalid public keys');\n\t\t}\n\t\tconst [r, nonce, keys] = encapBatched(this.publicKeys, id);\n\t\tconst encryptedShares = msgAndInfos.map((msgAndInfo, i) =>\n\t\t\txor(msgAndInfo.msg, kdf(keys[i], msgAndInfo.info)),\n\t\t);\n\t\tconst encryptedRandomness = xor(randomnessKey, r.toBytes());\n\n\t\treturn {\n\t\t\tBonehFranklinBLS12381: {\n\t\t\t\tnonce: nonce.toBytes(),\n\t\t\t\tencryptedShares,\n\t\t\t\tencryptedRandomness,\n\t\t\t},\n\t\t\t$kind: 'BonehFranklinBLS12381',\n\t\t};\n\t}\n\n\t/**\n\t * Returns true if the user secret key is valid for the given public key and id.\n\t * @param user_secret_key - The user secret key.\n\t * @param id - The identity.\n\t * @param public_key - The public key.\n\t * @returns True if the user secret key is valid for the given public key and id.\n\t */\n\tstatic verifyUserSecretKey(userSecretKey: G1Element, id: string, publicKey: G2Element): boolean {\n\t\tconst lhs = userSecretKey.pairing(G2Element.generator()).toBytes();\n\t\tconst rhs = G1Element.hashToCurve(fromHex(id)).pairing(publicKey).toBytes();\n\t\treturn lhs.length === rhs.length && lhs.every((value, index) => value === rhs[index]);\n\t}\n\n\t/**\n\t * Identity-based decryption.\n\t *\n\t * @param nonce The encryption nonce.\n\t * @param sk The user secret key.\n\t * @param ciphertext The encrypted message.\n\t * @param info An info parameter also included in the KDF.\n\t * @returns The decrypted message.\n\t */\n\tstatic decrypt(\n\t\tnonce: G2Element,\n\t\tsk: G1Element,\n\t\tciphertext: Uint8Array,\n\t\tinfo: Uint8Array,\n\t): Uint8Array {\n\t\treturn xor(ciphertext, kdf(decap(nonce, sk), info));\n\t}\n}\n\n/**\n * Batched identity-based key-encapsulation mechanism: encapsulate multiple keys for given identity using different key servers.\n *\n * @param publicKeys Public keys for a set of key servers.\n * @param id The identity used to encapsulate the keys.\n * @returns A common nonce of the keys and a list of keys, 32 bytes each.\n */\nfunction encapBatched(publicKeys: G2Element[], id: Uint8Array): [Scalar, G2Element, GTElement[]] {\n\tif (publicKeys.length === 0) {\n\t\tthrow new Error('No public keys provided');\n\t}\n\tconst r = Scalar.random();\n\tconst nonce = G2Element.generator().multiply(r);\n\tconst gid = G1Element.hashToCurve(id).multiply(r);\n\treturn [r, nonce, publicKeys.map((public_key) => gid.pairing(public_key))];\n}\n\n/**\n * Decapsulate a key using a user secret key and the nonce.\n *\n * @param usk The user secret key.\n * @param nonce The nonce.\n * @returns The encapsulated key.\n */\nfunction decap(nonce: G2Element, usk: G1Element): GTElement {\n\treturn usk.pairing(nonce);\n}\n"],
5
+ "mappings": "AAGA,SAAS,eAAe;AAIxB,SAAS,WAAW,WAAW,cAAc;AAC7C,SAAS,WAAW;AAEpB,SAAS,WAAW;AAKb,MAAM,MAAkB,IAAI,YAAY,EAAE,OAAO,0BAA0B;AAK3E,MAAM,UAAsB,IAAI,YAAY,EAAE,OAAO,8BAA8B;AAKnF,MAAe,WAAW;AAAA,EAGhC,YAAY,WAAqB;AAChC,SAAK,YAAY;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKA,OAAe;AACd,WAAO,KAAK,UAAU;AAAA,EACvB;AAcD;AAMO,MAAM,sCAAsC,WAAW;AAAA,EAG7D,YAAY,UAAuB;AAClC,UAAM,SAAS,IAAI,CAAC,YAAY,QAAQ,QAAQ,CAAC;AACjD,SAAK,aAAa,SAAS,IAAI,CAAC,YAAY,UAAU,UAAU,QAAQ,EAAE,CAAC;AAAA,EAC5E;AAAA,EAEA,eACC,IACA,aACA,eACmC;AACnC,QAAI,KAAK,WAAW,WAAW,KAAK,KAAK,WAAW,WAAW,YAAY,QAAQ;AAClF,YAAM,IAAI,MAAM,qBAAqB;AAAA,IACtC;AACA,UAAM,CAAC,GAAG,OAAO,IAAI,IAAI,aAAa,KAAK,YAAY,EAAE;AACzD,UAAM,kBAAkB,YAAY;AAAA,MAAI,CA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@@
1
- export { AesGcm256 } from './aes.js';
2
- export { encrypt } from './encrypt.js';
3
- export { getAllowlistedKeyServers, retrieveKeyServers, verifyKeyServer, type KeyServer, } from './key-server.js';
4
- export { KeyStore } from './key-store.js';
1
+ export { getAllowlistedKeyServers } from './key-server.js';
2
+ export { SealClient, type SealClientOptions } from './client.js';
5
3
  export { SessionKey } from './session-key.js';
6
- export { EncryptedObject } from './types.js';
package/dist/esm/index.js CHANGED
@@ -1,21 +1,9 @@
1
- import { AesGcm256 } from "./aes.js";
2
- import { encrypt } from "./encrypt.js";
3
- import {
4
- getAllowlistedKeyServers,
5
- retrieveKeyServers,
6
- verifyKeyServer
7
- } from "./key-server.js";
8
- import { KeyStore } from "./key-store.js";
1
+ import { getAllowlistedKeyServers } from "./key-server.js";
2
+ import { SealClient } from "./client.js";
9
3
  import { SessionKey } from "./session-key.js";
10
- import { EncryptedObject } from "./types.js";
11
4
  export {
12
- AesGcm256,
13
- EncryptedObject,
14
- KeyStore,
5
+ SealClient,
15
6
  SessionKey,
16
- encrypt,
17
- getAllowlistedKeyServers,
18
- retrieveKeyServers,
19
- verifyKeyServer
7
+ getAllowlistedKeyServers
20
8
  };
21
9
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/index.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nexport { AesGcm256 } from './aes.js';\nexport { encrypt } from './encrypt.js';\nexport {\n\tgetAllowlistedKeyServers,\n\tretrieveKeyServers,\n\tverifyKeyServer,\n\ttype KeyServer,\n} from './key-server.js';\nexport { KeyStore } from './key-store.js';\nexport { SessionKey } from './session-key.js';\nexport { EncryptedObject } from './types.js';\n"],
5
- "mappings": "AAGA,SAAS,iBAAiB;AAC1B,SAAS,eAAe;AACxB;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,OAEM;AACP,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nexport { getAllowlistedKeyServers } from './key-server.js';\nexport { SealClient, type SealClientOptions } from './client.js';\nexport { SessionKey } from './session-key.js';\n"],
5
+ "mappings": "AAGA,SAAS,gCAAgC;AACzC,SAAS,kBAA0C;AACnD,SAAS,kBAAkB;",
6
6
  "names": []
7
7
  }
package/dist/esm/kdf.d.ts CHANGED
@@ -7,3 +7,8 @@ import type { GTElement } from './bls12381.js';
7
7
  * @returns The derived key.
8
8
  */
9
9
  export declare function kdf(element: GTElement, info: Uint8Array): Uint8Array;
10
+ export declare enum KeyPurpose {
11
+ EncryptedRandomness = 0,
12
+ DEM = 1
13
+ }
14
+ export declare function deriveKey(purpose: KeyPurpose, baseKey: Uint8Array): Uint8Array;
package/dist/esm/kdf.js CHANGED
@@ -1,9 +1,36 @@
1
1
  import { hkdf } from "@noble/hashes/hkdf";
2
+ import { hmac } from "@noble/hashes/hmac";
2
3
  import { sha3_256 } from "@noble/hashes/sha3";
3
4
  function kdf(element, info) {
4
- return hkdf(sha3_256, element.toBytes(), "", info, 32);
5
+ const GT_ELEMENT_BYTE_LENGTH = 576;
6
+ const PERMUTATION = [0, 2, 4, 1, 3, 5];
7
+ const COEFFICIENT_SIZE = GT_ELEMENT_BYTE_LENGTH / PERMUTATION.length;
8
+ const bytes = element.toBytes();
9
+ let permutedBytes = new Uint8Array(GT_ELEMENT_BYTE_LENGTH);
10
+ PERMUTATION.forEach((pi, i) => {
11
+ permutedBytes.set(
12
+ bytes.slice(i * COEFFICIENT_SIZE, (i + 1) * COEFFICIENT_SIZE),
13
+ pi * COEFFICIENT_SIZE
14
+ );
15
+ });
16
+ return hkdf(sha3_256, permutedBytes, "", info, 32);
17
+ }
18
+ var KeyPurpose = /* @__PURE__ */ ((KeyPurpose2) => {
19
+ KeyPurpose2[KeyPurpose2["EncryptedRandomness"] = 0] = "EncryptedRandomness";
20
+ KeyPurpose2[KeyPurpose2["DEM"] = 1] = "DEM";
21
+ return KeyPurpose2;
22
+ })(KeyPurpose || {});
23
+ function deriveKey(purpose, baseKey) {
24
+ switch (purpose) {
25
+ case 0 /* EncryptedRandomness */:
26
+ return hmac(sha3_256, baseKey, new Uint8Array([0]));
27
+ case 1 /* DEM */:
28
+ return hmac(sha3_256, baseKey, new Uint8Array([1]));
29
+ }
5
30
  }
6
31
  export {
32
+ KeyPurpose,
33
+ deriveKey,
7
34
  kdf
8
35
  };
9
36
  //# sourceMappingURL=kdf.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/kdf.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { hkdf } from '@noble/hashes/hkdf';\nimport { sha3_256 } from '@noble/hashes/sha3';\n\nimport type { GTElement } from './bls12381.js';\n\n/**\n * The default key derivation function.\n *\n * @param element The GTElement to derive the key from.\n * @param info Optional context and application specific information.\n * @returns The derived key.\n */\nexport function kdf(element: GTElement, info: Uint8Array): Uint8Array {\n\treturn hkdf(sha3_256, element.toBytes(), '', info, 32);\n}\n"],
5
- "mappings": "AAGA,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAWlB,SAAS,IAAI,SAAoB,MAA8B;AACrE,SAAO,KAAK,UAAU,QAAQ,QAAQ,GAAG,IAAI,MAAM,EAAE;AACtD;",
6
- "names": []
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { hkdf } from '@noble/hashes/hkdf';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha3_256 } from '@noble/hashes/sha3';\n\nimport type { GTElement } from './bls12381.js';\n\n/**\n * The default key derivation function.\n *\n * @param element The GTElement to derive the key from.\n * @param info Optional context and application specific information.\n * @returns The derived key.\n */\nexport function kdf(element: GTElement, info: Uint8Array): Uint8Array {\n\t// This permutation flips the order of 6 pairs of coefficients of the GT element.\n\t// The permutation may be computed as:\n\t// for i in 0..3 {\n\t// for j in 0..2 {\n\t// PERMUTATION[i + j * 3] = i * 2 + j;\n\t// }\n\t// }\n\tconst GT_ELEMENT_BYTE_LENGTH = 576;\n\tconst PERMUTATION = [0, 2, 4, 1, 3, 5];\n\tconst COEFFICIENT_SIZE = GT_ELEMENT_BYTE_LENGTH / PERMUTATION.length;\n\n\tconst bytes = element.toBytes();\n\tlet permutedBytes = new Uint8Array(GT_ELEMENT_BYTE_LENGTH);\n\tPERMUTATION.forEach((pi, i) => {\n\t\tpermutedBytes.set(\n\t\t\tbytes.slice(i * COEFFICIENT_SIZE, (i + 1) * COEFFICIENT_SIZE),\n\t\t\tpi * COEFFICIENT_SIZE,\n\t\t);\n\t});\n\treturn hkdf(sha3_256, permutedBytes, '', info, 32);\n}\n\nexport enum KeyPurpose {\n\tEncryptedRandomness,\n\tDEM,\n}\n\nexport function deriveKey(purpose: KeyPurpose, baseKey: Uint8Array): Uint8Array {\n\tswitch (purpose) {\n\t\tcase KeyPurpose.EncryptedRandomness:\n\t\t\treturn hmac(sha3_256, baseKey, new Uint8Array([0]));\n\t\tcase KeyPurpose.DEM:\n\t\t\treturn hmac(sha3_256, baseKey, new Uint8Array([1]));\n\t}\n}\n"],
5
+ "mappings": "AAGA,SAAS,YAAY;AACrB,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAWlB,SAAS,IAAI,SAAoB,MAA8B;AAQrE,QAAM,yBAAyB;AAC/B,QAAM,cAAc,CAAC,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AACrC,QAAM,mBAAmB,yBAAyB,YAAY;AAE9D,QAAM,QAAQ,QAAQ,QAAQ;AAC9B,MAAI,gBAAgB,IAAI,WAAW,sBAAsB;AACzD,cAAY,QAAQ,CAAC,IAAI,MAAM;AAC9B,kBAAc;AAAA,MACb,MAAM,MAAM,IAAI,mBAAmB,IAAI,KAAK,gBAAgB;AAAA,MAC5D,KAAK;AAAA,IACN;AAAA,EACD,CAAC;AACD,SAAO,KAAK,UAAU,eAAe,IAAI,MAAM,EAAE;AAClD;AAEO,IAAK,aAAL,kBAAKA,gBAAL;AACN,EAAAA,wBAAA;AACA,EAAAA,wBAAA;AAFW,SAAAA;AAAA,GAAA;AAKL,SAAS,UAAU,SAAqB,SAAiC;AAC/E,UAAQ,SAAS;AAAA,IAChB,KAAK;AACJ,aAAO,KAAK,UAAU,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC;AAAA,IACnD,KAAK;AACJ,aAAO,KAAK,UAAU,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC;AAAA,EACpD;AACD;",
6
+ "names": ["KeyPurpose"]
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import type { SuiClient } from '@mysten/sui/client';
2
2
  export type KeyServer = {
3
- objectId: Uint8Array;
3
+ objectId: string;
4
4
  name: string;
5
5
  url: string;
6
6
  keyType: KeyServerType;
@@ -14,7 +14,7 @@ export declare enum KeyServerType {
14
14
  * @param network - The network to use.
15
15
  * @returns The object id's of the key servers.
16
16
  */
17
- export declare function getAllowlistedKeyServers(network: 'testnet' | 'mainnet'): Uint8Array[];
17
+ export declare function getAllowlistedKeyServers(network: 'testnet' | 'mainnet'): string[];
18
18
  /**
19
19
  * Given a list of key server object IDs, returns a list of SealKeyServer
20
20
  * from onchain state containing name, objectId, URL and pk.
@@ -24,15 +24,15 @@ export declare function getAllowlistedKeyServers(network: 'testnet' | 'mainnet')
24
24
  * @returns - An array of SealKeyServer.
25
25
  */
26
26
  export declare function retrieveKeyServers({ objectIds, client, }: {
27
- objectIds: Uint8Array[];
27
+ objectIds: string[];
28
28
  client: SuiClient;
29
29
  }): Promise<KeyServer[]>;
30
30
  /**
31
- * Given a KeyServer, fetch the proof of possesion (PoP) from the URL and verify it
31
+ * Given a KeyServer, fetch the proof of possession (PoP) from the URL and verify it
32
32
  * against the pubkey. This should be used only rarely when the dapp uses a dynamic
33
33
  * set of key servers.
34
34
  *
35
35
  * @param server - The KeyServer to verify.
36
36
  * @returns - True if the key server is valid, false otherwise.
37
37
  */
38
- export declare function verifyKeyServer(server: KeyServer): Promise<boolean>;
38
+ export declare function verifyKeyServer(server: KeyServer, timeout: number): Promise<boolean>;
@@ -1,26 +1,26 @@
1
- import { fromBase64, fromHex, toHex } from "@mysten/bcs";
2
- import { bcs } from "@mysten/sui/bcs";
1
+ import { fromBase64, fromHex } from "@mysten/bcs";
3
2
  import { bls12_381 } from "@noble/curves/bls12-381";
3
+ import { KeyServerMove } from "./bcs.js";
4
+ import {
5
+ InvalidGetObjectError,
6
+ SealAPIError,
7
+ UnsupportedFeatureError,
8
+ UnsupportedNetworkError
9
+ } from "./error.js";
4
10
  import { DST_POP } from "./ibe.js";
11
+ import { PACKAGE_VERSION } from "./version.js";
5
12
  var KeyServerType = /* @__PURE__ */ ((KeyServerType2) => {
6
13
  KeyServerType2[KeyServerType2["BonehFranklinBLS12381"] = 0] = "BonehFranklinBLS12381";
7
14
  return KeyServerType2;
8
15
  })(KeyServerType || {});
9
- const KeyServerMove = bcs.struct("KeyServer", {
10
- id: bcs.Address,
11
- name: bcs.string(),
12
- url: bcs.string(),
13
- key_type: bcs.u8(),
14
- pk: bcs.vector(bcs.u8())
15
- });
16
16
  function getAllowlistedKeyServers(network) {
17
17
  if (network === "testnet") {
18
18
  return [
19
- fromHex("0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8"),
20
- fromHex("0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06")
19
+ "0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8",
20
+ "0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06"
21
21
  ];
22
22
  } else {
23
- throw new Error("Network not supported");
23
+ throw new UnsupportedNetworkError(`Unsupported network ${network}`);
24
24
  }
25
25
  }
26
26
  async function retrieveKeyServers({
@@ -30,20 +30,22 @@ async function retrieveKeyServers({
30
30
  return await Promise.all(
31
31
  objectIds.map(async (objectId) => {
32
32
  const res = await client.getObject({
33
- id: toHex(objectId),
33
+ id: objectId,
34
34
  options: {
35
35
  showBcs: true
36
36
  }
37
37
  });
38
38
  if (!res || res.error || !res.data) {
39
- throw new Error(`KeyServer ${objectId} not found; ${res.error}`);
39
+ throw new InvalidGetObjectError(`KeyServer ${objectId} not found; ${res.error}`);
40
40
  }
41
41
  if (!res.data.bcs || !("bcsBytes" in res.data.bcs)) {
42
- throw new Error(`Invalid KeyServer query: ${objectId}, expected object, got package`);
42
+ throw new InvalidGetObjectError(
43
+ `Invalid KeyServer query: ${objectId}, expected object, got package`
44
+ );
43
45
  }
44
46
  let ks = KeyServerMove.parse(fromBase64(res.data.bcs.bcsBytes));
45
- if (ks.key_type !== 0) {
46
- throw new Error("Unsupported key type");
47
+ if (ks.keyType !== 0) {
48
+ throw new UnsupportedFeatureError(`Unsupported key type ${ks.keyType}`);
47
49
  }
48
50
  return {
49
51
  objectId,
@@ -55,18 +57,24 @@ async function retrieveKeyServers({
55
57
  })
56
58
  );
57
59
  }
58
- async function verifyKeyServer(server) {
60
+ async function verifyKeyServer(server, timeout) {
61
+ const requestId = crypto.randomUUID();
59
62
  const response = await fetch(server.url + "/v1/service", {
60
63
  method: "GET",
61
64
  headers: {
62
- "Content-Type": "application/json"
63
- }
65
+ "Content-Type": "application/json",
66
+ "Request-Id": requestId,
67
+ "Client-Sdk-Type": "typescript",
68
+ "Client-Sdk-Version": PACKAGE_VERSION
69
+ },
70
+ signal: AbortSignal.timeout(timeout)
64
71
  });
72
+ await SealAPIError.assertResponse(response, requestId);
65
73
  const serviceResponse = await response.json();
66
74
  if (serviceResponse.service_id !== server.objectId) {
67
75
  return false;
68
76
  }
69
- const fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...server.objectId]);
77
+ const fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...fromHex(server.objectId)]);
70
78
  return bls12_381.verifyShortSignature(fromBase64(serviceResponse.pop), fullMsg, server.pk);
71
79
  }
72
80
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/key-server.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromBase64, fromHex, toHex } from '@mysten/bcs';\nimport { bcs } from '@mysten/sui/bcs';\nimport type { SuiClient } from '@mysten/sui/client';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nimport { DST_POP } from './ibe.js';\n\nexport type KeyServer = {\n\tobjectId: Uint8Array;\n\tname: string;\n\turl: string;\n\tkeyType: KeyServerType;\n\tpk: Uint8Array;\n};\n\nexport enum KeyServerType {\n\tBonehFranklinBLS12381 = 0,\n}\n\n// The Move struct for the KeyServer object.\nconst KeyServerMove = bcs.struct('KeyServer', {\n\tid: bcs.Address,\n\tname: bcs.string(),\n\turl: bcs.string(),\n\tkey_type: bcs.u8(),\n\tpk: bcs.vector(bcs.u8()),\n});\n\n/**\n * Returns a static list of Seal key server object ids that the dapp can choose to use.\n * @param network - The network to use.\n * @returns The object id's of the key servers.\n */\nexport function getAllowlistedKeyServers(network: 'testnet' | 'mainnet'): Uint8Array[] {\n\tif (network === 'testnet') {\n\t\treturn [\n\t\t\tfromHex('0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8'),\n\t\t\tfromHex('0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06'),\n\t\t];\n\t} else {\n\t\tthrow new Error('Network not supported');\n\t}\n}\n\n/**\n * Given a list of key server object IDs, returns a list of SealKeyServer\n * from onchain state containing name, objectId, URL and pk.\n *\n * @param objectIds - The key server object IDs.\n * @param client - The SuiClient to use.\n * @returns - An array of SealKeyServer.\n */\nexport async function retrieveKeyServers({\n\tobjectIds,\n\tclient,\n}: {\n\tobjectIds: Uint8Array[];\n\tclient: SuiClient;\n}): Promise<KeyServer[]> {\n\treturn await Promise.all(\n\t\tobjectIds.map(async (objectId) => {\n\t\t\tconst res = await client.getObject({\n\t\t\t\tid: toHex(objectId),\n\t\t\t\toptions: {\n\t\t\t\t\tshowBcs: true,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (!res || res.error || !res.data) {\n\t\t\t\tthrow new Error(`KeyServer ${objectId} not found; ${res.error}`);\n\t\t\t}\n\n\t\t\tif (!res.data.bcs || !('bcsBytes' in res.data.bcs)) {\n\t\t\t\tthrow new Error(`Invalid KeyServer query: ${objectId}, expected object, got package`);\n\t\t\t}\n\n\t\t\tlet ks = KeyServerMove.parse(fromBase64(res.data.bcs!.bcsBytes));\n\t\t\tif (ks.key_type !== 0) {\n\t\t\t\tthrow new Error('Unsupported key type');\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tobjectId,\n\t\t\t\tname: ks.name,\n\t\t\t\turl: ks.url,\n\t\t\t\tkeyType: KeyServerType.BonehFranklinBLS12381,\n\t\t\t\tpk: new Uint8Array(ks.pk),\n\t\t\t};\n\t\t}),\n\t);\n}\n\n/**\n * Given a KeyServer, fetch the proof of possesion (PoP) from the URL and verify it\n * against the pubkey. This should be used only rarely when the dapp uses a dynamic\n * set of key servers.\n *\n * @param server - The KeyServer to verify.\n * @returns - True if the key server is valid, false otherwise.\n */\nexport async function verifyKeyServer(server: KeyServer): Promise<boolean> {\n\tconst response = await fetch(server.url! + '/v1/service', {\n\t\tmethod: 'GET',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t},\n\t});\n\tconst serviceResponse = await response.json();\n\n\tif (serviceResponse.service_id !== server.objectId) {\n\t\treturn false;\n\t}\n\tconst fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...server.objectId]);\n\treturn bls12_381.verifyShortSignature(fromBase64(serviceResponse.pop), fullMsg, server.pk);\n}\n"],
5
- "mappings": "AAEA,SAAS,YAAY,SAAS,aAAa;AAC3C,SAAS,WAAW;AAEpB,SAAS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QACT,KAAK,GAAG;AAAA,QACR,SAAS;AAAA,QACT,IAAI,IAAI,WAAW,GAAG,EAAE;AAAA,MACzB;AAAA,IACD,CAAC;AAAA,EACF;AACD;AAUA,eAAsB,gBAAgB,QAAqC;AAC1E,QAAM,WAAW,MAAM,MAAM,OAAO,MAAO,eAAe;AAAA,IACzD,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,IACjB;AAAA,EACD,CAAC;AACD,QAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,MAAI,gBAAgB,eAAe,OAAO,UAAU;AACnD,WAAO;AAAA,EACR;AACA,QAAM,UAAU,IAAI,WAAW,CAAC,GAAG,SAAS,GAAG,OAAO,IAAI,GAAG,OAAO,QAAQ,CAAC;AAC7E,SAAO,UAAU,qBAAqB,WAAW,gBAAgB,GAAG,GAAG,SAAS,OAAO,EAAE;AAC1F;",
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromBase64, fromHex } from '@mysten/bcs';\nimport type { SuiClient } from '@mysten/sui/client';\nimport { bls12_381 } from '@noble/curves/bls12-381';\n\nimport { KeyServerMove } from './bcs.js';\nimport {\n\tInvalidGetObjectError,\n\tSealAPIError,\n\tUnsupportedFeatureError,\n\tUnsupportedNetworkError,\n} from './error.js';\nimport { DST_POP } from './ibe.js';\nimport { PACKAGE_VERSION } from './version.js';\n\nexport type KeyServer = {\n\tobjectId: string;\n\tname: string;\n\turl: string;\n\tkeyType: KeyServerType;\n\tpk: Uint8Array;\n};\n\nexport enum KeyServerType {\n\tBonehFranklinBLS12381 = 0,\n}\n\n/**\n * Returns a static list of Seal key server object ids that the dapp can choose to use.\n * @param network - The network to use.\n * @returns The object id's of the key servers.\n */\nexport function getAllowlistedKeyServers(network: 'testnet' | 'mainnet'): string[] {\n\tif (network === 'testnet') {\n\t\treturn [\n\t\t\t'0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8',\n\t\t\t'0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06',\n\t\t];\n\t} else {\n\t\tthrow new UnsupportedNetworkError(`Unsupported network ${network}`);\n\t}\n}\n\n/**\n * Given a list of key server object IDs, returns a list of SealKeyServer\n * from onchain state containing name, objectId, URL and pk.\n *\n * @param objectIds - The key server object IDs.\n * @param client - The SuiClient to use.\n * @returns - An array of SealKeyServer.\n */\nexport async function retrieveKeyServers({\n\tobjectIds,\n\tclient,\n}: {\n\tobjectIds: string[];\n\tclient: SuiClient;\n}): Promise<KeyServer[]> {\n\t// todo: do not fetch the same object ID if this is fetched before.\n\treturn await Promise.all(\n\t\tobjectIds.map(async (objectId) => {\n\t\t\tconst res = await client.getObject({\n\t\t\t\tid: objectId,\n\t\t\t\toptions: {\n\t\t\t\t\tshowBcs: true,\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (!res || res.error || !res.data) {\n\t\t\t\tthrow new InvalidGetObjectError(`KeyServer ${objectId} not found; ${res.error}`);\n\t\t\t}\n\n\t\t\tif (!res.data.bcs || !('bcsBytes' in res.data.bcs)) {\n\t\t\t\tthrow new InvalidGetObjectError(\n\t\t\t\t\t`Invalid KeyServer query: ${objectId}, expected object, got package`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet ks = KeyServerMove.parse(fromBase64(res.data.bcs!.bcsBytes));\n\t\t\tif (ks.keyType !== 0) {\n\t\t\t\tthrow new UnsupportedFeatureError(`Unsupported key type ${ks.keyType}`);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tobjectId,\n\t\t\t\tname: ks.name,\n\t\t\t\turl: ks.url,\n\t\t\t\tkeyType: KeyServerType.BonehFranklinBLS12381,\n\t\t\t\tpk: new Uint8Array(ks.pk),\n\t\t\t};\n\t\t}),\n\t);\n}\n\n/**\n * Given a KeyServer, fetch the proof of possession (PoP) from the URL and verify it\n * against the pubkey. This should be used only rarely when the dapp uses a dynamic\n * set of key servers.\n *\n * @param server - The KeyServer to verify.\n * @returns - True if the key server is valid, false otherwise.\n */\nexport async function verifyKeyServer(server: KeyServer, timeout: number): Promise<boolean> {\n\tconst requestId = crypto.randomUUID();\n\tconst response = await fetch(server.url! + '/v1/service', {\n\t\tmethod: 'GET',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'Request-Id': requestId,\n\t\t\t'Client-Sdk-Type': 'typescript',\n\t\t\t'Client-Sdk-Version': PACKAGE_VERSION,\n\t\t},\n\t\tsignal: AbortSignal.timeout(timeout),\n\t});\n\n\tawait SealAPIError.assertResponse(response, requestId);\n\tconst serviceResponse = await response.json();\n\n\tif (serviceResponse.service_id !== server.objectId) {\n\t\treturn false;\n\t}\n\tconst fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...fromHex(server.objectId)]);\n\treturn bls12_381.verifyShortSignature(fromBase64(serviceResponse.pop), fullMsg, server.pk);\n}\n"],
5
+ "mappings": "AAEA,SAAS,YAAY,eAAe;AAEpC,SAAS,iBAAiB;AAE1B,SAAS,qBAAqB;AAC9B;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAUzB,IAAK,gBAAL,kBAAKA,mBAAL;AACN,EAAAA,8BAAA,2BAAwB,KAAxB;AADW,SAAAA;AAAA,GAAA;AASL,SAAS,yBAAyB,SAA0C;AAClF,MAAI,YAAY,WAAW;AAC1B,WAAO;AAAA,MACN;AAAA,MACA;AAAA,IACD;AAAA,EACD,OAAO;AACN,UAAM,IAAI,wBAAwB,uBAAuB,OAAO,EAAE;AAAA,EACnE;AACD;AAUA,eAAsB,mBAAmB;AAAA,EACxC;AAAA,EACA;AACD,GAGyB;AAExB,SAAO,MAAM,QAAQ;AAAA,IACpB,UAAU,IAAI,OAAO,aAAa;AACjC,YAAM,MAAM,MAAM,OAAO,UAAU;AAAA,QAClC,IAAI;AAAA,QACJ,SAAS;AAAA,UACR,SAAS;AAA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F;",
6
6
  "names": ["KeyServerType"]
7
7
  }
@@ -0,0 +1,17 @@
1
+ import type { Certificate } from './session-key.js';
2
+ /**
3
+ * Helper function to request all keys from URL with requestSig, txBytes, ephemeral pubkey.
4
+ * Then decrypt the Seal key with ephemeral secret key. Returns a list decryption keys with
5
+ * their full IDs.
6
+ *
7
+ * @param url - The URL of the key server.
8
+ * @param requestSig - The Base64 string of request signature.
9
+ * @param txBytes - The transaction bytes.
10
+ * @param encKey - The ephemeral secret key.
11
+ * @param certificate - The certificate.
12
+ * @returns - A list of full ID and the decrypted key.
13
+ */
14
+ export declare function fetchKeysForAllIds(url: string, requestSig: string, txBytes: Uint8Array, encKey: Uint8Array, certificate: Certificate, timeout: number, signal?: AbortSignal): Promise<{
15
+ fullId: string;
16
+ key: Uint8Array;
17
+ }[]>;
@@ -0,0 +1,41 @@
1
+ import { fromBase64, toBase64, toHex } from "@mysten/bcs";
2
+ import { elgamalDecrypt, toPublicKey, toVerificationKey } from "./elgamal.js";
3
+ import { SealAPIError } from "./error.js";
4
+ import { PACKAGE_VERSION } from "./version.js";
5
+ async function fetchKeysForAllIds(url, requestSig, txBytes, encKey, certificate, timeout, signal) {
6
+ const encKeyPk = toPublicKey(encKey);
7
+ const encVerificationKey = toVerificationKey(encKey);
8
+ const body = {
9
+ ptb: toBase64(txBytes.slice(1)),
10
+ // removes the byte of the transaction type version
11
+ enc_key: toBase64(encKeyPk),
12
+ enc_verification_key: toBase64(encVerificationKey),
13
+ request_signature: requestSig,
14
+ // already b64
15
+ certificate
16
+ };
17
+ const timeoutSignal = AbortSignal.timeout(timeout);
18
+ const combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
19
+ const requestId = crypto.randomUUID();
20
+ const response = await fetch(url + "/v1/fetch_key", {
21
+ method: "POST",
22
+ headers: {
23
+ "Content-Type": "application/json",
24
+ "Request-Id": requestId,
25
+ "Client-Sdk-Type": "typescript",
26
+ "Client-Sdk-Version": PACKAGE_VERSION
27
+ },
28
+ body: JSON.stringify(body),
29
+ signal: combinedSignal
30
+ });
31
+ await SealAPIError.assertResponse(response, requestId);
32
+ const resp = await response.json();
33
+ return resp.decryption_keys.map((dk) => ({
34
+ fullId: toHex(new Uint8Array(dk.id)),
35
+ key: elgamalDecrypt(encKey, dk.encrypted_key.map(fromBase64))
36
+ }));
37
+ }
38
+ export {
39
+ fetchKeysForAllIds
40
+ };
41
+ //# sourceMappingURL=keys.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/keys.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64, toBase64, toHex } from '@mysten/bcs';\n\nimport { elgamalDecrypt, toPublicKey, toVerificationKey } from './elgamal.js';\nimport { SealAPIError } from './error.js';\nimport type { Certificate } from './session-key.js';\nimport { PACKAGE_VERSION } from './version.js';\n\n/**\n * Helper function to request all keys from URL with requestSig, txBytes, ephemeral pubkey.\n * Then decrypt the Seal key with ephemeral secret key. Returns a list decryption keys with\n * their full IDs.\n *\n * @param url - The URL of the key server.\n * @param requestSig - The Base64 string of request signature.\n * @param txBytes - The transaction bytes.\n * @param encKey - The ephemeral secret key.\n * @param certificate - The certificate.\n * @returns - A list of full ID and the decrypted key.\n */\nexport async function fetchKeysForAllIds(\n\turl: string,\n\trequestSig: string,\n\ttxBytes: Uint8Array,\n\tencKey: Uint8Array,\n\tcertificate: Certificate,\n\ttimeout: number,\n\tsignal?: AbortSignal,\n): Promise<{ fullId: string; key: Uint8Array }[]> {\n\tconst encKeyPk = toPublicKey(encKey);\n\tconst encVerificationKey = toVerificationKey(encKey);\n\tconst body = {\n\t\tptb: toBase64(txBytes.slice(1)), // removes the byte of the transaction type version\n\t\tenc_key: toBase64(encKeyPk),\n\t\tenc_verification_key: toBase64(encVerificationKey),\n\t\trequest_signature: requestSig, // already b64\n\t\tcertificate,\n\t};\n\n\tconst timeoutSignal = AbortSignal.timeout(timeout);\n\tconst combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;\n\n\tconst requestId = crypto.randomUUID();\n\tconst response = await fetch(url + '/v1/fetch_key', {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'Request-Id': requestId,\n\t\t\t'Client-Sdk-Type': 'typescript',\n\t\t\t'Client-Sdk-Version': PACKAGE_VERSION,\n\t\t},\n\t\tbody: JSON.stringify(body),\n\t\tsignal: combinedSignal,\n\t});\n\tawait SealAPIError.assertResponse(response, requestId);\n\n\tconst resp = await response.json();\n\treturn resp.decryption_keys.map((dk: { id: Uint8Array; encrypted_key: [string, string] }) => ({\n\t\tfullId: toHex(new Uint8Array(dk.id)),\n\t\tkey: elgamalDecrypt(encKey, dk.encrypted_key.map(fromBase64) as [Uint8Array, Uint8Array]),\n\t}));\n}\n"],
5
+ "mappings": "AAGA,SAAS,YAAY,UAAU,aAAa;AAE5C,SAAS,gBAAgB,aAAa,yBAAyB;AAC/D,SAAS,oBAAoB;AAE7B,SAAS,uBAAuB;AAchC,eAAsB,mBACrB,KACA,YACA,SACA,QACA,aACA,SACA,QACiD;AACjD,QAAM,WAAW,YAAY,MAAM;AACnC,QAAM,qBAAqB,kBAAkB,MAAM;AACnD,QAAM,OAAO;AAAA,IACZ,KAAK,SAAS,QAAQ,MAAM,CAAC,CAAC;AAAA;AAAA,IAC9B,SAAS,SAAS,QAAQ;AAAA,IAC1B,sBAAsB,SAAS,kBAAkB;AAAA,IACjD,mBAAmB;AAAA;AAAA,IACnB;AAAA,EACD;AAEA,QAAM,gBAAgB,YAAY,QAAQ,OAAO;AACjD,QAAM,iBAAiB,SAAS,YAAY,IAAI,CAAC,QAAQ,aAAa,CAAC,IAAI;AAE3E,QAAM,YAAY,OAAO,WAAW;AACpC,QAAM,WAAW,MAAM,MAAM,MAAM,iBAAiB;AAAA,IACnD,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,MAChB,cAAc;AAAA,MACd,mBAAmB;AAAA,MACnB,sBAAsB;AAAA,IACvB;AAAA,IACA,MAAM,KAAK,UAAU,IAAI;AAAA,IACzB,QAAQ;AAAA,EACT,CAAC;AACD,QAAM,aAAa,eAAe,UAAU,SAAS;AAErD,QAAM,OAAO,MAAM,SAAS,KAAK;AACjC,SAAO,KAAK,gBAAgB,IAAI,CAAC,QAA6D;AAAA,IAC7F,QAAQ,MAAM,IAAI,WAAW,GAAG,EAAE,CAAC;AAAA,IACnC,KAAK,eAAe,QAAQ,GAAG,cAAc,IAAI,UAAU,CAA6B;AAAA,EACzF,EAAE;AACH;",
6
+ "names": []
7
+ }