@icure/api 8.0.0-RC.5 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/icc-api/api/IccAccesslogApi.d.ts +3 -7
- package/icc-api/api/IccAccesslogApi.js +2 -2
- package/icc-api/api/IccAccesslogApi.js.map +1 -1
- package/icc-api/api/IccAgendaApi.d.ts +1 -1
- package/icc-api/api/IccAgendaApi.js +2 -2
- package/icc-api/api/IccAgendaApi.js.map +1 -1
- package/icc-api/api/IccAnonymousAccessApi.d.ts +10 -0
- package/icc-api/api/IccAnonymousAccessApi.js +33 -0
- package/icc-api/api/IccAnonymousAccessApi.js.map +1 -1
- package/icc-api/api/IccApplicationsettingsApi.d.ts +1 -1
- package/icc-api/api/IccApplicationsettingsApi.js +2 -2
- package/icc-api/api/IccApplicationsettingsApi.js.map +1 -1
- package/icc-api/api/IccArticleApi.d.ts +1 -1
- package/icc-api/api/IccArticleApi.js +2 -2
- package/icc-api/api/IccArticleApi.js.map +1 -1
- package/icc-api/api/IccAuthApi.d.ts +4 -2
- package/icc-api/api/IccAuthApi.js +11 -4
- package/icc-api/api/IccAuthApi.js.map +1 -1
- package/icc-api/api/IccCalendarItemApi.d.ts +4 -12
- package/icc-api/api/IccCalendarItemApi.js +2 -2
- package/icc-api/api/IccCalendarItemApi.js.map +1 -1
- package/icc-api/api/IccCalendarItemTypeApi.d.ts +1 -1
- package/icc-api/api/IccCalendarItemTypeApi.js +2 -2
- package/icc-api/api/IccCalendarItemTypeApi.js.map +1 -1
- package/icc-api/api/IccClassificationApi.d.ts +4 -12
- package/icc-api/api/IccClassificationApi.js +2 -2
- package/icc-api/api/IccClassificationApi.js.map +1 -1
- package/icc-api/api/IccClassificationTemplateApi.d.ts +1 -1
- package/icc-api/api/IccClassificationTemplateApi.js +2 -2
- package/icc-api/api/IccClassificationTemplateApi.js.map +1 -1
- package/icc-api/api/IccCodeApi.d.ts +1 -1
- package/icc-api/api/IccCodeApi.js +2 -2
- package/icc-api/api/IccCodeApi.js.map +1 -1
- package/icc-api/api/IccContactApi.d.ts +3 -11
- package/icc-api/api/IccContactApi.js.map +1 -1
- package/icc-api/api/IccDataownerApi.d.ts +1 -1
- package/icc-api/api/IccDataownerApi.js +2 -2
- package/icc-api/api/IccDataownerApi.js.map +1 -1
- package/icc-api/api/IccDeviceApi.d.ts +1 -1
- package/icc-api/api/IccDeviceApi.js +2 -2
- package/icc-api/api/IccDeviceApi.js.map +1 -1
- package/icc-api/api/IccDoctemplateApi.d.ts +1 -1
- package/icc-api/api/IccDoctemplateApi.js +2 -2
- package/icc-api/api/IccDoctemplateApi.js.map +1 -1
- package/icc-api/api/IccDocumentApi.d.ts +3 -7
- package/icc-api/api/IccDocumentApi.js +2 -2
- package/icc-api/api/IccDocumentApi.js.map +1 -1
- package/icc-api/api/IccEntityrefApi.d.ts +1 -1
- package/icc-api/api/IccEntityrefApi.js +2 -2
- package/icc-api/api/IccEntityrefApi.js.map +1 -1
- package/icc-api/api/IccEntitytemplateApi.d.ts +1 -1
- package/icc-api/api/IccEntitytemplateApi.js +2 -2
- package/icc-api/api/IccEntitytemplateApi.js.map +1 -1
- package/icc-api/api/IccFormApi.d.ts +4 -12
- package/icc-api/api/IccFormApi.js +2 -2
- package/icc-api/api/IccFormApi.js.map +1 -1
- package/icc-api/api/IccFrontendmigrationApi.d.ts +1 -1
- package/icc-api/api/IccFrontendmigrationApi.js +2 -2
- package/icc-api/api/IccFrontendmigrationApi.js.map +1 -1
- package/icc-api/api/IccGroupApi.d.ts +1 -1
- package/icc-api/api/IccGroupApi.js +2 -2
- package/icc-api/api/IccGroupApi.js.map +1 -1
- package/icc-api/api/IccHcpartyApi.d.ts +1 -1
- package/icc-api/api/IccHcpartyApi.js +2 -2
- package/icc-api/api/IccHcpartyApi.js.map +1 -1
- package/icc-api/api/IccHelementApi.d.ts +4 -12
- package/icc-api/api/IccHelementApi.js +2 -2
- package/icc-api/api/IccHelementApi.js.map +1 -1
- package/icc-api/api/IccIcureApi.d.ts +1 -1
- package/icc-api/api/IccIcureApi.js +2 -2
- package/icc-api/api/IccIcureApi.js.map +1 -1
- package/icc-api/api/IccInsuranceApi.d.ts +1 -1
- package/icc-api/api/IccInsuranceApi.js +2 -2
- package/icc-api/api/IccInsuranceApi.js.map +1 -1
- package/icc-api/api/IccInvoiceApi.d.ts +4 -12
- package/icc-api/api/IccInvoiceApi.js +2 -2
- package/icc-api/api/IccInvoiceApi.js.map +1 -1
- package/icc-api/api/IccKeywordApi.d.ts +1 -1
- package/icc-api/api/IccKeywordApi.js +2 -2
- package/icc-api/api/IccKeywordApi.js.map +1 -1
- package/icc-api/api/IccMaintenanceTaskApi.d.ts +3 -7
- package/icc-api/api/IccMaintenanceTaskApi.js +2 -2
- package/icc-api/api/IccMaintenanceTaskApi.js.map +1 -1
- package/icc-api/api/IccMedexApi.d.ts +1 -1
- package/icc-api/api/IccMedexApi.js +2 -2
- package/icc-api/api/IccMedexApi.js.map +1 -1
- package/icc-api/api/IccMedicallocationApi.d.ts +1 -1
- package/icc-api/api/IccMedicallocationApi.js +2 -2
- package/icc-api/api/IccMedicallocationApi.js.map +1 -1
- package/icc-api/api/IccMessageApi.d.ts +3 -7
- package/icc-api/api/IccMessageApi.js +2 -2
- package/icc-api/api/IccMessageApi.js.map +1 -1
- package/icc-api/api/IccPatientApi.d.ts +3 -7
- package/icc-api/api/IccPatientApi.js +2 -2
- package/icc-api/api/IccPatientApi.js.map +1 -1
- package/icc-api/api/IccPermissionApi.d.ts +1 -1
- package/icc-api/api/IccPermissionApi.js +2 -2
- package/icc-api/api/IccPermissionApi.js.map +1 -1
- package/icc-api/api/IccPlaceApi.d.ts +1 -1
- package/icc-api/api/IccPlaceApi.js +2 -2
- package/icc-api/api/IccPlaceApi.js.map +1 -1
- package/icc-api/api/IccReceiptApi.d.ts +3 -7
- package/icc-api/api/IccReceiptApi.js +2 -2
- package/icc-api/api/IccReceiptApi.js.map +1 -1
- package/icc-api/api/IccReplicationApi.d.ts +1 -1
- package/icc-api/api/IccReplicationApi.js +2 -2
- package/icc-api/api/IccReplicationApi.js.map +1 -1
- package/icc-api/api/IccRoleApi.d.ts +1 -1
- package/icc-api/api/IccRoleApi.js +2 -2
- package/icc-api/api/IccRoleApi.js.map +1 -1
- package/icc-api/api/IccTarificationApi.d.ts +1 -1
- package/icc-api/api/IccTarificationApi.js +2 -2
- package/icc-api/api/IccTarificationApi.js.map +1 -1
- package/icc-api/api/IccTimeTableApi.d.ts +3 -7
- package/icc-api/api/IccTimeTableApi.js +2 -2
- package/icc-api/api/IccTimeTableApi.js.map +1 -1
- package/icc-api/api/IccTopicApi.d.ts +3 -7
- package/icc-api/api/IccTopicApi.js +2 -2
- package/icc-api/api/IccTopicApi.js.map +1 -1
- package/icc-api/api/IccUserApi.d.ts +22 -1
- package/icc-api/api/IccUserApi.js +59 -2
- package/icc-api/api/IccUserApi.js.map +1 -1
- package/icc-api/api/XHR.d.ts +1 -1
- package/icc-api/api/XHR.js +4 -3
- package/icc-api/api/XHR.js.map +1 -1
- package/icc-api/api/internal/IccExchangeDataMapApi.d.ts +0 -3
- package/icc-api/api/internal/IccExchangeDataMapApi.js +0 -31
- package/icc-api/api/internal/IccExchangeDataMapApi.js.map +1 -1
- package/icc-api/api/internal/IccSecureDelegationKeyMapApi.d.ts +2 -6
- package/icc-api/api/internal/IccSecureDelegationKeyMapApi.js.map +1 -1
- package/icc-api/model/MedicalLocation.d.ts +3 -0
- package/icc-api/model/MedicalLocation.js.map +1 -1
- package/icc-api/model/PaginatedListMedicalLocation.d.ts +20 -0
- package/icc-api/model/PaginatedListMedicalLocation.js +10 -0
- package/icc-api/model/PaginatedListMedicalLocation.js.map +1 -0
- package/icc-api/model/requests/BulkShareOrUpdateMetadataParams.d.ts +12 -0
- package/icc-api/model/requests/BulkShareOrUpdateMetadataParams.js +3 -0
- package/icc-api/model/requests/BulkShareOrUpdateMetadataParams.js.map +1 -0
- package/icc-x-api/auth/AuthService.d.ts +2 -1
- package/icc-x-api/auth/AuthService.js.map +1 -1
- package/icc-x-api/auth/AuthenticationProvider.d.ts +1 -1
- package/icc-x-api/auth/AuthenticationProvider.js +1 -1
- package/icc-x-api/auth/AuthenticationProvider.js.map +1 -1
- package/icc-x-api/auth/EnsembleAuthService.d.ts +1 -1
- package/icc-x-api/auth/EnsembleAuthService.js +2 -2
- package/icc-x-api/auth/EnsembleAuthService.js.map +1 -1
- package/icc-x-api/auth/JwtAuthService.d.ts +0 -2
- package/icc-x-api/auth/JwtAuthService.js +3 -15
- package/icc-x-api/auth/JwtAuthService.js.map +1 -1
- package/icc-x-api/auth/JwtBridgedAuthService.d.ts +1 -1
- package/icc-x-api/auth/JwtBridgedAuthService.js +4 -4
- package/icc-x-api/auth/JwtBridgedAuthService.js.map +1 -1
- package/icc-x-api/auth/JwtUtils.d.ts +10 -0
- package/icc-x-api/auth/JwtUtils.js +31 -0
- package/icc-x-api/auth/JwtUtils.js.map +1 -0
- package/icc-x-api/auth/SmartAuthProvider.d.ts +132 -0
- package/icc-x-api/auth/SmartAuthProvider.js +419 -0
- package/icc-x-api/auth/SmartAuthProvider.js.map +1 -0
- package/icc-x-api/crypto/BaseExchangeDataManager.d.ts +20 -0
- package/icc-x-api/crypto/BaseExchangeDataManager.js +32 -2
- package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/ConfidentialEntities.d.ts +2 -6
- package/icc-x-api/crypto/ConfidentialEntities.js.map +1 -1
- package/icc-x-api/crypto/CryptoStrategies.d.ts +3 -1
- package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
- package/icc-x-api/crypto/ExchangeDataManager.d.ts +3 -1
- package/icc-x-api/crypto/ExchangeDataManager.js +36 -22
- package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/ExchangeDataMapManager.d.ts +0 -5
- package/icc-x-api/crypto/ExchangeDataMapManager.js +0 -11
- package/icc-x-api/crypto/ExchangeDataMapManager.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtils.d.ts +4 -16
- package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +4 -16
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +12 -3
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/icc-x-api/crypto/KeyPairRecoverer.d.ts +34 -0
- package/icc-x-api/crypto/KeyPairRecoverer.js +32 -0
- package/icc-x-api/crypto/KeyPairRecoverer.js.map +1 -0
- package/icc-x-api/crypto/RecoveryDataEncryption.d.ts +85 -0
- package/icc-x-api/crypto/RecoveryDataEncryption.js +171 -0
- package/icc-x-api/crypto/RecoveryDataEncryption.js.map +1 -0
- package/icc-x-api/crypto/SecureDelegationsManager.js +2 -2
- 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 +4 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js +4 -3
- package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
- package/icc-x-api/icc-bekmehr-x-api.d.ts +1 -0
- package/icc-x-api/icc-bekmehr-x-api.js +37 -36
- package/icc-x-api/icc-bekmehr-x-api.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.js +15 -12
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/icc-crypto-x-api.d.ts +1 -0
- package/icc-x-api/icc-crypto-x-api.js.map +1 -1
- package/icc-x-api/icc-maintenance-task-x-api.d.ts +1 -1
- package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.d.ts +18 -0
- package/icc-x-api/icc-patient-x-api.js +29 -0
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/icc-x-api/icc-recovery-x-api.d.ts +127 -0
- package/icc-x-api/icc-recovery-x-api.js +217 -0
- package/icc-x-api/icc-recovery-x-api.js.map +1 -1
- package/icc-x-api/icc-user-x-api.js +15 -2
- package/icc-x-api/icc-user-x-api.js.map +1 -1
- package/icc-x-api/index.d.ts +68 -23
- package/icc-x-api/index.js +85 -38
- package/icc-x-api/index.js.map +1 -1
- package/icc-x-api/utils/collection-utils.d.ts +14 -1
- package/icc-x-api/utils/collection-utils.js +49 -3
- package/icc-x-api/utils/collection-utils.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.RecoveryDataEncryption = exports.RecoveryDataUseFailureReason = void 0;
|
|
13
|
+
const RecoveryData_1 = require("../../icc-api/model/internal/RecoveryData");
|
|
14
|
+
const utils_1 = require("../utils");
|
|
15
|
+
const XHR_1 = require("../../icc-api/api/XHR");
|
|
16
|
+
var XHRError = XHR_1.XHR.XHRError;
|
|
17
|
+
var RecoveryDataUseFailureReason;
|
|
18
|
+
(function (RecoveryDataUseFailureReason) {
|
|
19
|
+
/**
|
|
20
|
+
* The recovery data matching the provided recovery key does not exist. It could have been deleted, or it could have been expired.
|
|
21
|
+
*/
|
|
22
|
+
RecoveryDataUseFailureReason["Missing"] = "MISSING";
|
|
23
|
+
/**
|
|
24
|
+
* The recovery data exists but it is not available to the current user. The user may have used a recovery key that he created while logged in as
|
|
25
|
+
* a different user.
|
|
26
|
+
*/
|
|
27
|
+
RecoveryDataUseFailureReason["Unauthorized"] = "UNAUTHORIZED";
|
|
28
|
+
/**
|
|
29
|
+
* The recovery data exists and is available to the current user, but it is not of the expected type.
|
|
30
|
+
*/
|
|
31
|
+
RecoveryDataUseFailureReason["InvalidType"] = "INVALID_TYPE";
|
|
32
|
+
/**
|
|
33
|
+
* The recovery data exists and is available to the current user, but its content could not be interpreted. The data may have been created
|
|
34
|
+
* with an unsupported SDK version.
|
|
35
|
+
*/
|
|
36
|
+
RecoveryDataUseFailureReason["InvalidContent"] = "INVALID_CONTENT";
|
|
37
|
+
})(RecoveryDataUseFailureReason = exports.RecoveryDataUseFailureReason || (exports.RecoveryDataUseFailureReason = {}));
|
|
38
|
+
/**
|
|
39
|
+
* @internal this class is for internal use only and may change without notice.
|
|
40
|
+
*/
|
|
41
|
+
class RecoveryDataEncryption {
|
|
42
|
+
constructor(primitives, baseRecoveryApi) {
|
|
43
|
+
this.primitives = primitives;
|
|
44
|
+
this.baseRecoveryApi = baseRecoveryApi;
|
|
45
|
+
}
|
|
46
|
+
recoveryKeyToId(recoveryKey) {
|
|
47
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
48
|
+
return (0, utils_1.ua2hex)(yield this.primitives.sha256((0, utils_1.hex2ua)(recoveryKey)));
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
createAndSaveKeyPairsRecoveryDataFor(recipient, keyPairs, lifetimeSeconds) {
|
|
52
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
53
|
+
const content = {};
|
|
54
|
+
for (const [delegateId, pairs] of Object.entries(keyPairs)) {
|
|
55
|
+
const entries = [];
|
|
56
|
+
for (const { pair, algorithm } of pairs) {
|
|
57
|
+
entries.push({
|
|
58
|
+
pair: {
|
|
59
|
+
privateKey: (0, utils_1.ua2b64)(yield this.primitives.RSA.exportKey(pair.privateKey, 'pkcs8')),
|
|
60
|
+
publicKey: (0, utils_1.ua2b64)(yield this.primitives.RSA.exportKey(pair.publicKey, 'spki')),
|
|
61
|
+
},
|
|
62
|
+
algorithm,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
content[delegateId] = entries;
|
|
66
|
+
}
|
|
67
|
+
return yield this.createRecoveryData(recipient, RecoveryData_1.RecoveryData.Type.KEYPAIR_RECOVERY, lifetimeSeconds, content);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
getAndDecryptKeyPairsRecoveryData(recoveryKey, autoDeleteOnSuccess) {
|
|
71
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
72
|
+
const getRecoveryDataResult = yield this.getRecoveryDataAndDecrypt(recoveryKey, RecoveryData_1.RecoveryData.Type.KEYPAIR_RECOVERY);
|
|
73
|
+
if ('failure' in getRecoveryDataResult) {
|
|
74
|
+
return getRecoveryDataResult;
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
const recoveredKeysData = getRecoveryDataResult.decryptedJson;
|
|
78
|
+
const recoveredKeys = {};
|
|
79
|
+
for (const [delegateId, pairs] of Object.entries(recoveredKeysData)) {
|
|
80
|
+
const delegateKeys = {};
|
|
81
|
+
for (const { pair, algorithm } of pairs) {
|
|
82
|
+
delegateKeys[(0, utils_1.ua2hex)((0, utils_1.b64_2ua)(pair.publicKey))] = {
|
|
83
|
+
privateKey: yield this.primitives.RSA.importKey('pkcs8', (0, utils_1.b64_2ua)(pair.privateKey), ['decrypt'], algorithm),
|
|
84
|
+
publicKey: yield this.primitives.RSA.importKey('spki', (0, utils_1.b64_2ua)(pair.publicKey), ['encrypt'], algorithm),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
recoveredKeys[delegateId] = delegateKeys;
|
|
88
|
+
}
|
|
89
|
+
if (autoDeleteOnSuccess) {
|
|
90
|
+
yield this.baseRecoveryApi.deleteRecoveryData(yield this.recoveryKeyToId(recoveryKey)).catch((e) => {
|
|
91
|
+
console.warn(`Failed to auto-delete recovery data, ignoring. ${e}`);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
return { success: recoveredKeys };
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
createAndSaveExchangeDataRecoveryData(recipient, exchangeDataInfo, lifetimeSeconds) {
|
|
99
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
100
|
+
return yield this.createRecoveryData(recipient, RecoveryData_1.RecoveryData.Type.EXCHANGE_KEY_RECOVERY, lifetimeSeconds, exchangeDataInfo.map((x) => ({
|
|
101
|
+
exchangeDataId: x.exchangeDataId,
|
|
102
|
+
rawAccessControlSecret: (0, utils_1.ua2b64)(x.rawAccessControlSecret),
|
|
103
|
+
rawSharedSignatureKey: (0, utils_1.ua2b64)(x.rawSharedSignatureKey),
|
|
104
|
+
rawExchangeKey: (0, utils_1.ua2b64)(x.rawExchangeKey),
|
|
105
|
+
})));
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
getAndDecryptExchangeDataRecoveryData(recoveryKey) {
|
|
109
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
110
|
+
const getRecoveryDataResult = yield this.getRecoveryDataAndDecrypt(recoveryKey, RecoveryData_1.RecoveryData.Type.EXCHANGE_KEY_RECOVERY);
|
|
111
|
+
if ('failure' in getRecoveryDataResult)
|
|
112
|
+
return getRecoveryDataResult;
|
|
113
|
+
return {
|
|
114
|
+
success: getRecoveryDataResult.decryptedJson.map((x) => ({
|
|
115
|
+
exchangeDataId: x.exchangeDataId,
|
|
116
|
+
rawAccessControlSecret: (0, utils_1.b64_2ua)(x.rawAccessControlSecret),
|
|
117
|
+
rawSharedSignatureKey: (0, utils_1.b64_2ua)(x.rawSharedSignatureKey),
|
|
118
|
+
rawExchangeKey: (0, utils_1.b64_2ua)(x.rawExchangeKey),
|
|
119
|
+
})),
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
getRecoveryDataAndDecrypt(recoveryKey, expectedType) {
|
|
124
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
125
|
+
const id = yield this.recoveryKeyToId(recoveryKey);
|
|
126
|
+
const getResult = yield this.baseRecoveryApi.getRecoveryData(id).then((r) => ({ recoveryData: r }), (e) => {
|
|
127
|
+
if (e instanceof XHRError) {
|
|
128
|
+
if (e.statusCode === 404) {
|
|
129
|
+
return { failure: RecoveryDataUseFailureReason.Missing };
|
|
130
|
+
}
|
|
131
|
+
else if (e.statusCode === 403) {
|
|
132
|
+
return { failure: RecoveryDataUseFailureReason.Unauthorized };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
throw e;
|
|
136
|
+
});
|
|
137
|
+
if ('failure' in getResult)
|
|
138
|
+
return getResult;
|
|
139
|
+
const { recoveryData } = getResult;
|
|
140
|
+
if (recoveryData.type !== expectedType)
|
|
141
|
+
return { failure: RecoveryDataUseFailureReason.InvalidType };
|
|
142
|
+
const decryptionKey = yield this.primitives.AES.importKey('raw', (0, utils_1.hex2ua)(recoveryKey));
|
|
143
|
+
const decryptionResult = yield this.primitives.AES.decrypt(decryptionKey, (0, utils_1.string2ua)((0, utils_1.a2b)(recoveryData.encryptedSelf)))
|
|
144
|
+
.then((d) => JSON.parse((0, utils_1.ua2utf8)(d)))
|
|
145
|
+
.then((r) => ({ success: r }), () => ({ failure: RecoveryDataUseFailureReason.InvalidContent }));
|
|
146
|
+
if ('failure' in decryptionResult)
|
|
147
|
+
return decryptionResult;
|
|
148
|
+
return { recoveryData, decryptedJson: decryptionResult.success };
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
createRecoveryData(recipient, type, lifetimeSeconds, content) {
|
|
152
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
153
|
+
const recoveryKey = yield this.primitives.AES.generateCryptoKey(false);
|
|
154
|
+
const recoveryKeyHex = (0, utils_1.ua2hex)(yield this.primitives.AES.exportKey(recoveryKey, 'raw'));
|
|
155
|
+
const id = yield this.recoveryKeyToId(recoveryKeyHex);
|
|
156
|
+
const encryptedSelf = (0, utils_1.b2a)((0, utils_1.ua2string)(yield this.primitives.AES.encrypt(recoveryKey, (0, utils_1.utf8_2ua)(JSON.stringify(content)))));
|
|
157
|
+
const expirationInstant = lifetimeSeconds ? Date.now() + lifetimeSeconds * 1000 : undefined;
|
|
158
|
+
const data = new RecoveryData_1.RecoveryData({
|
|
159
|
+
id,
|
|
160
|
+
encryptedSelf,
|
|
161
|
+
expirationInstant,
|
|
162
|
+
recipient,
|
|
163
|
+
type,
|
|
164
|
+
});
|
|
165
|
+
yield this.baseRecoveryApi.createRecoveryData(data);
|
|
166
|
+
return recoveryKeyHex;
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
exports.RecoveryDataEncryption = RecoveryDataEncryption;
|
|
171
|
+
//# sourceMappingURL=RecoveryDataEncryption.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RecoveryDataEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/RecoveryDataEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,4EAAwE;AACxE,oCAA6G;AAC7G,+CAA2C;AAC3C,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAK9B,IAAY,4BAmBX;AAnBD,WAAY,4BAA4B;IACtC;;OAEG;IACH,mDAAmB,CAAA;IACnB;;;OAGG;IACH,6DAA6B,CAAA;IAC7B;;OAEG;IACH,4DAA4B,CAAA;IAC5B;;;OAGG;IACH,kEAAkC,CAAA;AACpC,CAAC,EAnBW,4BAA4B,GAA5B,oCAA4B,KAA5B,oCAA4B,QAmBvC;AAaD;;GAEG;AACH,MAAa,sBAAsB;IACjC,YAA6B,UAA4B,EAAmB,eAAmC;QAAlF,eAAU,GAAV,UAAU,CAAkB;QAAmB,oBAAe,GAAf,eAAe,CAAoB;IAAG,CAAC;IAE7G,eAAe,CAAC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DataApi } from '../../icc-api/api/internal/IccRecoveryDataApi'\nimport { IccExchangeDataApi } from '../../icc-api/api/internal/IccExchangeDataApi'\nimport { RecoveryData } from '../../icc-api/model/internal/RecoveryData'\nimport { a2b, b2a, b64_2ua, hex2ua, string2ua, ua2b64, ua2hex, ua2string, ua2utf8, utf8_2ua } from '../utils'\nimport { XHR } from '../../icc-api/api/XHR'\nimport XHRError = XHR.XHRError\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { KeyPairUpdateRequest } from '../maintenance/KeyPairUpdateRequest'\nimport { get } from 'lodash'\n\nexport enum RecoveryDataUseFailureReason {\n /**\n * The recovery data matching the provided recovery key does not exist. It could have been deleted, or it could have been expired.\n */\n Missing = 'MISSING',\n /**\n * The recovery data exists but it is not available to the current user. The user may have used a recovery key that he created while logged in as\n * a different user.\n */\n Unauthorized = 'UNAUTHORIZED',\n /**\n * The recovery data exists and is available to the current user, but it is not of the expected type.\n */\n InvalidType = 'INVALID_TYPE',\n /**\n * The recovery data exists and is available to the current user, but its content could not be interpreted. The data may have been created\n * with an unsupported SDK version.\n */\n InvalidContent = 'INVALID_CONTENT',\n}\n\n// accessControlSecret, sharedSignatureKey, and exchangeKey all raw bytes b64 encoded\ntype ExchangeDataRecoveryDataContent = {\n exchangeDataId: string\n rawAccessControlSecret: string\n rawSharedSignatureKey: string\n rawExchangeKey: string\n}[]\n// delegateId -> { pair: { privateKey: base64pkcs8, publicKey: base64spki }, algorithm: ShaVersion }[]\ntype KeyPairRecoveryDataContent = { [delegateId: string]: { pair: KeyPair<string>; algorithm: ShaVersion }[] }\ntype RecoveryDataContent = KeyPairRecoveryDataContent | ExchangeDataRecoveryDataContent\n\n/**\n * @internal this class is for internal use only and may change without notice.\n */\nexport class RecoveryDataEncryption {\n constructor(private readonly primitives: CryptoPrimitives, private readonly baseRecoveryApi: IccRecoveryDataApi) {}\n\n async recoveryKeyToId(recoveryKey: string): Promise<string> {\n return ua2hex(await this.primitives.sha256(hex2ua(recoveryKey)))\n }\n\n async createAndSaveKeyPairsRecoveryDataFor(\n recipient: string,\n keyPairs: { [delegateId: string]: { pair: KeyPair<CryptoKey>; algorithm: ShaVersion }[] },\n lifetimeSeconds: number | undefined\n ): Promise<string> {\n const content: KeyPairRecoveryDataContent = {}\n for (const [delegateId, pairs] of Object.entries(keyPairs)) {\n const entries: { pair: KeyPair<string>; algorithm: ShaVersion }[] = []\n for (const { pair, algorithm } of pairs) {\n entries.push({\n pair: {\n privateKey: ua2b64(await this.primitives.RSA.exportKey(pair.privateKey, 'pkcs8')),\n publicKey: ua2b64(await this.primitives.RSA.exportKey(pair.publicKey, 'spki')),\n },\n algorithm,\n })\n }\n content[delegateId] = entries\n }\n return await this.createRecoveryData(recipient, RecoveryData.Type.KEYPAIR_RECOVERY, lifetimeSeconds, content)\n }\n\n async getAndDecryptKeyPairsRecoveryData(\n recoveryKey: string,\n autoDeleteOnSuccess: boolean\n ): Promise<{ success: { [dataOwnerId: string]: { [publicKeySpki: string]: KeyPair<CryptoKey> } } } | { failure: RecoveryDataUseFailureReason }> {\n const getRecoveryDataResult = await this.getRecoveryDataAndDecrypt(recoveryKey, RecoveryData.Type.KEYPAIR_RECOVERY)\n if ('failure' in getRecoveryDataResult) {\n return getRecoveryDataResult\n } else {\n const recoveredKeysData = getRecoveryDataResult.decryptedJson as KeyPairRecoveryDataContent\n const recoveredKeys: { [delegateId: string]: { [publicKeySpki: string]: KeyPair<CryptoKey> } } = {}\n for (const [delegateId, pairs] of Object.entries(recoveredKeysData)) {\n const delegateKeys: { [publicKeySpki: string]: KeyPair<CryptoKey> } = {}\n for (const { pair, algorithm } of pairs) {\n delegateKeys[ua2hex(b64_2ua(pair.publicKey))] = {\n privateKey: await this.primitives.RSA.importKey('pkcs8', b64_2ua(pair.privateKey), ['decrypt'], algorithm),\n publicKey: await this.primitives.RSA.importKey('spki', b64_2ua(pair.publicKey), ['encrypt'], algorithm),\n }\n }\n recoveredKeys[delegateId] = delegateKeys\n }\n if (autoDeleteOnSuccess) {\n await this.baseRecoveryApi.deleteRecoveryData(await this.recoveryKeyToId(recoveryKey)).catch((e) => {\n console.warn(`Failed to auto-delete recovery data, ignoring. ${e}`)\n })\n }\n return { success: recoveredKeys }\n }\n }\n\n async createAndSaveExchangeDataRecoveryData(\n recipient: string,\n exchangeDataInfo: {\n exchangeDataId: string\n rawAccessControlSecret: ArrayBuffer\n rawSharedSignatureKey: ArrayBuffer\n rawExchangeKey: ArrayBuffer\n }[],\n lifetimeSeconds: number | undefined\n ): Promise<string> {\n return await this.createRecoveryData(\n recipient,\n RecoveryData.Type.EXCHANGE_KEY_RECOVERY,\n lifetimeSeconds,\n exchangeDataInfo.map((x) => ({\n exchangeDataId: x.exchangeDataId,\n rawAccessControlSecret: ua2b64(x.rawAccessControlSecret),\n rawSharedSignatureKey: ua2b64(x.rawSharedSignatureKey),\n rawExchangeKey: ua2b64(x.rawExchangeKey),\n }))\n )\n }\n\n async getAndDecryptExchangeDataRecoveryData(\n recoveryKey: string\n ): Promise<\n | { success: { exchangeDataId: string; rawAccessControlSecret: ArrayBuffer; rawSharedSignatureKey: ArrayBuffer; rawExchangeKey: ArrayBuffer }[] }\n | { failure: RecoveryDataUseFailureReason }\n > {\n const getRecoveryDataResult = await this.getRecoveryDataAndDecrypt(recoveryKey, RecoveryData.Type.EXCHANGE_KEY_RECOVERY)\n if ('failure' in getRecoveryDataResult) return getRecoveryDataResult\n return {\n success: (getRecoveryDataResult.decryptedJson as ExchangeDataRecoveryDataContent).map((x) => ({\n exchangeDataId: x.exchangeDataId,\n rawAccessControlSecret: b64_2ua(x.rawAccessControlSecret),\n rawSharedSignatureKey: b64_2ua(x.rawSharedSignatureKey),\n rawExchangeKey: b64_2ua(x.rawExchangeKey),\n })),\n }\n }\n\n async getRecoveryDataAndDecrypt(\n recoveryKey: string,\n expectedType: RecoveryData.Type\n ): Promise<{ recoveryData: RecoveryData; decryptedJson: any } | { failure: RecoveryDataUseFailureReason }> {\n const id = await this.recoveryKeyToId(recoveryKey)\n const getResult = await this.baseRecoveryApi.getRecoveryData(id).then(\n (r) => ({ recoveryData: r }),\n (e) => {\n if (e instanceof XHRError) {\n if (e.statusCode === 404) {\n return { failure: RecoveryDataUseFailureReason.Missing }\n } else if (e.statusCode === 403) {\n return { failure: RecoveryDataUseFailureReason.Unauthorized }\n }\n }\n throw e\n }\n )\n if ('failure' in getResult) return getResult\n const { recoveryData } = getResult\n if (recoveryData.type !== expectedType) return { failure: RecoveryDataUseFailureReason.InvalidType }\n const decryptionKey = await this.primitives.AES.importKey('raw', hex2ua(recoveryKey))\n const decryptionResult = await this.primitives.AES.decrypt(decryptionKey, string2ua(a2b(recoveryData.encryptedSelf)))\n .then((d) => JSON.parse(ua2utf8(d)))\n .then(\n (r): { success: RecoveryDataContent } => ({ success: r }),\n () => ({ failure: RecoveryDataUseFailureReason.InvalidContent })\n )\n if ('failure' in decryptionResult) return decryptionResult\n return { recoveryData, decryptedJson: decryptionResult.success }\n }\n async createRecoveryData(\n recipient: string,\n type: RecoveryData.Type,\n lifetimeSeconds: number | undefined,\n content: RecoveryDataContent\n ): Promise<string> {\n const recoveryKey = await this.primitives.AES.generateCryptoKey(false)\n const recoveryKeyHex = ua2hex(await this.primitives.AES.exportKey(recoveryKey, 'raw'))\n const id = await this.recoveryKeyToId(recoveryKeyHex)\n const encryptedSelf = b2a(ua2string(await this.primitives.AES.encrypt(recoveryKey, utf8_2ua(JSON.stringify(content)))))\n const expirationInstant = lifetimeSeconds ? Date.now() + lifetimeSeconds * 1000 : undefined\n const data: RecoveryData = new RecoveryData({\n id,\n encryptedSelf,\n expirationInstant,\n recipient,\n type,\n })\n await this.baseRecoveryApi.createRecoveryData(data)\n return recoveryKeyHex\n }\n}\n"]}
|
|
@@ -84,7 +84,7 @@ class SecureDelegationsManager {
|
|
|
84
84
|
makeShareOrUpdateRequestParams(entityWithType, delegateId, shareSecretIds, shareEncryptionKeys, shareOwningEntityIds, newDelegationPermissions) {
|
|
85
85
|
var _a, _b, _c;
|
|
86
86
|
return __awaiter(this, void 0, void 0, function* () {
|
|
87
|
-
const exchangeDataInfo = yield this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, entityWithType.type, (_a = entityWithType.entity.secretForeignKeys) !== null && _a !== void 0 ? _a : []);
|
|
87
|
+
const exchangeDataInfo = yield this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, entityWithType.type, (_a = entityWithType.entity.secretForeignKeys) !== null && _a !== void 0 ? _a : [], false);
|
|
88
88
|
const accessControlHashes = yield this.accessControlSecretUtils.secureDelegationKeysFor(exchangeDataInfo.accessControlSecret, entityWithType.type, (_b = entityWithType.entity.secretForeignKeys) !== null && _b !== void 0 ? _b : []);
|
|
89
89
|
const existingSecureDelegation = this.getExistingCanonicalKeyAndSecureDelegation(entityWithType.entity, accessControlHashes);
|
|
90
90
|
if (existingSecureDelegation) {
|
|
@@ -131,7 +131,7 @@ class SecureDelegationsManager {
|
|
|
131
131
|
var _a, _b, _c;
|
|
132
132
|
return __awaiter(this, void 0, void 0, function* () {
|
|
133
133
|
// Be wary of explicit delegator and explicit delegate
|
|
134
|
-
const exchangeDataInfo = yield this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, entity.type, (_a = entity.entity.secretForeignKeys) !== null && _a !== void 0 ? _a : []);
|
|
134
|
+
const exchangeDataInfo = yield this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, entity.type, (_a = entity.entity.secretForeignKeys) !== null && _a !== void 0 ? _a : [], false);
|
|
135
135
|
const accessControlHashes = yield this.accessControlSecretUtils.secureDelegationKeysFor(exchangeDataInfo.accessControlSecret, entity.type, (_b = entity.entity.secretForeignKeys) !== null && _b !== void 0 ? _b : []);
|
|
136
136
|
const accessControlKeys = (yield this.accessControlSecretUtils.accessControlKeysFor(exchangeDataInfo.accessControlSecret, entity.type, (_c = entity.entity.secretForeignKeys) !== null && _c !== void 0 ? _c : [])).map((x) => (0, utils_2.ua2hex)(x));
|
|
137
137
|
const accessControlKeysToHashes = accessControlKeys
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SecureDelegationsManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/SecureDelegationsManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wFAAoF;AAKpF,oFAA6E;AAC7E,mCAA2F;AAK3F,oCAAyC;AAIzC,2EAAuE;AACvE,sHAAkH;AAClH,IAAO,mBAAmB,GAAG,qEAAiC,CAAC,mBAAmB,CAAA;AAClF,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACzD,2EAAuE;AAGvE,MAAa,wBAAwB;IACnC,YACmB,mBAAwC,EACxC,sBAA8C,EAC9C,2BAAwD,EACxD,wBAAkD,EAClD,QAAmC,EACnC,UAA4B,EAC5B,YAA8B,EAC9B,gBAAkC,EAClC,6BAAsC;QARtC,wBAAmB,GAAnB,mBAAmB,CAAqB;QACxC,2BAAsB,GAAtB,sBAAsB,CAAwB;QAC9C,gCAA2B,GAA3B,2BAA2B,CAA6B;QACxD,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,aAAQ,GAAR,QAAQ,CAA2B;QACnC,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,kCAA6B,GAA7B,6BAA6B,CAAS;QAGxC,uBAAkB,GAO/B,IAAI,oDAAuB,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAA;IATvD,CAAC;IAWJ;;;;;;;;;;OAUG;IACG,sCAAsC,CAC1C,MAA2C,EAC3C,UAAwC,EACxC,SAAmB,EACnB,eAAyB,EACzB,cAAwB,EACxB,eAA2E;;YAE3E,MAAM,cAAc,GAA4B,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAA;YAC5E,MAAM,kBAAkB,GAAG,MAAM,IAAI,CAAC,wBAAwB,CAC5D,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CAAC,iBAAiB,0CAAG,yBAAyB,CAAC,CAAA;QACjG,OAAO,CACL,MAAA,gBAAgB,CAAC,CAAC,CAAC,mCACnB,CAAC,CAAC,CAAC,yBAAyB,IAAI,CAAC,CAAC,yBAAyB;YACzD,CAAC,CAAC,EAAE,YAAY,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,yBAAyB,EAAE;YAC1F,CAAC,CAAC,SAAS,CAAC,CACf,CAAA;IACH,CAAC;CACF;AA/ZD,4DA+ZC","sourcesContent":["import { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { fingerprintV2, hexPublicKeysWithSha1Of, hexPublicKeysWithSha256Of } from './utils'\nimport { ExchangeDataManager } from './ExchangeDataManager'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { SecureDelegationsEncryption } from './SecureDelegationsEncryption'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { hex2ua, ua2hex } from '../utils'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { EntitySharedMetadataUpdateRequest } from '../../icc-api/model/requests/EntitySharedMetadataUpdateRequest'\nimport EntryUpdateTypeEnum = EntitySharedMetadataUpdateRequest.EntryUpdateTypeEnum\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { SecurityMetadata } from '../../icc-api/model/SecurityMetadata'\nimport { ExchangeDataMapManager } from './ExchangeDataMapManager'\n\nexport class SecureDelegationsManager {\n constructor(\n private readonly exchangeDataManager: ExchangeDataManager,\n private readonly exchangeDataMapManager: ExchangeDataMapManager,\n private readonly secureDelegationsEncryption: SecureDelegationsEncryption,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n private readonly userKeys: UserEncryptionKeysManager,\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly cryptoStrategies: CryptoStrategies,\n private readonly selfNeedsAnonymousDelegations: boolean\n ) {}\n\n private readonly dataOwnerInfoCache: LruTemporisedAsyncCache<\n string,\n {\n requiresAnonymousDelegations: boolean\n availablePublicKeysHexWithSha1: string[]\n availablePublicKeysHexWithSha256: string[]\n }\n > = new LruTemporisedAsyncCache(100, () => 30 * 60 * 1000)\n\n /**\n * Note: this method does not save the updated entity.\n * @param entity an entity, must already have secret foreign keys initialised.\n * @param entityType the type of the entity\n * @param secretIds the initial secret ids to include and share with the auto-delegations\n * @param owningEntityIds the initial owning entity ids to include and share with the auto-delegations\n * @param encryptionKeys the initial encryption keys to include and share with the auto-delegations\n * @param autoDelegations the data owners which will initially have access to the entity in addition to the current data owner and the access level\n * they will have on the entity.\n * @return the entity with the security metadata initialised for the provided parameters.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T & { secretForeignKeys: string[] },\n entityType: EntityWithDelegationTypeName,\n secretIds: string[],\n owningEntityIds: string[],\n encryptionKeys: string[],\n autoDelegations: { [delegateId: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<T> {\n const entityWithType: EncryptedEntityWithType = { entity, type: entityType }\n const rootDelegationInfo = await this.makeSecureDelegationInfo(\n entityWithType,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n secretIds,\n encryptionKeys,\n owningEntityIds,\n AccessLevelEnum.WRITE,\n undefined\n )\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const otherDelegationsInfo: {\n canonicalDelegationKey: string\n canonicalAccessControlKey: string\n delegation: SecureDelegation\n delegationKeyEquivalences: { [p: string]: string }\n encryptedExchangeDataId: { [fp: string]: string } | undefined\n }[] = []\n for (const [delegateId, permissions] of Object.entries(autoDelegations)) {\n if (delegateId !== selfId) {\n otherDelegationsInfo.push(\n await this.makeSecureDelegationInfo(\n entityWithType,\n delegateId,\n secretIds,\n encryptionKeys,\n owningEntityIds,\n permissions,\n rootDelegationInfo.canonicalDelegationKey\n )\n )\n }\n }\n const secureDelegations = Object.fromEntries(\n [rootDelegationInfo, ...otherDelegationsInfo].map(({ canonicalDelegationKey, delegation }) => [canonicalDelegationKey, delegation])\n )\n const keysEquivalences = {\n ...rootDelegationInfo.delegationKeyEquivalences,\n }\n for (const { delegationKeyEquivalences: otherKeyEquivalences } of otherDelegationsInfo) {\n Object.assign(keysEquivalences, otherKeyEquivalences)\n }\n const newExchangeDataMaps = Object.fromEntries(\n otherDelegationsInfo\n .filter(({ encryptedExchangeDataId }) => !!encryptedExchangeDataId)\n .map(({ canonicalAccessControlKey, encryptedExchangeDataId }) => [canonicalAccessControlKey, encryptedExchangeDataId!])\n )\n await this.exchangeDataMapManager.createExchangeDataMaps(newExchangeDataMaps)\n return {\n ...entity,\n securityMetadata: new SecurityMetadata({ secureDelegations, keysEquivalences }),\n }\n }\n\n /**\n * Make a request for sharing an entity with a delegate or to update existing shared metadata by adding additional secretIds, encryptionKeys or\n * owningEntityIds if there is already some metadata shared between the current data owner and the delegate. In case there is already a delegation\n * for the delegate, and it already contains all the provided metadata, this method returns undefined, since there is no need to make any request to\n * share the provided data.\n * @param entityWithType an entity with type\n * @param delegateId the id of the delegate\n * @param shareSecretIds the secret ids to share\n * @param shareEncryptionKeys the encryption keys to share\n * @param shareOwningEntityIds the owning entity ids to share\n * @param newDelegationPermissions the permissions to grant to the delegate in case a new delegation needs to be created. If this method creates an\n * update request instead of a share request, this parameter is ignored.\n * @return the request to share the entity, or the request to update the shared metadata for the entity, or undefined if there is no need to update\n * the entity to allow the delegate to access the provided data.\n */\n async makeShareOrUpdateRequestParams(\n entityWithType: EncryptedEntityWithType,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newDelegationPermissions: EntityShareRequest.RequestedPermissionInternal\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n const exchangeDataInfo = await this.exchangeDataManager.getOrCreateEncryptionDataTo(\n delegateId,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n const accessControlHashes = await this.accessControlSecretUtils.secureDelegationKeysFor(\n exchangeDataInfo.accessControlSecret,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n const existingSecureDelegation = this.getExistingCanonicalKeyAndSecureDelegation(entityWithType.entity, accessControlHashes)\n if (existingSecureDelegation) {\n const updateParams = await this.makeUpdateRequestParams(\n existingSecureDelegation.canonicalKey,\n existingSecureDelegation.secureDelegation,\n exchangeDataInfo,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds\n )\n return updateParams ? { update: updateParams } : undefined\n } else {\n const accessControlKeys = (\n await this.accessControlSecretUtils.accessControlKeysFor(\n exchangeDataInfo.accessControlSecret,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n ).map((x) => ua2hex(x))\n return {\n share: await this.makeShareRequestParams(\n exchangeDataInfo,\n accessControlKeys,\n delegateId,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds,\n newDelegationPermissions\n ),\n }\n }\n }\n\n private async makeUpdateRequestParams(\n canonicalKey: string,\n existingDelegation: SecureDelegation,\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[]\n ): Promise<EntitySharedMetadataUpdateRequest | undefined> {\n const existingSecretIds = new Set(await this.secureDelegationsEncryption.decryptSecretIds(existingDelegation, exchangeDataInfo.exchangeKey))\n const existingEncryptionKeys = new Set(\n await this.secureDelegationsEncryption.decryptEncryptionKeys(existingDelegation, exchangeDataInfo.exchangeKey)\n )\n const existingOwningEntityIds = new Set(\n await this.secureDelegationsEncryption.decryptOwningEntityIds(existingDelegation, exchangeDataInfo.exchangeKey)\n )\n const newSecretIds = shareSecretIds.filter((id) => !existingSecretIds.has(id))\n const newEncryptionKeys = shareEncryptionKeys.filter((key) => !existingEncryptionKeys.has(key))\n const newOwningEntityIds = shareOwningEntityIds.filter((id) => !existingOwningEntityIds.has(id))\n if (newSecretIds.length || newEncryptionKeys.length || newOwningEntityIds.length) {\n const encryptedNewSecretIds = await this.secureDelegationsEncryption.encryptSecretIds(newSecretIds, exchangeDataInfo.exchangeKey)\n const encryptedNewEncryptionKeys = await this.secureDelegationsEncryption.encryptEncryptionKeys(newEncryptionKeys, exchangeDataInfo.exchangeKey)\n const encryptedNewOwningEntityIds = await this.secureDelegationsEncryption.encryptOwningEntityIds(\n newOwningEntityIds,\n exchangeDataInfo.exchangeKey\n )\n return new EntitySharedMetadataUpdateRequest({\n metadataAccessControlHash: canonicalKey,\n secretIds: Object.fromEntries(encryptedNewSecretIds.map((id) => [id, EntryUpdateTypeEnum.CREATE])),\n encryptionKeys: Object.fromEntries(encryptedNewEncryptionKeys.map((key) => [key, EntryUpdateTypeEnum.CREATE])),\n owningEntityIds: Object.fromEntries(encryptedNewOwningEntityIds.map((id) => [id, EntryUpdateTypeEnum.CREATE])),\n })\n } else return undefined\n }\n\n private async makeShareRequestParams(\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n accessControlKeys: string[],\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newDelegationPermissions: EntityShareRequest.RequestedPermissionInternal\n ): Promise<EntityShareRequest> {\n return new EntityShareRequest({\n ...(await this.makeSecureDelegationEncryptedData(exchangeDataInfo, delegateId, shareSecretIds, shareEncryptionKeys, shareOwningEntityIds)),\n requestedPermissions: newDelegationPermissions,\n accessControlKeys,\n })\n }\n\n private async makeSecureDelegationInfo(\n entity: EncryptedEntityWithType,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n permissions: AccessLevelEnum,\n parentDelegationKey: string | undefined\n ): Promise<{\n canonicalDelegationKey: string\n canonicalAccessControlKey: string\n delegation: SecureDelegation\n encryptedExchangeDataId: { [fp: string]: string } | undefined\n delegationKeyEquivalences: { [alias: string]: string }\n }> {\n // Be wary of explicit delegator and explicit delegate\n const exchangeDataInfo = await this.exchangeDataManager.getOrCreateEncryptionDataTo(\n delegateId,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n const accessControlHashes = await this.accessControlSecretUtils.secureDelegationKeysFor(\n exchangeDataInfo.accessControlSecret,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n const accessControlKeys = (\n await this.accessControlSecretUtils.accessControlKeysFor(\n exchangeDataInfo.accessControlSecret,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n ).map((x) => ua2hex(x))\n const accessControlKeysToHashes = accessControlKeys\n .map((key, index) => {\n return [key, accessControlHashes[index]]\n })\n .sort((a, b) => a[1].localeCompare(b[1]))\n\n const canonicalKey = accessControlKeysToHashes[0][1]\n const keyEquivalences = Object.fromEntries(accessControlKeysToHashes.slice(1).map((hash) => [hash[1], canonicalKey]))\n const encryptedDelegationInfo = await this.makeSecureDelegationEncryptedData(\n exchangeDataInfo,\n delegateId,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds\n )\n const delegation = new SecureDelegation({\n delegator: encryptedDelegationInfo?.explicitDelegator,\n delegate: encryptedDelegationInfo?.explicitDelegate,\n secretIds: encryptedDelegationInfo?.secretIds,\n encryptionKeys: encryptedDelegationInfo?.encryptionKeys,\n owningEntityIds: encryptedDelegationInfo?.owningEntityIds,\n parentDelegations: parentDelegationKey ? [parentDelegationKey] : undefined,\n exchangeDataId: encryptedDelegationInfo?.exchangeDataId,\n encryptedExchangeDataId: encryptedDelegationInfo?.encryptedExchangeDataId,\n permissions: permissions,\n })\n return {\n canonicalDelegationKey: canonicalKey,\n canonicalAccessControlKey: accessControlKeysToHashes[0][0],\n delegation,\n encryptedExchangeDataId: encryptedDelegationInfo?.encryptedExchangeDataId,\n delegationKeyEquivalences: keyEquivalences,\n }\n }\n\n private async makeSecureDelegationEncryptedData(\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[]\n ): Promise<{\n explicitDelegator?: string\n explicitDelegate?: string\n secretIds?: string[]\n encryptionKeys?: string[]\n owningEntityIds?: string[]\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string } // TODO if secure delegation info, check cache before calculating\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeDataIdInfo =\n delegateId === selfId\n ? this.makeExchangeDataIdInfoForSelf(selfId, exchangeDataInfo.exchangeData)\n : await this.makeExchangeDataIdInfoForDelegate(selfId, delegateId, exchangeDataInfo.exchangeData)\n const encryptedSecretIds = await this.secureDelegationsEncryption.encryptSecretIds(shareSecretIds, exchangeDataInfo.exchangeKey)\n const encryptedEncryptionKeys = await this.secureDelegationsEncryption.encryptEncryptionKeys(shareEncryptionKeys, exchangeDataInfo.exchangeKey)\n const encryptedOwningEntityIds = await this.secureDelegationsEncryption.encryptOwningEntityIds(shareOwningEntityIds, exchangeDataInfo.exchangeKey)\n return {\n ...exchangeDataIdInfo,\n secretIds: encryptedSecretIds,\n encryptionKeys: encryptedEncryptionKeys,\n owningEntityIds: encryptedOwningEntityIds,\n }\n }\n\n private async makeExchangeDataIdInfoForDelegate(\n selfId: string,\n delegateId: string,\n exchangeData: ExchangeData\n ): Promise<{\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string }\n explicitDelegator?: string\n explicitDelegate?: string\n }> {\n const delegateInfo = await this.getDataOwnerInfo(delegateId)\n if (!delegateInfo.requiresAnonymousDelegations && !this.selfNeedsAnonymousDelegations) {\n return {\n explicitDelegator: selfId,\n explicitDelegate: delegateId,\n exchangeDataId: exchangeData.id,\n }\n } else if (delegateInfo.requiresAnonymousDelegations && !this.selfNeedsAnonymousDelegations) {\n return {\n explicitDelegator: selfId,\n encryptedExchangeDataId: await this.secureDelegationsEncryption.encryptExchangeDataId(\n exchangeData.id!,\n Object.fromEntries(this.userKeys.getSelfVerifiedKeys().map((keyInfo) => [keyInfo.fingerprint, keyInfo.pair.publicKey]))\n ),\n }\n } else if (!delegateInfo.requiresAnonymousDelegations && this.selfNeedsAnonymousDelegations) {\n /**\n * Important: this requires that the exchange data signature also validates the authenticity of the public keys included in there.\n */\n const fingerprintsOfVerifiedExchangeData = new Set(Object.keys(exchangeData.exchangeKey))\n const delegateVerifiedKeys: { [fp: string]: CryptoKey } = {}\n for (const keyHex of [...delegateInfo.availablePublicKeysHexWithSha1, ...delegateInfo.availablePublicKeysHexWithSha256]) {\n const currFp = fingerprintV2(keyHex)\n const shaVersion = delegateInfo.availablePublicKeysHexWithSha1.includes(keyHex) ? 'sha-1' : 'sha-256'\n if (fingerprintsOfVerifiedExchangeData.has(currFp)) {\n delegateVerifiedKeys[currFp] = await this.primitives.RSA.importKey('spki', hex2ua(keyHex), ['encrypt'], shaVersion)\n }\n }\n if (!Object.keys(delegateVerifiedKeys).length)\n throw new Error('Illegal state: could not find any verified key for delegate in verified exchange data.')\n return {\n explicitDelegate: delegateId,\n encryptedExchangeDataId: await this.secureDelegationsEncryption.encryptExchangeDataId(exchangeData.id!, delegateVerifiedKeys),\n }\n } else return {}\n }\n\n private makeExchangeDataIdInfoForSelf(\n selfId: string,\n exchangeData: ExchangeData\n ): {\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string }\n explicitDelegator?: string\n explicitDelegate?: string\n } {\n if (this.selfNeedsAnonymousDelegations) {\n return {}\n } else {\n return {\n exchangeDataId: exchangeData.id,\n explicitDelegator: selfId,\n explicitDelegate: selfId,\n }\n }\n }\n\n private async getDataOwnerInfo(dataOwnerId: string) {\n return this.dataOwnerInfoCache.get(dataOwnerId, async () => {\n const dataOwnerWithType = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n return {\n item: {\n requiresAnonymousDelegations: this.cryptoStrategies.dataOwnerRequiresAnonymousDelegation(dataOwnerWithType),\n availablePublicKeysHexWithSha1: Array.from(hexPublicKeysWithSha1Of(dataOwnerWithType.stub)),\n availablePublicKeysHexWithSha256: Array.from(hexPublicKeysWithSha256Of(dataOwnerWithType.stub)),\n },\n }\n })\n }\n\n private getExistingCanonicalKeyAndSecureDelegation(\n entity: EncryptedEntityStub | EncryptedEntity,\n hashes: string[]\n ): { canonicalKey: string; secureDelegation: SecureDelegation } | undefined {\n const securityMetadata = entity.securityMetadata ?? {}\n const canonicalByEquivalences = Array.from(new Set(hashes.flatMap((hash) => securityMetadata.keysEquivalences?.[hash] ?? [])))\n const directRetrievals = hashes.flatMap((hash) => {\n const retrievedMetadata = securityMetadata.secureDelegations?.[hash]\n return retrievedMetadata ? { canonicalKey: hash, secureDelegation: retrievedMetadata } : []\n })\n if (\n directRetrievals.length > 1 ||\n canonicalByEquivalences.length > 1 ||\n (!!canonicalByEquivalences[0] && !!directRetrievals[0]?.canonicalKey && canonicalByEquivalences[0] !== directRetrievals[0]?.canonicalKey)\n )\n throw new Error('Illegal state: multiple secure delegations matching equivalent hashes of entity.')\n const canonicalFromEquivalences = canonicalByEquivalences[0]\n const retrievedFromEquivalences = securityMetadata.secureDelegations?.[canonicalFromEquivalences]\n return (\n directRetrievals[0] ??\n (!!canonicalFromEquivalences && !!retrievedFromEquivalences\n ? { canonicalKey: canonicalFromEquivalences, secureDelegation: retrievedFromEquivalences }\n : undefined)\n )\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SecureDelegationsManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/SecureDelegationsManager.ts"],"names":[],"mappings":";;;;;;;;;;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,CAAC,CAAC,yBAAyB;YACzD,CAAC,CAAC,EAAE,YAAY,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,yBAAyB,EAAE;YAC1F,CAAC,CAAC,SAAS,CAAC,CACf,CAAA;IACH,CAAC;CACF;AAjaD,4DAiaC","sourcesContent":["import { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { LruTemporisedAsyncCache } from '../utils/lru-temporised-async-cache'\nimport { fingerprintV2, hexPublicKeysWithSha1Of, hexPublicKeysWithSha256Of } from './utils'\nimport { ExchangeDataManager } from './ExchangeDataManager'\nimport { ExchangeData } from '../../icc-api/model/internal/ExchangeData'\nimport { SecureDelegationsEncryption } from './SecureDelegationsEncryption'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { hex2ua, ua2hex } from '../utils'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { EntitySharedMetadataUpdateRequest } from '../../icc-api/model/requests/EntitySharedMetadataUpdateRequest'\nimport EntryUpdateTypeEnum = EntitySharedMetadataUpdateRequest.EntryUpdateTypeEnum\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { SecurityMetadata } from '../../icc-api/model/SecurityMetadata'\nimport { ExchangeDataMapManager } from './ExchangeDataMapManager'\n\nexport class SecureDelegationsManager {\n constructor(\n private readonly exchangeDataManager: ExchangeDataManager,\n private readonly exchangeDataMapManager: ExchangeDataMapManager,\n private readonly secureDelegationsEncryption: SecureDelegationsEncryption,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\n private readonly userKeys: UserEncryptionKeysManager,\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly cryptoStrategies: CryptoStrategies,\n private readonly selfNeedsAnonymousDelegations: boolean\n ) {}\n\n private readonly dataOwnerInfoCache: LruTemporisedAsyncCache<\n string,\n {\n requiresAnonymousDelegations: boolean\n availablePublicKeysHexWithSha1: string[]\n availablePublicKeysHexWithSha256: string[]\n }\n > = new LruTemporisedAsyncCache(100, () => 30 * 60 * 1000)\n\n /**\n * Note: this method does not save the updated entity.\n * @param entity an entity, must already have secret foreign keys initialised.\n * @param entityType the type of the entity\n * @param secretIds the initial secret ids to include and share with the auto-delegations\n * @param owningEntityIds the initial owning entity ids to include and share with the auto-delegations\n * @param encryptionKeys the initial encryption keys to include and share with the auto-delegations\n * @param autoDelegations the data owners which will initially have access to the entity in addition to the current data owner and the access level\n * they will have on the entity.\n * @return the entity with the security metadata initialised for the provided parameters.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T & { secretForeignKeys: string[] },\n entityType: EntityWithDelegationTypeName,\n secretIds: string[],\n owningEntityIds: string[],\n encryptionKeys: string[],\n autoDelegations: { [delegateId: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<T> {\n const entityWithType: EncryptedEntityWithType = { entity, type: entityType }\n const rootDelegationInfo = await this.makeSecureDelegationInfo(\n entityWithType,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n secretIds,\n encryptionKeys,\n owningEntityIds,\n AccessLevelEnum.WRITE,\n undefined\n )\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const otherDelegationsInfo: {\n canonicalDelegationKey: string\n canonicalAccessControlKey: string\n delegation: SecureDelegation\n delegationKeyEquivalences: { [p: string]: string }\n encryptedExchangeDataId: { [fp: string]: string } | undefined\n }[] = []\n for (const [delegateId, permissions] of Object.entries(autoDelegations)) {\n if (delegateId !== selfId) {\n otherDelegationsInfo.push(\n await this.makeSecureDelegationInfo(\n entityWithType,\n delegateId,\n secretIds,\n encryptionKeys,\n owningEntityIds,\n permissions,\n rootDelegationInfo.canonicalDelegationKey\n )\n )\n }\n }\n const secureDelegations = Object.fromEntries(\n [rootDelegationInfo, ...otherDelegationsInfo].map(({ canonicalDelegationKey, delegation }) => [canonicalDelegationKey, delegation])\n )\n const keysEquivalences = {\n ...rootDelegationInfo.delegationKeyEquivalences,\n }\n for (const { delegationKeyEquivalences: otherKeyEquivalences } of otherDelegationsInfo) {\n Object.assign(keysEquivalences, otherKeyEquivalences)\n }\n const newExchangeDataMaps = Object.fromEntries(\n otherDelegationsInfo\n .filter(({ encryptedExchangeDataId }) => !!encryptedExchangeDataId)\n .map(({ canonicalAccessControlKey, encryptedExchangeDataId }) => [canonicalAccessControlKey, encryptedExchangeDataId!])\n )\n await this.exchangeDataMapManager.createExchangeDataMaps(newExchangeDataMaps)\n return {\n ...entity,\n securityMetadata: new SecurityMetadata({ secureDelegations, keysEquivalences }),\n }\n }\n\n /**\n * Make a request for sharing an entity with a delegate or to update existing shared metadata by adding additional secretIds, encryptionKeys or\n * owningEntityIds if there is already some metadata shared between the current data owner and the delegate. In case there is already a delegation\n * for the delegate, and it already contains all the provided metadata, this method returns undefined, since there is no need to make any request to\n * share the provided data.\n * @param entityWithType an entity with type\n * @param delegateId the id of the delegate\n * @param shareSecretIds the secret ids to share\n * @param shareEncryptionKeys the encryption keys to share\n * @param shareOwningEntityIds the owning entity ids to share\n * @param newDelegationPermissions the permissions to grant to the delegate in case a new delegation needs to be created. If this method creates an\n * update request instead of a share request, this parameter is ignored.\n * @return the request to share the entity, or the request to update the shared metadata for the entity, or undefined if there is no need to update\n * the entity to allow the delegate to access the provided data.\n */\n async makeShareOrUpdateRequestParams(\n entityWithType: EncryptedEntityWithType,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newDelegationPermissions: EntityShareRequest.RequestedPermissionInternal\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n const exchangeDataInfo = await this.exchangeDataManager.getOrCreateEncryptionDataTo(\n delegateId,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? [],\n false\n )\n const accessControlHashes = await this.accessControlSecretUtils.secureDelegationKeysFor(\n exchangeDataInfo.accessControlSecret,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n const existingSecureDelegation = this.getExistingCanonicalKeyAndSecureDelegation(entityWithType.entity, accessControlHashes)\n if (existingSecureDelegation) {\n const updateParams = await this.makeUpdateRequestParams(\n existingSecureDelegation.canonicalKey,\n existingSecureDelegation.secureDelegation,\n exchangeDataInfo,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds\n )\n return updateParams ? { update: updateParams } : undefined\n } else {\n const accessControlKeys = (\n await this.accessControlSecretUtils.accessControlKeysFor(\n exchangeDataInfo.accessControlSecret,\n entityWithType.type,\n entityWithType.entity.secretForeignKeys ?? []\n )\n ).map((x) => ua2hex(x))\n return {\n share: await this.makeShareRequestParams(\n exchangeDataInfo,\n accessControlKeys,\n delegateId,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds,\n newDelegationPermissions\n ),\n }\n }\n }\n\n private async makeUpdateRequestParams(\n canonicalKey: string,\n existingDelegation: SecureDelegation,\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[]\n ): Promise<EntitySharedMetadataUpdateRequest | undefined> {\n const existingSecretIds = new Set(await this.secureDelegationsEncryption.decryptSecretIds(existingDelegation, exchangeDataInfo.exchangeKey))\n const existingEncryptionKeys = new Set(\n await this.secureDelegationsEncryption.decryptEncryptionKeys(existingDelegation, exchangeDataInfo.exchangeKey)\n )\n const existingOwningEntityIds = new Set(\n await this.secureDelegationsEncryption.decryptOwningEntityIds(existingDelegation, exchangeDataInfo.exchangeKey)\n )\n const newSecretIds = shareSecretIds.filter((id) => !existingSecretIds.has(id))\n const newEncryptionKeys = shareEncryptionKeys.filter((key) => !existingEncryptionKeys.has(key))\n const newOwningEntityIds = shareOwningEntityIds.filter((id) => !existingOwningEntityIds.has(id))\n if (newSecretIds.length || newEncryptionKeys.length || newOwningEntityIds.length) {\n const encryptedNewSecretIds = await this.secureDelegationsEncryption.encryptSecretIds(newSecretIds, exchangeDataInfo.exchangeKey)\n const encryptedNewEncryptionKeys = await this.secureDelegationsEncryption.encryptEncryptionKeys(newEncryptionKeys, exchangeDataInfo.exchangeKey)\n const encryptedNewOwningEntityIds = await this.secureDelegationsEncryption.encryptOwningEntityIds(\n newOwningEntityIds,\n exchangeDataInfo.exchangeKey\n )\n return new EntitySharedMetadataUpdateRequest({\n metadataAccessControlHash: canonicalKey,\n secretIds: Object.fromEntries(encryptedNewSecretIds.map((id) => [id, EntryUpdateTypeEnum.CREATE])),\n encryptionKeys: Object.fromEntries(encryptedNewEncryptionKeys.map((key) => [key, EntryUpdateTypeEnum.CREATE])),\n owningEntityIds: Object.fromEntries(encryptedNewOwningEntityIds.map((id) => [id, EntryUpdateTypeEnum.CREATE])),\n })\n } else return undefined\n }\n\n private async makeShareRequestParams(\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n accessControlKeys: string[],\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newDelegationPermissions: EntityShareRequest.RequestedPermissionInternal\n ): Promise<EntityShareRequest> {\n return new EntityShareRequest({\n ...(await this.makeSecureDelegationEncryptedData(exchangeDataInfo, delegateId, shareSecretIds, shareEncryptionKeys, shareOwningEntityIds)),\n requestedPermissions: newDelegationPermissions,\n accessControlKeys,\n })\n }\n\n private async makeSecureDelegationInfo(\n entity: EncryptedEntityWithType,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n permissions: AccessLevelEnum,\n parentDelegationKey: string | undefined\n ): Promise<{\n canonicalDelegationKey: string\n canonicalAccessControlKey: string\n delegation: SecureDelegation\n encryptedExchangeDataId: { [fp: string]: string } | undefined\n delegationKeyEquivalences: { [alias: string]: string }\n }> {\n // Be wary of explicit delegator and explicit delegate\n const exchangeDataInfo = await this.exchangeDataManager.getOrCreateEncryptionDataTo(\n delegateId,\n entity.type,\n entity.entity.secretForeignKeys ?? [],\n false\n )\n const accessControlHashes = await this.accessControlSecretUtils.secureDelegationKeysFor(\n exchangeDataInfo.accessControlSecret,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n const accessControlKeys = (\n await this.accessControlSecretUtils.accessControlKeysFor(\n exchangeDataInfo.accessControlSecret,\n entity.type,\n entity.entity.secretForeignKeys ?? []\n )\n ).map((x) => ua2hex(x))\n const accessControlKeysToHashes = accessControlKeys\n .map((key, index) => {\n return [key, accessControlHashes[index]]\n })\n .sort((a, b) => a[1].localeCompare(b[1]))\n\n const canonicalKey = accessControlKeysToHashes[0][1]\n const keyEquivalences = Object.fromEntries(accessControlKeysToHashes.slice(1).map((hash) => [hash[1], canonicalKey]))\n const encryptedDelegationInfo = await this.makeSecureDelegationEncryptedData(\n exchangeDataInfo,\n delegateId,\n shareSecretIds,\n shareEncryptionKeys,\n shareOwningEntityIds\n )\n const delegation = new SecureDelegation({\n delegator: encryptedDelegationInfo?.explicitDelegator,\n delegate: encryptedDelegationInfo?.explicitDelegate,\n secretIds: encryptedDelegationInfo?.secretIds,\n encryptionKeys: encryptedDelegationInfo?.encryptionKeys,\n owningEntityIds: encryptedDelegationInfo?.owningEntityIds,\n parentDelegations: parentDelegationKey ? [parentDelegationKey] : undefined,\n exchangeDataId: encryptedDelegationInfo?.exchangeDataId,\n encryptedExchangeDataId: encryptedDelegationInfo?.encryptedExchangeDataId,\n permissions: permissions,\n })\n return {\n canonicalDelegationKey: canonicalKey,\n canonicalAccessControlKey: accessControlKeysToHashes[0][0],\n delegation,\n encryptedExchangeDataId: encryptedDelegationInfo?.encryptedExchangeDataId,\n delegationKeyEquivalences: keyEquivalences,\n }\n }\n\n private async makeSecureDelegationEncryptedData(\n exchangeDataInfo: { exchangeData: ExchangeData; accessControlSecret: string; exchangeKey: CryptoKey },\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[]\n ): Promise<{\n explicitDelegator?: string\n explicitDelegate?: string\n secretIds?: string[]\n encryptionKeys?: string[]\n owningEntityIds?: string[]\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string } // TODO if secure delegation info, check cache before calculating\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const exchangeDataIdInfo =\n delegateId === selfId\n ? this.makeExchangeDataIdInfoForSelf(selfId, exchangeDataInfo.exchangeData)\n : await this.makeExchangeDataIdInfoForDelegate(selfId, delegateId, exchangeDataInfo.exchangeData)\n const encryptedSecretIds = await this.secureDelegationsEncryption.encryptSecretIds(shareSecretIds, exchangeDataInfo.exchangeKey)\n const encryptedEncryptionKeys = await this.secureDelegationsEncryption.encryptEncryptionKeys(shareEncryptionKeys, exchangeDataInfo.exchangeKey)\n const encryptedOwningEntityIds = await this.secureDelegationsEncryption.encryptOwningEntityIds(shareOwningEntityIds, exchangeDataInfo.exchangeKey)\n return {\n ...exchangeDataIdInfo,\n secretIds: encryptedSecretIds,\n encryptionKeys: encryptedEncryptionKeys,\n owningEntityIds: encryptedOwningEntityIds,\n }\n }\n\n private async makeExchangeDataIdInfoForDelegate(\n selfId: string,\n delegateId: string,\n exchangeData: ExchangeData\n ): Promise<{\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string }\n explicitDelegator?: string\n explicitDelegate?: string\n }> {\n const delegateInfo = await this.getDataOwnerInfo(delegateId)\n if (!delegateInfo.requiresAnonymousDelegations && !this.selfNeedsAnonymousDelegations) {\n return {\n explicitDelegator: selfId,\n explicitDelegate: delegateId,\n exchangeDataId: exchangeData.id,\n }\n } else if (delegateInfo.requiresAnonymousDelegations && !this.selfNeedsAnonymousDelegations) {\n return {\n explicitDelegator: selfId,\n encryptedExchangeDataId: await this.secureDelegationsEncryption.encryptExchangeDataId(\n exchangeData.id!,\n Object.fromEntries(this.userKeys.getSelfVerifiedKeys().map((keyInfo) => [keyInfo.fingerprint, keyInfo.pair.publicKey]))\n ),\n }\n } else if (!delegateInfo.requiresAnonymousDelegations && this.selfNeedsAnonymousDelegations) {\n /**\n * Important: this requires that the exchange data signature also validates the authenticity of the public keys included in there.\n */\n const fingerprintsOfVerifiedExchangeData = new Set(Object.keys(exchangeData.exchangeKey))\n const delegateVerifiedKeys: { [fp: string]: CryptoKey } = {}\n for (const keyHex of [...delegateInfo.availablePublicKeysHexWithSha1, ...delegateInfo.availablePublicKeysHexWithSha256]) {\n const currFp = fingerprintV2(keyHex)\n const shaVersion = delegateInfo.availablePublicKeysHexWithSha1.includes(keyHex) ? 'sha-1' : 'sha-256'\n if (fingerprintsOfVerifiedExchangeData.has(currFp)) {\n delegateVerifiedKeys[currFp] = await this.primitives.RSA.importKey('spki', hex2ua(keyHex), ['encrypt'], shaVersion)\n }\n }\n if (!Object.keys(delegateVerifiedKeys).length)\n throw new Error('Illegal state: could not find any verified key for delegate in verified exchange data.')\n return {\n explicitDelegate: delegateId,\n encryptedExchangeDataId: await this.secureDelegationsEncryption.encryptExchangeDataId(exchangeData.id!, delegateVerifiedKeys),\n }\n } else return {}\n }\n\n private makeExchangeDataIdInfoForSelf(\n selfId: string,\n exchangeData: ExchangeData\n ): {\n exchangeDataId?: string\n encryptedExchangeDataId?: { [fp: string]: string }\n explicitDelegator?: string\n explicitDelegate?: string\n } {\n if (this.selfNeedsAnonymousDelegations) {\n return {}\n } else {\n return {\n exchangeDataId: exchangeData.id,\n explicitDelegator: selfId,\n explicitDelegate: selfId,\n }\n }\n }\n\n private async getDataOwnerInfo(dataOwnerId: string) {\n return this.dataOwnerInfoCache.get(dataOwnerId, async () => {\n const dataOwnerWithType = await this.dataOwnerApi.getCryptoActorStub(dataOwnerId)\n return {\n item: {\n requiresAnonymousDelegations: this.cryptoStrategies.dataOwnerRequiresAnonymousDelegation(dataOwnerWithType),\n availablePublicKeysHexWithSha1: Array.from(hexPublicKeysWithSha1Of(dataOwnerWithType.stub)),\n availablePublicKeysHexWithSha256: Array.from(hexPublicKeysWithSha256Of(dataOwnerWithType.stub)),\n },\n }\n })\n }\n\n private getExistingCanonicalKeyAndSecureDelegation(\n entity: EncryptedEntityStub | EncryptedEntity,\n hashes: string[]\n ): { canonicalKey: string; secureDelegation: SecureDelegation } | undefined {\n const securityMetadata = entity.securityMetadata ?? {}\n const canonicalByEquivalences = Array.from(new Set(hashes.flatMap((hash) => securityMetadata.keysEquivalences?.[hash] ?? [])))\n const directRetrievals = hashes.flatMap((hash) => {\n const retrievedMetadata = securityMetadata.secureDelegations?.[hash]\n return retrievedMetadata ? { canonicalKey: hash, secureDelegation: retrievedMetadata } : []\n })\n if (\n directRetrievals.length > 1 ||\n canonicalByEquivalences.length > 1 ||\n (!!canonicalByEquivalences[0] && !!directRetrievals[0]?.canonicalKey && canonicalByEquivalences[0] !== directRetrievals[0]?.canonicalKey)\n )\n throw new Error('Illegal state: multiple secure delegations matching equivalent hashes of entity.')\n const canonicalFromEquivalences = canonicalByEquivalences[0]\n const retrievedFromEquivalences = securityMetadata.secureDelegations?.[canonicalFromEquivalences]\n return (\n directRetrievals[0] ??\n (!!canonicalFromEquivalences && !!retrievedFromEquivalences\n ? { canonicalKey: canonicalFromEquivalences, secureDelegation: retrievedFromEquivalences }\n : undefined)\n )\n }\n}\n"]}
|
|
@@ -70,7 +70,7 @@ class ShamirKeysManager {
|
|
|
70
70
|
const delegatesKeys = {};
|
|
71
71
|
let updatedSelf = self;
|
|
72
72
|
for (const delegateId of new Set(Object.values(keySplitsToUpdate).flatMap((x) => x.notariesIds))) {
|
|
73
|
-
const res = yield this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, undefined, undefined);
|
|
73
|
+
const res = yield this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, undefined, undefined, false);
|
|
74
74
|
delegatesKeys[delegateId] = res.exchangeKey;
|
|
75
75
|
}
|
|
76
76
|
for (const [key, params] of Object.entries(keySplitsToUpdate)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShamirKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ShamirKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,oCAAyC;AAEzC,yEAA6E;AAE7E;;GAEG;AACH,MAAa,iBAAiB;IAC5B,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,qBAAgD,EAChD,mBAAwC;QAHxC,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,wBAAmB,GAAnB,mBAAmB,CAAqB;IACxD,CAAC;IAEJ;;;;;OAKG;IACH,qBAAqB,CAAC,SAA0B;;QAC9C,MAAM,wBAAwB,GAAG,MAAM,CAAC,IAAI,CAAC,MAAA,SAAS,CAAC,0BAA0B,mCAAI,EAAE,CAAC,CAAA;QACxF,IAAI,wBAAwB,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAM,EAAE,GAAG,MAAA,SAAS,CAAC,SAAS,0CAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAA;YAC1C,IAAI,CAAC,EAAE,EAAE;gBACP,OAAO,CAAC,KAAK,CAAC,4EAA4E,CAAC,CAAA;aAC5F;;gBAAM,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,wBAAwB,EAAE,CAAA;SACjD;QACD,OAAO,EAAE,CAAA;IACX,CAAC;IAED;;;;;;;;OAQG;IACG,gBAAgB,CACpB,iBAA+F,EAC/F,iBAA2B;;YAE3B,MAAM,IAAI,GAAG,yCAAuB,CAAC,aAAa,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,mBAAmB,EAAE,CAAC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AAyC;;YAEzC,OAAO,WAAW,CAAC,MAAM,CACvB,CAAO,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;gBAAC,OAAA,iCAC7B,CAAC,MAAM,GAAG,CAAC,KACd,CAAC,UAAU,CAAC,EAAE,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IACjG,CAAA;cAAA,EACF,OAAO,CAAC,OAAO,CAAC,EAAsC,CAAC,CACxD,CAAA;QACH,CAAC;KAAA;CACF;AAvJD,8CAuJC","sourcesContent":["import { DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyPair } from './RSA'\nimport { hex2ua, ua2hex } from '../utils'\nimport { ExchangeDataManager } from './ExchangeDataManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * Allows to create or update shamir split keys.\n */\nexport class ShamirKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly exchangeDataManager: ExchangeDataManager\n ) {}\n\n /**\n * Get information on existing private keys splits for the provided data owner. For each private key of the provided data owner which has been\n * split using the Shamir sharing algorithm gives the list of the notaries (other data owners) which hold a copy of the key part.\n * @param dataOwner a data owner\n * @return the existing splits for the current data owner as a publicKeyFingerprint -> notariesIds object\n */\n getExistingSplitsInfo(dataOwner: DataOwnerOrStub): { [keyPairFingerprint: string]: string[] } {\n const legacyPartitionDelegates = Object.keys(dataOwner.privateKeyShamirPartitions ?? {})\n if (legacyPartitionDelegates.length > 0) {\n const fp = dataOwner.publicKey?.slice(-32)\n if (!fp) {\n console.error('Invalid data owner: the owner has legacy key partitions but no legacy key.')\n } else return { [fp]: legacyPartitionDelegates }\n }\n return {}\n }\n\n /**\n * Creates, updates or deletes shamir splits for keys of the current data owner. Any request to update the splits for a specific key will completely\n * replace any existing data on that split (all previous notaries will be ignored).\n * Note: currently you can only split the legacy key pair.\n * @param keySplitsToUpdate the fingerprints of key pairs which will have updated/new splits and the details on how to create the updated splits.\n * @param keySplitsToDelete the fingerprints or hex-encoded spki public keys which will not be shared anymore.\n * @throws if the parameters refer to non-existing or unavailable keys, have split creation details, or if they request to delete a non-existing\n * split.\n */\n async updateSelfSplits(\n keySplitsToUpdate: { [publicKeyHexOrFp: string]: { notariesIds: string[]; minShares: number } },\n keySplitsToDelete: string[]\n ): Promise<CryptoActorStubWithType> {\n const self = CryptoActorStubWithType.fromDataOwner(await this.dataOwnerApi.getCurrentDataOwner())\n const toUpdateSet = new Set(Object.keys(keySplitsToUpdate).map((x) => x.slice(-32)))\n const toDeleteSet = new Set(keySplitsToDelete.slice(-32))\n const intersection = Array.from(toDeleteSet).filter((x) => toUpdateSet.has(x))\n const existingSplits = new Set(Object.keys(this.getExistingSplitsInfo(self.stub)))\n const allKeys = this.encryptionKeysManager.getDecryptionKeys()\n if (toDeleteSet.size !== keySplitsToDelete.length || toUpdateSet.size !== Object.keys(keySplitsToUpdate).length || intersection.length > 0)\n throw new Error(`Duplicate keys in input:\\nkeySplitsToUpdate: ${keySplitsToUpdate}\\nkeySplitsToDelete: ${keySplitsToDelete}`)\n Object.entries(keySplitsToUpdate).forEach(([key, params]) => this.validateShamirParams(key, params))\n if (!Array.from(existingSplits).every((x) => existingSplits.has(x))) {\n throw new Error(`Requested to delete non-existing split.\\nexistingSplits: ${Array.from(existingSplits)}\\ntoDelete:${Array.from(toDeleteSet)}`)\n }\n if (Array.from(toUpdateSet).some((x) => !allKeys[x])) {\n throw new Error(`Private key is not available for some of the requested key split updates. ${keySplitsToUpdate}`)\n }\n const delegatesKeys: { [delegateId: string]: CryptoKey } = {}\n let updatedSelf = self\n for (const delegateId of new Set(Object.values(keySplitsToUpdate).flatMap((x) => x.notariesIds))) {\n const res = await this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, undefined, undefined)\n delegatesKeys[delegateId] = res.exchangeKey\n }\n for (const [key, params] of Object.entries(keySplitsToUpdate)) {\n updatedSelf = await this.updateKeySplit(updatedSelf, key.slice(-32), params.notariesIds, params.minShares, delegatesKeys, allKeys)\n }\n for (const keyFp of toDeleteSet) {\n updatedSelf = this.deleteKeySplit(updatedSelf, keyFp)\n }\n return await this.dataOwnerApi.modifyCryptoActorStub(updatedSelf)\n }\n\n /*TODO\n * Get suggested recovery keys: analyse transfer keys and shamir to get keys which should be shared with shamir for optimal recovery.\n */\n\n private validateShamirParams(key: string, params: { notariesIds: string[]; minShares: number }) {\n if (params.notariesIds.length > 0) {\n if (params.minShares > params.notariesIds.length) {\n throw new Error(`Invalid parameters for key ${key}: min shares can't be greater than the number of delegates. ${params}`)\n }\n } else throw new Error(`Invalid parameters for key ${key}: must have at least one delegate. ${params}`)\n }\n\n private deleteKeySplit(dataOwner: CryptoActorStubWithType, keyFp: string): CryptoActorStubWithType {\n if (keyFp !== dataOwner.stub.publicKey?.slice(-32)) {\n throw new Error('Currently it is possible to use shamir splits only for the legacy public key')\n }\n return {\n type: dataOwner.type,\n stub: {\n ...dataOwner.stub,\n privateKeyShamirPartitions: {},\n },\n }\n }\n\n private async updateKeySplit(\n dataOwner: CryptoActorStubWithType,\n keyFp: string,\n delegateIds: string[],\n minShares: number,\n delegatesKeys: { [p: string]: CryptoKey },\n allKeys: { [p: string]: KeyPair<CryptoKey> }\n ): Promise<CryptoActorStubWithType> {\n if (keyFp !== dataOwner.stub.publicKey?.slice(-32)) {\n throw new Error('Currently it is possible to use shamir splits only for the legacy public key')\n }\n return {\n type: dataOwner.type,\n stub: {\n ...dataOwner.stub,\n privateKeyShamirPartitions: await this.createPartitionsFor(allKeys[keyFp], delegateIds, minShares, delegatesKeys),\n },\n }\n }\n\n private async createPartitionsFor(\n keyPair: KeyPair<CryptoKey>,\n delegateIds: string[],\n minShares: number,\n delegatesKeys: { [p: string]: CryptoKey }\n ): Promise<{ [delegateId: string]: string }> {\n const exportedKey = await this.primitives.RSA.exportKey(keyPair.privateKey, 'pkcs8')\n if (delegateIds.length == 1) {\n return await this.encryptShares([exportedKey], delegateIds, delegatesKeys)\n } else {\n const exportedKeysHex = ua2hex(exportedKey)\n const stringShares = this.primitives.shamir.share(exportedKeysHex, delegateIds.length, minShares)\n const paddedStringShares = stringShares.map((x) => `f${x}`) // Shares are uneven length, apart from that they are perfect hexes\n for (const share of paddedStringShares) {\n if (!/^(?:[0-9a-f][0-9a-f])+$/g.test(share)) throw new Error('Unexpected result of shamir split: padded shares should be a valid hex value')\n if (share !== ua2hex(hex2ua(share))) throw new Error('Unexpected result with encoding-decoding share')\n }\n return await this.encryptShares(\n paddedStringShares.map((x) => hex2ua(x)),\n delegateIds,\n delegatesKeys\n )\n }\n }\n\n private async encryptShares(\n shares: ArrayBuffer[],\n delegateIds: string[],\n delegatesKeys: { [p: string]: CryptoKey }\n ): Promise<{ [delegateId: string]: string }> {\n return delegateIds.reduce(\n async (acc, delegateId, index) => ({\n ...(await acc),\n [delegateId]: ua2hex(await this.primitives.AES.encrypt(delegatesKeys[delegateId], shares[index])),\n }),\n Promise.resolve({} as { [delegateId: string]: string })\n )\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ShamirKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ShamirKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,oCAAyC;AAEzC,yEAA6E;AAE7E;;GAEG;AACH,MAAa,iBAAiB;IAC5B,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,qBAAgD,EAChD,mBAAwC;QAHxC,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,wBAAmB,GAAnB,mBAAmB,CAAqB;IAC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,CAAC,CAAA;gBACjG,MAAM,kBAAkB,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA,CAAC,mEAAmE;gBAC/H,KAAK,MAAM,KAAK,IAAI,kBAAkB,EAAE;oBACtC,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,KAAK,CAAC;wBAAE,MAAM,IAAI,KAAK,CAAC,8EAA8E,CAAC,CAAA;oBAC5I,IAAI,KAAK,KAAK,IAAA,cAAM,EAAC,IAAA,cAAM,EAAC,KAAK,CAAC,CAAC;wBAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;iBACvG;gBACD,OAAO,MAAM,IAAI,CAAC,aAAa,CAC7B,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,cAAM,EAAC,CAAC,CAAC,CAAC,EACxC,WAAW,EACX,aAAa,CACd,CAAA;aACF;QACH,CAAC;KAAA;IAEa,aAAa,CACzB,MAAqB,EACrB,WAAqB,EACrB,aAAyC;;YAEzC,OAAO,WAAW,CAAC,MAAM,CACvB,CAAO,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;gBAAC,OAAA,iCAC7B,CAAC,MAAM,GAAG,CAAC,KACd,CAAC,UAAU,CAAC,EAAE,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IACjG,CAAA;cAAA,EACF,OAAO,CAAC,OAAO,CAAC,EAAsC,CAAC,CACxD,CAAA;QACH,CAAC;KAAA;CACF;AAvJD,8CAuJC","sourcesContent":["import { DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyPair } from './RSA'\nimport { hex2ua, ua2hex } from '../utils'\nimport { ExchangeDataManager } from './ExchangeDataManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * Allows to create or update shamir split keys.\n */\nexport class ShamirKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly exchangeDataManager: ExchangeDataManager\n ) {}\n\n /**\n * Get information on existing private keys splits for the provided data owner. For each private key of the provided data owner which has been\n * split using the Shamir sharing algorithm gives the list of the notaries (other data owners) which hold a copy of the key part.\n * @param dataOwner a data owner\n * @return the existing splits for the current data owner as a publicKeyFingerprint -> notariesIds object\n */\n getExistingSplitsInfo(dataOwner: DataOwnerOrStub): { [keyPairFingerprint: string]: string[] } {\n const legacyPartitionDelegates = Object.keys(dataOwner.privateKeyShamirPartitions ?? {})\n if (legacyPartitionDelegates.length > 0) {\n const fp = dataOwner.publicKey?.slice(-32)\n if (!fp) {\n console.error('Invalid data owner: the owner has legacy key partitions but no legacy key.')\n } else return { [fp]: legacyPartitionDelegates }\n }\n return {}\n }\n\n /**\n * Creates, updates or deletes shamir splits for keys of the current data owner. Any request to update the splits for a specific key will completely\n * replace any existing data on that split (all previous notaries will be ignored).\n * Note: currently you can only split the legacy key pair.\n * @param keySplitsToUpdate the fingerprints of key pairs which will have updated/new splits and the details on how to create the updated splits.\n * @param keySplitsToDelete the fingerprints or hex-encoded spki public keys which will not be shared anymore.\n * @throws if the parameters refer to non-existing or unavailable keys, have split creation details, or if they request to delete a non-existing\n * split.\n */\n async updateSelfSplits(\n keySplitsToUpdate: { [publicKeyHexOrFp: string]: { notariesIds: string[]; minShares: number } },\n keySplitsToDelete: string[]\n ): Promise<CryptoActorStubWithType> {\n const self = CryptoActorStubWithType.fromDataOwner(await this.dataOwnerApi.getCurrentDataOwner())\n const toUpdateSet = new Set(Object.keys(keySplitsToUpdate).map((x) => x.slice(-32)))\n const toDeleteSet = new Set(keySplitsToDelete.slice(-32))\n const intersection = Array.from(toDeleteSet).filter((x) => toUpdateSet.has(x))\n const existingSplits = new Set(Object.keys(this.getExistingSplitsInfo(self.stub)))\n const allKeys = this.encryptionKeysManager.getDecryptionKeys()\n if (toDeleteSet.size !== keySplitsToDelete.length || toUpdateSet.size !== Object.keys(keySplitsToUpdate).length || intersection.length > 0)\n throw new Error(`Duplicate keys in input:\\nkeySplitsToUpdate: ${keySplitsToUpdate}\\nkeySplitsToDelete: ${keySplitsToDelete}`)\n Object.entries(keySplitsToUpdate).forEach(([key, params]) => this.validateShamirParams(key, params))\n if (!Array.from(existingSplits).every((x) => existingSplits.has(x))) {\n throw new Error(`Requested to delete non-existing split.\\nexistingSplits: ${Array.from(existingSplits)}\\ntoDelete:${Array.from(toDeleteSet)}`)\n }\n if (Array.from(toUpdateSet).some((x) => !allKeys[x])) {\n throw new Error(`Private key is not available for some of the requested key split updates. ${keySplitsToUpdate}`)\n }\n const delegatesKeys: { [delegateId: string]: CryptoKey } = {}\n let updatedSelf = self\n for (const delegateId of new Set(Object.values(keySplitsToUpdate).flatMap((x) => x.notariesIds))) {\n const res = await this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, undefined, undefined, false)\n delegatesKeys[delegateId] = res.exchangeKey\n }\n for (const [key, params] of Object.entries(keySplitsToUpdate)) {\n updatedSelf = await this.updateKeySplit(updatedSelf, key.slice(-32), params.notariesIds, params.minShares, delegatesKeys, allKeys)\n }\n for (const keyFp of toDeleteSet) {\n updatedSelf = this.deleteKeySplit(updatedSelf, keyFp)\n }\n return await this.dataOwnerApi.modifyCryptoActorStub(updatedSelf)\n }\n\n /*TODO\n * Get suggested recovery keys: analyse transfer keys and shamir to get keys which should be shared with shamir for optimal recovery.\n */\n\n private validateShamirParams(key: string, params: { notariesIds: string[]; minShares: number }) {\n if (params.notariesIds.length > 0) {\n if (params.minShares > params.notariesIds.length) {\n throw new Error(`Invalid parameters for key ${key}: min shares can't be greater than the number of delegates. ${params}`)\n }\n } else throw new Error(`Invalid parameters for key ${key}: must have at least one delegate. ${params}`)\n }\n\n private deleteKeySplit(dataOwner: CryptoActorStubWithType, keyFp: string): CryptoActorStubWithType {\n if (keyFp !== dataOwner.stub.publicKey?.slice(-32)) {\n throw new Error('Currently it is possible to use shamir splits only for the legacy public key')\n }\n return {\n type: dataOwner.type,\n stub: {\n ...dataOwner.stub,\n privateKeyShamirPartitions: {},\n },\n }\n }\n\n private async updateKeySplit(\n dataOwner: CryptoActorStubWithType,\n keyFp: string,\n delegateIds: string[],\n minShares: number,\n delegatesKeys: { [p: string]: CryptoKey },\n allKeys: { [p: string]: KeyPair<CryptoKey> }\n ): Promise<CryptoActorStubWithType> {\n if (keyFp !== dataOwner.stub.publicKey?.slice(-32)) {\n throw new Error('Currently it is possible to use shamir splits only for the legacy public key')\n }\n return {\n type: dataOwner.type,\n stub: {\n ...dataOwner.stub,\n privateKeyShamirPartitions: await this.createPartitionsFor(allKeys[keyFp], delegateIds, minShares, delegatesKeys),\n },\n }\n }\n\n private async createPartitionsFor(\n keyPair: KeyPair<CryptoKey>,\n delegateIds: string[],\n minShares: number,\n delegatesKeys: { [p: string]: CryptoKey }\n ): Promise<{ [delegateId: string]: string }> {\n const exportedKey = await this.primitives.RSA.exportKey(keyPair.privateKey, 'pkcs8')\n if (delegateIds.length == 1) {\n return await this.encryptShares([exportedKey], delegateIds, delegatesKeys)\n } else {\n const exportedKeysHex = ua2hex(exportedKey)\n const stringShares = this.primitives.shamir.share(exportedKeysHex, delegateIds.length, minShares)\n const paddedStringShares = stringShares.map((x) => `f${x}`) // Shares are uneven length, apart from that they are perfect hexes\n for (const share of paddedStringShares) {\n if (!/^(?:[0-9a-f][0-9a-f])+$/g.test(share)) throw new Error('Unexpected result of shamir split: padded shares should be a valid hex value')\n if (share !== ua2hex(hex2ua(share))) throw new Error('Unexpected result with encoding-decoding share')\n }\n return await this.encryptShares(\n paddedStringShares.map((x) => hex2ua(x)),\n delegateIds,\n delegatesKeys\n )\n }\n }\n\n private async encryptShares(\n shares: ArrayBuffer[],\n delegateIds: string[],\n delegatesKeys: { [p: string]: CryptoKey }\n ): Promise<{ [delegateId: string]: string }> {\n return delegateIds.reduce(\n async (acc, delegateId, index) => ({\n ...(await acc),\n [delegateId]: ua2hex(await this.primitives.AES.encrypt(delegatesKeys[delegateId], shares[index])),\n }),\n Promise.resolve({} as { [delegateId: string]: string })\n )\n }\n}\n"]}
|
|
@@ -4,6 +4,7 @@ import { IcureStorageFacade } from '../storage/IcureStorageFacade';
|
|
|
4
4
|
import { CryptoPrimitives } from './CryptoPrimitives';
|
|
5
5
|
import { KeyRecovery } from './KeyRecovery';
|
|
6
6
|
import { CryptoStrategies } from './CryptoStrategies';
|
|
7
|
+
import { KeyPairRecoverer } from './KeyPairRecoverer';
|
|
7
8
|
/**
|
|
8
9
|
* Allows to manage public and private keys for the current user and his parent hierarchy.
|
|
9
10
|
*/
|
|
@@ -14,10 +15,11 @@ export declare class UserEncryptionKeysManager {
|
|
|
14
15
|
private readonly keyRecovery;
|
|
15
16
|
private readonly strategies;
|
|
16
17
|
private readonly initialiseParentKeys;
|
|
18
|
+
private readonly keypairRecoverer;
|
|
17
19
|
private selfId;
|
|
18
20
|
private selfLegacyPublicKey;
|
|
19
21
|
private keysCache;
|
|
20
|
-
constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, icureStorage: IcureStorageFacade, keyRecovery: KeyRecovery, strategies: CryptoStrategies, initialiseParentKeys: boolean);
|
|
22
|
+
constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, icureStorage: IcureStorageFacade, keyRecovery: KeyRecovery, strategies: CryptoStrategies, initialiseParentKeys: boolean, keypairRecoverer: KeyPairRecoverer);
|
|
21
23
|
/**
|
|
22
24
|
* @internal
|
|
23
25
|
* Get all key pairs available for the current data owner and his parents.
|
|
@@ -38,6 +40,7 @@ export declare class UserEncryptionKeysManager {
|
|
|
38
40
|
dataOwnerId: string;
|
|
39
41
|
keys: {
|
|
40
42
|
pair: KeyPair<CryptoKey>;
|
|
43
|
+
verified: boolean;
|
|
41
44
|
}[];
|
|
42
45
|
}[];
|
|
43
46
|
}>;
|
|
@@ -18,13 +18,14 @@ const nothingKeyRecovererAndVerifier = (x) => Promise.resolve(x.reduce((acc, { d
|
|
|
18
18
|
* Allows to manage public and private keys for the current user and his parent hierarchy.
|
|
19
19
|
*/
|
|
20
20
|
class UserEncryptionKeysManager {
|
|
21
|
-
constructor(primitives, dataOwnerApi, icureStorage, keyRecovery, strategies, initialiseParentKeys) {
|
|
21
|
+
constructor(primitives, dataOwnerApi, icureStorage, keyRecovery, strategies, initialiseParentKeys, keypairRecoverer) {
|
|
22
22
|
this.primitives = primitives;
|
|
23
23
|
this.dataOwnerApi = dataOwnerApi;
|
|
24
24
|
this.icureStorage = icureStorage;
|
|
25
25
|
this.keyRecovery = keyRecovery;
|
|
26
26
|
this.strategies = strategies;
|
|
27
27
|
this.initialiseParentKeys = initialiseParentKeys;
|
|
28
|
+
this.keypairRecoverer = keypairRecoverer;
|
|
28
29
|
this.keysCache = undefined;
|
|
29
30
|
}
|
|
30
31
|
/**
|
|
@@ -49,7 +50,7 @@ class UserEncryptionKeysManager {
|
|
|
49
50
|
},
|
|
50
51
|
parents: remainingHierarchy.map((x) => ({
|
|
51
52
|
dataOwnerId: x,
|
|
52
|
-
keys: Object.values(this.keysCache[x]).map(({ pair }) => ({ pair })),
|
|
53
|
+
keys: Object.values(this.keysCache[x]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice })),
|
|
53
54
|
})),
|
|
54
55
|
};
|
|
55
56
|
});
|
|
@@ -108,7 +109,7 @@ class UserEncryptionKeysManager {
|
|
|
108
109
|
*/
|
|
109
110
|
initialiseKeys() {
|
|
110
111
|
return __awaiter(this, void 0, void 0, function* () {
|
|
111
|
-
const newKey = yield this.doLoadKeys((x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives), (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives));
|
|
112
|
+
const newKey = yield this.doLoadKeys((x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives, this.keypairRecoverer), (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives));
|
|
112
113
|
return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined;
|
|
113
114
|
});
|
|
114
115
|
}
|