@mysten/seal 0.0.0-experimental-20250330082435

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 +31 -0
  2. package/README.md +4 -0
  3. package/dist/cjs/bcs.d.ts +132 -0
  4. package/dist/cjs/bcs.js +67 -0
  5. package/dist/cjs/bcs.js.map +7 -0
  6. package/dist/cjs/bls12381.d.ts +37 -0
  7. package/dist/cjs/bls12381.js +110 -0
  8. package/dist/cjs/bls12381.js.map +7 -0
  9. package/dist/cjs/client.d.ts +83 -0
  10. package/dist/cjs/client.js +283 -0
  11. package/dist/cjs/client.js.map +7 -0
  12. package/dist/cjs/decrypt.d.ts +15 -0
  13. package/dist/cjs/decrypt.js +94 -0
  14. package/dist/cjs/decrypt.js.map +7 -0
  15. package/dist/cjs/dem.d.ts +36 -0
  16. package/dist/cjs/dem.js +173 -0
  17. package/dist/cjs/dem.js.map +7 -0
  18. package/dist/cjs/elgamal.d.ts +11 -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 +33 -0
  22. package/dist/cjs/encrypt.js +118 -0
  23. package/dist/cjs/encrypt.js.map +7 -0
  24. package/dist/cjs/error.d.ts +58 -0
  25. package/dist/cjs/error.js +175 -0
  26. package/dist/cjs/error.js.map +7 -0
  27. package/dist/cjs/ibe.d.ts +63 -0
  28. package/dist/cjs/ibe.js +104 -0
  29. package/dist/cjs/ibe.js.map +7 -0
  30. package/dist/cjs/index.d.ts +4 -0
  31. package/dist/cjs/index.js +31 -0
  32. package/dist/cjs/index.js.map +7 -0
  33. package/dist/cjs/kdf.d.ts +14 -0
  34. package/dist/cjs/kdf.js +64 -0
  35. package/dist/cjs/kdf.js.map +7 -0
  36. package/dist/cjs/key-server.d.ts +38 -0
  37. package/dist/cjs/key-server.js +101 -0
  38. package/dist/cjs/key-server.js.map +7 -0
  39. package/dist/cjs/keys.d.ts +17 -0
  40. package/dist/cjs/keys.js +61 -0
  41. package/dist/cjs/keys.js.map +7 -0
  42. package/dist/cjs/package.json +5 -0
  43. package/dist/cjs/session-key.d.ts +42 -0
  44. package/dist/cjs/session-key.js +140 -0
  45. package/dist/cjs/session-key.js.map +7 -0
  46. package/dist/cjs/types.d.ts +1 -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 +10 -0
  50. package/dist/cjs/utils.js +51 -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 +132 -0
  56. package/dist/esm/bcs.js +47 -0
  57. package/dist/esm/bcs.js.map +7 -0
  58. package/dist/esm/bls12381.d.ts +37 -0
  59. package/dist/esm/bls12381.js +90 -0
  60. package/dist/esm/bls12381.js.map +7 -0
  61. package/dist/esm/client.d.ts +83 -0
  62. package/dist/esm/client.js +268 -0
  63. package/dist/esm/client.js.map +7 -0
  64. package/dist/esm/decrypt.d.ts +15 -0
  65. package/dist/esm/decrypt.js +74 -0
  66. package/dist/esm/decrypt.js.map +7 -0
  67. package/dist/esm/dem.d.ts +36 -0
  68. package/dist/esm/dem.js +153 -0
  69. package/dist/esm/dem.js.map +7 -0
  70. package/dist/esm/elgamal.d.ts +11 -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 +33 -0
  74. package/dist/esm/encrypt.js +98 -0
  75. package/dist/esm/encrypt.js.map +7 -0
  76. package/dist/esm/error.d.ts +58 -0
  77. package/dist/esm/error.js +155 -0
  78. package/dist/esm/error.js.map +7 -0
  79. package/dist/esm/ibe.d.ts +63 -0
  80. package/dist/esm/ibe.js +84 -0
  81. package/dist/esm/ibe.js.map +7 -0
  82. package/dist/esm/index.d.ts +4 -0
  83. package/dist/esm/index.js +10 -0
  84. package/dist/esm/index.js.map +7 -0
  85. package/dist/esm/kdf.d.ts +14 -0
  86. package/dist/esm/kdf.js +44 -0
  87. package/dist/esm/kdf.js.map +7 -0
  88. package/dist/esm/key-server.d.ts +38 -0
  89. package/dist/esm/key-server.js +86 -0
  90. package/dist/esm/key-server.js.map +7 -0
  91. package/dist/esm/keys.d.ts +17 -0
  92. package/dist/esm/keys.js +41 -0
  93. package/dist/esm/keys.js.map +7 -0
  94. package/dist/esm/package.json +5 -0
  95. package/dist/esm/session-key.d.ts +42 -0
  96. package/dist/esm/session-key.js +124 -0
  97. package/dist/esm/session-key.js.map +7 -0
  98. package/dist/esm/types.d.ts +1 -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 +10 -0
  102. package/dist/esm/utils.js +31 -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 +59 -0
@@ -0,0 +1,63 @@
1
+ import type { IBEEncryptions } from './bcs.js';
2
+ import { G1Element, G2Element } from './bls12381.js';
3
+ import type { KeyServer } from './key-server.js';
4
+ /**
5
+ * The domain separation tag for the hash-to-group function.
6
+ */
7
+ export declare const DST: Uint8Array;
8
+ /**
9
+ * The domain separation tag for the signing proof of possession.
10
+ */
11
+ export declare const DST_POP: Uint8Array;
12
+ /**
13
+ * The interface for the key servers.
14
+ */
15
+ export declare abstract class IBEServers {
16
+ objectIds: string[];
17
+ constructor(objectIds: string[]);
18
+ /**
19
+ * The number of key servers.
20
+ */
21
+ size(): number;
22
+ /**
23
+ * Encrypt a batch of messages for the given identity.
24
+ *
25
+ * @param id The identity.
26
+ * @param msgAndIndices The messages and the corresponding indices of the share being encrypted.
27
+ * @returns The encrypted messages.
28
+ */
29
+ abstract encryptBatched(id: Uint8Array, msgAndIndices: {
30
+ msg: Uint8Array;
31
+ index: number;
32
+ }[], randomnessKey: Uint8Array): typeof IBEEncryptions.$inferType;
33
+ }
34
+ /**
35
+ * Identity-based encryption based on the Boneh-Franklin IBE scheme.
36
+ * This object represents a set of key servers that can be used to encrypt messages for a given identity.
37
+ */
38
+ export declare class BonehFranklinBLS12381Services extends IBEServers {
39
+ readonly publicKeys: G2Element[];
40
+ constructor(services: KeyServer[]);
41
+ encryptBatched(id: Uint8Array, msgAndIndices: {
42
+ msg: Uint8Array;
43
+ index: number;
44
+ }[], randomnessKey: Uint8Array): typeof IBEEncryptions.$inferType;
45
+ /**
46
+ * Returns true if the user secret key is valid for the given public key and id.
47
+ * @param user_secret_key - The user secret key.
48
+ * @param id - The identity.
49
+ * @param public_key - The public key.
50
+ * @returns True if the user secret key is valid for the given public key and id.
51
+ */
52
+ static verifyUserSecretKey(userSecretKey: G1Element, id: string, publicKey: G2Element): boolean;
53
+ /**
54
+ * Identity-based decryption.
55
+ *
56
+ * @param nonce The encryption nonce.
57
+ * @param sk The user secret key.
58
+ * @param ciphertext The encrypted message.
59
+ * @param info An info parameter also included in the KDF.
60
+ * @returns The decrypted message.
61
+ */
62
+ static decrypt(nonce: G2Element, sk: G1Element, ciphertext: Uint8Array, id: Uint8Array, [objectId, index]: [string, number]): Uint8Array;
63
+ }
@@ -0,0 +1,84 @@
1
+ import { fromHex } from "@mysten/bcs";
2
+ import { G1Element, G2Element, Scalar } from "./bls12381.js";
3
+ import { kdf } from "./kdf.js";
4
+ import { xor } from "./utils.js";
5
+ const DST = new TextEncoder().encode("SUI-SEAL-IBE-BLS12381-00");
6
+ const DST_POP = new TextEncoder().encode("SUI-SEAL-IBE-BLS12381-POP-00");
7
+ class IBEServers {
8
+ constructor(objectIds) {
9
+ this.objectIds = objectIds;
10
+ }
11
+ /**
12
+ * The number of key servers.
13
+ */
14
+ size() {
15
+ return this.objectIds.length;
16
+ }
17
+ }
18
+ class BonehFranklinBLS12381Services extends IBEServers {
19
+ constructor(services) {
20
+ super(services.map((service) => service.objectId));
21
+ this.publicKeys = services.map((service) => G2Element.fromBytes(service.pk));
22
+ }
23
+ encryptBatched(id, msgAndIndices, randomnessKey) {
24
+ if (this.publicKeys.length === 0 || this.publicKeys.length !== msgAndIndices.length) {
25
+ throw new Error("Invalid public keys");
26
+ }
27
+ const [r, nonce, keys] = encapBatched(this.publicKeys, id);
28
+ const encryptedShares = msgAndIndices.map(
29
+ (msgAndIndex, i) => xor(msgAndIndex.msg, kdf(keys[i], nonce, id, this.objectIds[i], msgAndIndex.index))
30
+ );
31
+ const encryptedRandomness = xor(randomnessKey, r.toBytes());
32
+ return {
33
+ BonehFranklinBLS12381: {
34
+ nonce: nonce.toBytes(),
35
+ encryptedShares,
36
+ encryptedRandomness
37
+ },
38
+ $kind: "BonehFranklinBLS12381"
39
+ };
40
+ }
41
+ /**
42
+ * Returns true if the user secret key is valid for the given public key and id.
43
+ * @param user_secret_key - The user secret key.
44
+ * @param id - The identity.
45
+ * @param public_key - The public key.
46
+ * @returns True if the user secret key is valid for the given public key and id.
47
+ */
48
+ static verifyUserSecretKey(userSecretKey, id, publicKey) {
49
+ const lhs = userSecretKey.pairing(G2Element.generator()).toBytes();
50
+ const rhs = G1Element.hashToCurve(fromHex(id)).pairing(publicKey).toBytes();
51
+ return lhs.length === rhs.length && lhs.every((value, index) => value === rhs[index]);
52
+ }
53
+ /**
54
+ * Identity-based decryption.
55
+ *
56
+ * @param nonce The encryption nonce.
57
+ * @param sk The user secret key.
58
+ * @param ciphertext The encrypted message.
59
+ * @param info An info parameter also included in the KDF.
60
+ * @returns The decrypted message.
61
+ */
62
+ static decrypt(nonce, sk, ciphertext, id, [objectId, index]) {
63
+ return xor(ciphertext, kdf(decap(nonce, sk), nonce, id, objectId, index));
64
+ }
65
+ }
66
+ function encapBatched(publicKeys, id) {
67
+ if (publicKeys.length === 0) {
68
+ throw new Error("No public keys provided");
69
+ }
70
+ const r = Scalar.random();
71
+ const nonce = G2Element.generator().multiply(r);
72
+ const gid = G1Element.hashToCurve(id).multiply(r);
73
+ return [r, nonce, publicKeys.map((public_key) => gid.pairing(public_key))];
74
+ }
75
+ function decap(nonce, usk) {
76
+ return usk.pairing(nonce);
77
+ }
78
+ export {
79
+ BonehFranklinBLS12381Services,
80
+ DST,
81
+ DST_POP,
82
+ IBEServers
83
+ };
84
+ //# sourceMappingURL=ibe.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/ibe.ts"],
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 msgAndIndices The messages and the corresponding indices of the share being encrypted.\n\t * @returns The encrypted messages.\n\t */\n\tabstract encryptBatched(\n\t\tid: Uint8Array,\n\t\tmsgAndIndices: { msg: Uint8Array; index: number }[],\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\tmsgAndIndices: { msg: Uint8Array; index: number }[],\n\t\trandomnessKey: Uint8Array,\n\t): typeof IBEEncryptions.$inferType {\n\t\tif (this.publicKeys.length === 0 || this.publicKeys.length !== msgAndIndices.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 = msgAndIndices.map((msgAndIndex, i) =>\n\t\t\txor(msgAndIndex.msg, kdf(keys[i], nonce, id, this.objectIds[i], msgAndIndex.index)),\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\tid: Uint8Array,\n\t\t[objectId, index]: [string, number],\n\t): Uint8Array {\n\t\treturn xor(ciphertext, kdf(decap(nonce, sk), nonce, id, objectId, index));\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,eACA,eACmC;AACnC,QAAI,KAAK,WAAW,WAAW,KAAK,KAAK,WAAW,WAAW,cAAc,QAAQ;AACpF,YAAM,IAAI,MAAM,qBAAqB;AAAA,IACtC;AACA,UAAM,CAAC,GAAG,OAAO,IAAI,IAAI,aAAa,KAAK,YAAY,EAAE;AACzD,UAAM,kBAAkB,cAAc;AAAA,MAAI,CAAC,aAAa,MACvD,IAAI,YAAY,KAAK,IAAI,KAAK,CAAC,GAAG,OAAO,IAAI,KAAK,UAAU,CAAC,GAAG,YAAY,KAAK,CAAC;AAAA,IACnF;AACA,UAAM,sBAAsB,IAAI,eAAe,EAAE,QAAQ,CAAC;AAE1D,WAAO;AAAA,MACN,uBAAuB;AAAA,QACtB,OAAO,MAAM,QAAQ;AAAA,QACrB;AAAA,QACA;AAAA,MACD;AAAA,MACA,OAAO;AAAA,IACR;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,OAAO,oBAAoB,eAA0B,IAAY,WAA+B;AAC/F,UAAM,MAAM,cAAc,QAAQ,UAAU,UAAU,CAAC,EAAE,QAAQ;AACjE,UAAM,MAAM,UAAU,YAAY,QAAQ,EAAE,CAAC,EAAE,QAAQ,SAAS,EAAE,QAAQ;AAC1E,WAAO,IAAI,WAAW,IAAI,UAAU,IAAI,MAAM,CAAC,OAAO,UAAU,UAAU,IAAI,KAAK,CAAC;AAAA,EACrF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,OAAO,QACN,OACA,IACA,YACA,IACA,CAAC,UAAU,KAAK,GACH;AACb,WAAO,IAAI,YAAY,IAAI,MAAM,OAAO,EAAE,GAAG,OAAO,IAAI,UAAU,KAAK,CAAC;AAAA,EACzE;AACD;AASA,SAAS,aAAa,YAAyB,IAAkD;AAChG,MAAI,WAAW,WAAW,GAAG;AAC5B,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC1C;AACA,QAAM,IAAI,OAAO,OAAO;AACxB,QAAM,QAAQ,UAAU,UAAU,EAAE,SAAS,CAAC;AAC9C,QAAM,MAAM,UAAU,YAAY,EAAE,EAAE,SAAS,CAAC;AAChD,SAAO,CAAC,GAAG,OAAO,WAAW,IAAI,CAAC,eAAe,IAAI,QAAQ,UAAU,CAAC,CAAC;AAC1E;AASA,SAAS,MAAM,OAAkB,KAA2B;AAC3D,SAAO,IAAI,QAAQ,KAAK;AACzB;",
6
+ "names": []
7
+ }
@@ -0,0 +1,4 @@
1
+ export { getAllowlistedKeyServers } from './key-server.js';
2
+ export { SealClient, type SealClientOptions } from './client.js';
3
+ export { SessionKey } from './session-key.js';
4
+ export * from './error.js';
@@ -0,0 +1,10 @@
1
+ import { getAllowlistedKeyServers } from "./key-server.js";
2
+ import { SealClient } from "./client.js";
3
+ import { SessionKey } from "./session-key.js";
4
+ export * from "./error.js";
5
+ export {
6
+ SealClient,
7
+ SessionKey,
8
+ getAllowlistedKeyServers
9
+ };
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.ts"],
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';\nexport * from './error.js';\n"],
5
+ "mappings": "AAGA,SAAS,gCAAgC;AACzC,SAAS,kBAA0C;AACnD,SAAS,kBAAkB;AAC3B,cAAc;",
6
+ "names": []
7
+ }
@@ -0,0 +1,14 @@
1
+ import type { G2Element, GTElement } from './bls12381.js';
2
+ /**
3
+ * The default key derivation function.
4
+ *
5
+ * @param element The GTElement to derive the key from.
6
+ * @param info Optional context and application specific information.
7
+ * @returns The derived key.
8
+ */
9
+ export declare function kdf(element: GTElement, nonce: G2Element, id: Uint8Array, objectId: string, index: number): Uint8Array;
10
+ export declare enum KeyPurpose {
11
+ EncryptedRandomness = 0,
12
+ DEM = 1
13
+ }
14
+ export declare function deriveKey(purpose: KeyPurpose, baseKey: Uint8Array): Uint8Array;
@@ -0,0 +1,44 @@
1
+ import { fromHex } from "@mysten/bcs";
2
+ import { hkdf } from "@noble/hashes/hkdf";
3
+ import { hmac } from "@noble/hashes/hmac";
4
+ import { sha3_256 } from "@noble/hashes/sha3";
5
+ import { G1Element } from "./bls12381.js";
6
+ function kdf(element, nonce, id, objectId, index) {
7
+ const GT_ELEMENT_BYTE_LENGTH = 576;
8
+ const PERMUTATION = [0, 2, 4, 1, 3, 5];
9
+ const COEFFICIENT_SIZE = GT_ELEMENT_BYTE_LENGTH / PERMUTATION.length;
10
+ const bytes = element.toBytes();
11
+ let permutedBytes = new Uint8Array(GT_ELEMENT_BYTE_LENGTH);
12
+ PERMUTATION.forEach((pi, i) => {
13
+ permutedBytes.set(
14
+ bytes.slice(i * COEFFICIENT_SIZE, (i + 1) * COEFFICIENT_SIZE),
15
+ pi * COEFFICIENT_SIZE
16
+ );
17
+ });
18
+ const inputBytes = new Uint8Array([
19
+ ...permutedBytes,
20
+ ...nonce.toBytes(),
21
+ ...G1Element.hashToCurve(id).toBytes()
22
+ ]);
23
+ const info = new Uint8Array([...fromHex(objectId), index]);
24
+ return hkdf(sha3_256, inputBytes, "", info, 32);
25
+ }
26
+ var KeyPurpose = /* @__PURE__ */ ((KeyPurpose2) => {
27
+ KeyPurpose2[KeyPurpose2["EncryptedRandomness"] = 0] = "EncryptedRandomness";
28
+ KeyPurpose2[KeyPurpose2["DEM"] = 1] = "DEM";
29
+ return KeyPurpose2;
30
+ })(KeyPurpose || {});
31
+ function deriveKey(purpose, baseKey) {
32
+ switch (purpose) {
33
+ case 0 /* EncryptedRandomness */:
34
+ return hmac(sha3_256, baseKey, new Uint8Array([0]));
35
+ case 1 /* DEM */:
36
+ return hmac(sha3_256, baseKey, new Uint8Array([1]));
37
+ }
38
+ }
39
+ export {
40
+ KeyPurpose,
41
+ deriveKey,
42
+ kdf
43
+ };
44
+ //# sourceMappingURL=kdf.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/kdf.ts"],
4
+ "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex } from '@mysten/bcs';\nimport { hkdf } from '@noble/hashes/hkdf';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha3_256 } from '@noble/hashes/sha3';\n\nimport { G1Element } from './bls12381.js';\nimport type { G2Element, 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(\n\telement: GTElement,\n\tnonce: G2Element,\n\tid: Uint8Array,\n\tobjectId: string,\n\tindex: number,\n): 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\tconst inputBytes = new Uint8Array([\n\t\t...permutedBytes,\n\t\t...nonce.toBytes(),\n\t\t...G1Element.hashToCurve(id).toBytes(),\n\t]);\n\tconst info = new Uint8Array([...fromHex(objectId), index]);\n\treturn hkdf(sha3_256, inputBytes, '', 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,eAAe;AACxB,SAAS,YAAY;AACrB,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,SAAS,iBAAiB;AAUnB,SAAS,IACf,SACA,OACA,IACA,UACA,OACa;AAQb,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,QAAM,aAAa,IAAI,WAAW;AAAA,IACjC,GAAG;AAAA,IACH,GAAG,MAAM,QAAQ;AAAA,IACjB,GAAG,UAAU,YAAY,EAAE,EAAE,QAAQ;AAAA,EACtC,CAAC;AACD,QAAM,OAAO,IAAI,WAAW,CAAC,GAAG,QAAQ,QAAQ,GAAG,KAAK,CAAC;AACzD,SAAO,KAAK,UAAU,YAAY,IAAI,MAAM,EAAE;AAC/C;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
+ }
@@ -0,0 +1,38 @@
1
+ import type { SuiClient } from '@mysten/sui/client';
2
+ export type KeyServer = {
3
+ objectId: string;
4
+ name: string;
5
+ url: string;
6
+ keyType: KeyServerType;
7
+ pk: Uint8Array;
8
+ };
9
+ export declare enum KeyServerType {
10
+ BonehFranklinBLS12381 = 0
11
+ }
12
+ /**
13
+ * Returns a static list of Seal key server object ids that the dapp can choose to use.
14
+ * @param network - The network to use.
15
+ * @returns The object id's of the key servers.
16
+ */
17
+ export declare function getAllowlistedKeyServers(network: 'testnet' | 'mainnet'): string[];
18
+ /**
19
+ * Given a list of key server object IDs, returns a list of SealKeyServer
20
+ * from onchain state containing name, objectId, URL and pk.
21
+ *
22
+ * @param objectIds - The key server object IDs.
23
+ * @param client - The SuiClient to use.
24
+ * @returns - An array of SealKeyServer.
25
+ */
26
+ export declare function retrieveKeyServers({ objectIds, client, }: {
27
+ objectIds: string[];
28
+ client: SuiClient;
29
+ }): Promise<KeyServer[]>;
30
+ /**
31
+ * Given a KeyServer, fetch the proof of possession (PoP) from the URL and verify it
32
+ * against the pubkey. This should be used only rarely when the dapp uses a dynamic
33
+ * set of key servers.
34
+ *
35
+ * @param server - The KeyServer to verify.
36
+ * @returns - True if the key server is valid, false otherwise.
37
+ */
38
+ export declare function verifyKeyServer(server: KeyServer, timeout: number): Promise<boolean>;
@@ -0,0 +1,86 @@
1
+ import { fromBase64, fromHex } from "@mysten/bcs";
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";
10
+ import { DST_POP } from "./ibe.js";
11
+ import { PACKAGE_VERSION } from "./version.js";
12
+ var KeyServerType = /* @__PURE__ */ ((KeyServerType2) => {
13
+ KeyServerType2[KeyServerType2["BonehFranklinBLS12381"] = 0] = "BonehFranklinBLS12381";
14
+ return KeyServerType2;
15
+ })(KeyServerType || {});
16
+ function getAllowlistedKeyServers(network) {
17
+ if (network === "testnet") {
18
+ return [
19
+ "0xb35a7228d8cf224ad1e828c0217c95a5153bafc2906d6f9c178197dce26fbcf8",
20
+ "0x2d6cde8a9d9a65bde3b0a346566945a63b4bfb70e9a06c41bdb70807e2502b06"
21
+ ];
22
+ } else {
23
+ throw new UnsupportedNetworkError(`Unsupported network ${network}`);
24
+ }
25
+ }
26
+ async function retrieveKeyServers({
27
+ objectIds,
28
+ client
29
+ }) {
30
+ return await Promise.all(
31
+ objectIds.map(async (objectId) => {
32
+ const res = await client.getObject({
33
+ id: objectId,
34
+ options: {
35
+ showBcs: true
36
+ }
37
+ });
38
+ if (!res || res.error || !res.data) {
39
+ throw new InvalidGetObjectError(`KeyServer ${objectId} not found; ${res.error}`);
40
+ }
41
+ if (!res.data.bcs || !("bcsBytes" in res.data.bcs)) {
42
+ throw new InvalidGetObjectError(
43
+ `Invalid KeyServer query: ${objectId}, expected object, got package`
44
+ );
45
+ }
46
+ let ks = KeyServerMove.parse(fromBase64(res.data.bcs.bcsBytes));
47
+ if (ks.keyType !== 0) {
48
+ throw new UnsupportedFeatureError(`Unsupported key type ${ks.keyType}`);
49
+ }
50
+ return {
51
+ objectId,
52
+ name: ks.name,
53
+ url: ks.url,
54
+ keyType: 0 /* BonehFranklinBLS12381 */,
55
+ pk: new Uint8Array(ks.pk)
56
+ };
57
+ })
58
+ );
59
+ }
60
+ async function verifyKeyServer(server, timeout) {
61
+ const requestId = crypto.randomUUID();
62
+ const response = await fetch(server.url + "/v1/service", {
63
+ method: "GET",
64
+ headers: {
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)
71
+ });
72
+ await SealAPIError.assertResponse(response, requestId);
73
+ const serviceResponse = await response.json();
74
+ if (serviceResponse.service_id !== server.objectId) {
75
+ return false;
76
+ }
77
+ const fullMsg = new Uint8Array([...DST_POP, ...server.pk, ...fromHex(server.objectId)]);
78
+ return bls12_381.verifyShortSignature(fromBase64(serviceResponse.pop), fullMsg, server.pk);
79
+ }
80
+ export {
81
+ KeyServerType,
82
+ getAllowlistedKeyServers,
83
+ retrieveKeyServers,
84
+ verifyKeyServer
85
+ };
86
+ //# sourceMappingURL=key-server.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/key-server.ts"],
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;AAAA,QACV;AAAA,MACD,CAAC;AACD,UAAI,CAAC,OAAO,IAAI,SAAS,CAAC,IAAI,MAAM;AACnC,cAAM,IAAI,sBAAsB,aAAa,QAAQ,eAAe,IAAI,KAAK,EAAE;AAAA,MAChF;AAEA,UAAI,CAAC,IAAI,KAAK,OAAO,EAAE,cAAc,IAAI,KAAK,MAAM;AACnD,cAAM,IAAI;AAAA,UACT,4BAA4B,QAAQ;AAAA,QACrC;AAAA,MACD;AAEA,UAAI,KAAK,cAAc,MAAM,WAAW,IAAI,KAAK,IAAK,QAAQ,CAAC;AAC/D,UAAI,GAAG,YAAY,GAAG;AACrB,cAAM,IAAI,wBAAwB,wBAAwB,GAAG,OAAO,EAAE;AAAA,MACvE;AAEA,aAAO;AAAA,QACN;AAAA,QACA,MAAM,GAAG;AAAA,QACT,KAAK,GAAG;AAAA,QACR,SAAS;AAAA,QACT,IAAI,IAAI,WAAW,GAAG,EAAE;AAAA,MACzB;AAAA,IACD,CAAC;AAAA,EACF;AACD;AAUA,eAAsB,gBAAgB,QAAmB,SAAmC;AAC3F,QAAM,YAAY,OAAO,WAAW;AACpC,QAAM,WAAW,MAAM,MAAM,OAAO,MAAO,eAAe;AAAA,IACzD,QAAQ;AAAA,IACR,SAAS;AAAA,MACR,gBAAgB;AAAA,MAChB,cAAc;AAAA,MACd,mBAAmB;AAAA,MACnB,sBAAsB;AAAA,IACvB;AAAA,IACA,QAAQ,YAAY,QAAQ,OAAO;AAAA,EACpC,CAAC;AAED,QAAM,aAAa,eAAe,UAAU,SAAS;AACrD,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,QAAQ,OAAO,QAAQ,CAAC,CAAC;AACtF,SAAO,UAAU,qBAAqB,WAAW,gBAAgB,GAAG,GAAG,SAAS,OAAO,EAAE;AAC1F;",
6
+ "names": ["KeyServerType"]
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
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "private": true,
3
+ "type": "module",
4
+ "sideEffects": false
5
+ }
@@ -0,0 +1,42 @@
1
+ import type { Signer } from '@mysten/sui/cryptography';
2
+ export declare const RequestFormat: import("@mysten/bcs").BcsType<{
3
+ ptb: number[];
4
+ encKey: number[];
5
+ encVerificationKey: number[];
6
+ }, {
7
+ ptb: Iterable<number> & {
8
+ length: number;
9
+ };
10
+ encKey: Iterable<number> & {
11
+ length: number;
12
+ };
13
+ encVerificationKey: Iterable<number> & {
14
+ length: number;
15
+ };
16
+ }>;
17
+ export type Certificate = {
18
+ user: string;
19
+ session_vk: string;
20
+ creation_time: number;
21
+ ttl_min: number;
22
+ signature: string;
23
+ };
24
+ export declare class SessionKey {
25
+ #private;
26
+ constructor({ address, packageId, ttlMin, signer, }: {
27
+ address: string;
28
+ packageId: string;
29
+ ttlMin: number;
30
+ signer?: Signer;
31
+ });
32
+ isExpired(): boolean;
33
+ getAddress(): string;
34
+ getPackageId(): string;
35
+ getPersonalMessage(): Uint8Array;
36
+ setPersonalMessageSignature(personalMessageSignature: string): Promise<void>;
37
+ getCertificate(): Promise<Certificate>;
38
+ createRequestParams(txBytes: Uint8Array): Promise<{
39
+ decryptionKey: Uint8Array;
40
+ requestSignature: string;
41
+ }>;
42
+ }
@@ -0,0 +1,124 @@
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 _address, _packageId, _creationTimeMs, _ttlMin, _sessionKey, _personalMessageSignature, _signer;
9
+ import { toBase64 } from "@mysten/bcs";
10
+ import { bcs } from "@mysten/sui/bcs";
11
+ import { SuiGraphQLClient } from "@mysten/sui/graphql";
12
+ import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
13
+ import { isValidSuiAddress, isValidSuiObjectId } from "@mysten/sui/utils";
14
+ import { verifyPersonalMessageSignature } from "@mysten/sui/verify";
15
+ import { generateSecretKey, toPublicKey, toVerificationKey } from "./elgamal.js";
16
+ import {
17
+ ExpiredSessionKeyError,
18
+ InvalidPersonalMessageSignatureError,
19
+ UserError
20
+ } from "./error.js";
21
+ const RequestFormat = bcs.struct("RequestFormat", {
22
+ ptb: bcs.vector(bcs.U8),
23
+ encKey: bcs.vector(bcs.U8),
24
+ encVerificationKey: bcs.vector(bcs.U8)
25
+ });
26
+ class SessionKey {
27
+ constructor({
28
+ address,
29
+ packageId,
30
+ ttlMin,
31
+ signer
32
+ }) {
33
+ __privateAdd(this, _address);
34
+ __privateAdd(this, _packageId);
35
+ __privateAdd(this, _creationTimeMs);
36
+ __privateAdd(this, _ttlMin);
37
+ __privateAdd(this, _sessionKey);
38
+ __privateAdd(this, _personalMessageSignature);
39
+ __privateAdd(this, _signer);
40
+ if (!isValidSuiObjectId(packageId) || !isValidSuiAddress(address)) {
41
+ throw new UserError(`Invalid package ID ${packageId} or address ${address}`);
42
+ }
43
+ if (ttlMin > 10 || ttlMin < 1) {
44
+ throw new UserError(`Invalid TTL ${ttlMin}, must be between 1 and 10`);
45
+ }
46
+ __privateSet(this, _address, address);
47
+ __privateSet(this, _packageId, packageId);
48
+ __privateSet(this, _creationTimeMs, Date.now());
49
+ __privateSet(this, _ttlMin, ttlMin);
50
+ __privateSet(this, _sessionKey, Ed25519Keypair.generate());
51
+ __privateSet(this, _signer, signer);
52
+ }
53
+ isExpired() {
54
+ return __privateGet(this, _creationTimeMs) + __privateGet(this, _ttlMin) * 60 * 1e3 - 1e4 < Date.now();
55
+ }
56
+ getAddress() {
57
+ return __privateGet(this, _address);
58
+ }
59
+ getPackageId() {
60
+ return __privateGet(this, _packageId);
61
+ }
62
+ getPersonalMessage() {
63
+ const creationTimeUtc = new Date(__privateGet(this, _creationTimeMs)).toISOString().slice(0, 19).replace("T", " ") + " UTC";
64
+ const message = `Accessing keys of package ${__privateGet(this, _packageId)} for ${__privateGet(this, _ttlMin)} mins from ${creationTimeUtc}, session key ${toBase64(__privateGet(this, _sessionKey).getPublicKey().toRawBytes())}`;
65
+ return new TextEncoder().encode(message);
66
+ }
67
+ async setPersonalMessageSignature(personalMessageSignature) {
68
+ try {
69
+ await verifyPersonalMessageSignature(this.getPersonalMessage(), personalMessageSignature, {
70
+ address: __privateGet(this, _address),
71
+ client: new SuiGraphQLClient({
72
+ url: "https://sui-testnet.mystenlabs.com/graphql"
73
+ })
74
+ });
75
+ __privateSet(this, _personalMessageSignature, personalMessageSignature);
76
+ } catch (e) {
77
+ throw new InvalidPersonalMessageSignatureError("Not valid");
78
+ }
79
+ }
80
+ async getCertificate() {
81
+ if (!__privateGet(this, _personalMessageSignature)) {
82
+ if (__privateGet(this, _signer)) {
83
+ const { signature } = await __privateGet(this, _signer).signPersonalMessage(this.getPersonalMessage());
84
+ __privateSet(this, _personalMessageSignature, signature);
85
+ } else {
86
+ throw new InvalidPersonalMessageSignatureError("Personal message signature is not set");
87
+ }
88
+ }
89
+ return {
90
+ user: __privateGet(this, _address),
91
+ session_vk: toBase64(__privateGet(this, _sessionKey).getPublicKey().toRawBytes()),
92
+ creation_time: __privateGet(this, _creationTimeMs),
93
+ ttl_min: __privateGet(this, _ttlMin),
94
+ signature: __privateGet(this, _personalMessageSignature)
95
+ };
96
+ }
97
+ async createRequestParams(txBytes) {
98
+ if (this.isExpired()) {
99
+ throw new ExpiredSessionKeyError();
100
+ }
101
+ const egSk = generateSecretKey();
102
+ const msgToSign = RequestFormat.serialize({
103
+ ptb: txBytes.slice(1),
104
+ encKey: toPublicKey(egSk),
105
+ encVerificationKey: toVerificationKey(egSk)
106
+ }).toBytes();
107
+ return {
108
+ decryptionKey: egSk,
109
+ requestSignature: toBase64(await __privateGet(this, _sessionKey).sign(msgToSign))
110
+ };
111
+ }
112
+ }
113
+ _address = new WeakMap();
114
+ _packageId = new WeakMap();
115
+ _creationTimeMs = new WeakMap();
116
+ _ttlMin = new WeakMap();
117
+ _sessionKey = new WeakMap();
118
+ _personalMessageSignature = new WeakMap();
119
+ _signer = new WeakMap();
120
+ export {
121
+ RequestFormat,
122
+ SessionKey
123
+ };
124
+ //# sourceMappingURL=session-key.js.map