@icure/api 8.1.9 → 8.2.1
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/icc-x-api/crypto/BaseExchangeDataManager.d.ts +19 -9
- package/icc-x-api/crypto/BaseExchangeDataManager.js +25 -5
- package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/CryptoStrategies.d.ts +2 -1
- package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
- package/icc-x-api/crypto/ExchangeDataManager.d.ts +25 -2
- package/icc-x-api/crypto/ExchangeDataManager.js +98 -5
- package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtils.d.ts +3 -1
- package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +3 -3
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/icc-x-api/crypto/SecureDelegationsManager.d.ts +3 -1
- package/icc-x-api/crypto/SecureDelegationsManager.js +10 -6
- package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.d.ts +2 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js +18 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
- package/icc-x-api/crypto/utils.js +1 -1
- package/icc-x-api/crypto/utils.js.map +1 -1
- package/icc-x-api/icc-accesslog-x-api.d.ts +6 -0
- package/icc-x-api/icc-accesslog-x-api.js +6 -2
- package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
- package/icc-x-api/icc-calendar-item-x-api.d.ts +4 -0
- package/icc-x-api/icc-calendar-item-x-api.js +3 -1
- package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
- package/icc-x-api/icc-classification-x-api.d.ts +3 -0
- package/icc-x-api/icc-classification-x-api.js +3 -1
- package/icc-x-api/icc-classification-x-api.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.d.ts +3 -0
- package/icc-x-api/icc-contact-x-api.js +3 -1
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/icc-crypto-x-api.d.ts +29 -0
- package/icc-x-api/icc-crypto-x-api.js +36 -0
- package/icc-x-api/icc-crypto-x-api.js.map +1 -1
- package/icc-x-api/icc-document-x-api.d.ts +3 -0
- package/icc-x-api/icc-document-x-api.js +3 -1
- package/icc-x-api/icc-document-x-api.js.map +1 -1
- package/icc-x-api/icc-form-x-api.d.ts +3 -0
- package/icc-x-api/icc-form-x-api.js +3 -1
- package/icc-x-api/icc-form-x-api.js.map +1 -1
- package/icc-x-api/icc-helement-x-api.d.ts +3 -0
- package/icc-x-api/icc-helement-x-api.js +3 -1
- package/icc-x-api/icc-helement-x-api.js.map +1 -1
- package/icc-x-api/icc-invoice-x-api.d.ts +3 -0
- package/icc-x-api/icc-invoice-x-api.js +3 -1
- package/icc-x-api/icc-invoice-x-api.js.map +1 -1
- package/icc-x-api/icc-maintenance-task-x-api.d.ts +3 -0
- package/icc-x-api/icc-maintenance-task-x-api.js +3 -1
- package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
- package/icc-x-api/icc-message-x-api.d.ts +3 -0
- package/icc-x-api/icc-message-x-api.js +3 -1
- package/icc-x-api/icc-message-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.d.ts +3 -0
- package/icc-x-api/icc-patient-x-api.js +6 -2
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/icc-x-api/icc-receipt-x-api.d.ts +3 -0
- package/icc-x-api/icc-receipt-x-api.js +3 -1
- package/icc-x-api/icc-receipt-x-api.js.map +1 -1
- package/icc-x-api/icc-recovery-x-api.js +8 -1
- package/icc-x-api/icc-recovery-x-api.js.map +1 -1
- package/icc-x-api/icc-time-table-x-api.d.ts +3 -0
- package/icc-x-api/icc-time-table-x-api.js +3 -1
- package/icc-x-api/icc-time-table-x-api.js.map +1 -1
- package/icc-x-api/icc-topic-x-api.d.ts +3 -0
- package/icc-x-api/icc-topic-x-api.js +3 -1
- package/icc-x-api/icc-topic-x-api.js.map +1 -1
- package/icc-x-api/index.d.ts +16 -0
- package/icc-x-api/index.js +8 -2
- package/icc-x-api/index.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-x-api/autofix-anonymity-test.js +18 -4
- package/test/icc-x-api/autofix-anonymity-test.js.map +1 -1
- package/test/icc-x-api/crypto/exchange-data-manager-test.js +30 -30
- package/test/icc-x-api/crypto/exchange-data-manager-test.js.map +1 -1
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js +2 -2
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js.map +1 -1
- package/test/icc-x-api/icc-hcparty-x-api-test.js +2 -14
- package/test/icc-x-api/icc-hcparty-x-api-test.js.map +1 -1
- package/test/icc-x-api/keyless-api.d.ts +1 -0
- package/test/icc-x-api/keyless-api.js +125 -0
- package/test/icc-x-api/keyless-api.js.map +1 -0
- package/test/utils/FakeEncryptionKeysManager.js +1 -1
- package/test/utils/FakeEncryptionKeysManager.js.map +1 -1
- package/test/utils/FakeExchangeDataManager.d.ts +8 -0
- package/test/utils/FakeExchangeDataManager.js +3 -0
- package/test/utils/FakeExchangeDataManager.js.map +1 -1
- package/test/utils/KeylessCryptoStrategies.d.ts +23 -0
- package/test/utils/KeylessCryptoStrategies.js +26 -0
- package/test/utils/KeylessCryptoStrategies.js.map +1 -0
- package/test/utils/test_utils.d.ts +7 -0
- package/test/utils/test_utils.js +30 -1
- package/test/utils/test_utils.js.map +1 -1
|
@@ -125,6 +125,7 @@ export declare class BaseExchangeDataManager {
|
|
|
125
125
|
exchangeData: ExchangeData;
|
|
126
126
|
exchangeKey: CryptoKey;
|
|
127
127
|
accessControlSecret: string;
|
|
128
|
+
sharedSignatureKey: CryptoKey;
|
|
128
129
|
}>;
|
|
129
130
|
tryRawDecryptExchangeData(exchangeData: ExchangeData, decryptionKeys: {
|
|
130
131
|
[publicKeyFingerprint: string]: KeyPair<CryptoKey>;
|
|
@@ -156,9 +157,18 @@ export declare class BaseExchangeDataManager {
|
|
|
156
157
|
/**
|
|
157
158
|
* Same as [tryUpdateExchangeData] but the decrypted content is already provided.
|
|
158
159
|
*/
|
|
159
|
-
updateExchangeDataWithRawDecryptedContent(exchangeData
|
|
160
|
-
|
|
161
|
-
|
|
160
|
+
updateExchangeDataWithRawDecryptedContent({ exchangeData, newEncryptionKeys, rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey, newDelegatorSignatureKeys, }: {
|
|
161
|
+
exchangeData: ExchangeData;
|
|
162
|
+
newEncryptionKeys: {
|
|
163
|
+
[fp: string]: CryptoKey;
|
|
164
|
+
};
|
|
165
|
+
newDelegatorSignatureKeys: {
|
|
166
|
+
[keyPairFingerprint: string]: CryptoKey;
|
|
167
|
+
};
|
|
168
|
+
rawExchangeKey: ArrayBuffer;
|
|
169
|
+
rawAccessControlSecret: ArrayBuffer;
|
|
170
|
+
rawSharedSignatureKey: ArrayBuffer;
|
|
171
|
+
}): Promise<{
|
|
162
172
|
exchangeData: ExchangeData;
|
|
163
173
|
exchangeKey: CryptoKey;
|
|
164
174
|
accessControlSecret: string;
|
|
@@ -166,14 +176,14 @@ export declare class BaseExchangeDataManager {
|
|
|
166
176
|
private bytesToSignForSharedSignature;
|
|
167
177
|
private bytesToSignForDelegatorSignature;
|
|
168
178
|
private generateExchangeKey;
|
|
169
|
-
|
|
170
|
-
|
|
179
|
+
importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey>;
|
|
180
|
+
exportExchangeKey(key: CryptoKey): Promise<ArrayBuffer>;
|
|
171
181
|
private generateSharedSignatureKey;
|
|
172
|
-
|
|
173
|
-
|
|
182
|
+
importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey>;
|
|
183
|
+
exportSharedSignatureKey(key: CryptoKey): Promise<ArrayBuffer>;
|
|
174
184
|
private generateAccessControlSecret;
|
|
175
|
-
|
|
176
|
-
|
|
185
|
+
importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string>;
|
|
186
|
+
exportAccessControlSecret(secret: string): Promise<ArrayBuffer>;
|
|
177
187
|
private encryptDataWithKeys;
|
|
178
188
|
private extractHmacFromRsaPrivate;
|
|
179
189
|
private signDataWithDelegatorKeys;
|
|
@@ -230,8 +230,8 @@ class BaseExchangeDataManager {
|
|
|
230
230
|
createExchangeData(delegateId, signatureKeys, encryptionKeys, optionalAttributes = {}) {
|
|
231
231
|
var _a;
|
|
232
232
|
return __awaiter(this, void 0, void 0, function* () {
|
|
233
|
-
if (!Object.keys(
|
|
234
|
-
throw new Error('Must specify at least one
|
|
233
|
+
if (!Object.keys(encryptionKeys).length) {
|
|
234
|
+
throw new Error('Must specify at least one encryption key ');
|
|
235
235
|
}
|
|
236
236
|
const exchangeKey = yield this.generateExchangeKey();
|
|
237
237
|
const accessControlSecret = yield this.generateAccessControlSecret();
|
|
@@ -262,6 +262,7 @@ class BaseExchangeDataManager {
|
|
|
262
262
|
exchangeData: yield this.api.createExchangeData(exchangeData),
|
|
263
263
|
exchangeKey: exchangeKey.key,
|
|
264
264
|
accessControlSecret: accessControlSecret.secret,
|
|
265
|
+
sharedSignatureKey: sharedSignatureKey.key,
|
|
265
266
|
};
|
|
266
267
|
});
|
|
267
268
|
}
|
|
@@ -293,14 +294,23 @@ class BaseExchangeDataManager {
|
|
|
293
294
|
const rawSharedSignatureKey = yield this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys);
|
|
294
295
|
if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey)
|
|
295
296
|
return undefined;
|
|
296
|
-
return yield this.updateExchangeDataWithRawDecryptedContent(
|
|
297
|
+
return yield this.updateExchangeDataWithRawDecryptedContent({
|
|
298
|
+
exchangeData: exchangeData,
|
|
299
|
+
newEncryptionKeys: newEncryptionKeys,
|
|
300
|
+
rawExchangeKey: rawExchangeKey,
|
|
301
|
+
rawAccessControlSecret: rawAccessControlSecret,
|
|
302
|
+
rawSharedSignatureKey: rawSharedSignatureKey,
|
|
303
|
+
newDelegatorSignatureKeys: {},
|
|
304
|
+
});
|
|
297
305
|
});
|
|
298
306
|
}
|
|
299
307
|
/**
|
|
300
308
|
* Same as [tryUpdateExchangeData] but the decrypted content is already provided.
|
|
301
309
|
*/
|
|
302
|
-
updateExchangeDataWithRawDecryptedContent(exchangeData, newEncryptionKeys, rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey) {
|
|
310
|
+
updateExchangeDataWithRawDecryptedContent({ exchangeData, newEncryptionKeys, rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey, newDelegatorSignatureKeys, }) {
|
|
311
|
+
var _a;
|
|
303
312
|
return __awaiter(this, void 0, void 0, function* () {
|
|
313
|
+
const self = yield this.dataOwnerApi.getCurrentDataOwnerId();
|
|
304
314
|
const exchangeKey = yield this.importExchangeKey(new Uint8Array(rawExchangeKey));
|
|
305
315
|
const accessControlSecret = yield this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret));
|
|
306
316
|
const sharedSignatureKey = yield this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey));
|
|
@@ -308,7 +318,9 @@ class BaseExchangeDataManager {
|
|
|
308
318
|
const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret));
|
|
309
319
|
const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey));
|
|
310
320
|
const missingEntries = Object.keys(newEncryptionKeys).filter((fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp) || !existingSharedSignatureKeyEntries.has(fp));
|
|
311
|
-
|
|
321
|
+
const existingDelegatorSignatureEntries = new Set(Object.keys((_a = exchangeData.delegatorSignature) !== null && _a !== void 0 ? _a : {}));
|
|
322
|
+
const missingDelegatorSignatureEntries = exchangeData.delegator == self ? Object.keys(newDelegatorSignatureKeys).filter((fp) => !existingDelegatorSignatureEntries.has(fp)) : [];
|
|
323
|
+
if (!missingEntries.length && !missingDelegatorSignatureEntries.length)
|
|
312
324
|
return { exchangeData, exchangeKey, accessControlSecret };
|
|
313
325
|
const encryptionKeysForMissingEntries = missingEntries.reduce((obj, fp) => {
|
|
314
326
|
obj[fp] = newEncryptionKeys[fp];
|
|
@@ -333,6 +345,14 @@ class BaseExchangeDataManager {
|
|
|
333
345
|
publicKeysFingerprintsV2: Object.keys(updatedExchangeData.exchangeKey),
|
|
334
346
|
}), sharedSignatureKey);
|
|
335
347
|
}
|
|
348
|
+
if (missingDelegatorSignatureEntries.length > 0) {
|
|
349
|
+
const bytesToSign = yield this.bytesToSignForDelegatorSignature({ sharedSignatureKey });
|
|
350
|
+
const newSigned = yield this.signDataWithDelegatorKeys(bytesToSign, missingDelegatorSignatureEntries.reduce((obj, fp) => {
|
|
351
|
+
obj[fp] = newDelegatorSignatureKeys[fp];
|
|
352
|
+
return obj;
|
|
353
|
+
}, {}));
|
|
354
|
+
updatedExchangeData.delegatorSignature = Object.assign(Object.assign({}, updatedExchangeData.delegatorSignature), newSigned);
|
|
355
|
+
}
|
|
336
356
|
return { exchangeData: yield this.api.modifyExchangeData(new ExchangeData_1.ExchangeData(updatedExchangeData)), exchangeKey, accessControlSecret };
|
|
337
357
|
});
|
|
338
358
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,4EAAwE;AAExE,+CAA2C;AAE3C,oCAAoE;AACpE,4BAA2B;AAC3B,mCAA4D;AAC5D,IAAO,QAAQ,GAAG,SAAG,CAAC,QAA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C,CAAC,CAAC,CAAA;QAC9E,CAAC;KAAA;IAEa,uBAAuB,CAAC,OAAoB,EAAE,GAAc,EAAE,SAAiB;;YAC3F,OAAO,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,UAAU,CAAC,OAAO,CAAC,EAAE,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAA;QAC5F,CAAC;KAAA;CACF;AAriBD,0DAqiBC","sourcesContent":["import { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { IccExchangeDataApi } from '../../icc-api/api/internal/IccExchangeDataApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { b64_2ua, hex2ua, ua2b64, ua2hex, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport XHRError = XHR.XHRError\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * Functions to create and get exchange data.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeDataManager {\n constructor(\n readonly api: IccExchangeDataApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly primitives: CryptoPrimitives,\n private readonly selfRequiresAnonymousDelegations: boolean,\n private readonly doNotUseBulkGet: boolean\n ) {}\n\n /**\n * Get all the exchange data where the current data owner is the delegator or the delegate. However, some data owners, generally HCPs, may have a\n * prohibitively high amount of exchange data. If the crypto strategies specify that the current data owner requires anonymous delegation this\n * method returns all the exchange data found for the data owner, else the method returns undefined.\n * @return all the exchange data for the current data owner or undefined if the crypto strategies don't allow to retrieve all data for the current\n * data owner.\n */\n async getAllExchangeDataForCurrentDataOwnerIfAllowed(): Promise<ExchangeData[] | undefined> {\n if (!this.selfRequiresAnonymousDelegations) return undefined\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n let latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, undefined, 1000)\n const allRetrieved = latestResult.rows ?? []\n while (latestResult.nextKeyPair?.startKeyDocId) {\n latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, latestResult.nextKeyPair.startKeyDocId, 1000)\n if (latestResult.rows) allRetrieved.push(...latestResult.rows)\n }\n return allRetrieved\n }\n\n /**\n * Get all exchange data for the provided delegator-delegate pair.\n * @param delegatorId id of a delegator data owner.\n * @param delegateId id of a delegate data owner.\n * @return all exchange data for the provided delegator-delegate pair.\n */\n async getExchangeDataByDelegatorDelegatePair(delegatorId: string, delegateId: string): Promise<ExchangeData[]> {\n return await this.api.getExchangeDataByDelegatorDelegate(delegatorId, delegateId)\n }\n\n /**\n * Get the exchange data with the provided id.\n * @param exchangeDataId id of the exchange data.\n * @return the exchange data with the provided id or undefined if no exchange data with such id could be found.\n */\n async getExchangeDataById(exchangeDataId: string): Promise<ExchangeData | undefined> {\n return await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && e.statusCode === 404) {\n return undefined\n } else throw e\n })\n }\n\n async getExchangeDataByIds(exchangeDataIds: string[]): Promise<ExchangeData[]> {\n if (this.doNotUseBulkGet) {\n const res: ExchangeData[] = []\n for (const exchangeDataId of exchangeDataIds) {\n const curr = await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && (e.statusCode === 404 || e.statusCode === 403)) {\n return undefined\n } else throw e\n })\n if (curr) res.push(curr)\n }\n return res\n } else {\n return await this.api.getExchangeDataByIds({ ids: exchangeDataIds })\n }\n }\n\n /**\n * Verifies the authenticity of the exchange data by checking the signature.\n * Note that all exchange data created by data owners other than the current data owner (including members of his hierarchy)\n * will always be unverified.\n * @param data collects the following information about the exchange data being verified:\n * - exchangeData the exchange data to verify.\n * - decryptedAccessControlSecret the access control secret decrypted from the exchange data.\n * - decryptedExchangeKey the exchange key decrypted from the exchange data.\n * - decryptedSharedSignatureKey the shared signature key decrypted from the exchange data.\n * @param verificationKeys verification keys for delegator signature by fingerprint.\n * @param verifyAsDelegator if true the method will also verify that the hmac key used for the signature was created by the delegator of the\n * exchange data. If true and the data was not created by the current data owner this method will return false.\n * @return the exchange data which could be verified given his signature and the available verification keys.\n * @throws if any of the provided exchange data has been created by a data owner other than the current data owner.\n */\n async verifyExchangeData(\n data: {\n exchangeData: ExchangeData\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n decryptedSharedSignatureKey: CryptoKey\n },\n verificationKeys: { [fp: string]: CryptoKey },\n verifyAsDelegator: boolean\n ): Promise<boolean> {\n if (verifyAsDelegator && data.exchangeData.delegator !== (await this.dataOwnerApi.getCurrentDataOwnerId())) return false\n if (verifyAsDelegator && !(await this.verifyDelegatorSignature(data.exchangeData, data.decryptedSharedSignatureKey, verificationKeys)))\n return false\n const sharedSignatureData = await this.bytesToSignForSharedSignature({\n decryptedAccessControlSecret: data.decryptedAccessControlSecret,\n decryptedExchangeKey: data.decryptedExchangeKey,\n delegator: data.exchangeData.delegator,\n delegate: data.exchangeData.delegate,\n publicKeysFingerprintsV2: [\n ...new Set([\n ...Object.keys(data.exchangeData.exchangeKey),\n ...Object.keys(data.exchangeData.accessControlSecret),\n ...Object.keys(data.exchangeData.sharedSignatureKey),\n ]),\n ],\n })\n return await this.verifyDataWithSharedKey(sharedSignatureData, data.decryptedSharedSignatureKey, data.exchangeData.sharedSignature)\n }\n\n /**\n * Extracts and decrypts the access control secret from the provided exchange data.\n * These need to be hashed together with the entity class and confidentiality level in order to get the actual access control key\n * which will be sent to the server.\n * @param exchangeData the exchange data from which to extract access control secrets.\n * @param decryptionKeys rsa key pairs to use for decryption of the access control secret.\n * @return an object composed of:\n * - successfulDecryptions: array of all successfully decrypted access control keys\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptAccessControlSecret(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: string[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.accessControlSecret,\n (d) => this.importAccessControlSecret(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the exchange keys from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptExchangeKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.exchangeKey,\n (d) => this.importExchangeKey(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the shared signature key from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptSharedSignatureKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.sharedSignatureKey,\n (d) => this.importSharedSignatureKey(new Uint8Array(d))\n )\n }\n\n private async tryDecryptExchangeData<T>(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n encryptedDataSelector: (data: ExchangeData) => { [keyPairFingerprint: string]: string },\n unmarshalDecrypted: (decrypted: ArrayBuffer) => Promise<T>\n ): Promise<{\n successfulDecryptions: T[]\n failedDecryptions: ExchangeData[]\n }> {\n const successfulDecryptions: T[] = []\n const failedDecryptions: ExchangeData[] = []\n for (const ed of exchangeData) {\n try {\n const decrypted = await this.tryDecrypt(encryptedDataSelector(ed), decryptionKeys)\n if (decrypted) {\n successfulDecryptions.push(await unmarshalDecrypted(decrypted))\n } else {\n failedDecryptions.push(ed)\n }\n } catch (e) {\n failedDecryptions.push(ed)\n }\n }\n return { successfulDecryptions, failedDecryptions }\n }\n\n private async tryDecrypt(\n encryptedData: { [keyPairFingerprintV2: string]: string },\n decryptionKeys: { [publicKeyFingerprintV1: string]: KeyPair<CryptoKey> }\n ): Promise<ArrayBuffer | undefined> {\n const decryptionKeysWithV2Fp = Object.keys(decryptionKeys).reduce((prev, fp) => {\n return {\n ...prev,\n [fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp]: decryptionKeys[fp],\n }\n }, {} as { [publicKeyFingerprint: string]: KeyPair<CryptoKey> })\n for (const [fp, encrypted] of Object.entries(encryptedData)) {\n try {\n const key = decryptionKeysWithV2Fp[fp]?.privateKey\n if (key) return await this.primitives.RSA.decrypt(key, b64_2ua(encrypted))\n } catch (e) {\n // Try with another key\n }\n }\n }\n\n /**\n * Creates exchange data from the current data owner to the provided delegate, uploading the newly created exchange data to the cloud.\n * This assumes that the keys have been verified.\n * @param delegateId id of the delegate for the new exchange data.\n * @param signatureKeys private keys to use for signing the created data.\n * @param encryptionKeys public keys to use for the encryption of the exchange data (from delegator and delegate).\n * @param optionalAttributes optional precalculated attributes for the creation of data\n * @return the newly created exchange data, and its decrypted exchange key and access control secret.\n */\n async createExchangeData(\n delegateId: string,\n signatureKeys: { [keyPairFingerprint: string]: CryptoKey },\n encryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n optionalAttributes: {\n id?: string\n } = {}\n ): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }> {\n if (!Object.keys(signatureKeys).length || !Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one signature key and ')\n }\n const exchangeKey = await this.generateExchangeKey()\n const accessControlSecret = await this.generateAccessControlSecret()\n const sharedSignatureKey = await this.generateSharedSignatureKey()\n const encryptedExchangeKey = await this.encryptDataWithKeys(exchangeKey.rawBytes, encryptionKeys)\n const encryptedAccessControlSecret = await this.encryptDataWithKeys(accessControlSecret.rawBytes, encryptionKeys)\n const encryptedSharedSignatureKey = await this.encryptDataWithKeys(sharedSignatureKey.rawBytes, encryptionKeys)\n const baseExchangeData = {\n id: optionalAttributes.id ?? this.primitives.randomUuid(),\n delegator: await this.dataOwnerApi.getCurrentDataOwnerId(),\n delegate: delegateId,\n exchangeKey: encryptedExchangeKey,\n accessControlSecret: encryptedAccessControlSecret,\n sharedSignatureKey: encryptedSharedSignatureKey,\n }\n const sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: baseExchangeData.delegate,\n delegator: baseExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret.secret,\n decryptedExchangeKey: exchangeKey.key,\n publicKeysFingerprintsV2: Object.keys(encryptionKeys).map(fingerprintV1toV2),\n }),\n sharedSignatureKey.key\n )\n const delegatorSignature = await this.signDataWithDelegatorKeys(\n await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: sharedSignatureKey.key,\n }),\n signatureKeys\n )\n const exchangeData = new ExchangeData({ ...baseExchangeData, delegatorSignature, sharedSignature })\n return {\n exchangeData: await this.api.createExchangeData(exchangeData),\n exchangeKey: exchangeKey.key,\n accessControlSecret: accessControlSecret.secret,\n }\n }\n\n async tryRawDecryptExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<\n | {\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return { rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey }\n }\n\n /**\n * Updates existing exchange data and uploads it to the cloud in order to share it also with additional public keys, useful for example in cases\n * where one of the data owners involved in the exchange data has lost one of his keys.\n * If the content of the exchange data could not be decrypted using the provided keys the method will not update anything and will return undefined.\n * This method assumes that the new encryption keys have been verified.\n * @param exchangeData exchange data to update.\n * @param decryptionKeys keys to use to extract the content of the exchange data which will be shared with the new keys.\n * @param newEncryptionKeys new keys to add to the exchange data.\n * @return the updated exchange data, and its decrypted exchange key and access control secret, or undefined if the exchange data content could not\n * be decrypted and the exchange data could not be updated.\n */\n async tryUpdateExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n newEncryptionKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<\n | {\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return await this.updateExchangeDataWithRawDecryptedContent(\n exchangeData,\n newEncryptionKeys,\n rawExchangeKey,\n rawAccessControlSecret,\n rawSharedSignatureKey\n )\n }\n\n /**\n * Same as [tryUpdateExchangeData] but the decrypted content is already provided.\n */\n async updateExchangeDataWithRawDecryptedContent(\n exchangeData: ExchangeData,\n newEncryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n rawExchangeKey: ArrayBuffer,\n rawAccessControlSecret: ArrayBuffer,\n rawSharedSignatureKey: ArrayBuffer\n ): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }> {\n const exchangeKey = await this.importExchangeKey(new Uint8Array(rawExchangeKey))\n const accessControlSecret = await this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret))\n const sharedSignatureKey = await this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey))\n const existingExchangeKeyEntries = new Set(Object.keys(exchangeData.exchangeKey))\n const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret))\n const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey))\n const missingEntries = Object.keys(newEncryptionKeys).filter(\n (fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp) || !existingSharedSignatureKeyEntries.has(fp)\n )\n if (!missingEntries.length) return { exchangeData, exchangeKey, accessControlSecret }\n const encryptionKeysForMissingEntries = missingEntries.reduce((obj, fp) => {\n obj[fp] = newEncryptionKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n const updatedExchangeData = _.cloneDeep(exchangeData)\n updatedExchangeData.exchangeKey = {\n ...exchangeData.exchangeKey,\n ...(await this.encryptDataWithKeys(rawExchangeKey, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.accessControlSecret = {\n ...exchangeData.accessControlSecret,\n ...(await this.encryptDataWithKeys(rawAccessControlSecret, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.sharedSignatureKey = {\n ...exchangeData.sharedSignatureKey,\n ...(await this.encryptDataWithKeys(rawSharedSignatureKey, encryptionKeysForMissingEntries)),\n }\n const isVerified = await this.verifyExchangeData(\n {\n exchangeData,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n decryptedSharedSignatureKey: sharedSignatureKey,\n },\n {},\n false\n )\n if (isVerified) {\n updatedExchangeData.sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: updatedExchangeData.delegate,\n delegator: updatedExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n publicKeysFingerprintsV2: Object.keys(updatedExchangeData.exchangeKey),\n }),\n sharedSignatureKey\n )\n }\n return { exchangeData: await this.api.modifyExchangeData(new ExchangeData(updatedExchangeData)), exchangeKey, accessControlSecret }\n }\n\n private async bytesToSignForSharedSignature(data: {\n delegator: string\n delegate: string\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n publicKeysFingerprintsV2: string[]\n }): Promise<ArrayBuffer> {\n // Use array of array to ensure that order is preserved regardless of how the specific js implementation orders\n // the keys of an object\n const signObject = [\n ['delegator', data.delegator],\n ['delegate', data.delegate],\n ['exchangeKey', ua2hex(await this.primitives.AES.exportKey(data.decryptedExchangeKey, 'raw'))],\n ['accessControlSecret', data.decryptedAccessControlSecret],\n ['publicKeysFingerprints', data.publicKeysFingerprintsV2.sort()],\n ]\n const signJson = JSON.stringify(signObject)\n return utf8_2ua(signJson)\n }\n\n private async bytesToSignForDelegatorSignature(data: { sharedSignatureKey: CryptoKey }): Promise<ArrayBuffer> {\n return this.primitives.sha256(await this.primitives.HMAC.exportKey(data.sharedSignatureKey))\n }\n\n // Generates a new exchange key\n private async generateExchangeKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = await this.primitives.randomBytes(32)\n return {\n key: await this.importExchangeKey(rawBytes),\n rawBytes,\n }\n }\n\n private async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n private async exportExchangeKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.AES.exportKey(key, 'raw')\n }\n\n private async generateSharedSignatureKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const key = await this.primitives.HMAC.generateKey()\n return { key, rawBytes: await this.primitives.HMAC.exportKey(key) }\n }\n\n private async importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.HMAC.importKey(decryptedBytes)\n }\n\n private async exportSharedSignatureKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.HMAC.exportKey(key)\n }\n\n // Generates a new access control secret\n private async generateAccessControlSecret(): Promise<{\n secret: string // the imported secret\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = this.primitives.randomBytes(16)\n return {\n secret: await this.importAccessControlSecret(rawBytes),\n rawBytes,\n }\n }\n\n private importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n private exportAccessControlSecret(secret: string): Promise<ArrayBuffer> {\n return Promise.resolve(hex2ua(secret))\n }\n\n private async encryptDataWithKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprintV1: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprintV2: string]: string }> {\n const res: { [keyPairFingerprintV2: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp] = ua2b64(await this.primitives.RSA.encrypt(key, new Uint8Array(rawData)))\n }\n return res\n }\n\n private async extractHmacFromRsaPrivate(privateRsaKey: CryptoKey): Promise<CryptoKey> {\n if (privateRsaKey.algorithm.name != 'RSA-OAEP' && !privateRsaKey.usages.includes('decrypt')) {\n throw new Error('Internal error: got unexpected key for signature/verification')\n }\n const keyBytes = await this.primitives.RSA.exportKey(privateRsaKey, 'pkcs8')\n const keyAsHmacBytes = await this.primitives.sha512(keyBytes)\n return await this.primitives.HMAC.importKey(keyAsHmacBytes, false)\n }\n\n private async signDataWithDelegatorKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprint: string]: string }> {\n const res: { [keyPairFingerprint: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintV1toV2(fp)] = ua2b64(await this.primitives.HMAC.sign(await this.extractHmacFromRsaPrivate(key), new Uint8Array(rawData)))\n }\n return res\n }\n\n private async verifyDelegatorSignature(\n exchangeData: ExchangeData,\n decryptedSharedSignatureKey: CryptoKey,\n verificationKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<Boolean> {\n const delegatorSignatureData = await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: decryptedSharedSignatureKey,\n })\n const keysByV2Fp = Object.fromEntries(Object.entries(verificationKeys).map(([fp, key]): [string, CryptoKey] => [fingerprintV1toV2(fp), key]))\n for (const [fp, signature] of Object.entries(exchangeData.delegatorSignature ?? {})) {\n const verificationKey = keysByV2Fp[fp]\n if (\n verificationKey &&\n (await this.primitives.HMAC.verify(await this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, b64_2ua(signature)))\n )\n return true\n }\n return false\n }\n\n private async signDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey): Promise<string> {\n return ua2b64(await this.primitives.HMAC.sign(key, new Uint8Array(rawData)))\n }\n\n private async verifyDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey, signature: string): Promise<boolean> {\n return await this.primitives.HMAC.verify(key, new Uint8Array(rawData), b64_2ua(signature))\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"BaseExchangeDataManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/BaseExchangeDataManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,4EAAwE;AAExE,+CAA2C;AAE3C,oCAAoE;AACpE,4BAA2B;AAC3B,mCAA4D;AAC5D,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B;;;;GAIG;AACH,MAAa,uBAAuB;IAClC,YACW,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,EAAE,IAAA,eAAO,EAAC,SAAS,CAAC,CAAC,CAAA;QAC5F,CAAC;KAAA;CACF;AAlkBD,0DAkkBC","sourcesContent":["import { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair } from './RSA'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { IccExchangeDataApi } from '../../icc-api/api/internal/IccExchangeDataApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { b64_2ua, hex2ua, ua2b64, ua2hex, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { fingerprintIsV1, fingerprintV1toV2 } from './utils'\nimport XHRError = XHR.XHRError\n\n/**\n * @internal this class is intended for internal use only and may be modified without notice\n * Functions to create and get exchange data.\n * The methods of this api require to pass the appropriate keys for encryption/decryption manually.\n */\nexport class BaseExchangeDataManager {\n constructor(\n readonly api: IccExchangeDataApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly primitives: CryptoPrimitives,\n private readonly selfRequiresAnonymousDelegations: boolean,\n private readonly doNotUseBulkGet: boolean\n ) {}\n\n /**\n * Get all the exchange data where the current data owner is the delegator or the delegate. However, some data owners, generally HCPs, may have a\n * prohibitively high amount of exchange data. If the crypto strategies specify that the current data owner requires anonymous delegation this\n * method returns all the exchange data found for the data owner, else the method returns undefined.\n * @return all the exchange data for the current data owner or undefined if the crypto strategies don't allow to retrieve all data for the current\n * data owner.\n */\n async getAllExchangeDataForCurrentDataOwnerIfAllowed(): Promise<ExchangeData[] | undefined> {\n if (!this.selfRequiresAnonymousDelegations) return undefined\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n let latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, undefined, 1000)\n const allRetrieved = latestResult.rows ?? []\n while (latestResult.nextKeyPair?.startKeyDocId) {\n latestResult = await this.api.getExchangeDataByParticipant(dataOwnerId, latestResult.nextKeyPair.startKeyDocId, 1000)\n if (latestResult.rows) allRetrieved.push(...latestResult.rows)\n }\n return allRetrieved\n }\n\n /**\n * Get all exchange data for the provided delegator-delegate pair.\n * @param delegatorId id of a delegator data owner.\n * @param delegateId id of a delegate data owner.\n * @return all exchange data for the provided delegator-delegate pair.\n */\n async getExchangeDataByDelegatorDelegatePair(delegatorId: string, delegateId: string): Promise<ExchangeData[]> {\n return await this.api.getExchangeDataByDelegatorDelegate(delegatorId, delegateId)\n }\n\n /**\n * Get the exchange data with the provided id.\n * @param exchangeDataId id of the exchange data.\n * @return the exchange data with the provided id or undefined if no exchange data with such id could be found.\n */\n async getExchangeDataById(exchangeDataId: string): Promise<ExchangeData | undefined> {\n return await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && e.statusCode === 404) {\n return undefined\n } else throw e\n })\n }\n\n async getExchangeDataByIds(exchangeDataIds: string[]): Promise<ExchangeData[]> {\n if (this.doNotUseBulkGet) {\n const res: ExchangeData[] = []\n for (const exchangeDataId of exchangeDataIds) {\n const curr = await this.api.getExchangeDataById(exchangeDataId).catch((e) => {\n if (e instanceof XHRError && (e.statusCode === 404 || e.statusCode === 403)) {\n return undefined\n } else throw e\n })\n if (curr) res.push(curr)\n }\n return res\n } else {\n return await this.api.getExchangeDataByIds({ ids: exchangeDataIds })\n }\n }\n\n /**\n * Verifies the authenticity of the exchange data by checking the signature.\n * Note that all exchange data created by data owners other than the current data owner (including members of his hierarchy)\n * will always be unverified.\n * @param data collects the following information about the exchange data being verified:\n * - exchangeData the exchange data to verify.\n * - decryptedAccessControlSecret the access control secret decrypted from the exchange data.\n * - decryptedExchangeKey the exchange key decrypted from the exchange data.\n * - decryptedSharedSignatureKey the shared signature key decrypted from the exchange data.\n * @param verificationKeys verification keys for delegator signature by fingerprint.\n * @param verifyAsDelegator if true the method will also verify that the hmac key used for the signature was created by the delegator of the\n * exchange data. If true and the data was not created by the current data owner this method will return false.\n * @return the exchange data which could be verified given his signature and the available verification keys.\n * @throws if any of the provided exchange data has been created by a data owner other than the current data owner.\n */\n async verifyExchangeData(\n data: {\n exchangeData: ExchangeData\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n decryptedSharedSignatureKey: CryptoKey\n },\n verificationKeys: { [fp: string]: CryptoKey },\n verifyAsDelegator: boolean\n ): Promise<boolean> {\n if (verifyAsDelegator && data.exchangeData.delegator !== (await this.dataOwnerApi.getCurrentDataOwnerId())) return false\n if (verifyAsDelegator && !(await this.verifyDelegatorSignature(data.exchangeData, data.decryptedSharedSignatureKey, verificationKeys)))\n return false\n const sharedSignatureData = await this.bytesToSignForSharedSignature({\n decryptedAccessControlSecret: data.decryptedAccessControlSecret,\n decryptedExchangeKey: data.decryptedExchangeKey,\n delegator: data.exchangeData.delegator,\n delegate: data.exchangeData.delegate,\n publicKeysFingerprintsV2: [\n ...new Set([\n ...Object.keys(data.exchangeData.exchangeKey),\n ...Object.keys(data.exchangeData.accessControlSecret),\n ...Object.keys(data.exchangeData.sharedSignatureKey),\n ]),\n ],\n })\n return await this.verifyDataWithSharedKey(sharedSignatureData, data.decryptedSharedSignatureKey, data.exchangeData.sharedSignature)\n }\n\n /**\n * Extracts and decrypts the access control secret from the provided exchange data.\n * These need to be hashed together with the entity class and confidentiality level in order to get the actual access control key\n * which will be sent to the server.\n * @param exchangeData the exchange data from which to extract access control secrets.\n * @param decryptionKeys rsa key pairs to use for decryption of the access control secret.\n * @return an object composed of:\n * - successfulDecryptions: array of all successfully decrypted access control keys\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptAccessControlSecret(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: string[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.accessControlSecret,\n (d) => this.importAccessControlSecret(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the exchange keys from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptExchangeKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.exchangeKey,\n (d) => this.importExchangeKey(new Uint8Array(d))\n )\n }\n\n /**\n * Extract and decrypts the shared signature key from the provided exchange data.\n * @param exchangeData the exchange data from which to extract exchange keys.\n * @param decryptionKeys rsa key pairs to use for the decryption of the exchange keys.\n * @return an object composed of:\n * - successfulDecryptions: array containing the successfully decrypted exchange keys.\n * - failedDecryptions: array containing all exchange data for which the access control key could not be decrypted (using the provided keys).\n */\n async tryDecryptSharedSignatureKeys(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{\n successfulDecryptions: CryptoKey[]\n failedDecryptions: ExchangeData[]\n }> {\n return await this.tryDecryptExchangeData(\n exchangeData,\n decryptionKeys,\n (ed) => ed.sharedSignatureKey,\n (d) => this.importSharedSignatureKey(new Uint8Array(d))\n )\n }\n\n private async tryDecryptExchangeData<T>(\n exchangeData: ExchangeData[],\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n encryptedDataSelector: (data: ExchangeData) => { [keyPairFingerprint: string]: string },\n unmarshalDecrypted: (decrypted: ArrayBuffer) => Promise<T>\n ): Promise<{\n successfulDecryptions: T[]\n failedDecryptions: ExchangeData[]\n }> {\n const successfulDecryptions: T[] = []\n const failedDecryptions: ExchangeData[] = []\n for (const ed of exchangeData) {\n try {\n const decrypted = await this.tryDecrypt(encryptedDataSelector(ed), decryptionKeys)\n if (decrypted) {\n successfulDecryptions.push(await unmarshalDecrypted(decrypted))\n } else {\n failedDecryptions.push(ed)\n }\n } catch (e) {\n failedDecryptions.push(ed)\n }\n }\n return { successfulDecryptions, failedDecryptions }\n }\n\n private async tryDecrypt(\n encryptedData: { [keyPairFingerprintV2: string]: string },\n decryptionKeys: { [publicKeyFingerprintV1: string]: KeyPair<CryptoKey> }\n ): Promise<ArrayBuffer | undefined> {\n const decryptionKeysWithV2Fp = Object.keys(decryptionKeys).reduce((prev, fp) => {\n return {\n ...prev,\n [fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp]: decryptionKeys[fp],\n }\n }, {} as { [publicKeyFingerprint: string]: KeyPair<CryptoKey> })\n for (const [fp, encrypted] of Object.entries(encryptedData)) {\n try {\n const key = decryptionKeysWithV2Fp[fp]?.privateKey\n if (key) return await this.primitives.RSA.decrypt(key, b64_2ua(encrypted))\n } catch (e) {\n // Try with another key\n }\n }\n }\n\n /**\n * Creates exchange data from the current data owner to the provided delegate, uploading the newly created exchange data to the cloud.\n * This assumes that the keys have been verified.\n * @param delegateId id of the delegate for the new exchange data.\n * @param signatureKeys private keys to use for signing the created data.\n * @param encryptionKeys public keys to use for the encryption of the exchange data (from delegator and delegate).\n * @param optionalAttributes optional precalculated attributes for the creation of data\n * @return the newly created exchange data, and its decrypted exchange key and access control secret.\n */\n async createExchangeData(\n delegateId: string,\n signatureKeys: { [keyPairFingerprint: string]: CryptoKey },\n encryptionKeys: { [keyPairFingerprint: string]: CryptoKey },\n optionalAttributes: {\n id?: string\n } = {}\n ): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n sharedSignatureKey: CryptoKey\n }> {\n if (!Object.keys(encryptionKeys).length) {\n throw new Error('Must specify at least one encryption key ')\n }\n const exchangeKey = await this.generateExchangeKey()\n const accessControlSecret = await this.generateAccessControlSecret()\n const sharedSignatureKey = await this.generateSharedSignatureKey()\n const encryptedExchangeKey = await this.encryptDataWithKeys(exchangeKey.rawBytes, encryptionKeys)\n const encryptedAccessControlSecret = await this.encryptDataWithKeys(accessControlSecret.rawBytes, encryptionKeys)\n const encryptedSharedSignatureKey = await this.encryptDataWithKeys(sharedSignatureKey.rawBytes, encryptionKeys)\n const baseExchangeData = {\n id: optionalAttributes.id ?? this.primitives.randomUuid(),\n delegator: await this.dataOwnerApi.getCurrentDataOwnerId(),\n delegate: delegateId,\n exchangeKey: encryptedExchangeKey,\n accessControlSecret: encryptedAccessControlSecret,\n sharedSignatureKey: encryptedSharedSignatureKey,\n }\n const sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: baseExchangeData.delegate,\n delegator: baseExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret.secret,\n decryptedExchangeKey: exchangeKey.key,\n publicKeysFingerprintsV2: Object.keys(encryptionKeys).map(fingerprintV1toV2),\n }),\n sharedSignatureKey.key\n )\n const delegatorSignature = await this.signDataWithDelegatorKeys(\n await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: sharedSignatureKey.key,\n }),\n signatureKeys\n )\n const exchangeData = new ExchangeData({ ...baseExchangeData, delegatorSignature, sharedSignature })\n return {\n exchangeData: await this.api.createExchangeData(exchangeData),\n exchangeKey: exchangeKey.key,\n accessControlSecret: accessControlSecret.secret,\n sharedSignatureKey: sharedSignatureKey.key,\n }\n }\n\n async tryRawDecryptExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<\n | {\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return { rawExchangeKey, rawAccessControlSecret, rawSharedSignatureKey }\n }\n\n /**\n * Updates existing exchange data and uploads it to the cloud in order to share it also with additional public keys, useful for example in cases\n * where one of the data owners involved in the exchange data has lost one of his keys.\n * If the content of the exchange data could not be decrypted using the provided keys the method will not update anything and will return undefined.\n * This method assumes that the new encryption keys have been verified.\n * @param exchangeData exchange data to update.\n * @param decryptionKeys keys to use to extract the content of the exchange data which will be shared with the new keys.\n * @param newEncryptionKeys new keys to add to the exchange data.\n * @return the updated exchange data, and its decrypted exchange key and access control secret, or undefined if the exchange data content could not\n * be decrypted and the exchange data could not be updated.\n */\n async tryUpdateExchangeData(\n exchangeData: ExchangeData,\n decryptionKeys: { [publicKeyFingerprint: string]: KeyPair<CryptoKey> },\n newEncryptionKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<\n | {\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }\n | undefined\n > {\n const rawExchangeKey = await this.tryDecrypt(exchangeData.exchangeKey, decryptionKeys)\n const rawAccessControlSecret = await this.tryDecrypt(exchangeData.accessControlSecret, decryptionKeys)\n const rawSharedSignatureKey = await this.tryDecrypt(exchangeData.sharedSignatureKey, decryptionKeys)\n if (!rawExchangeKey || !rawAccessControlSecret || !rawSharedSignatureKey) return undefined\n return await this.updateExchangeDataWithRawDecryptedContent({\n exchangeData: exchangeData,\n newEncryptionKeys: newEncryptionKeys,\n rawExchangeKey: rawExchangeKey,\n rawAccessControlSecret: rawAccessControlSecret,\n rawSharedSignatureKey: rawSharedSignatureKey,\n newDelegatorSignatureKeys: {},\n })\n }\n\n /**\n * Same as [tryUpdateExchangeData] but the decrypted content is already provided.\n */\n async updateExchangeDataWithRawDecryptedContent({\n exchangeData,\n newEncryptionKeys,\n rawExchangeKey,\n rawAccessControlSecret,\n rawSharedSignatureKey,\n newDelegatorSignatureKeys,\n }: {\n exchangeData: ExchangeData\n newEncryptionKeys: { [fp: string]: CryptoKey }\n newDelegatorSignatureKeys: { [keyPairFingerprint: string]: CryptoKey }\n rawExchangeKey: ArrayBuffer\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n }): Promise<{\n exchangeData: ExchangeData\n exchangeKey: CryptoKey\n accessControlSecret: string\n }> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeKey = await this.importExchangeKey(new Uint8Array(rawExchangeKey))\n const accessControlSecret = await this.importAccessControlSecret(new Uint8Array(rawAccessControlSecret))\n const sharedSignatureKey = await this.importSharedSignatureKey(new Uint8Array(rawSharedSignatureKey))\n const existingExchangeKeyEntries = new Set(Object.keys(exchangeData.exchangeKey))\n const existingAcsEntries = new Set(Object.keys(exchangeData.accessControlSecret))\n const existingSharedSignatureKeyEntries = new Set(Object.keys(exchangeData.sharedSignatureKey))\n const missingEntries = Object.keys(newEncryptionKeys).filter(\n (fp) => !existingAcsEntries.has(fp) || !existingExchangeKeyEntries.has(fp) || !existingSharedSignatureKeyEntries.has(fp)\n )\n const existingDelegatorSignatureEntries = new Set(Object.keys(exchangeData.delegatorSignature ?? {}))\n const missingDelegatorSignatureEntries =\n exchangeData.delegator == self ? Object.keys(newDelegatorSignatureKeys).filter((fp) => !existingDelegatorSignatureEntries.has(fp)) : []\n if (!missingEntries.length && !missingDelegatorSignatureEntries.length) return { exchangeData, exchangeKey, accessControlSecret }\n const encryptionKeysForMissingEntries = missingEntries.reduce((obj, fp) => {\n obj[fp] = newEncryptionKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n const updatedExchangeData = _.cloneDeep(exchangeData)\n updatedExchangeData.exchangeKey = {\n ...exchangeData.exchangeKey,\n ...(await this.encryptDataWithKeys(rawExchangeKey, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.accessControlSecret = {\n ...exchangeData.accessControlSecret,\n ...(await this.encryptDataWithKeys(rawAccessControlSecret, encryptionKeysForMissingEntries)),\n }\n updatedExchangeData.sharedSignatureKey = {\n ...exchangeData.sharedSignatureKey,\n ...(await this.encryptDataWithKeys(rawSharedSignatureKey, encryptionKeysForMissingEntries)),\n }\n const isVerified = await this.verifyExchangeData(\n {\n exchangeData,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n decryptedSharedSignatureKey: sharedSignatureKey,\n },\n {},\n false\n )\n if (isVerified) {\n updatedExchangeData.sharedSignature = await this.signDataWithSharedKey(\n await this.bytesToSignForSharedSignature({\n delegate: updatedExchangeData.delegate,\n delegator: updatedExchangeData.delegator,\n decryptedAccessControlSecret: accessControlSecret,\n decryptedExchangeKey: exchangeKey,\n publicKeysFingerprintsV2: Object.keys(updatedExchangeData.exchangeKey),\n }),\n sharedSignatureKey\n )\n }\n if (missingDelegatorSignatureEntries.length > 0) {\n const bytesToSign = await this.bytesToSignForDelegatorSignature({ sharedSignatureKey })\n const newSigned = await this.signDataWithDelegatorKeys(\n bytesToSign,\n missingDelegatorSignatureEntries.reduce((obj, fp) => {\n obj[fp] = newDelegatorSignatureKeys[fp]\n return obj\n }, {} as { [keyPairFingerprint: string]: CryptoKey })\n )\n updatedExchangeData.delegatorSignature = {\n ...updatedExchangeData.delegatorSignature,\n ...newSigned,\n }\n }\n return { exchangeData: await this.api.modifyExchangeData(new ExchangeData(updatedExchangeData)), exchangeKey, accessControlSecret }\n }\n\n private async bytesToSignForSharedSignature(data: {\n delegator: string\n delegate: string\n decryptedAccessControlSecret: string\n decryptedExchangeKey: CryptoKey\n publicKeysFingerprintsV2: string[]\n }): Promise<ArrayBuffer> {\n // Use array of array to ensure that order is preserved regardless of how the specific js implementation orders\n // the keys of an object\n const signObject = [\n ['delegator', data.delegator],\n ['delegate', data.delegate],\n ['exchangeKey', ua2hex(await this.primitives.AES.exportKey(data.decryptedExchangeKey, 'raw'))],\n ['accessControlSecret', data.decryptedAccessControlSecret],\n ['publicKeysFingerprints', data.publicKeysFingerprintsV2.sort()],\n ]\n const signJson = JSON.stringify(signObject)\n return utf8_2ua(signJson)\n }\n\n private async bytesToSignForDelegatorSignature(data: { sharedSignatureKey: CryptoKey }): Promise<ArrayBuffer> {\n return this.primitives.sha256(await this.primitives.HMAC.exportKey(data.sharedSignatureKey))\n }\n\n // Generates a new exchange key\n private async generateExchangeKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = await this.primitives.randomBytes(32)\n return {\n key: await this.importExchangeKey(rawBytes),\n rawBytes,\n }\n }\n\n async importExchangeKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.AES.importKey('raw', decryptedBytes)\n }\n\n async exportExchangeKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.AES.exportKey(key, 'raw')\n }\n\n private async generateSharedSignatureKey(): Promise<{\n key: CryptoKey // the imported key\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const key = await this.primitives.HMAC.generateKey()\n return { key, rawBytes: await this.primitives.HMAC.exportKey(key) }\n }\n\n async importSharedSignatureKey(decryptedBytes: ArrayBuffer): Promise<CryptoKey> {\n return await this.primitives.HMAC.importKey(decryptedBytes)\n }\n\n async exportSharedSignatureKey(key: CryptoKey): Promise<ArrayBuffer> {\n return await this.primitives.HMAC.exportKey(key)\n }\n\n // Generates a new access control secret\n private async generateAccessControlSecret(): Promise<{\n secret: string // the imported secret\n rawBytes: ArrayBuffer // the bytes to encrypt for in the exchange data\n }> {\n const rawBytes = this.primitives.randomBytes(16)\n return {\n secret: await this.importAccessControlSecret(rawBytes),\n rawBytes,\n }\n }\n\n importAccessControlSecret(decryptedBytes: ArrayBuffer): Promise<string> {\n return Promise.resolve(ua2hex(decryptedBytes))\n }\n\n exportAccessControlSecret(secret: string): Promise<ArrayBuffer> {\n return Promise.resolve(hex2ua(secret))\n }\n\n private async encryptDataWithKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprintV1: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprintV2: string]: string }> {\n const res: { [keyPairFingerprintV2: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintIsV1(fp) ? fingerprintV1toV2(fp) : fp] = ua2b64(await this.primitives.RSA.encrypt(key, new Uint8Array(rawData)))\n }\n return res\n }\n\n private async extractHmacFromRsaPrivate(privateRsaKey: CryptoKey): Promise<CryptoKey> {\n if (privateRsaKey.algorithm.name != 'RSA-OAEP' && !privateRsaKey.usages.includes('decrypt')) {\n throw new Error('Internal error: got unexpected key for signature/verification')\n }\n const keyBytes = await this.primitives.RSA.exportKey(privateRsaKey, 'pkcs8')\n const keyAsHmacBytes = await this.primitives.sha512(keyBytes)\n return await this.primitives.HMAC.importKey(keyAsHmacBytes, false)\n }\n\n private async signDataWithDelegatorKeys(\n rawData: ArrayBuffer,\n keys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<{ [keyPairFingerprint: string]: string }> {\n const res: { [keyPairFingerprint: string]: string } = {}\n for (const [fp, key] of Object.entries(keys)) {\n res[fingerprintV1toV2(fp)] = ua2b64(await this.primitives.HMAC.sign(await this.extractHmacFromRsaPrivate(key), new Uint8Array(rawData)))\n }\n return res\n }\n\n private async verifyDelegatorSignature(\n exchangeData: ExchangeData,\n decryptedSharedSignatureKey: CryptoKey,\n verificationKeys: { [keyPairFingerprint: string]: CryptoKey }\n ): Promise<Boolean> {\n const delegatorSignatureData = await this.bytesToSignForDelegatorSignature({\n sharedSignatureKey: decryptedSharedSignatureKey,\n })\n const keysByV2Fp = Object.fromEntries(Object.entries(verificationKeys).map(([fp, key]): [string, CryptoKey] => [fingerprintV1toV2(fp), key]))\n for (const [fp, signature] of Object.entries(exchangeData.delegatorSignature ?? {})) {\n const verificationKey = keysByV2Fp[fp]\n if (\n verificationKey &&\n (await this.primitives.HMAC.verify(await this.extractHmacFromRsaPrivate(verificationKey), delegatorSignatureData, b64_2ua(signature)))\n )\n return true\n }\n return false\n }\n\n private async signDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey): Promise<string> {\n return ua2b64(await this.primitives.HMAC.sign(key, new Uint8Array(rawData)))\n }\n\n private async verifyDataWithSharedKey(rawData: ArrayBuffer, key: CryptoKey, signature: string): Promise<boolean> {\n return await this.primitives.HMAC.verify(key, new Uint8Array(rawData), b64_2ua(signature))\n }\n}\n"]}
|
|
@@ -65,8 +65,9 @@ export interface CryptoStrategies {
|
|
|
65
65
|
* - If this method returns a key pair the crypto api loads the key pair and considers it as a device key.
|
|
66
66
|
* - If this method returns false the initialisation will fail with a predefined error.
|
|
67
67
|
* - If this method throws an error the initialisation will propagate the error.
|
|
68
|
+
* - If this method return the string "keyless" the api will be initialized in keyless mode.
|
|
68
69
|
*/
|
|
69
|
-
generateNewKeyForDataOwner(self: DataOwnerWithType, cryptoPrimitives: CryptoPrimitives): Promise<KeyPair<CryptoKey> | boolean>;
|
|
70
|
+
generateNewKeyForDataOwner(self: DataOwnerWithType, cryptoPrimitives: CryptoPrimitives): Promise<KeyPair<CryptoKey> | boolean | 'keyless'>;
|
|
70
71
|
/**
|
|
71
72
|
* Verifies if the public keys of a data owner which will be the delegate of a new exchange key do actually belong to the person the data owner
|
|
72
73
|
* represents. This method is not called when the delegate would be the current data owner for the api.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CryptoStrategies.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoStrategies.ts"],"names":[],"mappings":"","sourcesContent":["import { KeyPair } from './RSA'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\n/**\n * Allows to customise the behaviour of the crypto api to better suit your needs.\n *\n * An important task which should be done in these crypto strategies is public key verification: in general there is no guarantee that the public keys\n * stored in the iCure database are authentic, i.e. created by the data owner they are associated to. This is because the database admins or a\n * malicious attacker may have added his own public keys to the data owner's public keys.\n * Sharing any kind of data using unverified public keys could potentially cause a data leak: this is why when creating new exchange keys or when\n * creating recovery data only verified keys will be considered. For decrypting existing data instead unverified keys will be used without issues.\n */\nexport interface CryptoStrategies {\n /**\n * Method called during initialisation of the crypto API to validate keys recovered through iCure's recovery methods and/or to allow recovery of\n * missing keys using means external to iCure.\n * On startup the iCure sdk will try to load all keys for the current data owner and its parent hierarchy: if the sdk can't find some of the keys\n * for any of the data owners (according to the public keys for the data owner in the iCure server) and/or the sdk could recover some private keys\n * but can't verify the authenticity of the key pairs this method will be called.\n * The recovered and verified keys will automatically be cached using the current api {@link KeyStorageFacade} and {@link StorageFacade}\n *\n * The input is an array containing an object for each data owner part of the current data owner hierarchy. The objects are ordered from the data\n * for the topmost parent of the current data owner hierarchy (first element) to the data for the current data owner (last element). Each object\n * contains:\n * - dataOwner: the data owner entity that this object refers to\n * - unknownKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the authenticity status (verified or unverified) is unknown\n * (no result was cached from a previous api instantiation and the key was not generated on the current device).\n * - unavailableKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the sdk could not recover a private key. May overlap\n * (partially or completely) with `unknownKeys`.\n *\n * The returned value must be an object associating to each data owner id an object with:\n * - `recoveredKeys`: all recovered keys (will be automatically considered as verified), by fingerprint.\n * - `keyAuthenticity`: an object associating to each public key fingerprint its authenticity. Note that if any of the keys from `unknownKeys` is\n * completely missing from this object the key will be considered as unverified in this api instance (same as if associated to false), but this\n * value won't be cached (will be again part of `unknownKeys` in future instances.\n * @param keysData all information on unknown and unavailable keys for each data owner part of the current data owner hierarchy.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @param keyPairRecoverer a key pair recoverer.\n * @return all recovered keys and key authenticity information, by data owner.\n */\n recoverAndVerifySelfHierarchyKeys(\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[],\n cryptoPrimitives: CryptoPrimitives,\n keyPairRecoverer: KeyPairRecoverer\n ): Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }>\n\n /**\n * The correct initialisation of the crypto API requires that at least 1 verified (or device) key pair is available for each data owner part of the\n * current data owner hierarchy. If no verified key is available for any of the data owner parents the api initialisation will automatically fail,\n * however if there is no verified key for the current data owner you can instead create a new crypto key.\n * @param self the current data owner.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @return depending on which values you return the api initialisation will proceed differently:\n * - If this method returns true a new key will be automatically generated by the sdk.\n * - If this method returns a key pair the crypto api loads the key pair and considers it as a device key.\n * - If this method returns false the initialisation will fail with a predefined error.\n * - If this method throws an error the initialisation will propagate the error.\n */\n generateNewKeyForDataOwner(self: DataOwnerWithType, cryptoPrimitives: CryptoPrimitives): Promise<KeyPair<CryptoKey> | boolean>\n\n /**\n * Verifies if the public keys of a data owner which will be the delegate of a new exchange key do actually belong to the person the data owner\n * represents. This method is not called when the delegate would be the current data owner for the api.\n *\n * The user will have to obtain the verified public keys of the delegate from outside iCure, for example by email with another hcp, by checking the\n * personal website of the other user, or by scanning verification qr codes at the doctor office...\n *\n * As long as one of the public keys is verified the creation of a new exchange key will succeed. If no public key is verified the operation will\n * fail.\n * @param delegate the potential data owner delegate.\n * @param publicKeys public keys requiring verification, in spki hex-encoded format.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @return all verified public keys, in spki hex-encoded format.\n */\n verifyDelegatePublicKeys(delegate: CryptoActorStubWithType, publicKeys: string[], cryptoPrimitives: CryptoPrimitives): Promise<string[]>\n\n /**\n * Specifies if a data owner requires anonymous delegations, i.e. his id should not appear unencrypted in new secure delegations. This should always\n * be the case for patient data owners.\n * @param dataOwner a data owner.\n * @return true if the delegations for the provided data owner should be anonymous.\n */\n dataOwnerRequiresAnonymousDelegation(dataOwner: CryptoActorStubWithType): boolean\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CryptoStrategies.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoStrategies.ts"],"names":[],"mappings":"","sourcesContent":["import { KeyPair } from './RSA'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\n/**\n * Allows to customise the behaviour of the crypto api to better suit your needs.\n *\n * An important task which should be done in these crypto strategies is public key verification: in general there is no guarantee that the public keys\n * stored in the iCure database are authentic, i.e. created by the data owner they are associated to. This is because the database admins or a\n * malicious attacker may have added his own public keys to the data owner's public keys.\n * Sharing any kind of data using unverified public keys could potentially cause a data leak: this is why when creating new exchange keys or when\n * creating recovery data only verified keys will be considered. For decrypting existing data instead unverified keys will be used without issues.\n */\nexport interface CryptoStrategies {\n /**\n * Method called during initialisation of the crypto API to validate keys recovered through iCure's recovery methods and/or to allow recovery of\n * missing keys using means external to iCure.\n * On startup the iCure sdk will try to load all keys for the current data owner and its parent hierarchy: if the sdk can't find some of the keys\n * for any of the data owners (according to the public keys for the data owner in the iCure server) and/or the sdk could recover some private keys\n * but can't verify the authenticity of the key pairs this method will be called.\n * The recovered and verified keys will automatically be cached using the current api {@link KeyStorageFacade} and {@link StorageFacade}\n *\n * The input is an array containing an object for each data owner part of the current data owner hierarchy. The objects are ordered from the data\n * for the topmost parent of the current data owner hierarchy (first element) to the data for the current data owner (last element). Each object\n * contains:\n * - dataOwner: the data owner entity that this object refers to\n * - unknownKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the authenticity status (verified or unverified) is unknown\n * (no result was cached from a previous api instantiation and the key was not generated on the current device).\n * - unavailableKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the sdk could not recover a private key. May overlap\n * (partially or completely) with `unknownKeys`.\n *\n * The returned value must be an object associating to each data owner id an object with:\n * - `recoveredKeys`: all recovered keys (will be automatically considered as verified), by fingerprint.\n * - `keyAuthenticity`: an object associating to each public key fingerprint its authenticity. Note that if any of the keys from `unknownKeys` is\n * completely missing from this object the key will be considered as unverified in this api instance (same as if associated to false), but this\n * value won't be cached (will be again part of `unknownKeys` in future instances.\n * @param keysData all information on unknown and unavailable keys for each data owner part of the current data owner hierarchy.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @param keyPairRecoverer a key pair recoverer.\n * @return all recovered keys and key authenticity information, by data owner.\n */\n recoverAndVerifySelfHierarchyKeys(\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[],\n cryptoPrimitives: CryptoPrimitives,\n keyPairRecoverer: KeyPairRecoverer\n ): Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }>\n\n /**\n * The correct initialisation of the crypto API requires that at least 1 verified (or device) key pair is available for each data owner part of the\n * current data owner hierarchy. If no verified key is available for any of the data owner parents the api initialisation will automatically fail,\n * however if there is no verified key for the current data owner you can instead create a new crypto key.\n * @param self the current data owner.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @return depending on which values you return the api initialisation will proceed differently:\n * - If this method returns true a new key will be automatically generated by the sdk.\n * - If this method returns a key pair the crypto api loads the key pair and considers it as a device key.\n * - If this method returns false the initialisation will fail with a predefined error.\n * - If this method throws an error the initialisation will propagate the error.\n * - If this method return the string \"keyless\" the api will be initialized in keyless mode.\n */\n generateNewKeyForDataOwner(self: DataOwnerWithType, cryptoPrimitives: CryptoPrimitives): Promise<KeyPair<CryptoKey> | boolean | 'keyless'>\n\n /**\n * Verifies if the public keys of a data owner which will be the delegate of a new exchange key do actually belong to the person the data owner\n * represents. This method is not called when the delegate would be the current data owner for the api.\n *\n * The user will have to obtain the verified public keys of the delegate from outside iCure, for example by email with another hcp, by checking the\n * personal website of the other user, or by scanning verification qr codes at the doctor office...\n *\n * As long as one of the public keys is verified the creation of a new exchange key will succeed. If no public key is verified the operation will\n * fail.\n * @param delegate the potential data owner delegate.\n * @param publicKeys public keys requiring verification, in spki hex-encoded format.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @return all verified public keys, in spki hex-encoded format.\n */\n verifyDelegatePublicKeys(delegate: CryptoActorStubWithType, publicKeys: string[], cryptoPrimitives: CryptoPrimitives): Promise<string[]>\n\n /**\n * Specifies if a data owner requires anonymous delegations, i.e. his id should not appear unencrypted in new secure delegations. This should always\n * be the case for patient data owners.\n * @param dataOwner a data owner.\n * @return true if the delegations for the provided data owner should be anonymous.\n */\n dataOwnerRequiresAnonymousDelegation(dataOwner: CryptoActorStubWithType): boolean\n}\n"]}
|
|
@@ -228,7 +228,7 @@ class DelegationsDeAnonymization {
|
|
|
228
228
|
delegate: delegationMembersDetails.delegate,
|
|
229
229
|
delegator: delegationMembersDetails.delegator,
|
|
230
230
|
delegationKey: delegationKey,
|
|
231
|
-
}, entityType, undefined, undefined, true, Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ])));
|
|
231
|
+
}, entityType, undefined, undefined, true, Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ])), undefined);
|
|
232
232
|
const encryptedKeyMap = (yield this.xapis.tryEncryptEntities([initalisedMapInfo.updatedEntity], entityType, this.delegationKeyMapFieldsToEncrypt, false, true, (x) => new SecureDelegationKeyMap_1.SecureDelegationKeyMap(x)))[0];
|
|
233
233
|
yield this.delegationKeyMapApi.create(encryptedKeyMap, new XHR_1.XHR.Header(AccessControlKeysHeadersProvider_1.ACCESS_CONTROL_KEYS_HEADER, yield this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)));
|
|
234
234
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DelegationsDeAnonymization.js","sourceRoot":"","sources":["../../../icc-x-api/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AC,KAAK,CAAC,kBAAkB,CACjC,CAAC,iBAAiB,CAAC,aAAa,CAAC,EACjC,UAAU,EACV,IAAI,CAAC,+BAA+B,EACpC,KAAK,EACL,IAAI,EACJ,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,+CAAsB,CAAC,CAAC,CAAC,CACrC,CACF,CAAC,CAAC,CAAC,CAAA;YACJ,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CACnC,eAAe,EACf,IAAI,SAAG,CAAC,MAAM,CACZ,6DAA0B,EAC1B,MAAM,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,EAAE,UAAU,CAAC,CAC5H,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA9QD,gEA8QC","sourcesContent":["import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { SecureDelegationKeyMap } from '../../icc-api/model/internal/SecureDelegationKeyMap'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedFieldsManifest, parseEncryptedFields } from '../utils'\nimport { IccSecureDelegationKeyMapApi } from '../../icc-api/api/internal/IccSecureDelegationKeyMapApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { AuthenticationProvider, NoAuthenticationProvider } from '../auth/AuthenticationProvider'\nimport { ACCESS_CONTROL_KEYS_HEADER, AccessControlKeysHeadersProvider } from './AccessControlKeysHeadersProvider'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { DelegationMembersDetails, SecurityMetadataDecryptor } from './SecurityMetadataDecryptor'\n\n// TODO could be optimised using bulk methods\nexport class DelegationsDeAnonymization {\n private readonly delegationKeyMapFieldsToEncrypt: EncryptedFieldsManifest\n private readonly delegationKeyMapApi: IccSecureDelegationKeyMapApi\n\n constructor(\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly securityMetadataDecryptor: SecurityMetadataDecryptor,\n private readonly xapis: ExtendedApisUtils,\n private readonly cryptoPrimitives: CryptoPrimitives,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n private readonly accessControlKeysHeadersProvider: AccessControlKeysHeadersProvider\n ) {\n this.delegationKeyMapFieldsToEncrypt = parseEncryptedFields(['delegate', 'delegator'], 'SecureDelegationKeyMap')\n this.delegationKeyMapApi = new IccSecureDelegationKeyMapApi(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Creates / updates information to allow the data owners in {@link shareWithDataOwners} to de-anonymize the delegations contained within\n * {@link entity}.\n * Note that the delegation de-anonymization information may be used also with other entities of the same type.\n */\n async createOrUpdateDeAnonymizationInfo(entityWithType: EncryptedEntityWithType, shareWithDataOwners: string[]) {\n const delegationsDetails = Object.entries(await this.securityMetadataDecryptor.getDelegationMemberDetails(entityWithType)).flatMap(\n ([canonicalKey, delegation]) => {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [[canonicalKey, delegation], ...aliases.map((alias) => [alias, delegation])] as [string, DelegationMembersDetails][]\n }\n )\n const delegationsForDeanonInfoSharing = delegationsDetails.filter(([_, delegationInfo]) => {\n // Drop fully explicit ones: they don't need de-anonymization info\n return !delegationInfo.fullyExplicit\n })\n // A subset of delegations for which deanon info is relevant AND for which we can also create new info instead of sharing only existing one.\n const delegationsForNewDeanonInfoCreation = delegationsForDeanonInfoSharing.filter(([_, delegationInfo]) => {\n // Drop those for which we don't have the full information needed for the creation of new data.\n return !!delegationInfo.delegate && !!delegationInfo.delegator && !!delegationInfo.accessControlSecret\n })\n const existingDelegationsMap = await this.getDecryptedSecureDelegationKeyMaps(\n delegationsForDeanonInfoSharing.map((x) => x[0]),\n entityWithType.type\n )\n for (const delMapToShare of existingDelegationsMap) {\n await this.ensureDelegationKeyMapSharedWith(entityWithType.type, delMapToShare, shareWithDataOwners)\n }\n const existingDelegationsMapKeys = new Set(existingDelegationsMap.map((x) => x.delegationKey))\n const delegationsToCreate = delegationsForNewDeanonInfoCreation.filter(([k, _]) => !existingDelegationsMapKeys.has(k))\n for (const [delKey, membersDetails] of delegationsToCreate) {\n await this.createSecureDelegationKeyMap(entityWithType.type, delKey, membersDetails, shareWithDataOwners)\n }\n }\n\n /**\n * Get the data owners which can access the entity. See {@link EncryptedEntityXApi.getDataOwnersWithAccessTo} for more details.\n * @param entityWithType an entity.\n */\n async getDataOwnersWithAccessTo(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return this.mergePermissions([\n await this.getDataOwnersWithAccessToSecureDelegations(entityWithType),\n {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entityWithType.entity.delegations ?? {}).map((k) => [k, AccessLevelEnum.WRITE])),\n hasUnknownAnonymousDataOwners: false,\n },\n ])\n }\n\n private async getDataOwnersWithAccessToSecureDelegations(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const secureDelegationDetails = await this.securityMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const secureDelegationWithUnknownMembers = Object.entries(secureDelegationDetails).flatMap(([canonicalKey, delegation]) => {\n if (!delegation.delegate || !delegation.delegator) {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [{ keys: [canonicalKey, ...aliases], delegation }]\n } else {\n return []\n }\n })\n const secureDelegationKeyMapsByDelegationKey = Object.fromEntries(\n (\n await this.getDecryptedSecureDelegationKeyMaps(\n secureDelegationWithUnknownMembers.flatMap(({ keys }) => keys),\n entityWithType.type\n )\n ).map((x) => [x.delegationKey, x])\n )\n const permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n function addAccess(dataOwnerId: string, level: AccessLevelEnum) {\n if (permissionsByDataOwnerId[dataOwnerId] !== AccessLevelEnum.WRITE) {\n permissionsByDataOwnerId[dataOwnerId] = level\n }\n }\n for (const delegation of Object.values(secureDelegationDetails)) {\n if (delegation.delegate) addAccess(delegation.delegate, delegation.accessLevel)\n if (delegation.delegator) addAccess(delegation.delegator, delegation.accessLevel)\n }\n for (const { keys, delegation } of secureDelegationWithUnknownMembers) {\n const bestKey = keys.find((k) => {\n const currMap = secureDelegationKeyMapsByDelegationKey[k]\n return currMap && !!currMap.delegator && !!currMap.delegate\n })\n if (bestKey) {\n const keyMap = secureDelegationKeyMapsByDelegationKey[bestKey]\n addAccess(keyMap.delegate!, delegation.accessLevel)\n addAccess(keyMap.delegator!, delegation.accessLevel)\n } else {\n hasUnknownAnonymousDataOwners = true\n }\n }\n return { permissionsByDataOwnerId, hasUnknownAnonymousDataOwners }\n }\n\n private async mergePermissions(\n values: {\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }[]\n ): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const accumulatedPermissions: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n for (const v of values) {\n hasUnknownAnonymousDataOwners = hasUnknownAnonymousDataOwners || v.hasUnknownAnonymousDataOwners\n for (const [dataOwnerId, level] of Object.entries(v.permissionsByDataOwnerId)) {\n if (accumulatedPermissions[dataOwnerId] !== AccessLevelEnum.WRITE) {\n accumulatedPermissions[dataOwnerId] = level\n }\n }\n }\n return {\n permissionsByDataOwnerId: accumulatedPermissions,\n hasUnknownAnonymousDataOwners,\n }\n }\n\n private async getDecryptedSecureDelegationKeyMaps(\n delegationIds: string[],\n entityType: EntityWithDelegationTypeName\n ): Promise<SecureDelegationKeyMap[]> {\n if (delegationIds.length) {\n const encryptedMaps = await this.delegationKeyMapApi.getByDelegationKeys(\n { ids: delegationIds },\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n const res: SecureDelegationKeyMap[] = []\n for (const encryptedMap of encryptedMaps) {\n // Use the original entity type\n const decryptionResult = (await this.xapis.tryDecryptEntities([encryptedMap], entityType, (x) => new SecureDelegationKeyMap(x)))[0]\n if (decryptionResult.decrypted) {\n res.push(decryptionResult.entity)\n }\n }\n return res\n } else return []\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async ensureDelegationKeyMapSharedWith(entityType: EntityWithDelegationTypeName, keyMap: SecureDelegationKeyMap, delegates: string[]) {\n if (!keyMap.delegator || !keyMap.delegate) throw new Error('Illegal state: key map is missing delegator or delegate info.')\n const dataOwnersWithAccessToMapThroughDelegation = Object.values(\n await this.securityMetadataDecryptor.getDelegationMemberDetails({\n type: entityType,\n entity: keyMap,\n })\n )\n .flatMap((x) => [x.delegate, x.delegator])\n .filter((x) => !!x) as string[]\n // Delegator and delegate got access to the entity when it was first created: no need to share with them ever.\n const dataOwnersWithAccessToMap = new Set([keyMap.delegate, keyMap.delegator, ...dataOwnersWithAccessToMapThroughDelegation])\n const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x))\n if (dataOwnersNeedingShare.length) {\n ;(\n await this.xapis.simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: keyMap,\n type: entityType,\n },\n Object.fromEntries(\n dataOwnersNeedingShare.map((x) => [\n x,\n {\n shareSecretIds: [],\n shareEncryptionKeys: ShareMetadataBehaviour.REQUIRED,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n },\n ])\n ),\n async (request) =>\n this.delegationKeyMapApi.bulkShareSecureDelegationKeyMap(\n request,\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n )\n ).updatedEntityOrThrow\n }\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async createSecureDelegationKeyMap(\n entityType: EntityWithDelegationTypeName,\n delegationKey: string,\n delegationMembersDetails: DelegationMembersDetails,\n delegates: string[]\n ) {\n if (!delegationMembersDetails.delegate || !delegationMembersDetails.delegator || !delegationMembersDetails.accessControlSecret)\n throw new Error('Illegal state: delegation members details are missing delegate, delegator or access control secret info.')\n const selfDoId = await this.dataOwnerApi.getCurrentDataOwnerId()\n // Ensure that both the delegator and delegate of the delegation this map refers tho can share it later on, even if they did not create it.\n // Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.\n const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId)\n const initalisedMapInfo = await this.xapis.entityWithInitialisedEncryptedMetadata<SecureDelegationKeyMap>(\n {\n id: this.cryptoPrimitives.randomUuid(),\n delegate: delegationMembersDetails.delegate,\n delegator: delegationMembersDetails.delegator,\n delegationKey: delegationKey,\n },\n entityType,\n undefined,\n undefined,\n true,\n Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ]))\n )\n const encryptedKeyMap = (\n await this.xapis.tryEncryptEntities(\n [initalisedMapInfo.updatedEntity],\n entityType,\n this.delegationKeyMapFieldsToEncrypt,\n false,\n true,\n (x) => new SecureDelegationKeyMap(x)\n )\n )[0]\n await this.delegationKeyMapApi.create(\n encryptedKeyMap,\n new XHR.Header(\n ACCESS_CONTROL_KEYS_HEADER,\n await this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)\n )\n )\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DelegationsDeAnonymization.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/DelegationsDeAnonymization.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,2EAAuE;AACvE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACzD,gGAA4F;AAE5F,qEAAiE;AACjE,wFAAoF;AACpF,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E,oCAAwE;AACxE,0GAAsG;AACtG,+CAA2C;AAC3C,2EAAiG;AACjG,yFAAiH;AAKjH,6CAA6C;AAC7C,MAAa,0BAA0B;IAIrC,YACmB,YAA8B,EAC9B,yBAAoD,EACpD,KAAwB,EACxB,gBAAkC,EAClC,wBAAkD,EACnE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK,EACQ,gCAAkE;QAblE,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,8BAAyB,GAAzB,yBAAyB,CAA2B;QACpD,UAAK,GAAL,KAAK,CAAmB;QACxB,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,6BAAwB,GAAxB,wBAAwB,CAA0B;QASlD,qCAAgC,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BAAgB,CAAC,UAAU,EAAE;gBACtC,QAAQ,EAAE,wBAAwB,CAAC,QAAQ;gBAC3C,SAAS,EAAE,wBAAwB,CAAC,SAAS;gBAC7C,aAAa,EAAE,aAAa;aAC7B,EACD,UAAU,EACV,SAAS,EACT,SAAS,EACT,IAAI,EACJ,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAC1E,SAAS,CACV,CAAA;YACD,MAAM,eAAe,GAAG,CACtB,MAAM,IAAI,CAAC,KAAK,CAAC,kBAAkB,CACjC,CAAC,iBAAiB,CAAC,aAAa,CAAC,EACjC,UAAU,EACV,IAAI,CAAC,+BAA+B,EACpC,KAAK,EACL,IAAI,EACJ,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,+CAAsB,CAAC,CAAC,CAAC,CACrC,CACF,CAAC,CAAC,CAAC,CAAA;YACJ,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CACnC,eAAe,EACf,IAAI,SAAG,CAAC,MAAM,CACZ,6DAA0B,EAC1B,MAAM,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,EAAE,UAAU,CAAC,CAC5H,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA/QD,gEA+QC","sourcesContent":["import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { SecureDelegationKeyMap } from '../../icc-api/model/internal/SecureDelegationKeyMap'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedFieldsManifest, parseEncryptedFields } from '../utils'\nimport { IccSecureDelegationKeyMapApi } from '../../icc-api/api/internal/IccSecureDelegationKeyMapApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { AuthenticationProvider, NoAuthenticationProvider } from '../auth/AuthenticationProvider'\nimport { ACCESS_CONTROL_KEYS_HEADER, AccessControlKeysHeadersProvider } from './AccessControlKeysHeadersProvider'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { DelegationMembersDetails, SecurityMetadataDecryptor } from './SecurityMetadataDecryptor'\n\n// TODO could be optimised using bulk methods\nexport class DelegationsDeAnonymization {\n private readonly delegationKeyMapFieldsToEncrypt: EncryptedFieldsManifest\n private readonly delegationKeyMapApi: IccSecureDelegationKeyMapApi\n\n constructor(\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly securityMetadataDecryptor: SecurityMetadataDecryptor,\n private readonly xapis: ExtendedApisUtils,\n private readonly cryptoPrimitives: CryptoPrimitives,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch,\n private readonly accessControlKeysHeadersProvider: AccessControlKeysHeadersProvider\n ) {\n this.delegationKeyMapFieldsToEncrypt = parseEncryptedFields(['delegate', 'delegator'], 'SecureDelegationKeyMap')\n this.delegationKeyMapApi = new IccSecureDelegationKeyMapApi(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Creates / updates information to allow the data owners in {@link shareWithDataOwners} to de-anonymize the delegations contained within\n * {@link entity}.\n * Note that the delegation de-anonymization information may be used also with other entities of the same type.\n */\n async createOrUpdateDeAnonymizationInfo(entityWithType: EncryptedEntityWithType, shareWithDataOwners: string[]) {\n const delegationsDetails = Object.entries(await this.securityMetadataDecryptor.getDelegationMemberDetails(entityWithType)).flatMap(\n ([canonicalKey, delegation]) => {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [[canonicalKey, delegation], ...aliases.map((alias) => [alias, delegation])] as [string, DelegationMembersDetails][]\n }\n )\n const delegationsForDeanonInfoSharing = delegationsDetails.filter(([_, delegationInfo]) => {\n // Drop fully explicit ones: they don't need de-anonymization info\n return !delegationInfo.fullyExplicit\n })\n // A subset of delegations for which deanon info is relevant AND for which we can also create new info instead of sharing only existing one.\n const delegationsForNewDeanonInfoCreation = delegationsForDeanonInfoSharing.filter(([_, delegationInfo]) => {\n // Drop those for which we don't have the full information needed for the creation of new data.\n return !!delegationInfo.delegate && !!delegationInfo.delegator && !!delegationInfo.accessControlSecret\n })\n const existingDelegationsMap = await this.getDecryptedSecureDelegationKeyMaps(\n delegationsForDeanonInfoSharing.map((x) => x[0]),\n entityWithType.type\n )\n for (const delMapToShare of existingDelegationsMap) {\n await this.ensureDelegationKeyMapSharedWith(entityWithType.type, delMapToShare, shareWithDataOwners)\n }\n const existingDelegationsMapKeys = new Set(existingDelegationsMap.map((x) => x.delegationKey))\n const delegationsToCreate = delegationsForNewDeanonInfoCreation.filter(([k, _]) => !existingDelegationsMapKeys.has(k))\n for (const [delKey, membersDetails] of delegationsToCreate) {\n await this.createSecureDelegationKeyMap(entityWithType.type, delKey, membersDetails, shareWithDataOwners)\n }\n }\n\n /**\n * Get the data owners which can access the entity. See {@link EncryptedEntityXApi.getDataOwnersWithAccessTo} for more details.\n * @param entityWithType an entity.\n */\n async getDataOwnersWithAccessTo(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return this.mergePermissions([\n await this.getDataOwnersWithAccessToSecureDelegations(entityWithType),\n {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entityWithType.entity.delegations ?? {}).map((k) => [k, AccessLevelEnum.WRITE])),\n hasUnknownAnonymousDataOwners: false,\n },\n ])\n }\n\n private async getDataOwnersWithAccessToSecureDelegations(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const secureDelegationDetails = await this.securityMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const secureDelegationWithUnknownMembers = Object.entries(secureDelegationDetails).flatMap(([canonicalKey, delegation]) => {\n if (!delegation.delegate || !delegation.delegator) {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [{ keys: [canonicalKey, ...aliases], delegation }]\n } else {\n return []\n }\n })\n const secureDelegationKeyMapsByDelegationKey = Object.fromEntries(\n (\n await this.getDecryptedSecureDelegationKeyMaps(\n secureDelegationWithUnknownMembers.flatMap(({ keys }) => keys),\n entityWithType.type\n )\n ).map((x) => [x.delegationKey, x])\n )\n const permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n function addAccess(dataOwnerId: string, level: AccessLevelEnum) {\n if (permissionsByDataOwnerId[dataOwnerId] !== AccessLevelEnum.WRITE) {\n permissionsByDataOwnerId[dataOwnerId] = level\n }\n }\n for (const delegation of Object.values(secureDelegationDetails)) {\n if (delegation.delegate) addAccess(delegation.delegate, delegation.accessLevel)\n if (delegation.delegator) addAccess(delegation.delegator, delegation.accessLevel)\n }\n for (const { keys, delegation } of secureDelegationWithUnknownMembers) {\n const bestKey = keys.find((k) => {\n const currMap = secureDelegationKeyMapsByDelegationKey[k]\n return currMap && !!currMap.delegator && !!currMap.delegate\n })\n if (bestKey) {\n const keyMap = secureDelegationKeyMapsByDelegationKey[bestKey]\n addAccess(keyMap.delegate!, delegation.accessLevel)\n addAccess(keyMap.delegator!, delegation.accessLevel)\n } else {\n hasUnknownAnonymousDataOwners = true\n }\n }\n return { permissionsByDataOwnerId, hasUnknownAnonymousDataOwners }\n }\n\n private async mergePermissions(\n values: {\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }[]\n ): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const accumulatedPermissions: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n for (const v of values) {\n hasUnknownAnonymousDataOwners = hasUnknownAnonymousDataOwners || v.hasUnknownAnonymousDataOwners\n for (const [dataOwnerId, level] of Object.entries(v.permissionsByDataOwnerId)) {\n if (accumulatedPermissions[dataOwnerId] !== AccessLevelEnum.WRITE) {\n accumulatedPermissions[dataOwnerId] = level\n }\n }\n }\n return {\n permissionsByDataOwnerId: accumulatedPermissions,\n hasUnknownAnonymousDataOwners,\n }\n }\n\n private async getDecryptedSecureDelegationKeyMaps(\n delegationIds: string[],\n entityType: EntityWithDelegationTypeName\n ): Promise<SecureDelegationKeyMap[]> {\n if (delegationIds.length) {\n const encryptedMaps = await this.delegationKeyMapApi.getByDelegationKeys(\n { ids: delegationIds },\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n const res: SecureDelegationKeyMap[] = []\n for (const encryptedMap of encryptedMaps) {\n // Use the original entity type\n const decryptionResult = (await this.xapis.tryDecryptEntities([encryptedMap], entityType, (x) => new SecureDelegationKeyMap(x)))[0]\n if (decryptionResult.decrypted) {\n res.push(decryptionResult.entity)\n }\n }\n return res\n } else return []\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async ensureDelegationKeyMapSharedWith(entityType: EntityWithDelegationTypeName, keyMap: SecureDelegationKeyMap, delegates: string[]) {\n if (!keyMap.delegator || !keyMap.delegate) throw new Error('Illegal state: key map is missing delegator or delegate info.')\n const dataOwnersWithAccessToMapThroughDelegation = Object.values(\n await this.securityMetadataDecryptor.getDelegationMemberDetails({\n type: entityType,\n entity: keyMap,\n })\n )\n .flatMap((x) => [x.delegate, x.delegator])\n .filter((x) => !!x) as string[]\n // Delegator and delegate got access to the entity when it was first created: no need to share with them ever.\n const dataOwnersWithAccessToMap = new Set([keyMap.delegate, keyMap.delegator, ...dataOwnersWithAccessToMapThroughDelegation])\n const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x))\n if (dataOwnersNeedingShare.length) {\n ;(\n await this.xapis.simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: keyMap,\n type: entityType,\n },\n Object.fromEntries(\n dataOwnersNeedingShare.map((x) => [\n x,\n {\n shareSecretIds: [],\n shareEncryptionKeys: ShareMetadataBehaviour.REQUIRED,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n },\n ])\n ),\n async (request) =>\n this.delegationKeyMapApi.bulkShareSecureDelegationKeyMap(\n request,\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n )\n ).updatedEntityOrThrow\n }\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async createSecureDelegationKeyMap(\n entityType: EntityWithDelegationTypeName,\n delegationKey: string,\n delegationMembersDetails: DelegationMembersDetails,\n delegates: string[]\n ) {\n if (!delegationMembersDetails.delegate || !delegationMembersDetails.delegator || !delegationMembersDetails.accessControlSecret)\n throw new Error('Illegal state: delegation members details are missing delegate, delegator or access control secret info.')\n const selfDoId = await this.dataOwnerApi.getCurrentDataOwnerId()\n // Ensure that both the delegator and delegate of the delegation this map refers tho can share it later on, even if they did not create it.\n // Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.\n const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId)\n const initalisedMapInfo = await this.xapis.entityWithInitialisedEncryptedMetadata<SecureDelegationKeyMap>(\n {\n id: this.cryptoPrimitives.randomUuid(),\n delegate: delegationMembersDetails.delegate,\n delegator: delegationMembersDetails.delegator,\n delegationKey: delegationKey,\n },\n entityType,\n undefined,\n undefined,\n true,\n Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ])),\n undefined\n )\n const encryptedKeyMap = (\n await this.xapis.tryEncryptEntities(\n [initalisedMapInfo.updatedEntity],\n entityType,\n this.delegationKeyMapFieldsToEncrypt,\n false,\n true,\n (x) => new SecureDelegationKeyMap(x)\n )\n )[0]\n await this.delegationKeyMapApi.create(\n encryptedKeyMap,\n new XHR.Header(\n ACCESS_CONTROL_KEYS_HEADER,\n await this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)\n )\n )\n }\n}\n"]}
|
|
@@ -32,14 +32,21 @@ export interface ExchangeDataManager {
|
|
|
32
32
|
* Gets any existing and verified exchange data from the current data owner to the provided delegate or creates new data if no verified data is
|
|
33
33
|
* available, then caches it.
|
|
34
34
|
* @param delegateId the id of the delegate.
|
|
35
|
-
* @param
|
|
35
|
+
* @param options
|
|
36
|
+
* - allowCreationWithoutDelegatorKey if true, when creating new exchange data, even if no verified key is available for the delegator the method
|
|
37
|
+
* will create the new exchange data anyway (will not be usable by the delegate without additional steps).
|
|
38
|
+
* - allowCreationWithoutDelegateKey if true, when creating new exchange data, even if no verified key is available for the delegate the method
|
|
36
39
|
* will create the new exchange data anyway (will not be usable by the delegate without additional steps).
|
|
37
40
|
* @return the access control secret and key of the data to use for encryption.
|
|
38
41
|
*/
|
|
39
|
-
getOrCreateEncryptionDataTo(delegateId: string,
|
|
42
|
+
getOrCreateEncryptionDataTo(delegateId: string, options?: {
|
|
43
|
+
allowCreationWithoutDelegatorKey?: boolean;
|
|
44
|
+
allowCreationWithoutDelegateKey?: boolean;
|
|
45
|
+
}): Promise<{
|
|
40
46
|
exchangeData: ExchangeData;
|
|
41
47
|
accessControlSecret: string;
|
|
42
48
|
exchangeKey: CryptoKey;
|
|
49
|
+
sharedSignatureKey: CryptoKey;
|
|
43
50
|
}>;
|
|
44
51
|
/**
|
|
45
52
|
* Retrieve the cached decrypted exchange data key associated with any of the provided hashes/entry keys of secure delegations.
|
|
@@ -86,4 +93,20 @@ export interface ExchangeDataManager {
|
|
|
86
93
|
* data owner, which can be used to search for data.
|
|
87
94
|
*/
|
|
88
95
|
getAllDelegationKeys(entityType: EntityWithDelegationTypeName): Promise<string[] | undefined>;
|
|
96
|
+
/**
|
|
97
|
+
* Injects already decrypted exchange data, allowing it to be used by the sdk.
|
|
98
|
+
* @param exchangeDataDetails the exchange data to inject, with the decrypted content and verified status.
|
|
99
|
+
* Note that the SDK won't verify that the provided decrypted content actually matches what is stored in the exchange
|
|
100
|
+
* data.
|
|
101
|
+
* @param reEncryptWithOwnKeys if true all the provided exchange data that is not encrypted with any of the self
|
|
102
|
+
* verified keys of the user will be re-encrypted with them. In case the user is also the delegator and the data is
|
|
103
|
+
* verified the delegator signature will be updated.
|
|
104
|
+
*/
|
|
105
|
+
injectDecryptedExchangeData(exchangeDataDetails: {
|
|
106
|
+
exchangeDataId: string;
|
|
107
|
+
accessControlSecret: ArrayBuffer;
|
|
108
|
+
exchangeKey: ArrayBuffer;
|
|
109
|
+
sharedSignatureKey: ArrayBuffer;
|
|
110
|
+
verified: boolean;
|
|
111
|
+
}[], reEncryptWithOwnKeys: boolean): Promise<void>;
|
|
89
112
|
}
|