@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.
- package/CHANGELOG.md +31 -0
- package/README.md +4 -0
- package/dist/cjs/bcs.d.ts +132 -0
- package/dist/cjs/bcs.js +67 -0
- package/dist/cjs/bcs.js.map +7 -0
- package/dist/cjs/bls12381.d.ts +37 -0
- package/dist/cjs/bls12381.js +110 -0
- package/dist/cjs/bls12381.js.map +7 -0
- package/dist/cjs/client.d.ts +83 -0
- package/dist/cjs/client.js +283 -0
- package/dist/cjs/client.js.map +7 -0
- package/dist/cjs/decrypt.d.ts +15 -0
- package/dist/cjs/decrypt.js +94 -0
- package/dist/cjs/decrypt.js.map +7 -0
- package/dist/cjs/dem.d.ts +36 -0
- package/dist/cjs/dem.js +173 -0
- package/dist/cjs/dem.js.map +7 -0
- package/dist/cjs/elgamal.d.ts +11 -0
- package/dist/cjs/elgamal.js +46 -0
- package/dist/cjs/elgamal.js.map +7 -0
- package/dist/cjs/encrypt.d.ts +33 -0
- package/dist/cjs/encrypt.js +118 -0
- package/dist/cjs/encrypt.js.map +7 -0
- package/dist/cjs/error.d.ts +58 -0
- package/dist/cjs/error.js +175 -0
- package/dist/cjs/error.js.map +7 -0
- package/dist/cjs/ibe.d.ts +63 -0
- package/dist/cjs/ibe.js +104 -0
- package/dist/cjs/ibe.js.map +7 -0
- package/dist/cjs/index.d.ts +4 -0
- package/dist/cjs/index.js +31 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/cjs/kdf.d.ts +14 -0
- package/dist/cjs/kdf.js +64 -0
- package/dist/cjs/kdf.js.map +7 -0
- package/dist/cjs/key-server.d.ts +38 -0
- package/dist/cjs/key-server.js +101 -0
- package/dist/cjs/key-server.js.map +7 -0
- package/dist/cjs/keys.d.ts +17 -0
- package/dist/cjs/keys.js +61 -0
- package/dist/cjs/keys.js.map +7 -0
- package/dist/cjs/package.json +5 -0
- package/dist/cjs/session-key.d.ts +42 -0
- package/dist/cjs/session-key.js +140 -0
- package/dist/cjs/session-key.js.map +7 -0
- package/dist/cjs/types.d.ts +1 -0
- package/dist/cjs/types.js +17 -0
- package/dist/cjs/types.js.map +7 -0
- package/dist/cjs/utils.d.ts +10 -0
- package/dist/cjs/utils.js +51 -0
- package/dist/cjs/utils.js.map +7 -0
- package/dist/cjs/version.d.ts +1 -0
- package/dist/cjs/version.js +25 -0
- package/dist/cjs/version.js.map +7 -0
- package/dist/esm/bcs.d.ts +132 -0
- package/dist/esm/bcs.js +47 -0
- package/dist/esm/bcs.js.map +7 -0
- package/dist/esm/bls12381.d.ts +37 -0
- package/dist/esm/bls12381.js +90 -0
- package/dist/esm/bls12381.js.map +7 -0
- package/dist/esm/client.d.ts +83 -0
- package/dist/esm/client.js +268 -0
- package/dist/esm/client.js.map +7 -0
- package/dist/esm/decrypt.d.ts +15 -0
- package/dist/esm/decrypt.js +74 -0
- package/dist/esm/decrypt.js.map +7 -0
- package/dist/esm/dem.d.ts +36 -0
- package/dist/esm/dem.js +153 -0
- package/dist/esm/dem.js.map +7 -0
- package/dist/esm/elgamal.d.ts +11 -0
- package/dist/esm/elgamal.js +26 -0
- package/dist/esm/elgamal.js.map +7 -0
- package/dist/esm/encrypt.d.ts +33 -0
- package/dist/esm/encrypt.js +98 -0
- package/dist/esm/encrypt.js.map +7 -0
- package/dist/esm/error.d.ts +58 -0
- package/dist/esm/error.js +155 -0
- package/dist/esm/error.js.map +7 -0
- package/dist/esm/ibe.d.ts +63 -0
- package/dist/esm/ibe.js +84 -0
- package/dist/esm/ibe.js.map +7 -0
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.js +10 -0
- package/dist/esm/index.js.map +7 -0
- package/dist/esm/kdf.d.ts +14 -0
- package/dist/esm/kdf.js +44 -0
- package/dist/esm/kdf.js.map +7 -0
- package/dist/esm/key-server.d.ts +38 -0
- package/dist/esm/key-server.js +86 -0
- package/dist/esm/key-server.js.map +7 -0
- package/dist/esm/keys.d.ts +17 -0
- package/dist/esm/keys.js +41 -0
- package/dist/esm/keys.js.map +7 -0
- package/dist/esm/package.json +5 -0
- package/dist/esm/session-key.d.ts +42 -0
- package/dist/esm/session-key.js +124 -0
- package/dist/esm/session-key.js.map +7 -0
- package/dist/esm/types.d.ts +1 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/types.js.map +7 -0
- package/dist/esm/utils.d.ts +10 -0
- package/dist/esm/utils.js +31 -0
- package/dist/esm/utils.js.map +7 -0
- package/dist/esm/version.d.ts +1 -0
- package/dist/esm/version.js +5 -0
- package/dist/esm/version.js.map +7 -0
- package/dist/tsconfig.esm.tsbuildinfo +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +59 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { SuiClient } from '@mysten/sui/client';
|
|
2
|
+
import { DemType, KemType } from './encrypt.js';
|
|
3
|
+
import type { KeyServer } from './key-server.js';
|
|
4
|
+
import type { SessionKey } from './session-key.js';
|
|
5
|
+
/**
|
|
6
|
+
* Configuration options for initializing a SealClient
|
|
7
|
+
* @property serverObjectIds: Array of object IDs for the key servers to use.
|
|
8
|
+
* @property verifyKeyServers: Whether to verify the key servers' authenticity.
|
|
9
|
+
* Should be false if servers are pre-verified (e.g., getAllowlistedKeyServers).
|
|
10
|
+
* Defaults to true.
|
|
11
|
+
* @property timeout: Timeout in milliseconds for network requests. Defaults to 10 seconds.
|
|
12
|
+
*/
|
|
13
|
+
export interface SealClientOptions {
|
|
14
|
+
suiClient: SuiClient;
|
|
15
|
+
serverObjectIds: string[];
|
|
16
|
+
verifyKeyServers?: boolean;
|
|
17
|
+
timeout?: number;
|
|
18
|
+
}
|
|
19
|
+
export declare class SealClient {
|
|
20
|
+
#private;
|
|
21
|
+
constructor(options: SealClientOptions);
|
|
22
|
+
/**
|
|
23
|
+
* Return an encrypted message under the identity.
|
|
24
|
+
*
|
|
25
|
+
* @param kemType - The type of KEM to use.
|
|
26
|
+
* @param demType - The type of DEM to use.
|
|
27
|
+
* @param threshold - The threshold for the TSS encryption.
|
|
28
|
+
* @param packageId - the packageId namespace.
|
|
29
|
+
* @param id - the identity to use.
|
|
30
|
+
* @param data - the data to encrypt.
|
|
31
|
+
* @param aad - optional additional authenticated data.
|
|
32
|
+
* @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.
|
|
33
|
+
* Since the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.
|
|
34
|
+
*/
|
|
35
|
+
encrypt({ kemType, demType, threshold, packageId, id, data, aad, }: {
|
|
36
|
+
kemType?: KemType;
|
|
37
|
+
demType?: DemType;
|
|
38
|
+
threshold: number;
|
|
39
|
+
packageId: string;
|
|
40
|
+
id: string;
|
|
41
|
+
data: Uint8Array;
|
|
42
|
+
aad?: Uint8Array;
|
|
43
|
+
}): Promise<{
|
|
44
|
+
encryptedObject: Uint8Array;
|
|
45
|
+
key: Uint8Array;
|
|
46
|
+
}>;
|
|
47
|
+
/**
|
|
48
|
+
* Decrypt the given encrypted bytes using cached keys.
|
|
49
|
+
* Calls fetchKeys in case one or more of the required keys is not cached yet.
|
|
50
|
+
* The function throws an error if the client's key servers are not a subset of
|
|
51
|
+
* the encrypted object's key servers (including the same weights) or if the
|
|
52
|
+
* threshold cannot be met.
|
|
53
|
+
*
|
|
54
|
+
* @param data - The encrypted bytes to decrypt.
|
|
55
|
+
* @param sessionKey - The session key to use.
|
|
56
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
57
|
+
* @returns - The decrypted plaintext corresponding to ciphertext.
|
|
58
|
+
*/
|
|
59
|
+
decrypt({ data, sessionKey, txBytes, }: {
|
|
60
|
+
data: Uint8Array;
|
|
61
|
+
sessionKey: SessionKey;
|
|
62
|
+
txBytes: Uint8Array;
|
|
63
|
+
}): Promise<Uint8Array<ArrayBufferLike>>;
|
|
64
|
+
getKeyServers(): Promise<KeyServer[]>;
|
|
65
|
+
/**
|
|
66
|
+
* Fetch keys from the key servers and update the cache.
|
|
67
|
+
*
|
|
68
|
+
* It is recommended to call this function once for all ids of all encrypted obejcts if
|
|
69
|
+
* there are multiple, then call decrypt for each object. This avoids calling fetchKey
|
|
70
|
+
* individually for each decrypt.
|
|
71
|
+
*
|
|
72
|
+
* @param ids - The ids of the encrypted objects.
|
|
73
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
74
|
+
* @param sessionKey - The session key to use.
|
|
75
|
+
* @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.
|
|
76
|
+
*/
|
|
77
|
+
fetchKeys({ ids, txBytes, sessionKey, threshold, }: {
|
|
78
|
+
ids: string[];
|
|
79
|
+
txBytes: Uint8Array;
|
|
80
|
+
sessionKey: SessionKey;
|
|
81
|
+
threshold: number;
|
|
82
|
+
}): Promise<void>;
|
|
83
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
var __typeError = (msg) => {
|
|
2
|
+
throw TypeError(msg);
|
|
3
|
+
};
|
|
4
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
5
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
6
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
7
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
|
|
8
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
9
|
+
var _suiClient, _serverObjectIds, _verifyKeyServers, _keyServers, _cachedKeys, _timeout, _SealClient_instances, createEncryptionInput_fn, validateEncryptionServices_fn, loadKeyServers_fn;
|
|
10
|
+
import { EncryptedObject } from "./bcs.js";
|
|
11
|
+
import { G1Element, G2Element } from "./bls12381.js";
|
|
12
|
+
import { decrypt } from "./decrypt.js";
|
|
13
|
+
import { AesGcm256, Hmac256Ctr } from "./dem.js";
|
|
14
|
+
import { DemType, encrypt, KemType } from "./encrypt.js";
|
|
15
|
+
import {
|
|
16
|
+
InconsistentKeyServersError,
|
|
17
|
+
InvalidKeyServerError,
|
|
18
|
+
InvalidThresholdError,
|
|
19
|
+
toMajorityError
|
|
20
|
+
} from "./error.js";
|
|
21
|
+
import { BonehFranklinBLS12381Services, DST } from "./ibe.js";
|
|
22
|
+
import { KeyServerType, retrieveKeyServers, verifyKeyServer } from "./key-server.js";
|
|
23
|
+
import { fetchKeysForAllIds } from "./keys.js";
|
|
24
|
+
import { createFullId } from "./utils.js";
|
|
25
|
+
class SealClient {
|
|
26
|
+
constructor(options) {
|
|
27
|
+
__privateAdd(this, _SealClient_instances);
|
|
28
|
+
__privateAdd(this, _suiClient);
|
|
29
|
+
__privateAdd(this, _serverObjectIds);
|
|
30
|
+
__privateAdd(this, _verifyKeyServers);
|
|
31
|
+
__privateAdd(this, _keyServers, null);
|
|
32
|
+
// A caching map for: fullId:object_id -> partial key.
|
|
33
|
+
__privateAdd(this, _cachedKeys, /* @__PURE__ */ new Map());
|
|
34
|
+
__privateAdd(this, _timeout);
|
|
35
|
+
__privateSet(this, _suiClient, options.suiClient);
|
|
36
|
+
__privateSet(this, _serverObjectIds, options.serverObjectIds);
|
|
37
|
+
__privateSet(this, _verifyKeyServers, options.verifyKeyServers ?? true);
|
|
38
|
+
__privateSet(this, _timeout, options.timeout ?? 1e4);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Return an encrypted message under the identity.
|
|
42
|
+
*
|
|
43
|
+
* @param kemType - The type of KEM to use.
|
|
44
|
+
* @param demType - The type of DEM to use.
|
|
45
|
+
* @param threshold - The threshold for the TSS encryption.
|
|
46
|
+
* @param packageId - the packageId namespace.
|
|
47
|
+
* @param id - the identity to use.
|
|
48
|
+
* @param data - the data to encrypt.
|
|
49
|
+
* @param aad - optional additional authenticated data.
|
|
50
|
+
* @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.
|
|
51
|
+
* Since the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.
|
|
52
|
+
*/
|
|
53
|
+
async encrypt({
|
|
54
|
+
kemType = KemType.BonehFranklinBLS12381DemCCA,
|
|
55
|
+
demType = DemType.AesGcm256,
|
|
56
|
+
threshold,
|
|
57
|
+
packageId,
|
|
58
|
+
id,
|
|
59
|
+
data,
|
|
60
|
+
aad = new Uint8Array()
|
|
61
|
+
}) {
|
|
62
|
+
return encrypt({
|
|
63
|
+
keyServers: await this.getKeyServers(),
|
|
64
|
+
kemType,
|
|
65
|
+
threshold,
|
|
66
|
+
packageId,
|
|
67
|
+
id,
|
|
68
|
+
encryptionInput: __privateMethod(this, _SealClient_instances, createEncryptionInput_fn).call(this, demType, data, aad)
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Decrypt the given encrypted bytes using cached keys.
|
|
73
|
+
* Calls fetchKeys in case one or more of the required keys is not cached yet.
|
|
74
|
+
* The function throws an error if the client's key servers are not a subset of
|
|
75
|
+
* the encrypted object's key servers (including the same weights) or if the
|
|
76
|
+
* threshold cannot be met.
|
|
77
|
+
*
|
|
78
|
+
* @param data - The encrypted bytes to decrypt.
|
|
79
|
+
* @param sessionKey - The session key to use.
|
|
80
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
81
|
+
* @returns - The decrypted plaintext corresponding to ciphertext.
|
|
82
|
+
*/
|
|
83
|
+
async decrypt({
|
|
84
|
+
data,
|
|
85
|
+
sessionKey,
|
|
86
|
+
txBytes
|
|
87
|
+
}) {
|
|
88
|
+
const encryptedObject = EncryptedObject.parse(data);
|
|
89
|
+
__privateMethod(this, _SealClient_instances, validateEncryptionServices_fn).call(this, encryptedObject.services.map((s) => s[0]), encryptedObject.threshold);
|
|
90
|
+
await this.fetchKeys({
|
|
91
|
+
ids: [encryptedObject.id],
|
|
92
|
+
txBytes,
|
|
93
|
+
sessionKey,
|
|
94
|
+
threshold: encryptedObject.threshold
|
|
95
|
+
});
|
|
96
|
+
return decrypt({ encryptedObject, keys: __privateGet(this, _cachedKeys) });
|
|
97
|
+
}
|
|
98
|
+
async getKeyServers() {
|
|
99
|
+
if (!__privateGet(this, _keyServers)) {
|
|
100
|
+
__privateSet(this, _keyServers, __privateMethod(this, _SealClient_instances, loadKeyServers_fn).call(this).catch((error) => {
|
|
101
|
+
__privateSet(this, _keyServers, null);
|
|
102
|
+
throw error;
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
return __privateGet(this, _keyServers);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Fetch keys from the key servers and update the cache.
|
|
109
|
+
*
|
|
110
|
+
* It is recommended to call this function once for all ids of all encrypted obejcts if
|
|
111
|
+
* there are multiple, then call decrypt for each object. This avoids calling fetchKey
|
|
112
|
+
* individually for each decrypt.
|
|
113
|
+
*
|
|
114
|
+
* @param ids - The ids of the encrypted objects.
|
|
115
|
+
* @param txBytes - The transaction bytes to use (that calls seal_approve* functions).
|
|
116
|
+
* @param sessionKey - The session key to use.
|
|
117
|
+
* @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.
|
|
118
|
+
*/
|
|
119
|
+
async fetchKeys({
|
|
120
|
+
ids,
|
|
121
|
+
txBytes,
|
|
122
|
+
sessionKey,
|
|
123
|
+
threshold
|
|
124
|
+
}) {
|
|
125
|
+
const keyServers = await this.getKeyServers();
|
|
126
|
+
if (threshold > keyServers.length || threshold < 1 || keyServers.length < 1) {
|
|
127
|
+
throw new InvalidThresholdError(
|
|
128
|
+
`Invalid threshold ${threshold} for ${keyServers.length} servers`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
let completedServerCount = 0;
|
|
132
|
+
const remainingKeyServers = /* @__PURE__ */ new Set();
|
|
133
|
+
const fullIds = ids.map((id) => createFullId(DST, sessionKey.getPackageId(), id));
|
|
134
|
+
for (const server of keyServers) {
|
|
135
|
+
let hasAllKeys = true;
|
|
136
|
+
for (const fullId of fullIds) {
|
|
137
|
+
if (!__privateGet(this, _cachedKeys).has(`${fullId}:${server.objectId}`)) {
|
|
138
|
+
hasAllKeys = false;
|
|
139
|
+
remainingKeyServers.add(server);
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (hasAllKeys) {
|
|
144
|
+
completedServerCount++;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (completedServerCount >= threshold) {
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
for (const server of remainingKeyServers) {
|
|
151
|
+
if (server.keyType !== KeyServerType.BonehFranklinBLS12381) {
|
|
152
|
+
throw new InvalidKeyServerError(
|
|
153
|
+
`Server ${server.objectId} has invalid key type: ${server.keyType}`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const cert = await sessionKey.getCertificate();
|
|
158
|
+
const signedRequest = await sessionKey.createRequestParams(txBytes);
|
|
159
|
+
const controller = new AbortController();
|
|
160
|
+
const errors = [];
|
|
161
|
+
const keyFetches = [...remainingKeyServers].map(async (server) => {
|
|
162
|
+
try {
|
|
163
|
+
const allKeys = await fetchKeysForAllIds(
|
|
164
|
+
server.url,
|
|
165
|
+
signedRequest.requestSignature,
|
|
166
|
+
txBytes,
|
|
167
|
+
signedRequest.decryptionKey,
|
|
168
|
+
cert,
|
|
169
|
+
__privateGet(this, _timeout),
|
|
170
|
+
controller.signal
|
|
171
|
+
);
|
|
172
|
+
let receivedIds = /* @__PURE__ */ new Set();
|
|
173
|
+
for (const { fullId, key } of allKeys) {
|
|
174
|
+
const keyElement = G1Element.fromBytes(key);
|
|
175
|
+
if (!BonehFranklinBLS12381Services.verifyUserSecretKey(
|
|
176
|
+
keyElement,
|
|
177
|
+
fullId,
|
|
178
|
+
G2Element.fromBytes(server.pk)
|
|
179
|
+
)) {
|
|
180
|
+
console.warn("Received invalid key from key server " + server.objectId);
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
__privateGet(this, _cachedKeys).set(`${fullId}:${server.objectId}`, keyElement);
|
|
184
|
+
receivedIds.add(fullId);
|
|
185
|
+
}
|
|
186
|
+
const expectedIds = new Set(fullIds);
|
|
187
|
+
const hasAllKeys = receivedIds.size === expectedIds.size && [...receivedIds].every((id) => expectedIds.has(id));
|
|
188
|
+
if (hasAllKeys) {
|
|
189
|
+
completedServerCount++;
|
|
190
|
+
if (completedServerCount >= threshold) {
|
|
191
|
+
controller.abort();
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (!controller.signal.aborted) {
|
|
196
|
+
errors.push(error);
|
|
197
|
+
}
|
|
198
|
+
if (remainingKeyServers.size - errors.length < threshold - completedServerCount) {
|
|
199
|
+
controller.abort(error);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
await Promise.allSettled(keyFetches);
|
|
204
|
+
if (completedServerCount < threshold) {
|
|
205
|
+
throw toMajorityError(errors);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
_suiClient = new WeakMap();
|
|
210
|
+
_serverObjectIds = new WeakMap();
|
|
211
|
+
_verifyKeyServers = new WeakMap();
|
|
212
|
+
_keyServers = new WeakMap();
|
|
213
|
+
_cachedKeys = new WeakMap();
|
|
214
|
+
_timeout = new WeakMap();
|
|
215
|
+
_SealClient_instances = new WeakSet();
|
|
216
|
+
createEncryptionInput_fn = function(type, data, aad) {
|
|
217
|
+
switch (type) {
|
|
218
|
+
case DemType.AesGcm256:
|
|
219
|
+
return new AesGcm256(data, aad);
|
|
220
|
+
case DemType.Hmac256Ctr:
|
|
221
|
+
return new Hmac256Ctr(data, aad);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
validateEncryptionServices_fn = function(services, threshold) {
|
|
225
|
+
const serverObjectIdsMap = /* @__PURE__ */ new Map();
|
|
226
|
+
for (const objectId of __privateGet(this, _serverObjectIds)) {
|
|
227
|
+
serverObjectIdsMap.set(objectId, (serverObjectIdsMap.get(objectId) ?? 0) + 1);
|
|
228
|
+
}
|
|
229
|
+
const servicesMap = /* @__PURE__ */ new Map();
|
|
230
|
+
for (const service of services) {
|
|
231
|
+
servicesMap.set(service, (servicesMap.get(service) ?? 0) + 1);
|
|
232
|
+
}
|
|
233
|
+
for (const [objectId, count] of serverObjectIdsMap) {
|
|
234
|
+
if (servicesMap.get(objectId) !== count) {
|
|
235
|
+
throw new InconsistentKeyServersError(
|
|
236
|
+
`Client's key servers must be a subset of the encrypted object's key servers`
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (threshold > __privateGet(this, _serverObjectIds).length) {
|
|
241
|
+
throw new InvalidThresholdError(
|
|
242
|
+
`Invalid threshold ${threshold} for ${__privateGet(this, _serverObjectIds).length} servers`
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
loadKeyServers_fn = async function() {
|
|
247
|
+
const keyServers = await retrieveKeyServers({
|
|
248
|
+
objectIds: __privateGet(this, _serverObjectIds),
|
|
249
|
+
client: __privateGet(this, _suiClient)
|
|
250
|
+
});
|
|
251
|
+
if (keyServers.length === 0) {
|
|
252
|
+
throw new InvalidKeyServerError("No key servers found");
|
|
253
|
+
}
|
|
254
|
+
if (__privateGet(this, _verifyKeyServers)) {
|
|
255
|
+
await Promise.all(
|
|
256
|
+
keyServers.map(async (server) => {
|
|
257
|
+
if (!await verifyKeyServer(server, __privateGet(this, _timeout))) {
|
|
258
|
+
throw new InvalidKeyServerError(`Key server ${server.objectId} is not valid`);
|
|
259
|
+
}
|
|
260
|
+
})
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
return keyServers;
|
|
264
|
+
};
|
|
265
|
+
export {
|
|
266
|
+
SealClient
|
|
267
|
+
};
|
|
268
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/client.ts"],
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { SuiClient } from '@mysten/sui/client';\n\nimport { EncryptedObject } from './bcs.js';\nimport { G1Element, G2Element } from './bls12381.js';\nimport { decrypt } from './decrypt.js';\nimport type { EncryptionInput } from './dem.js';\nimport { AesGcm256, Hmac256Ctr } from './dem.js';\nimport { DemType, encrypt, KemType } from './encrypt.js';\nimport {\n\tInconsistentKeyServersError,\n\tInvalidKeyServerError,\n\tInvalidThresholdError,\n\ttoMajorityError,\n} from './error.js';\nimport { BonehFranklinBLS12381Services, DST } from './ibe.js';\nimport { KeyServerType, retrieveKeyServers, verifyKeyServer } from './key-server.js';\nimport type { KeyServer } from './key-server.js';\nimport { fetchKeysForAllIds } from './keys.js';\nimport type { SessionKey } from './session-key.js';\nimport type { KeyCacheKey } from './types.js';\nimport { createFullId } from './utils.js';\n\n/**\n * Configuration options for initializing a SealClient\n * @property serverObjectIds: Array of object IDs for the key servers to use.\n * @property verifyKeyServers: Whether to verify the key servers' authenticity.\n * \t Should be false if servers are pre-verified (e.g., getAllowlistedKeyServers).\n * \t Defaults to true.\n * @property timeout: Timeout in milliseconds for network requests. Defaults to 10 seconds.\n */\nexport interface SealClientOptions {\n\tsuiClient: SuiClient;\n\tserverObjectIds: string[];\n\tverifyKeyServers?: boolean;\n\ttimeout?: number;\n}\n\nexport class SealClient {\n\t#suiClient: SuiClient;\n\t#serverObjectIds: string[];\n\t#verifyKeyServers: boolean;\n\t#keyServers: Promise<KeyServer[]> | null = null;\n\t// A caching map for: fullId:object_id -> partial key.\n\t#cachedKeys = new Map<KeyCacheKey, G1Element>();\n\t#timeout: number;\n\n\tconstructor(options: SealClientOptions) {\n\t\tthis.#suiClient = options.suiClient;\n\t\tthis.#serverObjectIds = options.serverObjectIds;\n\t\tthis.#verifyKeyServers = options.verifyKeyServers ?? true;\n\t\tthis.#timeout = options.timeout ?? 10_000;\n\t}\n\n\t/**\n\t * Return an encrypted message under the identity.\n\t *\n\t * @param kemType - The type of KEM to use.\n\t * @param demType - The type of DEM to use.\n\t * @param threshold - The threshold for the TSS encryption.\n\t * @param packageId - the packageId namespace.\n\t * @param id - the identity to use.\n\t * @param data - the data to encrypt.\n\t * @param aad - optional additional authenticated data.\n\t * @returns The bcs bytes of the encrypted object containing all metadata and the 256-bit symmetric key that was used to encrypt the object.\n\t * \tSince the symmetric key can be used to decrypt, it should not be shared but can be used e.g. for backup.\n\t */\n\tasync encrypt({\n\t\tkemType = KemType.BonehFranklinBLS12381DemCCA,\n\t\tdemType = DemType.AesGcm256,\n\t\tthreshold,\n\t\tpackageId,\n\t\tid,\n\t\tdata,\n\t\taad = new Uint8Array(),\n\t}: {\n\t\tkemType?: KemType;\n\t\tdemType?: DemType;\n\t\tthreshold: number;\n\t\tpackageId: string;\n\t\tid: string;\n\t\tdata: Uint8Array;\n\t\taad?: Uint8Array;\n\t}) {\n\t\t// TODO: Verify that packageId is first version of its package (else throw error).\n\t\treturn encrypt({\n\t\t\tkeyServers: await this.getKeyServers(),\n\t\t\tkemType,\n\t\t\tthreshold,\n\t\t\tpackageId,\n\t\t\tid,\n\t\t\tencryptionInput: this.#createEncryptionInput(demType, data, aad),\n\t\t});\n\t}\n\n\t#createEncryptionInput(type: DemType, data: Uint8Array, aad: Uint8Array): EncryptionInput {\n\t\tswitch (type) {\n\t\t\tcase DemType.AesGcm256:\n\t\t\t\treturn new AesGcm256(data, aad);\n\t\t\tcase DemType.Hmac256Ctr:\n\t\t\t\treturn new Hmac256Ctr(data, aad);\n\t\t}\n\t}\n\n\t/**\n\t * Decrypt the given encrypted bytes using cached keys.\n\t * Calls fetchKeys in case one or more of the required keys is not cached yet.\n\t * The function throws an error if the client's key servers are not a subset of\n\t * the encrypted object's key servers (including the same weights) or if the\n\t * threshold cannot be met.\n\t *\n\t * @param data - The encrypted bytes to decrypt.\n\t * @param sessionKey - The session key to use.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @returns - The decrypted plaintext corresponding to ciphertext.\n\t */\n\tasync decrypt({\n\t\tdata,\n\t\tsessionKey,\n\t\ttxBytes,\n\t}: {\n\t\tdata: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\ttxBytes: Uint8Array;\n\t}) {\n\t\tconst encryptedObject = EncryptedObject.parse(data);\n\n\t\tthis.#validateEncryptionServices(\n\t\t\tencryptedObject.services.map((s) => s[0]),\n\t\t\tencryptedObject.threshold,\n\t\t);\n\n\t\tawait this.fetchKeys({\n\t\t\tids: [encryptedObject.id],\n\t\t\ttxBytes,\n\t\t\tsessionKey,\n\t\t\tthreshold: encryptedObject.threshold,\n\t\t});\n\n\t\treturn decrypt({ encryptedObject, keys: this.#cachedKeys });\n\t}\n\n\t#validateEncryptionServices(services: string[], threshold: number) {\n\t\t// Check that the client's key servers are a subset of the encrypted object's key servers.\n\t\tconst serverObjectIdsMap = new Map<string, number>();\n\t\tfor (const objectId of this.#serverObjectIds) {\n\t\t\tserverObjectIdsMap.set(objectId, (serverObjectIdsMap.get(objectId) ?? 0) + 1);\n\t\t}\n\t\tconst servicesMap = new Map<string, number>();\n\t\tfor (const service of services) {\n\t\t\tservicesMap.set(service, (servicesMap.get(service) ?? 0) + 1);\n\t\t}\n\t\tfor (const [objectId, count] of serverObjectIdsMap) {\n\t\t\tif (servicesMap.get(objectId) !== count) {\n\t\t\t\tthrow new InconsistentKeyServersError(\n\t\t\t\t\t`Client's key servers must be a subset of the encrypted object's key servers`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// Check that the threshold can be met with the client's key servers.\n\t\tif (threshold > this.#serverObjectIds.length) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} for ${this.#serverObjectIds.length} servers`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync getKeyServers() {\n\t\tif (!this.#keyServers) {\n\t\t\tthis.#keyServers = this.#loadKeyServers().catch((error) => {\n\t\t\t\tthis.#keyServers = null;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\n\t\treturn this.#keyServers;\n\t}\n\n\tasync #loadKeyServers(): Promise<KeyServer[]> {\n\t\tconst keyServers = await retrieveKeyServers({\n\t\t\tobjectIds: this.#serverObjectIds,\n\t\t\tclient: this.#suiClient,\n\t\t});\n\n\t\tif (keyServers.length === 0) {\n\t\t\tthrow new InvalidKeyServerError('No key servers found');\n\t\t}\n\n\t\tif (this.#verifyKeyServers) {\n\t\t\tawait Promise.all(\n\t\t\t\tkeyServers.map(async (server) => {\n\t\t\t\t\tif (!(await verifyKeyServer(server, this.#timeout))) {\n\t\t\t\t\t\tthrow new InvalidKeyServerError(`Key server ${server.objectId} is not valid`);\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\treturn keyServers;\n\t}\n\n\t/**\n\t * Fetch keys from the key servers and update the cache.\n\t *\n\t * It is recommended to call this function once for all ids of all encrypted obejcts if\n\t * there are multiple, then call decrypt for each object. This avoids calling fetchKey\n\t * individually for each decrypt.\n\t *\n\t * @param ids - The ids of the encrypted objects.\n\t * @param txBytes - The transaction bytes to use (that calls seal_approve* functions).\n\t * @param sessionKey - The session key to use.\n\t * @param threshold - The threshold for the TSS encryptions. The function returns when a threshold of key servers had returned keys for all ids.\n\t */\n\tasync fetchKeys({\n\t\tids,\n\t\ttxBytes,\n\t\tsessionKey,\n\t\tthreshold,\n\t}: {\n\t\tids: string[];\n\t\ttxBytes: Uint8Array;\n\t\tsessionKey: SessionKey;\n\t\tthreshold: number;\n\t}) {\n\t\tconst keyServers = await this.getKeyServers();\n\t\tif (threshold > keyServers.length || threshold < 1 || keyServers.length < 1) {\n\t\t\tthrow new InvalidThresholdError(\n\t\t\t\t`Invalid threshold ${threshold} for ${keyServers.length} servers`,\n\t\t\t);\n\t\t}\n\n\t\tlet completedServerCount = 0;\n\t\tconst remainingKeyServers = new Set<KeyServer>();\n\t\tconst fullIds = ids.map((id) => createFullId(DST, sessionKey.getPackageId(), id));\n\n\t\t// Count a server as completed if it has keys for all fullIds.\n\t\t// Duplicated key server ids will be counted towards the threshold.\n\t\tfor (const server of keyServers) {\n\t\t\tlet hasAllKeys = true;\n\t\t\tfor (const fullId of fullIds) {\n\t\t\t\tif (!this.#cachedKeys.has(`${fullId}:${server.objectId}`)) {\n\t\t\t\t\thasAllKeys = false;\n\t\t\t\t\tremainingKeyServers.add(server);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (hasAllKeys) {\n\t\t\t\tcompletedServerCount++;\n\t\t\t}\n\t\t}\n\n\t\t// Return early if we have enough keys from cache.\n\t\tif (completedServerCount >= threshold) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Check server validities.\n\t\tfor (const server of remainingKeyServers) {\n\t\t\tif (server.keyType !== KeyServerType.BonehFranklinBLS12381) {\n\t\t\t\tthrow new InvalidKeyServerError(\n\t\t\t\t\t`Server ${server.objectId} has invalid key type: ${server.keyType}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst cert = await sessionKey.getCertificate();\n\t\tconst signedRequest = await sessionKey.createRequestParams(txBytes);\n\n\t\tconst controller = new AbortController();\n\t\tconst errors: Error[] = [];\n\n\t\tconst keyFetches = [...remainingKeyServers].map(async (server) => {\n\t\t\ttry {\n\t\t\t\tconst allKeys = await fetchKeysForAllIds(\n\t\t\t\t\tserver.url,\n\t\t\t\t\tsignedRequest.requestSignature,\n\t\t\t\t\ttxBytes,\n\t\t\t\t\tsignedRequest.decryptionKey,\n\t\t\t\t\tcert,\n\t\t\t\t\tthis.#timeout,\n\t\t\t\t\tcontroller.signal,\n\t\t\t\t);\n\t\t\t\t// Check validity of the keys and add them to the cache.\n\t\t\t\tlet receivedIds = new Set<string>();\n\t\t\t\tfor (const { fullId, key } of allKeys) {\n\t\t\t\t\tconst keyElement = G1Element.fromBytes(key);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!BonehFranklinBLS12381Services.verifyUserSecretKey(\n\t\t\t\t\t\t\tkeyElement,\n\t\t\t\t\t\t\tfullId,\n\t\t\t\t\t\t\tG2Element.fromBytes(server.pk),\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconsole.warn('Received invalid key from key server ' + server.objectId);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis.#cachedKeys.set(`${fullId}:${server.objectId}`, keyElement);\n\t\t\t\t\treceivedIds.add(fullId);\n\t\t\t\t}\n\n\t\t\t\t// Check if all the receivedIds are consistent with the requested fullIds.\n\t\t\t\t// If so, consider the key server got all keys and mark as completed.\n\t\t\t\tconst expectedIds = new Set(fullIds);\n\t\t\t\tconst hasAllKeys =\n\t\t\t\t\treceivedIds.size === expectedIds.size &&\n\t\t\t\t\t[...receivedIds].every((id) => expectedIds.has(id));\n\n\t\t\t\t// Return early if the completed servers is more than threshold.\n\t\t\t\tif (hasAllKeys) {\n\t\t\t\t\tcompletedServerCount++;\n\t\t\t\t\tif (completedServerCount >= threshold) {\n\t\t\t\t\t\tcontroller.abort();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (!controller.signal.aborted) {\n\t\t\t\t\terrors.push(error as Error);\n\t\t\t\t}\n\t\t\t\t// If there are too many errors that the threshold is not attainable, return early with error.\n\t\t\t\tif (remainingKeyServers.size - errors.length < threshold - completedServerCount) {\n\t\t\t\t\tcontroller.abort(error);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tawait Promise.allSettled(keyFetches);\n\n\t\tif (completedServerCount < threshold) {\n\t\t\tthrow toMajorityError(errors);\n\t\t}\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;AAAA;AAKA,SAAS,uBAAuB;AAChC,SAAS,WAA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vD;AAEA,MAAI,mBAAK,oBAAmB;AAC3B,UAAM,QAAQ;AAAA,MACb,WAAW,IAAI,OAAO,WAAW;AAChC,YAAI,CAAE,MAAM,gBAAgB,QAAQ,mBAAK,SAAQ,GAAI;AACpD,gBAAM,IAAI,sBAAsB,cAAc,OAAO,QAAQ,eAAe;AAAA,QAC7E;AAAA,MACD,CAAC;AAAA,IACF;AAAA,EACD;AAEA,SAAO;AACR;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { EncryptedObject } from './bcs.js';
|
|
2
|
+
import type { G1Element } from './bls12381.js';
|
|
3
|
+
import type { KeyCacheKey } from './types.js';
|
|
4
|
+
export interface DecryptOptions {
|
|
5
|
+
encryptedObject: typeof EncryptedObject.$inferType;
|
|
6
|
+
keys: Map<KeyCacheKey, G1Element>;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Decrypt the given encrypted bytes with the given cached secret keys for the full ID.
|
|
10
|
+
* It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers
|
|
11
|
+
* otherwise, this will throw an error.
|
|
12
|
+
*
|
|
13
|
+
* @returns - The decrypted plaintext corresponding to ciphertext.
|
|
14
|
+
*/
|
|
15
|
+
export declare function decrypt({ encryptedObject, keys }: DecryptOptions): Promise<Uint8Array>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { fromHex } from "@mysten/bcs";
|
|
2
|
+
import { combine as externalCombine } from "shamir-secret-sharing";
|
|
3
|
+
import { G2Element } from "./bls12381.js";
|
|
4
|
+
import { AesGcm256, Hmac256Ctr } from "./dem.js";
|
|
5
|
+
import { InvalidCiphertextError, UnsupportedFeatureError } from "./error.js";
|
|
6
|
+
import { BonehFranklinBLS12381Services, DST } from "./ibe.js";
|
|
7
|
+
import { deriveKey, KeyPurpose } from "./kdf.js";
|
|
8
|
+
import { createFullId } from "./utils.js";
|
|
9
|
+
async function decrypt({ encryptedObject, keys }) {
|
|
10
|
+
if (!encryptedObject.encryptedShares.BonehFranklinBLS12381) {
|
|
11
|
+
throw new UnsupportedFeatureError("Encryption mode not supported");
|
|
12
|
+
}
|
|
13
|
+
const fullId = createFullId(DST, encryptedObject.packageId, encryptedObject.id);
|
|
14
|
+
const inKeystore = encryptedObject.services.map((_, i) => i).filter((i) => keys.has(`${fullId}:${encryptedObject.services[i][0]}`));
|
|
15
|
+
if (inKeystore.length < encryptedObject.threshold) {
|
|
16
|
+
throw new Error("Not enough shares. Please fetch more keys.");
|
|
17
|
+
}
|
|
18
|
+
const encryptedShares = encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedShares;
|
|
19
|
+
if (encryptedShares.length !== encryptedObject.services.length) {
|
|
20
|
+
throw new InvalidCiphertextError(
|
|
21
|
+
`Mismatched shares ${encryptedShares.length} and services ${encryptedObject.services.length}`
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
const nonce = G2Element.fromBytes(encryptedObject.encryptedShares.BonehFranklinBLS12381.nonce);
|
|
25
|
+
const shares = inKeystore.map((i) => {
|
|
26
|
+
const [objectId, index] = encryptedObject.services[i];
|
|
27
|
+
const share = BonehFranklinBLS12381Services.decrypt(
|
|
28
|
+
nonce,
|
|
29
|
+
keys.get(`${fullId}:${objectId}`),
|
|
30
|
+
encryptedShares[i],
|
|
31
|
+
fromHex(fullId),
|
|
32
|
+
[objectId, index]
|
|
33
|
+
);
|
|
34
|
+
return { index, share };
|
|
35
|
+
});
|
|
36
|
+
const key = await combine(shares);
|
|
37
|
+
const demKey = deriveKey(KeyPurpose.DEM, key);
|
|
38
|
+
if (encryptedObject.ciphertext.Aes256Gcm) {
|
|
39
|
+
try {
|
|
40
|
+
return AesGcm256.decrypt(demKey, encryptedObject.ciphertext);
|
|
41
|
+
} catch {
|
|
42
|
+
throw new Error("Decryption failed");
|
|
43
|
+
}
|
|
44
|
+
} else if (encryptedObject.ciphertext.Plain) {
|
|
45
|
+
return demKey;
|
|
46
|
+
} else if (encryptedObject.ciphertext.Hmac256Ctr) {
|
|
47
|
+
try {
|
|
48
|
+
return Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);
|
|
49
|
+
} catch {
|
|
50
|
+
throw new Error("Decryption failed");
|
|
51
|
+
}
|
|
52
|
+
} else {
|
|
53
|
+
throw new Error("Invalid encrypted object");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async function combine(shares) {
|
|
57
|
+
if (shares.length === 0) {
|
|
58
|
+
throw new Error("Invalid shares length");
|
|
59
|
+
} else if (shares.length === 1) {
|
|
60
|
+
return Promise.resolve(shares[0].share);
|
|
61
|
+
}
|
|
62
|
+
return externalCombine(
|
|
63
|
+
shares.map(({ index, share }) => {
|
|
64
|
+
const packedShare = new Uint8Array(share.length + 1);
|
|
65
|
+
packedShare.set(share, 0);
|
|
66
|
+
packedShare[share.length] = index;
|
|
67
|
+
return packedShare;
|
|
68
|
+
})
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
export {
|
|
72
|
+
decrypt
|
|
73
|
+
};
|
|
74
|
+
//# sourceMappingURL=decrypt.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/decrypt.ts"],
|
|
4
|
+
"sourcesContent": ["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { fromHex } from '@mysten/bcs';\nimport { combine as externalCombine } from 'shamir-secret-sharing';\n\nimport type { EncryptedObject } from './bcs.js';\nimport type { G1Element } from './bls12381.js';\nimport { G2Element } from './bls12381.js';\nimport { AesGcm256, Hmac256Ctr } from './dem.js';\nimport { InvalidCiphertextError, UnsupportedFeatureError } from './error.js';\nimport { BonehFranklinBLS12381Services, DST } from './ibe.js';\nimport { deriveKey, KeyPurpose } from './kdf.js';\nimport type { KeyCacheKey } from './types.js';\nimport { createFullId } from './utils.js';\n\nexport interface DecryptOptions {\n\tencryptedObject: typeof EncryptedObject.$inferType;\n\tkeys: Map<KeyCacheKey, G1Element>;\n}\n\n/**\n * Decrypt the given encrypted bytes with the given cached secret keys for the full ID.\n * It's assumed that fetchKeys has been called to fetch the secret keys for enough key servers\n * otherwise, this will throw an error.\n *\n * @returns - The decrypted plaintext corresponding to ciphertext.\n */\nexport async function decrypt({ encryptedObject, keys }: DecryptOptions): Promise<Uint8Array> {\n\tif (!encryptedObject.encryptedShares.BonehFranklinBLS12381) {\n\t\tthrow new UnsupportedFeatureError('Encryption mode not supported');\n\t}\n\n\tconst fullId = createFullId(DST, encryptedObject.packageId, encryptedObject.id);\n\n\t// Get the indices of the service whose keys are in the keystore.\n\tconst inKeystore = encryptedObject.services\n\t\t.map((_, i) => i)\n\t\t.filter((i) => keys.has(`${fullId}:${encryptedObject.services[i][0]}`));\n\n\tif (inKeystore.length < encryptedObject.threshold) {\n\t\tthrow new Error('Not enough shares. Please fetch more keys.');\n\t}\n\n\tconst encryptedShares = encryptedObject.encryptedShares.BonehFranklinBLS12381.encryptedShares;\n\tif (encryptedShares.length !== encryptedObject.services.length) {\n\t\tthrow new InvalidCiphertextError(\n\t\t\t`Mismatched shares ${encryptedShares.length} and services ${encryptedObject.services.length}`,\n\t\t);\n\t}\n\n\tconst nonce = G2Element.fromBytes(encryptedObject.encryptedShares.BonehFranklinBLS12381.nonce);\n\n\t// Decrypt each share.\n\tconst shares = inKeystore.map((i: number) => {\n\t\tconst [objectId, index] = encryptedObject.services[i];\n\t\t// Use the index as the unique info parameter to allow for multiple shares per key server.\n\t\tconst share = BonehFranklinBLS12381Services.decrypt(\n\t\t\tnonce,\n\t\t\tkeys.get(`${fullId}:${objectId}`)!,\n\t\t\tencryptedShares[i],\n\t\t\tfromHex(fullId),\n\t\t\t[objectId, index],\n\t\t);\n\t\t// The Shamir secret sharing library expects the index/x-coordinate to be at the end of the share.\n\t\treturn { index, share };\n\t});\n\n\t// Combine the decrypted shares into the key.\n\tconst key = await combine(shares);\n\tconst demKey = deriveKey(KeyPurpose.DEM, key);\n\tif (encryptedObject.ciphertext.Aes256Gcm) {\n\t\ttry {\n\t\t\t// Decrypt the ciphertext with the key.\n\t\t\treturn AesGcm256.decrypt(demKey, encryptedObject.ciphertext);\n\t\t} catch {\n\t\t\tthrow new Error('Decryption failed');\n\t\t}\n\t} else if (encryptedObject.ciphertext.Plain) {\n\t\t// In case `Plain` mode is used, return the key.\n\t\treturn demKey;\n\t} else if (encryptedObject.ciphertext.Hmac256Ctr) {\n\t\ttry {\n\t\t\treturn Hmac256Ctr.decrypt(demKey, encryptedObject.ciphertext);\n\t\t} catch {\n\t\t\tthrow new Error('Decryption failed');\n\t\t}\n\t} else {\n\t\tthrow new Error('Invalid encrypted object');\n\t}\n}\n\n/**\n * Helper function that combines the shares into the key.\n * @param shares - The shares to combine.\n * @returns - The combined key.\n */\nasync function combine(shares: { index: number; share: Uint8Array }[]): Promise<Uint8Array> {\n\tif (shares.length === 0) {\n\t\tthrow new Error('Invalid shares length');\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": "AAGA,SAAS,eAAe;AACxB,SAAS,WAAW,uBAAuB;AAI3C,SAAS,iBAAiB;AAC1B,SAAS,WAAW,kBAAkB;AACtC,SAAS,wBAAwB,+BAA+B;AAChE,SAAS,+BAA+B,WAAW;AACnD,SAAS,WAAW,kBAAkB;AAEtC,SAAS,oBAAoB;AAc7B,eAAsB,QAAQ,EAAE,iBAAiB,KAAK,GAAwC;AAC7F,MAAI,CAAC,gBAAgB,gB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AgB,WAAW,OAAO;AAE5C,WAAO;AAAA,EACR,WAAW,gBAAgB,WAAW,YAAY;AACjD,QAAI;AACH,aAAO,WAAW,QAAQ,QAAQ,gBAAgB,UAAU;AAAA,IAC7D,QAAQ;AACP,YAAM,IAAI,MAAM,mBAAmB;AAAA,IACpC;AAAA,EACD,OAAO;AACN,UAAM,IAAI,MAAM,0BAA0B;AAAA,EAC3C;AACD;AAOA,eAAe,QAAQ,QAAqE;AAC3F,MAAI,OAAO,WAAW,GAAG;AACxB,UAAM,IAAI,MAAM,uBAAuB;AAAA,EACxC,WAAW,OAAO,WAAW,GAAG;AAG/B,WAAO,QAAQ,QAAQ,OAAO,CAAC,EAAE,KAAK;AAAA,EACvC;AAGA,SAAO;AAAA,IACN,OAAO,IAAI,CAAC,EAAE,OAAO,MAAM,MAAM;AAChC,YAAM,cAAc,IAAI,WAAW,MAAM,SAAS,CAAC;AACnD,kBAAY,IAAI,OAAO,CAAC;AACxB,kBAAY,MAAM,MAAM,IAAI;AAC5B,aAAO;AAAA,IACR,CAAC;AAAA,EACF;AACD;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Ciphertext } from './bcs.js';
|
|
2
|
+
export declare const iv: Uint8Array<ArrayBuffer>;
|
|
3
|
+
export interface EncryptionInput {
|
|
4
|
+
encrypt(key: Uint8Array): Promise<typeof Ciphertext.$inferInput>;
|
|
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<typeof Ciphertext.$inferInput>;
|
|
13
|
+
static decrypt(key: Uint8Array, ciphertext: typeof Ciphertext.$inferInput): Promise<Uint8Array>;
|
|
14
|
+
}
|
|
15
|
+
export declare class Plain implements EncryptionInput {
|
|
16
|
+
encrypt(_key: Uint8Array): Promise<typeof Ciphertext.$inferInput>;
|
|
17
|
+
generateKey(): Promise<Uint8Array>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Authenticated encryption using CTR mode with HMAC-SHA3-256 as a PRF.
|
|
21
|
+
* 1. Derive an encryption key, <i>k<sub>1</sub> = <b>hmac</b>(key, 1)</i>.
|
|
22
|
+
* 2. Chunk the message into blocks of 32 bytes, <i>m = m<sub>1</sub> || ... || m<sub>n</sub></i>.
|
|
23
|
+
* 3. Let the ciphertext be defined by <i>c = c<sub>1</sub> || ... || c<sub>n</sub></i> where <i>c<sub>i</sub> = m<sub>i</sub> ⊕ <b>hmac</b>(k<sub>1</sub>, i)</i>.
|
|
24
|
+
* 4. Compute a MAC over the AAD and the ciphertext, <i>mac = <b>hmac</b>(k<sub>2</sub>, aad || c) where k<sub>2</sub> = <b>hmac</b>(key, 2)</i>.
|
|
25
|
+
* 5. Return <i>mac || c</i>.
|
|
26
|
+
*/
|
|
27
|
+
export declare class Hmac256Ctr implements EncryptionInput {
|
|
28
|
+
readonly plaintext: Uint8Array;
|
|
29
|
+
readonly aad: Uint8Array;
|
|
30
|
+
constructor(msg: Uint8Array, aad: Uint8Array);
|
|
31
|
+
generateKey(): Promise<Uint8Array>;
|
|
32
|
+
encrypt(key: Uint8Array): Promise<typeof Ciphertext.$inferInput>;
|
|
33
|
+
static decrypt(key: Uint8Array, ciphertext: typeof Ciphertext.$inferInput): Promise<Uint8Array>;
|
|
34
|
+
private static computeMac;
|
|
35
|
+
private static encryptInCtrMode;
|
|
36
|
+
}
|