@mysten/seal 0.1.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 +12 -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 -12
  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
package/dist/cjs/aes.js DELETED
@@ -1,111 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var aes_exports = {};
20
- __export(aes_exports, {
21
- AesGcm256: () => AesGcm256,
22
- Plain: () => Plain,
23
- iv: () => iv
24
- });
25
- module.exports = __toCommonJS(aes_exports);
26
- const iv = Uint8Array.from([
27
- 138,
28
- 55,
29
- 153,
30
- 253,
31
- 198,
32
- 46,
33
- 121,
34
- 219,
35
- 160,
36
- 128,
37
- 89,
38
- 7,
39
- 214,
40
- 156,
41
- 148,
42
- 220
43
- ]);
44
- async function generateAesKey() {
45
- const key = await crypto.subtle.generateKey(
46
- {
47
- name: "AES-GCM",
48
- length: 256
49
- },
50
- true,
51
- ["encrypt", "decrypt"]
52
- );
53
- return await crypto.subtle.exportKey("raw", key).then((keyData) => new Uint8Array(keyData));
54
- }
55
- class AesGcm256 {
56
- constructor(msg, aad) {
57
- this.plaintext = new Uint8Array(msg);
58
- this.aad = aad;
59
- }
60
- generateKey() {
61
- return generateAesKey();
62
- }
63
- async encrypt(key) {
64
- const aesCryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);
65
- const blob = new Uint8Array(
66
- await crypto.subtle.encrypt(
67
- {
68
- name: "AES-GCM",
69
- iv,
70
- additionalData: this.aad
71
- },
72
- aesCryptoKey,
73
- this.plaintext
74
- )
75
- );
76
- return {
77
- Aes256Gcm: {
78
- blob,
79
- aad: this.aad ?? []
80
- }
81
- };
82
- }
83
- static async decrypt(key, ciphertext) {
84
- if (!("Aes256Gcm" in ciphertext)) {
85
- throw new Error("Invalid ciphertext");
86
- }
87
- const aesCryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
88
- return new Uint8Array(
89
- await crypto.subtle.decrypt(
90
- {
91
- name: "AES-GCM",
92
- iv,
93
- additionalData: new Uint8Array(ciphertext.Aes256Gcm.aad ?? [])
94
- },
95
- aesCryptoKey,
96
- new Uint8Array(ciphertext.Aes256Gcm.blob)
97
- )
98
- );
99
- }
100
- }
101
- class Plain {
102
- async encrypt(_key) {
103
- return {
104
- Plain: {}
105
- };
106
- }
107
- generateKey() {
108
- return generateAesKey();
109
- }
110
- }
111
- //# sourceMappingURL=aes.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/aes.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { CiphertextType } from './types.js';\n\n// Use a fixed IV for AES.\nexport const iv = Uint8Array.from([\n\t138, 55, 153, 253, 198, 46, 121, 219, 160, 128, 89, 7, 214, 156, 148, 220,\n]);\n\nasync function generateAesKey(): Promise<Uint8Array> {\n\tconst key = await crypto.subtle.generateKey(\n\t\t{\n\t\t\tname: 'AES-GCM',\n\t\t\tlength: 256,\n\t\t},\n\t\ttrue,\n\t\t['encrypt', 'decrypt'],\n\t);\n\treturn await crypto.subtle.exportKey('raw', key).then((keyData) => new Uint8Array(keyData));\n}\n\nexport interface EncryptionInput {\n\tencrypt(key: Uint8Array): Promise<CiphertextType>;\n\tgenerateKey(): Promise<Uint8Array>;\n}\n\nexport class AesGcm256 implements EncryptionInput {\n\treadonly plaintext: Uint8Array;\n\treadonly aad: Uint8Array;\n\n\tconstructor(msg: Uint8Array, aad: Uint8Array) {\n\t\tthis.plaintext = new Uint8Array(msg);\n\t\tthis.aad = aad;\n\t}\n\n\tgenerateKey(): Promise<Uint8Array> {\n\t\treturn generateAesKey();\n\t}\n\n\tasync encrypt(key: Uint8Array): Promise<CiphertextType> {\n\t\tconst aesCryptoKey = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt']);\n\n\t\tconst blob = new Uint8Array(\n\t\t\tawait crypto.subtle.encrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t\tadditionalData: this.aad,\n\t\t\t\t},\n\t\t\t\taesCryptoKey,\n\t\t\t\tthis.plaintext,\n\t\t\t),\n\t\t);\n\n\t\treturn {\n\t\t\tAes256Gcm: {\n\t\t\t\tblob,\n\t\t\t\taad: this.aad ?? [],\n\t\t\t},\n\t\t};\n\t}\n\n\tstatic async decrypt(key: Uint8Array, ciphertext: CiphertextType): Promise<Uint8Array> {\n\t\tif (!('Aes256Gcm' in ciphertext)) {\n\t\t\tthrow new Error('Invalid ciphertext');\n\t\t}\n\n\t\tconst aesCryptoKey = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['decrypt']);\n\n\t\t// TODO: add test to check if aad is wrong does throw an error.\n\t\treturn new Uint8Array(\n\t\t\tawait crypto.subtle.decrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t\tadditionalData: new Uint8Array(ciphertext.Aes256Gcm.aad ?? []),\n\t\t\t\t},\n\t\t\t\taesCryptoKey,\n\t\t\t\tnew Uint8Array(ciphertext.Aes256Gcm.blob),\n\t\t\t),\n\t\t);\n\t}\n}\n\nexport class Plain implements EncryptionInput {\n\tasync encrypt(_key: Uint8Array): Promise<CiphertextType> {\n\t\treturn {\n\t\t\tPlain: {},\n\t\t};\n\t}\n\n\tgenerateKey(): Promise<Uint8Array> {\n\t\treturn generateAesKey();\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMO,MAAM,KAAK,WAAW,KAAK;AAAA,EACjC;AAAA,EAAK;AAAA,EAAI;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAI;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AAAA,EAAI;AAAA,EAAG;AAAA,EAAK;AAAA,EAAK;AAAA,EAAK;AACvE,CAAC;AAED,eAAe,iBAAsC;AACpD,QAAM,MAAM,MAAM,OAAO,OAAO;AAAA,IAC/B;AAAA,MACC,MAAM;AAAA,MACN,QAAQ;AAAA,IACT;AAAA,IACA;AAAA,IACA,CAAC,WAAW,SAAS;AAAA,EACtB;AACA,SAAO,MAAM,OAAO,OAAO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AClC,WAAO,eAAe;AAAA,EACvB;AACD;",
6
- "names": []
7
- }
@@ -1,49 +0,0 @@
1
- import { G1Element } from './bls12381.js';
2
- import type { KeyServer } from './key-server.js';
3
- import type { SessionKey } from './session-key.js';
4
- import type { EncryptedObject } from './types.js';
5
- /**
6
- * A class to cache user secret keys after they have been fetched from key servers.
7
- */
8
- export declare class KeyStore {
9
- private readonly keys_map;
10
- constructor();
11
- private createMapKey;
12
- /** @internal */
13
- addKey(fullId: Uint8Array, objectId: Uint8Array, key: G1Element): void;
14
- /**
15
- * Get a key from this KeyStore or undefined if the key is not found.
16
- *
17
- * @param fullId The full ID used to derive the key.
18
- * @param objectId The object ID of the key server holding the key.
19
- */
20
- private getKey;
21
- /**
22
- * Check if the key store has a key for the given full ID and object ID.
23
- *
24
- * @param fullId The full ID used to derive the key.
25
- * @param objectId The object ID of the key server holding the key.
26
- */
27
- private hasKey;
28
- /**
29
- * Look up URLs of key servers and fetch key from servers with request signature,
30
- * cert and ephPk, then updates the caching keys_map.
31
- */
32
- fetchKeys({ keyServers, threshold: _threshold, packageId, ids, txBytes, sessionKey, }: {
33
- keyServers: KeyServer[];
34
- threshold: number;
35
- packageId: Uint8Array;
36
- ids: Uint8Array[];
37
- txBytes: Uint8Array;
38
- sessionKey: SessionKey;
39
- }): Promise<void>;
40
- /**
41
- * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.
42
- * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers
43
- * otherwise, this will throw an error.
44
- *
45
- * @param encryptedObject - EncryptedObject.
46
- * @returns - The decrypted plaintext corresponding to ciphertext.
47
- */
48
- decrypt(encryptedObject: typeof EncryptedObject.$inferType): Promise<Uint8Array>;
49
- }
@@ -1,203 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var key_store_exports = {};
20
- __export(key_store_exports, {
21
- KeyStore: () => KeyStore
22
- });
23
- module.exports = __toCommonJS(key_store_exports);
24
- var import_bcs = require("@mysten/bcs");
25
- var import_shamir_secret_sharing = require("shamir-secret-sharing");
26
- var import_aes = require("./aes.js");
27
- var import_bls12381 = require("./bls12381.js");
28
- var import_elgamal = require("./elgamal.js");
29
- var import_ibe = require("./ibe.js");
30
- var import_key_server = require("./key-server.js");
31
- var import_utils = require("./utils.js");
32
- class KeyStore {
33
- constructor() {
34
- this.keys_map = /* @__PURE__ */ new Map();
35
- }
36
- createMapKey(fullId, objectId) {
37
- return (0, import_bcs.toHex)(fullId) + ":" + (0, import_bcs.toHex)(objectId);
38
- }
39
- /** @internal */
40
- addKey(fullId, objectId, key) {
41
- this.keys_map.set(this.createMapKey(fullId, objectId), key);
42
- }
43
- /**
44
- * Get a key from this KeyStore or undefined if the key is not found.
45
- *
46
- * @param fullId The full ID used to derive the key.
47
- * @param objectId The object ID of the key server holding the key.
48
- */
49
- getKey(fullId, objectId) {
50
- return this.keys_map.get(this.createMapKey(fullId, objectId));
51
- }
52
- /**
53
- * Check if the key store has a key for the given full ID and object ID.
54
- *
55
- * @param fullId The full ID used to derive the key.
56
- * @param objectId The object ID of the key server holding the key.
57
- */
58
- hasKey(fullId, objectId) {
59
- return this.keys_map.has(this.createMapKey(fullId, objectId));
60
- }
61
- /**
62
- * Look up URLs of key servers and fetch key from servers with request signature,
63
- * cert and ephPk, then updates the caching keys_map.
64
- */
65
- async fetchKeys({
66
- keyServers,
67
- threshold: _threshold,
68
- packageId,
69
- ids,
70
- txBytes,
71
- sessionKey
72
- }) {
73
- if (ids.length !== 1) {
74
- throw new Error("Only one ID is supported");
75
- }
76
- const fullId = (0, import_utils.createFullId)(import_ibe.DST, packageId, ids[0]);
77
- const remainingKeyServers = keyServers.filter((ks) => !this.hasKey(fullId, ks.objectId));
78
- if (remainingKeyServers.length === 0) {
79
- return;
80
- }
81
- const cert = sessionKey.getCertificate();
82
- const signedRequest = await sessionKey.createRequestParams(txBytes);
83
- await Promise.all(
84
- remainingKeyServers.map(async (server) => {
85
- if (server.keyType !== import_key_server.KeyServerType.BonehFranklinBLS12381) {
86
- console.warn("Server has invalid key type: " + server.keyType);
87
- return;
88
- }
89
- const res = await fetchKey(
90
- server.url,
91
- signedRequest.request_signature,
92
- txBytes,
93
- signedRequest.decryption_key,
94
- cert
95
- );
96
- const key = import_bls12381.G1Element.fromBytes(res.key);
97
- if (!import_ibe.BonehFranklinBLS12381Services.verifyUserSecretKey(
98
- key,
99
- fullId,
100
- import_bls12381.G2Element.fromBytes(server.pk)
101
- )) {
102
- console.warn("Received invalid key from key server " + server.objectId);
103
- return;
104
- }
105
- this.addKey(fullId, server.objectId, key);
106
- })
107
- );
108
- }
109
- /**
110
- * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.
111
- * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers
112
- * otherwise, this will throw an error.
113
- *
114
- * @param encryptedObject - EncryptedObject.
115
- * @returns - The decrypted plaintext corresponding to ciphertext.
116
- */
117
- async decrypt(encryptedObject) {
118
- if (!encryptedObject.encrypted_shares.BonehFranklinBLS12381) {
119
- throw new Error("Encryption mode not supported");
120
- }
121
- const fullId = (0, import_utils.createFullId)(
122
- import_ibe.DST,
123
- encryptedObject.package_id,
124
- new Uint8Array(encryptedObject.id)
125
- );
126
- const in_keystore = encryptedObject.services.map((_, i) => i).filter((i) => this.hasKey(fullId, encryptedObject.services[i][0]));
127
- if (in_keystore.length < encryptedObject.threshold) {
128
- throw new Error("Not enough shares. Please fetch more keys.");
129
- }
130
- const encryptedShares = encryptedObject.encrypted_shares.BonehFranklinBLS12381.shares;
131
- if (encryptedShares.length !== encryptedObject.services.length) {
132
- throw new Error("Invalid input");
133
- }
134
- const nonce = import_bls12381.G2Element.fromBytes(
135
- encryptedObject.encrypted_shares.BonehFranklinBLS12381.encapsulation
136
- );
137
- const shares = in_keystore.map((i) => {
138
- const [objectId, index] = encryptedObject.services[i];
139
- const info = new Uint8Array([index]);
140
- let share = import_ibe.BonehFranklinBLS12381Services.decrypt(
141
- nonce,
142
- this.getKey(fullId, objectId),
143
- encryptedShares[i],
144
- info
145
- );
146
- return { index, share };
147
- });
148
- const key = await combine(shares);
149
- if (encryptedObject.ciphertext.Aes256Gcm) {
150
- try {
151
- return import_aes.AesGcm256.decrypt(key, encryptedObject.ciphertext);
152
- } catch {
153
- throw new Error("Decryption failed");
154
- }
155
- } else if (encryptedObject.ciphertext.Plain) {
156
- return key;
157
- } else {
158
- throw new Error("Invalid encrypted object");
159
- }
160
- }
161
- }
162
- async function fetchKey(url, requestSig, txBytes, enc_key, certificate) {
163
- const enc_key_pk = (0, import_elgamal.toPublicKey)(enc_key);
164
- const enc_verification_key = (0, import_elgamal.toVerificationKey)(enc_key);
165
- const body = {
166
- ptb: (0, import_bcs.toBase64)(txBytes.slice(1)),
167
- // removes the byte of the transaction type version
168
- enc_key: (0, import_bcs.toBase64)(enc_key_pk),
169
- enc_verification_key: (0, import_bcs.toBase64)(enc_verification_key),
170
- request_signature: requestSig,
171
- // already b64
172
- certificate
173
- };
174
- const response = await fetch(url + "/v1/fetch_key", {
175
- method: "POST",
176
- headers: {
177
- "Content-Type": "application/json"
178
- },
179
- body: JSON.stringify(body)
180
- });
181
- const resp = await response.json();
182
- const key = (0, import_elgamal.elgamalDecrypt)(enc_key, resp.decryption_keys[0].encrypted_key.map(import_bcs.fromBase64));
183
- return {
184
- fullId: resp.decryption_keys[0].fullId,
185
- key
186
- };
187
- }
188
- async function combine(shares) {
189
- if (shares.length === 0) {
190
- throw new Error("Invalid input");
191
- } else if (shares.length === 1) {
192
- return Promise.resolve(shares[0].share);
193
- }
194
- return (0, import_shamir_secret_sharing.combine)(
195
- shares.map(({ index, share }) => {
196
- const packedShare = new Uint8Array(share.length + 1);
197
- packedShare.set(share, 0);
198
- packedShare[share.length] = index;
199
- return packedShare;
200
- })
201
- );
202
- }
203
- //# sourceMappingURL=key-store.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/key-store.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromBase64, toBase64, toHex } from '@mysten/bcs';\nimport { combine as externalCombine } from 'shamir-secret-sharing';\n\nimport { AesGcm256 } from './aes.js';\nimport { G1Element, G2Element } from './bls12381.js';\nimport { elgamalDecrypt, toPublicKey, toVerificationKey } from './elgamal.js';\nimport { BonehFranklinBLS12381Services, DST } from './ibe.js';\nimport type { KeyServer } from './key-server.js';\nimport { KeyServerType } from './key-server.js';\nimport type { Certificate, SessionKey } from './session-key.js';\nimport type { EncryptedObject } from './types.js';\nimport { createFullId } from './utils.js';\n\n/**\n * A class to cache user secret keys after they have been fetched from key servers.\n */\nexport class KeyStore {\n\t// A caching map for: fullId:object_id -> partial key.\n\tprivate readonly keys_map: Map<string, G1Element>;\n\n\tconstructor() {\n\t\tthis.keys_map = new Map();\n\t}\n\n\tprivate createMapKey(fullId: Uint8Array, objectId: Uint8Array): string {\n\t\treturn toHex(fullId) + ':' + toHex(objectId);\n\t}\n\n\t/** @internal */\n\taddKey(fullId: Uint8Array, objectId: Uint8Array, key: G1Element) {\n\t\tthis.keys_map.set(this.createMapKey(fullId, objectId), key);\n\t}\n\n\t/**\n\t * Get a key from this KeyStore or undefined if the key is not found.\n\t *\n\t * @param fullId The full ID used to derive the key.\n\t * @param objectId The object ID of the key server holding the key.\n\t */\n\tprivate getKey(fullId: Uint8Array, objectId: Uint8Array): G1Element | undefined {\n\t\treturn this.keys_map.get(this.createMapKey(fullId, objectId));\n\t}\n\n\t/**\n\t * Check if the key store has a key for the given full ID and object ID.\n\t *\n\t * @param fullId The full ID used to derive the key.\n\t * @param objectId The object ID of the key server holding the key.\n\t */\n\tprivate hasKey(fullId: Uint8Array, objectId: Uint8Array): boolean {\n\t\treturn this.keys_map.has(this.createMapKey(fullId, objectId));\n\t}\n\n\t/**\n\t * Look up URLs of key servers and fetch key from servers with request signature,\n\t * cert and ephPk, then updates the caching keys_map.\n\t */\n\tasync fetchKeys({\n\t\tkeyServers,\n\t\tthreshold: _threshold,\n\t\tpackageId,\n\t\tids,\n\t\ttxBytes,\n\t\tsessionKey,\n\t}: {\n\t\tkeyServers: KeyServer[];\n\t\tthreshold: number;\n\t\tpackageId: Uint8Array;\n\t\tids: Uint8Array[];\n\t\ttxBytes: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t}) {\n\t\t// TODO: support multiple ids.\n\t\tif (ids.length !== 1) {\n\t\t\tthrow new Error('Only one ID is supported');\n\t\t}\n\t\tconst fullId = createFullId(DST, packageId, ids[0]);\n\t\tconst remainingKeyServers = keyServers.filter((ks) => !this.hasKey(fullId, ks.objectId));\n\t\tif (remainingKeyServers.length === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst cert = sessionKey.getCertificate();\n\t\tconst signedRequest = await sessionKey.createRequestParams(txBytes);\n\n\t\t// TODO: wait for t valid keys, either from completed promises (not failures) or from the cache.\n\t\t// TODO: detect an expired session key and raise an error.\n\t\tawait Promise.all(\n\t\t\tremainingKeyServers.map(async (server) => {\n\t\t\t\tif (server.keyType !== KeyServerType.BonehFranklinBLS12381) {\n\t\t\t\t\tconsole.warn('Server has invalid key type: ' + server.keyType);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst res = await fetchKey(\n\t\t\t\t\tserver.url,\n\t\t\t\t\tsignedRequest.request_signature,\n\t\t\t\t\ttxBytes,\n\t\t\t\t\tsignedRequest.decryption_key,\n\t\t\t\t\tcert,\n\t\t\t\t);\n\n\t\t\t\tconst key = G1Element.fromBytes(res.key);\n\t\t\t\tif (\n\t\t\t\t\t!BonehFranklinBLS12381Services.verifyUserSecretKey(\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tfullId,\n\t\t\t\t\t\tG2Element.fromBytes(server.pk),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tconsole.warn('Received invalid key from key server ' + server.objectId);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tthis.addKey(fullId, server.objectId, key);\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.\n\t * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers\n\t * otherwise, this will throw an error.\n\t *\n\t * @param encryptedObject - EncryptedObject.\n\t * @returns - The decrypted plaintext corresponding to ciphertext.\n\t */\n\tasync decrypt(encryptedObject: typeof EncryptedObject.$inferType): Promise<Uint8Array> {\n\t\tif (!encryptedObject.encrypted_shares.BonehFranklinBLS12381) {\n\t\t\tthrow new Error('Encryption mode not supported');\n\t\t}\n\n\t\tconst fullId = createFullId(\n\t\t\tDST,\n\t\t\tencryptedObject.package_id,\n\t\t\tnew Uint8Array(encryptedObject.id),\n\t\t);\n\n\t\t// Get the indices of the service whose keys are in the keystore.\n\t\tconst in_keystore = encryptedObject.services\n\t\t\t.map((_, i) => i)\n\t\t\t.filter((i) => this.hasKey(fullId, encryptedObject.services[i][0]));\n\t\tif (in_keystore.length < encryptedObject.threshold) {\n\t\t\tthrow new Error('Not enough shares. Please fetch more keys.');\n\t\t}\n\n\t\tconst encryptedShares = encryptedObject.encrypted_shares.BonehFranklinBLS12381.shares;\n\t\tif (encryptedShares.length !== encryptedObject.services.length) {\n\t\t\tthrow new Error('Invalid input');\n\t\t}\n\n\t\tconst nonce = G2Element.fromBytes(\n\t\t\tencryptedObject.encrypted_shares.BonehFranklinBLS12381.encapsulation,\n\t\t);\n\n\t\t// Decrypt each share.\n\t\tconst shares = in_keystore.map((i: number) => {\n\t\t\tconst [objectId, index] = encryptedObject.services[i];\n\t\t\t// Use the index as the unique info parameter to allow for multiple shares per key server.\n\t\t\tconst info = new Uint8Array([index]);\n\t\t\tlet share = BonehFranklinBLS12381Services.decrypt(\n\t\t\t\tnonce,\n\t\t\t\tthis.getKey(fullId, objectId)!,\n\t\t\t\tencryptedShares[i],\n\t\t\t\tinfo,\n\t\t\t);\n\t\t\t// The Shamir secret sharing library expects the index/x-coordinate to be at the end of the share.\n\t\t\treturn { index, share };\n\t\t});\n\n\t\t// Combine the decrypted shares into the key.\n\t\tconst key = await combine(shares);\n\n\t\tif (encryptedObject.ciphertext.Aes256Gcm) {\n\t\t\ttry {\n\t\t\t\t// Decrypt the ciphertext with the key.\n\t\t\t\treturn AesGcm256.decrypt(key, encryptedObject.ciphertext);\n\t\t\t} catch {\n\t\t\t\tthrow new Error('Decryption failed');\n\t\t\t}\n\t\t} else if (encryptedObject.ciphertext.Plain) {\n\t\t\t// In case `Plain` mode is used, return the key.\n\t\t\treturn key;\n\t\t} else {\n\t\t\tthrow new Error('Invalid encrypted object');\n\t\t}\n\t}\n}\n\n/**\n * Helper function to request a Seal key from URL with requestSig, txBytes, ephemeral pubkey.\n * Then decrypt the Seal key with ephemeral secret key.\n */\nasync function fetchKey(\n\turl: string,\n\trequestSig: string,\n\ttxBytes: Uint8Array,\n\tenc_key: Uint8Array,\n\tcertificate: Certificate,\n): Promise<{ fullId: Uint8Array; key: Uint8Array }> {\n\tconst enc_key_pk = toPublicKey(enc_key);\n\tconst enc_verification_key = toVerificationKey(enc_key);\n\tconst body = {\n\t\tptb: toBase64(txBytes.slice(1)), // removes the byte of the transaction type version\n\t\tenc_key: toBase64(enc_key_pk),\n\t\tenc_verification_key: toBase64(enc_verification_key),\n\t\trequest_signature: requestSig, // already b64\n\t\tcertificate,\n\t};\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},\n\t\tbody: JSON.stringify(body),\n\t});\n\tconst resp = await response.json();\n\t// TODO: handle the different error responses.\n\t// TODO: handle multiple decryption keys.\n\tconst key = elgamalDecrypt(enc_key, resp.decryption_keys[0].encrypted_key.map(fromBase64));\n\treturn {\n\t\tfullId: resp.decryption_keys[0].fullId,\n\t\tkey,\n\t};\n}\n\nasync function combine(shares: { index: number; share: Uint8Array }[]): Promise<Uint8Array> {\n\tif (shares.length === 0) {\n\t\tthrow new Error('Invalid input');\n\t} else if (shares.length === 1) {\n\t\t// The Shamir secret sharing library expects at least two shares.\n\t\t// If there is only one and the threshold is 1, the reconstructed secret is the same as the share.\n\t\treturn Promise.resolve(shares[0].share);\n\t}\n\n\t// The Shamir secret sharing library expects the index/x-coordinate to be at the end of the share\n\treturn externalCombine(\n\t\tshares.map(({ index, share }) => {\n\t\t\tconst packedShare = new Uint8Array(share.length + 1);\n\t\t\tpackedShare.set(share, 0);\n\t\t\tpackedShare[share.length] = index;\n\t\t\treturn packedShare;\n\t\t}),\n\t);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAA4C;AAC5C,mCAA2C;AAE3C,iBAA0B;AAC1B,sBAAqC;AACrC,qBAA+D;AAC/D,iBAAmD;AAEnD,wBAA8B;AAG9B,mBAA6B;AAKtB,MAAM,SAAS;AAAA,EAIrB,cAAc;AACb,SAAK,WAAW,oBAAI,IAAI;AAAA,EACzB;AAAA,EAEQ,aAAa,QAAoB,UAA8B;AACtE,eAAO,kBAAM,MAAM,IAAI,UAAM,kBAAM,QAAQ;AAAA,EAC5C;AAAA;AAAA,EAGA,OAAO,QAAoB,UAAsB,KAAgB;AAChE,SAAK,SAAS,IAAI,KAAK,aAAa,QAAQ,QAAQ,GAAG,GAAG;AAAA,E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AAO,CAAC;AACxB,kBAAY,MAAM,MAAM,IAAI;AAC5B,aAAO;AAAA,IACR,CAAC;AAAA,EACF;AACD;",
6
- "names": ["externalCombine"]
7
- }
package/dist/esm/aes.d.ts DELETED
@@ -1,18 +0,0 @@
1
- import type { CiphertextType } from './types.js';
2
- export declare const iv: Uint8Array<ArrayBuffer>;
3
- export interface EncryptionInput {
4
- encrypt(key: Uint8Array): Promise<CiphertextType>;
5
- generateKey(): Promise<Uint8Array>;
6
- }
7
- export declare class AesGcm256 implements EncryptionInput {
8
- readonly plaintext: Uint8Array;
9
- readonly aad: Uint8Array;
10
- constructor(msg: Uint8Array, aad: Uint8Array);
11
- generateKey(): Promise<Uint8Array>;
12
- encrypt(key: Uint8Array): Promise<CiphertextType>;
13
- static decrypt(key: Uint8Array, ciphertext: CiphertextType): Promise<Uint8Array>;
14
- }
15
- export declare class Plain implements EncryptionInput {
16
- encrypt(_key: Uint8Array): Promise<CiphertextType>;
17
- generateKey(): Promise<Uint8Array>;
18
- }
package/dist/esm/aes.js DELETED
@@ -1,91 +0,0 @@
1
- const iv = Uint8Array.from([
2
- 138,
3
- 55,
4
- 153,
5
- 253,
6
- 198,
7
- 46,
8
- 121,
9
- 219,
10
- 160,
11
- 128,
12
- 89,
13
- 7,
14
- 214,
15
- 156,
16
- 148,
17
- 220
18
- ]);
19
- async function generateAesKey() {
20
- const key = await crypto.subtle.generateKey(
21
- {
22
- name: "AES-GCM",
23
- length: 256
24
- },
25
- true,
26
- ["encrypt", "decrypt"]
27
- );
28
- return await crypto.subtle.exportKey("raw", key).then((keyData) => new Uint8Array(keyData));
29
- }
30
- class AesGcm256 {
31
- constructor(msg, aad) {
32
- this.plaintext = new Uint8Array(msg);
33
- this.aad = aad;
34
- }
35
- generateKey() {
36
- return generateAesKey();
37
- }
38
- async encrypt(key) {
39
- const aesCryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["encrypt"]);
40
- const blob = new Uint8Array(
41
- await crypto.subtle.encrypt(
42
- {
43
- name: "AES-GCM",
44
- iv,
45
- additionalData: this.aad
46
- },
47
- aesCryptoKey,
48
- this.plaintext
49
- )
50
- );
51
- return {
52
- Aes256Gcm: {
53
- blob,
54
- aad: this.aad ?? []
55
- }
56
- };
57
- }
58
- static async decrypt(key, ciphertext) {
59
- if (!("Aes256Gcm" in ciphertext)) {
60
- throw new Error("Invalid ciphertext");
61
- }
62
- const aesCryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
63
- return new Uint8Array(
64
- await crypto.subtle.decrypt(
65
- {
66
- name: "AES-GCM",
67
- iv,
68
- additionalData: new Uint8Array(ciphertext.Aes256Gcm.aad ?? [])
69
- },
70
- aesCryptoKey,
71
- new Uint8Array(ciphertext.Aes256Gcm.blob)
72
- )
73
- );
74
- }
75
- }
76
- class Plain {
77
- async encrypt(_key) {
78
- return {
79
- Plain: {}
80
- };
81
- }
82
- generateKey() {
83
- return generateAesKey();
84
- }
85
- }
86
- export {
87
- AesGcm256,
88
- Plain,
89
- iv
90
- };
91
- //# sourceMappingURL=aes.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/aes.ts"],
4
- "sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { CiphertextType } from './types.js';\n\n// Use a fixed IV for AES.\nexport const iv = Uint8Array.from([\n\t138, 55, 153, 253, 198, 46, 121, 219, 160, 128, 89, 7, 214, 156, 148, 220,\n]);\n\nasync function generateAesKey(): Promise<Uint8Array> {\n\tconst key = await crypto.subtle.generateKey(\n\t\t{\n\t\t\tname: 'AES-GCM',\n\t\t\tlength: 256,\n\t\t},\n\t\ttrue,\n\t\t['encrypt', 'decrypt'],\n\t);\n\treturn await crypto.subtle.exportKey('raw', key).then((keyData) => new Uint8Array(keyData));\n}\n\nexport interface EncryptionInput {\n\tencrypt(key: Uint8Array): Promise<CiphertextType>;\n\tgenerateKey(): Promise<Uint8Array>;\n}\n\nexport class AesGcm256 implements EncryptionInput {\n\treadonly plaintext: Uint8Array;\n\treadonly aad: Uint8Array;\n\n\tconstructor(msg: Uint8Array, aad: Uint8Array) {\n\t\tthis.plaintext = new Uint8Array(msg);\n\t\tthis.aad = aad;\n\t}\n\n\tgenerateKey(): Promise<Uint8Array> {\n\t\treturn generateAesKey();\n\t}\n\n\tasync encrypt(key: Uint8Array): Promise<CiphertextType> {\n\t\tconst aesCryptoKey = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt']);\n\n\t\tconst blob = new Uint8Array(\n\t\t\tawait crypto.subtle.encrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t\tadditionalData: this.aad,\n\t\t\t\t},\n\t\t\t\taesCryptoKey,\n\t\t\t\tthis.plaintext,\n\t\t\t),\n\t\t);\n\n\t\treturn {\n\t\t\tAes256Gcm: {\n\t\t\t\tblob,\n\t\t\t\taad: this.aad ?? [],\n\t\t\t},\n\t\t};\n\t}\n\n\tstatic async decrypt(key: Uint8Array, ciphertext: CiphertextType): Promise<Uint8Array> {\n\t\tif (!('Aes256Gcm' in ciphertext)) {\n\t\t\tthrow new Error('Invalid ciphertext');\n\t\t}\n\n\t\tconst aesCryptoKey = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['decrypt']);\n\n\t\t// TODO: add test to check if aad is wrong does throw an error.\n\t\treturn new Uint8Array(\n\t\t\tawait crypto.subtle.decrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t\tadditionalData: new Uint8Array(ciphertext.Aes256Gcm.aad ?? []),\n\t\t\t\t},\n\t\t\t\taesCryptoKey,\n\t\t\t\tnew Uint8Array(ciphertext.Aes256Gcm.blob),\n\t\t\t),\n\t\t);\n\t}\n}\n\nexport class Plain implements EncryptionInput {\n\tasync encrypt(_key: Uint8Array): Promise<CiphertextType> {\n\t\treturn {\n\t\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EAAE,eAAe,aAAa;AACjC,YAAM,IAAI,MAAM,oBAAoB;AAAA,IACrC;AAEA,UAAM,eAAe,MAAM,OAAO,OAAO,UAAU,OAAO,KAAK,WAAW,OAAO,CAAC,SAAS,CAAC;AAG5F,WAAO,IAAI;AAAA,MACV,MAAM,OAAO,OAAO;AAAA,QACnB;AAAA,UACC,MAAM;AAAA,UACN;AAAA,UACA,gBAAgB,IAAI,WAAW,WAAW,UAAU,OAAO,CAAC,CAAC;AAAA,QAC9D;AAAA,QACA;AAAA,QACA,IAAI,WAAW,WAAW,UAAU,IAAI;AAAA,MACzC;AAAA,IACD;AAAA,EACD;AACD;AAEO,MAAM,MAAiC;AAAA,EAC7C,MAAM,QAAQ,MAA2C;AACxD,WAAO;AAAA,MACN,OAAO,CAAC;AAAA,IACT;AAAA,EACD;AAAA,EAEA,cAAmC;AAClC,WAAO,eAAe;AAAA,EACvB;AACD;",
6
- "names": []
7
- }
@@ -1,49 +0,0 @@
1
- import { G1Element } from './bls12381.js';
2
- import type { KeyServer } from './key-server.js';
3
- import type { SessionKey } from './session-key.js';
4
- import type { EncryptedObject } from './types.js';
5
- /**
6
- * A class to cache user secret keys after they have been fetched from key servers.
7
- */
8
- export declare class KeyStore {
9
- private readonly keys_map;
10
- constructor();
11
- private createMapKey;
12
- /** @internal */
13
- addKey(fullId: Uint8Array, objectId: Uint8Array, key: G1Element): void;
14
- /**
15
- * Get a key from this KeyStore or undefined if the key is not found.
16
- *
17
- * @param fullId The full ID used to derive the key.
18
- * @param objectId The object ID of the key server holding the key.
19
- */
20
- private getKey;
21
- /**
22
- * Check if the key store has a key for the given full ID and object ID.
23
- *
24
- * @param fullId The full ID used to derive the key.
25
- * @param objectId The object ID of the key server holding the key.
26
- */
27
- private hasKey;
28
- /**
29
- * Look up URLs of key servers and fetch key from servers with request signature,
30
- * cert and ephPk, then updates the caching keys_map.
31
- */
32
- fetchKeys({ keyServers, threshold: _threshold, packageId, ids, txBytes, sessionKey, }: {
33
- keyServers: KeyServer[];
34
- threshold: number;
35
- packageId: Uint8Array;
36
- ids: Uint8Array[];
37
- txBytes: Uint8Array;
38
- sessionKey: SessionKey;
39
- }): Promise<void>;
40
- /**
41
- * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.
42
- * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers
43
- * otherwise, this will throw an error.
44
- *
45
- * @param encryptedObject - EncryptedObject.
46
- * @returns - The decrypted plaintext corresponding to ciphertext.
47
- */
48
- decrypt(encryptedObject: typeof EncryptedObject.$inferType): Promise<Uint8Array>;
49
- }