@icure/api 6.4.0 → 7.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/icc-api/api/IccDeviceApi.d.ts +1 -1
- package/icc-api/api/IccDeviceApi.js.map +1 -1
- package/icc-api/api/IccDoctemplateApi.js.map +1 -1
- package/icc-api/api/IccDocumentTemplateApi.js.map +1 -1
- package/icc-api/api/IccHcpartyApi.d.ts +1 -1
- package/icc-api/api/IccHcpartyApi.js.map +1 -1
- package/icc-api/api/IccPatientApi.d.ts +1 -1
- package/icc-api/api/IccPatientApi.js.map +1 -1
- package/icc-api/model/MaintenanceTask.d.ts +6 -5
- package/icc-api/model/MaintenanceTask.js +5 -0
- package/icc-api/model/MaintenanceTask.js.map +1 -1
- package/icc-api/model/User.d.ts +23 -1
- package/icc-api/model/User.js +21 -0
- package/icc-api/model/User.js.map +1 -1
- package/icc-api/model/models.d.ts +14 -0
- package/icc-api/model/models.js.map +1 -1
- package/icc-x-api/crypto/AES.d.ts +2 -0
- package/icc-x-api/crypto/AES.js +12 -0
- package/icc-x-api/crypto/AES.js.map +1 -1
- package/icc-x-api/crypto/BaseExchangeKeysManager.d.ts +122 -0
- package/icc-x-api/crypto/BaseExchangeKeysManager.js +356 -0
- package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -0
- package/icc-x-api/crypto/ConfidentialEntities.d.ts +58 -0
- package/icc-x-api/crypto/ConfidentialEntities.js +99 -0
- package/icc-x-api/crypto/ConfidentialEntities.js.map +1 -0
- package/icc-x-api/crypto/CryptoPrimitives.d.ts +31 -0
- package/icc-x-api/crypto/CryptoPrimitives.js +55 -0
- package/icc-x-api/crypto/CryptoPrimitives.js.map +1 -0
- package/icc-x-api/crypto/CryptoStrategies.d.ts +82 -0
- package/icc-x-api/crypto/CryptoStrategies.js +3 -0
- package/icc-x-api/crypto/CryptoStrategies.js.map +1 -0
- package/icc-x-api/crypto/EntitiesEncryption.d.ts +254 -0
- package/icc-x-api/crypto/EntitiesEncryption.js +700 -0
- package/icc-x-api/crypto/EntitiesEncryption.js.map +1 -0
- package/icc-x-api/crypto/ExchangeKeysManager.d.ts +56 -0
- package/icc-x-api/crypto/ExchangeKeysManager.js +147 -0
- package/icc-x-api/crypto/ExchangeKeysManager.js.map +1 -0
- package/icc-x-api/crypto/KeyManager.d.ts +103 -0
- package/icc-x-api/crypto/KeyManager.js +288 -0
- package/icc-x-api/crypto/KeyManager.js.map +1 -0
- package/icc-x-api/crypto/KeyRecovery.d.ts +34 -0
- package/icc-x-api/crypto/KeyRecovery.js +253 -0
- package/icc-x-api/crypto/KeyRecovery.js.map +1 -0
- package/icc-x-api/crypto/LegacyCryptoStrategies.d.ts +28 -0
- package/icc-x-api/crypto/LegacyCryptoStrategies.js +22 -0
- package/icc-x-api/crypto/LegacyCryptoStrategies.js.map +1 -0
- package/icc-x-api/crypto/RSA.d.ts +19 -20
- package/icc-x-api/crypto/RSA.js +30 -1
- package/icc-x-api/crypto/RSA.js.map +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.d.ts +43 -0
- package/icc-x-api/crypto/ShamirKeysManager.js +150 -0
- package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -0
- package/icc-x-api/crypto/ShareMetadataBehaviour.d.ts +19 -0
- package/icc-x-api/crypto/ShareMetadataBehaviour.js +24 -0
- package/icc-x-api/crypto/ShareMetadataBehaviour.js.map +1 -0
- package/icc-x-api/crypto/TransferKeysManager.d.ts +29 -0
- package/icc-x-api/crypto/TransferKeysManager.js +121 -0
- package/icc-x-api/crypto/TransferKeysManager.js.map +1 -0
- package/icc-x-api/crypto/utils.d.ts +46 -0
- package/icc-x-api/crypto/utils.js +128 -0
- package/icc-x-api/crypto/utils.js.map +1 -1
- package/icc-x-api/filters/ContactByHcPartyTagCodeDateFilter.d.ts +11 -0
- package/icc-x-api/filters/ContactByHcPartyTagCodeDateFilter.js +11 -0
- package/icc-x-api/filters/ContactByHcPartyTagCodeDateFilter.js.map +1 -1
- package/icc-x-api/filters/DeviceByHcPartyFilter.d.ts +11 -0
- package/icc-x-api/filters/DeviceByHcPartyFilter.js +11 -0
- package/icc-x-api/filters/DeviceByHcPartyFilter.js.map +1 -1
- package/icc-x-api/filters/DeviceByIdsFilter.d.ts +11 -0
- package/icc-x-api/filters/DeviceByIdsFilter.js +11 -0
- package/icc-x-api/filters/DeviceByIdsFilter.js.map +1 -1
- package/icc-x-api/filters/HealthElementByHcPartySecretForeignKeysFilter.d.ts +11 -0
- package/icc-x-api/filters/HealthElementByHcPartySecretForeignKeysFilter.js +11 -0
- package/icc-x-api/filters/HealthElementByHcPartySecretForeignKeysFilter.js.map +1 -1
- package/icc-x-api/icc-accesslog-x-api.d.ts +49 -4
- package/icc-x-api/icc-accesslog-x-api.js +112 -102
- package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
- package/icc-x-api/icc-calendar-item-x-api.d.ts +53 -5
- package/icc-x-api/icc-calendar-item-x-api.js +112 -100
- package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
- package/icc-x-api/icc-classification-x-api.d.ts +45 -2
- package/icc-x-api/icc-classification-x-api.js +89 -41
- package/icc-x-api/icc-classification-x-api.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.d.ts +57 -19
- package/icc-x-api/icc-contact-x-api.js +149 -154
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/icc-crypto-x-api.d.ts +266 -366
- package/icc-x-api/icc-crypto-x-api.js +416 -1327
- package/icc-x-api/icc-crypto-x-api.js.map +1 -1
- package/icc-x-api/icc-data-owner-x-api.d.ts +110 -11
- package/icc-x-api/icc-data-owner-x-api.js +188 -14
- package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
- package/icc-x-api/icc-doctemplate-x-api.js +3 -3
- package/icc-x-api/icc-doctemplate-x-api.js.map +1 -1
- package/icc-x-api/icc-document-x-api.d.ts +76 -5
- package/icc-x-api/icc-document-x-api.js +137 -59
- package/icc-x-api/icc-document-x-api.js.map +1 -1
- package/icc-x-api/icc-form-x-api.d.ts +47 -7
- package/icc-x-api/icc-form-x-api.js +85 -86
- package/icc-x-api/icc-form-x-api.js.map +1 -1
- package/icc-x-api/icc-hcparty-x-api.d.ts +1 -1
- package/icc-x-api/icc-hcparty-x-api.js +1 -1
- package/icc-x-api/icc-hcparty-x-api.js.map +1 -1
- package/icc-x-api/icc-helement-x-api.d.ts +50 -3
- package/icc-x-api/icc-helement-x-api.js +101 -118
- package/icc-x-api/icc-helement-x-api.js.map +1 -1
- package/icc-x-api/icc-icure-maintenance-x-api.d.ts +31 -0
- package/icc-x-api/icc-icure-maintenance-x-api.js +124 -0
- package/icc-x-api/icc-icure-maintenance-x-api.js.map +1 -0
- package/icc-x-api/icc-invoice-x-api.d.ts +45 -5
- package/icc-x-api/icc-invoice-x-api.js +89 -64
- package/icc-x-api/icc-invoice-x-api.js.map +1 -1
- package/icc-x-api/icc-maintenance-task-x-api.d.ts +38 -6
- package/icc-x-api/icc-maintenance-task-x-api.js +73 -102
- package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
- package/icc-x-api/icc-message-x-api.d.ts +55 -2
- package/icc-x-api/icc-message-x-api.js +92 -33
- package/icc-x-api/icc-message-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.d.ts +67 -7
- package/icc-x-api/icc-patient-x-api.js +409 -473
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/icc-x-api/icc-receipt-x-api.d.ts +49 -5
- package/icc-x-api/icc-receipt-x-api.js +85 -47
- package/icc-x-api/icc-receipt-x-api.js.map +1 -1
- package/icc-x-api/icc-time-table-x-api.d.ts +34 -10
- package/icc-x-api/icc-time-table-x-api.js +61 -18
- package/icc-x-api/icc-time-table-x-api.js.map +1 -1
- package/icc-x-api/index.d.ts +30 -1
- package/icc-x-api/index.js +112 -49
- package/icc-x-api/index.js.map +1 -1
- package/icc-x-api/maintenance/KeyPairUpdateRequest.d.ts +35 -0
- package/icc-x-api/maintenance/KeyPairUpdateRequest.js +54 -0
- package/icc-x-api/maintenance/KeyPairUpdateRequest.js.map +1 -0
- package/icc-x-api/storage/DefaultStorageEntryKeysFactory.d.ts +9 -0
- package/icc-x-api/storage/DefaultStorageEntryKeysFactory.js +23 -0
- package/icc-x-api/storage/DefaultStorageEntryKeysFactory.js.map +1 -0
- package/icc-x-api/storage/IcureStorageFacade.d.ts +55 -0
- package/icc-x-api/storage/IcureStorageFacade.js +95 -0
- package/icc-x-api/storage/IcureStorageFacade.js.map +1 -0
- package/icc-x-api/storage/StorageEntryKeysFactory.d.ts +31 -0
- package/icc-x-api/storage/StorageEntryKeysFactory.js +3 -0
- package/icc-x-api/storage/StorageEntryKeysFactory.js.map +1 -0
- package/icc-x-api/utils/collection-utils.d.ts +8 -0
- package/icc-x-api/utils/collection-utils.js +26 -0
- package/icc-x-api/utils/collection-utils.js.map +1 -0
- package/icc-x-api/utils/crypto-utils.d.ts +8 -1
- package/icc-x-api/utils/crypto-utils.js +19 -3
- package/icc-x-api/utils/crypto-utils.js.map +1 -1
- package/icc-x-api/utils/graph-utils.d.ts +45 -0
- package/icc-x-api/utils/graph-utils.js +203 -0
- package/icc-x-api/utils/graph-utils.js.map +1 -0
- package/icc-x-api/utils/lru-temporised-async-cache.d.ts +27 -0
- package/icc-x-api/utils/lru-temporised-async-cache.js +120 -0
- package/icc-x-api/utils/lru-temporised-async-cache.js.map +1 -0
- package/package.json +1 -1
|
@@ -14,8 +14,6 @@ const icc_api_1 = require("../icc-api");
|
|
|
14
14
|
const models = require("../icc-api/model/models");
|
|
15
15
|
const _ = require("lodash");
|
|
16
16
|
const moment = require("moment");
|
|
17
|
-
const binary_utils_1 = require("./utils/binary-utils");
|
|
18
|
-
const utils_1 = require("./utils");
|
|
19
17
|
const AuthenticationProvider_1 = require("./auth/AuthenticationProvider");
|
|
20
18
|
class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
21
19
|
constructor(host, headers, crypto, dataOwnerApi, encryptedKeys = ['descr', 'note'], authenticationProvider = new AuthenticationProvider_1.NoAuthenticationProvider(), fetchImpl = typeof window !== 'undefined'
|
|
@@ -28,47 +26,54 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
28
26
|
this.dataOwnerApi = dataOwnerApi;
|
|
29
27
|
this.encryptedKeys = encryptedKeys;
|
|
30
28
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Creates a new instance of health element with initialised encryption metadata (not in the database).
|
|
31
|
+
* @param user the current user.
|
|
32
|
+
* @param patient the patient this health element refers to.
|
|
33
|
+
* @param h initialised data for the health element. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify
|
|
34
|
+
* other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.
|
|
35
|
+
* @param options optional parameters:
|
|
36
|
+
* - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the
|
|
37
|
+
* auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with
|
|
38
|
+
* auto-delegations, in such case the access level specified here will be used. Currently only WRITE access is supported, but in future also read
|
|
39
|
+
* access will be possible.
|
|
40
|
+
* - preferredSfk: secret id of the patient to use as the secret foreign key to use for the classification. The default value will be a
|
|
41
|
+
* secret id of patient known by the topmost parent in the current data owner hierarchy.
|
|
42
|
+
* - confidential: if true, the entity will be created as confidential. Confidential entities are not shared with auto-delegations, and the default
|
|
43
|
+
* foreign key used is any key that is not shared with any of the data owner parents. By default entities are created as non-confidential.
|
|
44
|
+
* @return a new instance of health element.
|
|
45
|
+
*/
|
|
46
|
+
newInstance(user, patient, h, options = {}) {
|
|
47
|
+
var _a, _b, _c, _d, _e, _f;
|
|
48
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
49
|
+
const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user);
|
|
50
|
+
const helement = _.assign({
|
|
51
|
+
id: this.crypto.primitives.randomUuid(),
|
|
52
|
+
_type: 'org.taktik.icure.entities.HealthElement',
|
|
53
|
+
created: new Date().getTime(),
|
|
54
|
+
modified: new Date().getTime(),
|
|
55
|
+
responsible: dataOwnerId,
|
|
56
|
+
author: user.id,
|
|
57
|
+
codes: [],
|
|
58
|
+
tags: [],
|
|
59
|
+
healthElementId: this.crypto.primitives.randomUuid(),
|
|
60
|
+
openingDate: parseInt(moment().format('YYYYMMDDHHmmss')),
|
|
61
|
+
}, h || {});
|
|
62
|
+
const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user);
|
|
63
|
+
if (ownerId !== (yield this.dataOwnerApi.getCurrentDataOwnerId()))
|
|
64
|
+
throw new Error('Can only initialise entities as current data owner.');
|
|
65
|
+
const sfk = (_a = options.preferredSfk) !== null && _a !== void 0 ? _a : (!!options.confidential
|
|
66
|
+
? yield this.crypto.confidential.getConfidentialSecretId(patient)
|
|
67
|
+
: yield this.crypto.confidential.getAnySecretIdSharedWithParents(patient));
|
|
68
|
+
if (!sfk)
|
|
69
|
+
throw new Error(`Couldn't find any sfk of parent patient ${patient.id} for confidential=${!!options.confidential}`);
|
|
70
|
+
const extraDelegations = [
|
|
71
|
+
...Object.keys((_b = options.additionalDelegates) !== null && _b !== void 0 ? _b : {}),
|
|
72
|
+
...(options.confidential ? [] : [...((_d = (_c = user.autoDelegations) === null || _c === void 0 ? void 0 : _c.all) !== null && _d !== void 0 ? _d : []), ...((_f = (_e = user.autoDelegations) === null || _e === void 0 ? void 0 : _e.medicalInformation) !== null && _f !== void 0 ? _f : [])]),
|
|
73
|
+
];
|
|
74
|
+
const initialisationInfo = yield this.crypto.entities.entityWithInitialisedEncryptedMetadata(helement, patient.id, sfk, true, extraDelegations);
|
|
75
|
+
return new models.HealthElement(initialisationInfo.updatedEntity);
|
|
76
|
+
});
|
|
72
77
|
}
|
|
73
78
|
createHealthElement(body) {
|
|
74
79
|
throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption');
|
|
@@ -88,7 +93,7 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
88
93
|
return bodies
|
|
89
94
|
? this.encrypt(user, bodies.map((c) => _.cloneDeep(c)))
|
|
90
95
|
.then((hes) => super.createHealthElements(hes))
|
|
91
|
-
.then((hes) => this.decrypt(this.dataOwnerApi.
|
|
96
|
+
.then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), hes))
|
|
92
97
|
: Promise.resolve(null);
|
|
93
98
|
}
|
|
94
99
|
getHealthElement(healthElementId) {
|
|
@@ -104,7 +109,7 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
104
109
|
throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption');
|
|
105
110
|
}
|
|
106
111
|
getHealthElementsWithUser(user, body) {
|
|
107
|
-
return super.getHealthElements(body).then((hes) => this.decrypt(this.dataOwnerApi.
|
|
112
|
+
return super.getHealthElements(body).then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), hes));
|
|
108
113
|
}
|
|
109
114
|
newHealthElementDelegations(healthElementId, body) {
|
|
110
115
|
throw new Error('Cannot call a method that returns health element without providing a user for de/encryption');
|
|
@@ -125,9 +130,10 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
125
130
|
return super.findHealthElementsByHCPartyPatientForeignKeysUsingPost(hcPartyId, secretFKeys).then((hes) => this.decryptWithUser(user, hes));
|
|
126
131
|
}
|
|
127
132
|
findHealthElementsByHCPartyAndPatientWithUser(user, hcPartyId, patient, usingPost = false) {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
133
|
+
var _a;
|
|
134
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
135
|
+
let keysAndHcPartyId = yield this.crypto.entities.secretIdsForHcpHierarchyOf(patient);
|
|
136
|
+
const keys = (_a = keysAndHcPartyId.find((secretForeignKeys) => secretForeignKeys.ownerId == hcPartyId)) === null || _a === void 0 ? void 0 : _a.extracted;
|
|
131
137
|
if (keys == undefined) {
|
|
132
138
|
throw Error('No delegation for user');
|
|
133
139
|
}
|
|
@@ -140,12 +146,13 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
140
146
|
throw new Error('Cannot call a method that returns health element without providing a user for de/encryption');
|
|
141
147
|
}
|
|
142
148
|
modifyHealthElementWithUser(user, body) {
|
|
143
|
-
return body
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
+
return body ? this.modifyAs(this.dataOwnerApi.getDataOwnerIdOf(user), body) : Promise.resolve(null);
|
|
150
|
+
}
|
|
151
|
+
modifyAs(dataOwner, body) {
|
|
152
|
+
return this.encryptAs(dataOwner, [_.cloneDeep(body)])
|
|
153
|
+
.then((hes) => super.modifyHealthElement(hes[0]))
|
|
154
|
+
.then((he) => this.decrypt(dataOwner, [he]))
|
|
155
|
+
.then((hes) => hes[0]);
|
|
149
156
|
}
|
|
150
157
|
modifyHealthElements(body) {
|
|
151
158
|
throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption');
|
|
@@ -154,7 +161,7 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
154
161
|
return bodies
|
|
155
162
|
? this.encrypt(user, bodies.map((c) => _.cloneDeep(c)))
|
|
156
163
|
.then((hes) => super.modifyHealthElements(hes))
|
|
157
|
-
.then((hes) => this.decrypt(this.dataOwnerApi.
|
|
164
|
+
.then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), hes))
|
|
158
165
|
: Promise.resolve(null);
|
|
159
166
|
}
|
|
160
167
|
// noinspection JSUnusedGlobalSymbols
|
|
@@ -176,15 +183,15 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
176
183
|
* @param usingPost
|
|
177
184
|
*/
|
|
178
185
|
findBy(hcpartyId, patient, keepObsoleteVersions = false, usingPost = false) {
|
|
179
|
-
return this.crypto
|
|
180
|
-
.
|
|
186
|
+
return this.crypto.entities
|
|
187
|
+
.secretIdsForHcpHierarchyOf(patient)
|
|
181
188
|
.then((secretForeignKeys) => secretForeignKeys && secretForeignKeys.length > 0
|
|
182
189
|
? Promise.all(secretForeignKeys
|
|
183
190
|
.reduce((acc, level) => {
|
|
184
191
|
return acc.concat([
|
|
185
192
|
{
|
|
186
|
-
hcpartyId: level.
|
|
187
|
-
extractedKeys: level.
|
|
193
|
+
hcpartyId: level.ownerId,
|
|
194
|
+
extractedKeys: level.extracted.filter((key) => !acc.some((previousLevel) => previousLevel.extractedKeys.includes(key))),
|
|
188
195
|
},
|
|
189
196
|
]);
|
|
190
197
|
}, [])
|
|
@@ -220,69 +227,16 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
220
227
|
.then((helements) => this.decrypt(hcPartyId, helements));
|
|
221
228
|
}
|
|
222
229
|
encrypt(user, healthElements) {
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
.then((healthElement) => this.crypto.extractKeysFromDelegationsForHcpHierarchy(dataOwnerId, healthElement.id, healthElement.encryptionKeys))
|
|
228
|
-
.then((sfks) => this.crypto.AES.importKey('raw', (0, binary_utils_1.hex2ua)(sfks.extractedKeys[0].replace(/-/g, ''))))
|
|
229
|
-
.then((key) => (0, utils_1.crypt)(he, (obj) => this.crypto.AES.encrypt(key, (0, binary_utils_1.utf8_2ua)(JSON.stringify(obj, (k, v) => {
|
|
230
|
-
return v instanceof ArrayBuffer || v instanceof Uint8Array
|
|
231
|
-
? (0, binary_utils_1.b2a)(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))
|
|
232
|
-
: v;
|
|
233
|
-
}))), this.encryptedKeys))));
|
|
234
|
-
}
|
|
235
|
-
initEncryptionKeys(user, he) {
|
|
236
|
-
const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user);
|
|
237
|
-
return this.crypto.initEncryptionKeys(he, dataOwnerId).then((eks) => {
|
|
238
|
-
let promise = Promise.resolve(_.extend(he, {
|
|
239
|
-
encryptionKeys: eks.encryptionKeys,
|
|
240
|
-
}));
|
|
241
|
-
(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.medicalInformation || []) : []).forEach((delegateId) => (promise = promise.then((healthElement) => this.crypto
|
|
242
|
-
.appendEncryptionKeys(healthElement, dataOwnerId, delegateId, eks.secretId)
|
|
243
|
-
.then((extraEks) => {
|
|
244
|
-
return _.extend(extraEks.modifiedObject, {
|
|
245
|
-
encryptionKeys: extraEks.encryptionKeys,
|
|
246
|
-
});
|
|
247
|
-
})
|
|
248
|
-
.catch((e) => {
|
|
249
|
-
console.log(e.message);
|
|
250
|
-
return healthElement;
|
|
251
|
-
}))));
|
|
252
|
-
return promise;
|
|
253
|
-
});
|
|
230
|
+
return this.encryptAs(this.dataOwnerApi.getDataOwnerIdOf(user), healthElements);
|
|
231
|
+
}
|
|
232
|
+
encryptAs(owner, healthElements) {
|
|
233
|
+
return Promise.all(healthElements.map((he) => this.crypto.entities.tryEncryptEntity(he, owner, this.encryptedKeys, false, true, (x) => new models.HealthElement(x))));
|
|
254
234
|
}
|
|
255
235
|
decryptWithUser(user, hes) {
|
|
256
|
-
return this.decrypt(this.dataOwnerApi.
|
|
236
|
+
return this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), hes);
|
|
257
237
|
}
|
|
258
238
|
decrypt(dataOwnerId, hes) {
|
|
259
|
-
return Promise.all(hes.map((he) => this.crypto
|
|
260
|
-
.extractKeysFromDelegationsForHcpHierarchy(dataOwnerId, he.id, _.size(he.encryptionKeys) ? he.encryptionKeys : he.delegations)
|
|
261
|
-
.then(({ extractedKeys: sfks }) => {
|
|
262
|
-
if (!sfks || !sfks.length) {
|
|
263
|
-
console.log('Cannot decrypt helement', he.id);
|
|
264
|
-
return Promise.resolve(he);
|
|
265
|
-
}
|
|
266
|
-
if (he.encryptedSelf) {
|
|
267
|
-
return this.crypto.AES.importKey('raw', (0, binary_utils_1.hex2ua)(sfks[0].replace(/-/g, ''))).then((key) => new Promise((resolve) => this.crypto.AES.decrypt(key, (0, binary_utils_1.string2ua)((0, binary_utils_1.a2b)(he.encryptedSelf))).then((dec) => {
|
|
268
|
-
let jsonContent;
|
|
269
|
-
try {
|
|
270
|
-
jsonContent = dec && (0, binary_utils_1.ua2utf8)(dec);
|
|
271
|
-
jsonContent && _.assign(he, JSON.parse(jsonContent));
|
|
272
|
-
}
|
|
273
|
-
catch (e) {
|
|
274
|
-
console.log('Cannot parse he', he.id, jsonContent || '<- Invalid encoding');
|
|
275
|
-
}
|
|
276
|
-
resolve(he);
|
|
277
|
-
}, () => {
|
|
278
|
-
console.log('Cannot decrypt health element', he.id);
|
|
279
|
-
resolve(he);
|
|
280
|
-
})));
|
|
281
|
-
}
|
|
282
|
-
else {
|
|
283
|
-
return Promise.resolve(he);
|
|
284
|
-
}
|
|
285
|
-
})));
|
|
239
|
+
return Promise.all(hes.map((he) => this.crypto.entities.decryptEntity(he, dataOwnerId, (x) => new models.HealthElement(x)).then(({ entity }) => entity)));
|
|
286
240
|
}
|
|
287
241
|
filterHealthElementsBy(startDocumentId, limit, body) {
|
|
288
242
|
throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption');
|
|
@@ -319,6 +273,35 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
319
273
|
id: code,
|
|
320
274
|
});
|
|
321
275
|
}
|
|
276
|
+
/**
|
|
277
|
+
* @param healthElement a health element
|
|
278
|
+
* @return the id of the patient that the health element refers to, retrieved from the encrypted metadata. Normally there should only be one element
|
|
279
|
+
* in the returned array, but in case of entity merges there could be multiple values.
|
|
280
|
+
*/
|
|
281
|
+
decryptPatientIdOf(healthElement) {
|
|
282
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
283
|
+
return this.crypto.entities.owningEntityIdsOf(healthElement, undefined);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Share an existing health element with other data owners, allowing them to access the non-encrypted data of the health element and optionally also
|
|
288
|
+
* the encrypted content, with read-only or read-write permissions.
|
|
289
|
+
* @param delegateId the id of the data owner which will be granted access to the health element.
|
|
290
|
+
* @param healthElement the health element to share.
|
|
291
|
+
* @param options optional parameters to customize the sharing behaviour:
|
|
292
|
+
* - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted
|
|
293
|
+
* content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a
|
|
294
|
+
* health element does not have encrypted content.
|
|
295
|
+
* - sharePatientId: specifies if the id of the patient that this health element refers to should be shared with the delegate (defaults to
|
|
296
|
+
* {@link ShareMetadataBehaviour.IF_AVAILABLE}).
|
|
297
|
+
* @return a promise which will contain the updated health element.
|
|
298
|
+
*/
|
|
299
|
+
shareWith(delegateId, healthElement, options = {}) {
|
|
300
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
301
|
+
const self = yield this.dataOwnerApi.getCurrentDataOwnerId();
|
|
302
|
+
return yield this.modifyAs(self, yield this.crypto.entities.entityWithAutoExtendedEncryptedMetadata(healthElement, delegateId, undefined, options.shareEncryptionKey, options.sharePatientId));
|
|
303
|
+
});
|
|
304
|
+
}
|
|
322
305
|
}
|
|
323
306
|
exports.IccHelementXApi = IccHelementXApi;
|
|
324
307
|
//# sourceMappingURL=icc-helement-x-api.js.map
|
|
@@ -1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K,CAAC,GAAG,CAAC,CAAA;QACzB,OAAO,IAAI,MAAM,CAAC,IAAI,CAAC;YACrB,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;YACV,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;YACV,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;YACb,EAAE,EAAE,IAAI;SACT,CAAC,CAAA;IACJ,CAAC;CACF;AAhbD,0CAgbC","sourcesContent":["import { IccHelementApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as models from '../icc-api/model/models'\n\nimport * as _ from 'lodash'\nimport * as moment from 'moment'\nimport { a2b, b2a, hex2ua, string2ua, ua2utf8, utf8_2ua } from './utils/binary-utils'\nimport { FilterChainHealthElement, HealthElement, PaginatedListHealthElement } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { crypt } from './utils'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport class IccHelementXApi extends IccHelementApi {\n crypto: IccCryptoXApi\n dataOwnerApi: IccDataOwnerXApi\n\n private readonly encryptedKeys: Array<string>\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n crypto: IccCryptoXApi,\n dataOwnerApi: IccDataOwnerXApi,\n encryptedKeys: Array<string> = ['descr', 'note'],\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.crypto = crypto\n this.dataOwnerApi = dataOwnerApi\n this.encryptedKeys = encryptedKeys\n }\n\n newInstance(user: models.User, patient: models.Patient, h: any, confidential = false, delegates: string[] = []) {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n const helement = _.assign(\n {\n id: this.crypto.randomUuid(),\n _type: 'org.taktik.icure.entities.HealthElement',\n created: new Date().getTime(),\n modified: new Date().getTime(),\n responsible: dataOwnerId,\n author: user.id,\n codes: [],\n tags: [],\n healthElementId: this.crypto.randomUuid(),\n openingDate: parseInt(moment().format('YYYYMMDDHHmmss')),\n },\n h || {}\n )\n\n return this.initDelegationsAndEncryptionKeys(helement, patient, user, confidential, delegates)\n }\n\n initDelegationsAndEncryptionKeys(\n healthElement: models.HealthElement,\n patient: models.Patient,\n user: models.User,\n confidential: boolean,\n delegates: string[] = []\n ): Promise<models.HealthElement> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n\n return this.crypto.extractPreferredSfk(patient, dataOwnerId!, confidential).then(async (key) => {\n if (!key) {\n console.error(`SFK cannot be found for Health element ${key}. The healthElement will not be reachable from the patient side`)\n }\n const dels = await this.crypto.initObjectDelegations(healthElement, patient, dataOwnerId!, key ?? null)\n const eks = await this.crypto.initEncryptionKeys(healthElement, dataOwnerId!)\n _.extend(healthElement, {\n delegations: dels.delegations,\n cryptedForeignKeys: dels.cryptedForeignKeys,\n secretForeignKeys: dels.secretForeignKeys,\n encryptionKeys: eks.encryptionKeys,\n })\n\n let promise = Promise.resolve(healthElement)\n _.uniq(\n delegates.concat(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.medicalInformation || []) : [])\n ).forEach(\n (delegateId) =>\n (promise = promise.then((healthElement) =>\n this.crypto.addDelegationsAndEncryptionKeys(patient, healthElement, dataOwnerId!, delegateId, dels.secretId, eks.secretId).catch((e) => {\n console.log(e)\n return healthElement\n })\n ))\n )\n ;(user.autoDelegations && user.autoDelegations.anonymousMedicalInformation ? user.autoDelegations.anonymousMedicalInformation : []).forEach(\n (delegateId) =>\n (promise = promise.then((healthElement) =>\n this.crypto.addDelegationsAndEncryptionKeys(patient, healthElement, dataOwnerId!, delegateId, null, eks.secretId).catch((e) => {\n console.log(e)\n return healthElement\n })\n ))\n )\n return promise\n })\n }\n\n createHealthElement(body?: models.HealthElement): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n createHealthElementWithUser(user: models.User, body?: models.HealthElement): Promise<models.HealthElement | any> {\n return body\n ? this.encrypt(user, [_.cloneDeep(body)])\n .then((hes) => super.createHealthElement(hes[0]))\n .then((he) => this.decryptWithUser(user, [he]))\n .then((hes) => hes[0])\n : Promise.resolve(null)\n }\n\n createHealthElements(body?: Array<HealthElement>): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n createHealthElementsWithUser(user: models.User, bodies?: models.HealthElement[]): Promise<models.HealthElement[] | any> {\n return bodies\n ? this.encrypt(\n user,\n bodies.map((c) => _.cloneDeep(c))\n )\n .then((hes) => super.createHealthElements(hes))\n .then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerOf(user), hes))\n : Promise.resolve(null)\n }\n\n getHealthElement(healthElementId: string): never {\n throw new Error('Cannot call a method that returns health element without providing a user for de/encryption')\n }\n\n getHealthElementWithUser(user: models.User, healthElementId: string): Promise<models.HealthElement> {\n return super\n .getHealthElement(healthElementId)\n .then((he) => this.decryptWithUser(user, [he]))\n .then((hes) => hes[0])\n }\n\n getHealthElements(body?: models.ListOfIds): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n getHealthElementsWithUser(user: models.User, body?: models.ListOfIds): Promise<models.HealthElement[]> {\n return super.getHealthElements(body).then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerOf(user), hes))\n }\n\n newHealthElementDelegations(healthElementId: string, body?: Array<models.Delegation>): never {\n throw new Error('Cannot call a method that returns health element without providing a user for de/encryption')\n }\n\n newHealthElementDelegationsWithUser(user: models.User, healthElementId: string, body?: Array<models.Delegation>): Promise<models.HealthElement> {\n return super\n .newHealthElementDelegations(healthElementId, body)\n .then((he) => this.decryptWithUser(user, [he]))\n .then((he) => he[0])\n }\n\n findHealthElementsByHCPartyPatientForeignKeys(hcPartyId: string, secretFKeys: string): never {\n throw new Error('Cannot call a method that returns health element without providing a user for de/encryption')\n }\n\n findHealthElementsByHCPartyPatientForeignKeysWithUser(user: models.User, hcPartyId: string, secretFKeys: string): Promise<HealthElement[]> {\n return super.findHealthElementsByHCPartyPatientForeignKeys(hcPartyId, secretFKeys).then((hes) => this.decryptWithUser(user, hes))\n }\n\n findHealthElementsByHCPartyPatientForeignKeysArrayWithUser(user: models.User, hcPartyId: string, secretFKeys: string[]): Promise<HealthElement[]> {\n return super.findHealthElementsByHCPartyPatientForeignKeysUsingPost(hcPartyId, secretFKeys).then((hes) => this.decryptWithUser(user, hes))\n }\n\n findHealthElementsByHCPartyAndPatientWithUser(\n user: models.User,\n hcPartyId: string,\n patient: models.Patient,\n usingPost: boolean = false\n ): Promise<models.HealthElement[]> {\n return this.crypto.extractSFKsHierarchyFromDelegations(patient, hcPartyId).then((keysAndHcPartyId) => {\n const keys = keysAndHcPartyId.find((secretForeignKeys) => secretForeignKeys.hcpartyId == hcPartyId)?.extractedKeys\n\n if (keys == undefined) {\n throw Error('No delegation for user')\n }\n\n return usingPost\n ? this.findHealthElementsByHCPartyPatientForeignKeysArrayWithUser(user, hcPartyId, keys)\n : this.findHealthElementsByHCPartyPatientForeignKeysWithUser(user, hcPartyId, keys.join(','))\n })\n }\n\n modifyHealthElement(body?: HealthElement): never {\n throw new Error('Cannot call a method that returns health element without providing a user for de/encryption')\n }\n\n modifyHealthElementWithUser(user: models.User, body?: HealthElement): Promise<HealthElement | any> {\n return body\n ? this.encrypt(user, [_.cloneDeep(body)])\n .then((hes) => super.modifyHealthElement(hes[0]))\n .then((he) => this.decryptWithUser(user, [he]))\n .then((hes) => hes[0])\n : Promise.resolve(null)\n }\n\n modifyHealthElements(body?: Array<HealthElement>): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n modifyHealthElementsWithUser(user: models.User, bodies?: HealthElement[]): Promise<HealthElement[] | any> {\n return bodies\n ? this.encrypt(\n user,\n bodies.map((c) => _.cloneDeep(c))\n )\n .then((hes) => super.modifyHealthElements(hes))\n .then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerOf(user), hes))\n : Promise.resolve(null)\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * 1. Check whether there is a delegation with 'hcpartyId' or not.\n * 2. 'fetchHcParty[hcpartyId][1]': is encrypted AES exchange key by RSA public key of him.\n * 3. Obtain the AES exchange key, by decrypting the previous step value with hcparty private key\n * 3.1. KeyPair should be fetch from cache (in jwk)\n * 3.2. if it doesn't exist in the cache, it has to be loaded from Browser Local store, and then import it to WebCrypto\n * 4. Obtain the array of delegations which are delegated to his ID (hcpartyId) in this patient\n * 5. Decrypt and collect all keys (secretForeignKeys) within delegations of previous step (with obtained AES key of step 4)\n * 6. Do the REST call to get all helements with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the helements of the patient.\n *\n * @param hcpartyId\n * @param patient (Promise)\n * @param keepObsoleteVersions\n * @param usingPost\n */\n\n findBy(hcpartyId: string, patient: models.Patient, keepObsoleteVersions = false, usingPost = false) {\n return this.crypto\n .extractSFKsHierarchyFromDelegations(patient, hcpartyId)\n .then((secretForeignKeys) =>\n secretForeignKeys && secretForeignKeys.length > 0\n ? Promise.all(\n secretForeignKeys\n .reduce((acc, level) => {\n return acc.concat([\n {\n hcpartyId: level.hcpartyId,\n extractedKeys: level.extractedKeys.filter((key) => !acc.some((previousLevel) => previousLevel.extractedKeys.includes(key))),\n },\n ])\n }, [] as Array<{ hcpartyId: string; extractedKeys: Array<string> }>)\n .filter((l) => l.extractedKeys.length > 0)\n .map(({ hcpartyId, extractedKeys }) =>\n usingPost\n ? this.findByHCPartyPatientSecretFKeysArray(hcpartyId, _.uniq(extractedKeys))\n : this.findByHCPartyPatientSecretFKeys(hcpartyId, _.uniq(extractedKeys).join(','))\n )\n ).then((results) => _.uniqBy(_.flatMap(results), (x) => x.id))\n : Promise.resolve([])\n )\n .then((decryptedHelements: Array<models.HealthElement>) => {\n const byIds: { [key: string]: models.HealthElement } = {}\n\n if (keepObsoleteVersions) {\n return decryptedHelements\n } else {\n decryptedHelements.forEach((he) => {\n if (he.healthElementId) {\n const phe = byIds[he.healthElementId]\n if (!phe || !phe.modified || (he.modified && phe.modified < he.modified)) {\n byIds[he.healthElementId] = he\n }\n }\n })\n return _.values(byIds).filter((s: any) => !s.endOfLife)\n }\n })\n }\n\n findByHCPartyPatientSecretFKeys(hcPartyId: string, secretFKeys: string): Promise<Array<models.Contact> | any> {\n return super.findHealthElementsByHCPartyPatientForeignKeys(hcPartyId, secretFKeys).then((helements) => this.decrypt(hcPartyId, helements))\n }\n\n findByHCPartyPatientSecretFKeysArray(hcPartyId: string, secretFKeys: string[]): Promise<Array<models.Contact> | any> {\n return super\n .findHealthElementsByHCPartyPatientForeignKeysUsingPost(hcPartyId, secretFKeys)\n .then((helements) => this.decrypt(hcPartyId, helements))\n }\n\n encrypt(user: models.User, healthElements: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n return Promise.all(\n healthElements.map((he) =>\n (he.encryptionKeys && Object.keys(he.encryptionKeys).some((k) => !!he.encryptionKeys![k].length)\n ? Promise.resolve(he)\n : this.initEncryptionKeys(user, he)\n )\n .then((healthElement: HealthElement) =>\n this.crypto.extractKeysFromDelegationsForHcpHierarchy(dataOwnerId, healthElement.id!, healthElement.encryptionKeys!)\n )\n .then((sfks: { extractedKeys: Array<string>; hcpartyId: string }) =>\n this.crypto.AES.importKey('raw', hex2ua(sfks.extractedKeys[0].replace(/-/g, '')))\n )\n .then((key: CryptoKey) =>\n crypt(\n he,\n (obj: { [key: string]: string }) =>\n this.crypto.AES.encrypt(\n key,\n utf8_2ua(\n JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || v instanceof Uint8Array\n ? b2a(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n )\n ),\n this.encryptedKeys\n )\n )\n )\n )\n }\n\n initEncryptionKeys(user: models.User, he: models.HealthElement): Promise<models.HealthElement> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n return this.crypto.initEncryptionKeys(he, dataOwnerId!).then((eks) => {\n let promise = Promise.resolve(\n _.extend(he, {\n encryptionKeys: eks.encryptionKeys,\n })\n )\n ;(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.medicalInformation || []) : []).forEach(\n (delegateId) =>\n (promise = promise.then((healthElement) =>\n this.crypto\n .appendEncryptionKeys(healthElement, dataOwnerId!, delegateId, eks.secretId)\n .then((extraEks) => {\n return _.extend(extraEks.modifiedObject, {\n encryptionKeys: extraEks.encryptionKeys,\n })\n })\n .catch((e) => {\n console.log(e.message)\n return healthElement\n })\n ))\n )\n return promise\n })\n }\n\n decryptWithUser(user: models.User, hes: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n return this.decrypt(this.dataOwnerApi.getDataOwnerOf(user), hes)\n }\n\n decrypt(dataOwnerId: string, hes: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n return Promise.all(\n hes.map((he) =>\n this.crypto\n .extractKeysFromDelegationsForHcpHierarchy(dataOwnerId, he.id!, _.size(he.encryptionKeys) ? he.encryptionKeys! : he.delegations!)\n .then(({ extractedKeys: sfks }) => {\n if (!sfks || !sfks.length) {\n console.log('Cannot decrypt helement', he.id)\n return Promise.resolve(he)\n }\n if (he.encryptedSelf) {\n return this.crypto.AES.importKey('raw', hex2ua(sfks[0].replace(/-/g, ''))).then(\n (key) =>\n new Promise((resolve: (value: any) => any) =>\n this.crypto.AES.decrypt(key, string2ua(a2b(he.encryptedSelf!))).then(\n (dec) => {\n let jsonContent\n try {\n jsonContent = dec && ua2utf8(dec)\n jsonContent && _.assign(he, JSON.parse(jsonContent))\n } catch (e) {\n console.log('Cannot parse he', he.id, jsonContent || '<- Invalid encoding')\n }\n resolve(he)\n },\n () => {\n console.log('Cannot decrypt health element', he.id)\n resolve(he)\n }\n )\n )\n )\n } else {\n return Promise.resolve(he)\n }\n })\n )\n )\n }\n\n filterHealthElementsBy(startDocumentId?: string, limit?: number, body?: FilterChainHealthElement): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n filterByWithUser(\n user: models.User,\n startDocumentId?: string,\n limit?: number,\n body?: FilterChainHealthElement\n ): Promise<PaginatedListHealthElement> {\n return super\n .filterHealthElementsBy(startDocumentId, limit, body)\n .then((pl) => this.decryptWithUser(user, pl.rows!).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n // noinspection JSUnusedGlobalSymbols\n serviceToHealthElement(user: models.User, patient: models.Patient, heSvc: models.Service, descr: string) {\n return this.newInstance(user, patient, {\n idService: heSvc.id,\n author: heSvc.author,\n responsible: heSvc.responsible,\n openingDate: heSvc.valueDate || heSvc.openingDate,\n descr: descr,\n idOpeningContact: heSvc.contactId,\n modified: heSvc.modified,\n created: heSvc.created,\n codes: heSvc.codes,\n tags: heSvc.tags,\n }).then((he) => {\n return this.createHealthElement(he)\n })\n }\n\n // noinspection JSUnusedGlobalSymbols, JSMethodCanBeStatic\n stringToCode(code: string) {\n const c = code.split('|')\n return new models.Code({\n type: c[0],\n code: c[1],\n version: c[2],\n id: code,\n })\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"icc-helement-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-helement-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAA2C;AAG3C,kDAAiD;AAEjD,4BAA2B;AAC3B,iCAAgC;AAGhC,0EAAgG;AAGhG,MAAa,eAAgB,SAAQ,wBAAc;IAMjD,YACE,IAAY,EACZ,OAAkC,EAClC,MAAqB,EACrB,YAA8B,EAC9B,gBAA+B,CAAC,OAAO,EAAE,MAAM,CAAC,EAChD,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,C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,CAAC,CAAC,CAAC,CAAC;YACV,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;YACb,EAAE,EAAE,IAAI;SACT,CAAC,CAAA;IACJ,CAAC;IAED;;;;OAIG;IACG,kBAAkB,CAAC,aAAmC;;YAC1D,OAAO,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAAC,aAAa,EAAE,SAAS,CAAC,CAAA;QACzE,CAAC;KAAA;IAED;;;;;;;;;;;;OAYG;IACG,SAAS,CACb,UAAkB,EAClB,aAAmC,EACnC,UAGI,EAAE;;YAEN,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAA;YAC5D,OAAO,MAAM,IAAI,CAAC,QAAQ,CACxB,IAAI,EACJ,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,uCAAuC,CAChE,aAAa,EACb,UAAU,EACV,SAAS,EACT,OAAO,CAAC,kBAAkB,EAC1B,OAAO,CAAC,cAAc,CACvB,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA5XD,0CA4XC","sourcesContent":["import { IccHelementApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as models from '../icc-api/model/models'\n\nimport * as _ from 'lodash'\nimport * as moment from 'moment'\nimport { FilterChainHealthElement, HealthElement, PaginatedListHealthElement } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\n\nexport class IccHelementXApi extends IccHelementApi {\n crypto: IccCryptoXApi\n dataOwnerApi: IccDataOwnerXApi\n\n private readonly encryptedKeys: Array<string>\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n crypto: IccCryptoXApi,\n dataOwnerApi: IccDataOwnerXApi,\n encryptedKeys: Array<string> = ['descr', 'note'],\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.crypto = crypto\n this.dataOwnerApi = dataOwnerApi\n this.encryptedKeys = encryptedKeys\n }\n\n /**\n * Creates a new instance of health element with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this health element refers to.\n * @param h initialised data for the health element. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify\n * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.\n * @param options optional parameters:\n * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the\n * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with\n * auto-delegations, in such case the access level specified here will be used. Currently only WRITE access is supported, but in future also read\n * access will be possible.\n * - preferredSfk: secret id of the patient to use as the secret foreign key to use for the classification. The default value will be a\n * secret id of patient known by the topmost parent in the current data owner hierarchy.\n * - confidential: if true, the entity will be created as confidential. Confidential entities are not shared with auto-delegations, and the default\n * foreign key used is any key that is not shared with any of the data owner parents. By default entities are created as non-confidential.\n * @return a new instance of health element.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient,\n h: any,\n options: {\n additionalDelegates?: { [dataOwnerId: string]: 'WRITE' }\n preferredSfk?: string\n confidential?: boolean\n } = {}\n ) {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n const helement = _.assign(\n {\n id: this.crypto.primitives.randomUuid(),\n _type: 'org.taktik.icure.entities.HealthElement',\n created: new Date().getTime(),\n modified: new Date().getTime(),\n responsible: dataOwnerId,\n author: user.id,\n codes: [],\n tags: [],\n healthElementId: this.crypto.primitives.randomUuid(),\n openingDate: parseInt(moment().format('YYYYMMDDHHmmss')),\n },\n h || {}\n )\n\n const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) throw new Error('Can only initialise entities as current data owner.')\n const sfk =\n options.preferredSfk ??\n (!!options.confidential\n ? await this.crypto.confidential.getConfidentialSecretId(patient)\n : await this.crypto.confidential.getAnySecretIdSharedWithParents(patient))\n if (!sfk) throw new Error(`Couldn't find any sfk of parent patient ${patient.id} for confidential=${!!options.confidential}`)\n const extraDelegations = [\n ...Object.keys(options.additionalDelegates ?? {}),\n ...(options.confidential ? [] : [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])]),\n ]\n const initialisationInfo = await this.crypto.entities.entityWithInitialisedEncryptedMetadata(helement, patient.id, sfk, true, extraDelegations)\n return new models.HealthElement(initialisationInfo.updatedEntity)\n }\n\n createHealthElement(body?: models.HealthElement): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n createHealthElementWithUser(user: models.User, body?: models.HealthElement): Promise<models.HealthElement | any> {\n return body\n ? this.encrypt(user, [_.cloneDeep(body)])\n .then((hes) => super.createHealthElement(hes[0]))\n .then((he) => this.decryptWithUser(user, [he]))\n .then((hes) => hes[0])\n : Promise.resolve(null)\n }\n\n createHealthElements(body?: Array<HealthElement>): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n createHealthElementsWithUser(user: models.User, bodies?: models.HealthElement[]): Promise<models.HealthElement[] | any> {\n return bodies\n ? this.encrypt(\n user,\n bodies.map((c) => _.cloneDeep(c))\n )\n .then((hes) => super.createHealthElements(hes))\n .then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), hes))\n : Promise.resolve(null)\n }\n\n getHealthElement(healthElementId: string): never {\n throw new Error('Cannot call a method that returns health element without providing a user for de/encryption')\n }\n\n getHealthElementWithUser(user: models.User, healthElementId: string): Promise<models.HealthElement> {\n return super\n .getHealthElement(healthElementId)\n .then((he) => this.decryptWithUser(user, [he]))\n .then((hes) => hes[0])\n }\n\n getHealthElements(body?: models.ListOfIds): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n getHealthElementsWithUser(user: models.User, body?: models.ListOfIds): Promise<models.HealthElement[]> {\n return super.getHealthElements(body).then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), hes))\n }\n\n newHealthElementDelegations(healthElementId: string, body?: Array<models.Delegation>): never {\n throw new Error('Cannot call a method that returns health element without providing a user for de/encryption')\n }\n\n newHealthElementDelegationsWithUser(user: models.User, healthElementId: string, body?: Array<models.Delegation>): Promise<models.HealthElement> {\n return super\n .newHealthElementDelegations(healthElementId, body)\n .then((he) => this.decryptWithUser(user, [he]))\n .then((he) => he[0])\n }\n\n findHealthElementsByHCPartyPatientForeignKeys(hcPartyId: string, secretFKeys: string): never {\n throw new Error('Cannot call a method that returns health element without providing a user for de/encryption')\n }\n\n findHealthElementsByHCPartyPatientForeignKeysWithUser(user: models.User, hcPartyId: string, secretFKeys: string): Promise<HealthElement[]> {\n return super.findHealthElementsByHCPartyPatientForeignKeys(hcPartyId, secretFKeys).then((hes) => this.decryptWithUser(user, hes))\n }\n\n findHealthElementsByHCPartyPatientForeignKeysArrayWithUser(user: models.User, hcPartyId: string, secretFKeys: string[]): Promise<HealthElement[]> {\n return super.findHealthElementsByHCPartyPatientForeignKeysUsingPost(hcPartyId, secretFKeys).then((hes) => this.decryptWithUser(user, hes))\n }\n\n async findHealthElementsByHCPartyAndPatientWithUser(\n user: models.User,\n hcPartyId: string,\n patient: models.Patient,\n usingPost: boolean = false\n ): Promise<models.HealthElement[]> {\n let keysAndHcPartyId = await this.crypto.entities.secretIdsForHcpHierarchyOf(patient)\n const keys = keysAndHcPartyId.find((secretForeignKeys) => secretForeignKeys.ownerId == hcPartyId)?.extracted\n if (keys == undefined) {\n throw Error('No delegation for user')\n }\n return usingPost\n ? this.findHealthElementsByHCPartyPatientForeignKeysArrayWithUser(user, hcPartyId, keys)\n : this.findHealthElementsByHCPartyPatientForeignKeysWithUser(user, hcPartyId, keys.join(','))\n }\n\n modifyHealthElement(body?: HealthElement): never {\n throw new Error('Cannot call a method that returns health element without providing a user for de/encryption')\n }\n\n modifyHealthElementWithUser(user: models.User, body?: HealthElement): Promise<HealthElement | any> {\n return body ? this.modifyAs(this.dataOwnerApi.getDataOwnerIdOf(user), body) : Promise.resolve(null)\n }\n private modifyAs(dataOwner: string, body: HealthElement): Promise<HealthElement | any> {\n return this.encryptAs(dataOwner, [_.cloneDeep(body)])\n .then((hes) => super.modifyHealthElement(hes[0]))\n .then((he) => this.decrypt(dataOwner, [he]))\n .then((hes) => hes[0])\n }\n\n modifyHealthElements(body?: Array<HealthElement>): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n modifyHealthElementsWithUser(user: models.User, bodies?: HealthElement[]): Promise<HealthElement[] | any> {\n return bodies\n ? this.encrypt(\n user,\n bodies.map((c) => _.cloneDeep(c))\n )\n .then((hes) => super.modifyHealthElements(hes))\n .then((hes) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), hes))\n : Promise.resolve(null)\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * 1. Check whether there is a delegation with 'hcpartyId' or not.\n * 2. 'fetchHcParty[hcpartyId][1]': is encrypted AES exchange key by RSA public key of him.\n * 3. Obtain the AES exchange key, by decrypting the previous step value with hcparty private key\n * 3.1. KeyPair should be fetch from cache (in jwk)\n * 3.2. if it doesn't exist in the cache, it has to be loaded from Browser Local store, and then import it to WebCrypto\n * 4. Obtain the array of delegations which are delegated to his ID (hcpartyId) in this patient\n * 5. Decrypt and collect all keys (secretForeignKeys) within delegations of previous step (with obtained AES key of step 4)\n * 6. Do the REST call to get all helements with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the helements of the patient.\n *\n * @param hcpartyId\n * @param patient (Promise)\n * @param keepObsoleteVersions\n * @param usingPost\n */\n\n findBy(hcpartyId: string, patient: models.Patient, keepObsoleteVersions = false, usingPost = false) {\n return this.crypto.entities\n .secretIdsForHcpHierarchyOf(patient)\n .then((secretForeignKeys) =>\n secretForeignKeys && secretForeignKeys.length > 0\n ? Promise.all(\n secretForeignKeys\n .reduce((acc, level) => {\n return acc.concat([\n {\n hcpartyId: level.ownerId,\n extractedKeys: level.extracted.filter((key) => !acc.some((previousLevel) => previousLevel.extractedKeys.includes(key))),\n },\n ])\n }, [] as Array<{ hcpartyId: string; extractedKeys: Array<string> }>)\n .filter((l) => l.extractedKeys.length > 0)\n .map(({ hcpartyId, extractedKeys }) =>\n usingPost\n ? this.findByHCPartyPatientSecretFKeysArray(hcpartyId, _.uniq(extractedKeys))\n : this.findByHCPartyPatientSecretFKeys(hcpartyId, _.uniq(extractedKeys).join(','))\n )\n ).then((results) => _.uniqBy(_.flatMap(results), (x) => x.id))\n : Promise.resolve([])\n )\n .then((decryptedHelements: Array<models.HealthElement>) => {\n const byIds: { [key: string]: models.HealthElement } = {}\n\n if (keepObsoleteVersions) {\n return decryptedHelements\n } else {\n decryptedHelements.forEach((he) => {\n if (he.healthElementId) {\n const phe = byIds[he.healthElementId]\n if (!phe || !phe.modified || (he.modified && phe.modified < he.modified)) {\n byIds[he.healthElementId] = he\n }\n }\n })\n return _.values(byIds).filter((s: any) => !s.endOfLife)\n }\n })\n }\n\n findByHCPartyPatientSecretFKeys(hcPartyId: string, secretFKeys: string): Promise<Array<models.Contact> | any> {\n return super.findHealthElementsByHCPartyPatientForeignKeys(hcPartyId, secretFKeys).then((helements) => this.decrypt(hcPartyId, helements))\n }\n\n findByHCPartyPatientSecretFKeysArray(hcPartyId: string, secretFKeys: string[]): Promise<Array<models.Contact> | any> {\n return super\n .findHealthElementsByHCPartyPatientForeignKeysUsingPost(hcPartyId, secretFKeys)\n .then((helements) => this.decrypt(hcPartyId, helements))\n }\n\n encrypt(user: models.User, healthElements: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n return this.encryptAs(this.dataOwnerApi.getDataOwnerIdOf(user), healthElements)\n }\n\n private encryptAs(owner: string, healthElements: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n return Promise.all(\n healthElements.map((he) =>\n this.crypto.entities.tryEncryptEntity(he, owner, this.encryptedKeys, false, true, (x) => new models.HealthElement(x))\n )\n )\n }\n\n decryptWithUser(user: models.User, hes: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n return this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user), hes)\n }\n\n decrypt(dataOwnerId: string, hes: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n return Promise.all(\n hes.map((he) => this.crypto.entities.decryptEntity(he, dataOwnerId, (x) => new models.HealthElement(x)).then(({ entity }) => entity))\n )\n }\n\n filterHealthElementsBy(startDocumentId?: string, limit?: number, body?: FilterChainHealthElement): never {\n throw new Error('Cannot call a method that returns health elements without providing a user for de/encryption')\n }\n\n filterByWithUser(\n user: models.User,\n startDocumentId?: string,\n limit?: number,\n body?: FilterChainHealthElement\n ): Promise<PaginatedListHealthElement> {\n return super\n .filterHealthElementsBy(startDocumentId, limit, body)\n .then((pl) => this.decryptWithUser(user, pl.rows!).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n // noinspection JSUnusedGlobalSymbols\n serviceToHealthElement(user: models.User, patient: models.Patient, heSvc: models.Service, descr: string) {\n return this.newInstance(user, patient, {\n idService: heSvc.id,\n author: heSvc.author,\n responsible: heSvc.responsible,\n openingDate: heSvc.valueDate || heSvc.openingDate,\n descr: descr,\n idOpeningContact: heSvc.contactId,\n modified: heSvc.modified,\n created: heSvc.created,\n codes: heSvc.codes,\n tags: heSvc.tags,\n }).then((he) => {\n return this.createHealthElement(he)\n })\n }\n\n // noinspection JSUnusedGlobalSymbols, JSMethodCanBeStatic\n stringToCode(code: string) {\n const c = code.split('|')\n return new models.Code({\n type: c[0],\n code: c[1],\n version: c[2],\n id: code,\n })\n }\n\n /**\n * @param healthElement a health element\n * @return the id of the patient that the health element refers to, retrieved from the encrypted metadata. Normally there should only be one element\n * in the returned array, but in case of entity merges there could be multiple values.\n */\n async decryptPatientIdOf(healthElement: models.HealthElement): Promise<string[]> {\n return this.crypto.entities.owningEntityIdsOf(healthElement, undefined)\n }\n\n /**\n * Share an existing health element with other data owners, allowing them to access the non-encrypted data of the health element and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param delegateId the id of the data owner which will be granted access to the health element.\n * @param healthElement the health element to share.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * health element does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this health element refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * @return a promise which will contain the updated health element.\n */\n async shareWith(\n delegateId: string,\n healthElement: models.HealthElement,\n options: {\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.HealthElement> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n return await this.modifyAs(\n self,\n await this.crypto.entities.entityWithAutoExtendedEncryptedMetadata(\n healthElement,\n delegateId,\n undefined,\n options.shareEncryptionKey,\n options.sharePatientId\n )\n )\n }\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { KeyPair } from './crypto/RSA';
|
|
2
|
+
import { IccMaintenanceTaskXApi } from './icc-maintenance-task-x-api';
|
|
3
|
+
import { IccCryptoXApi } from './icc-crypto-x-api';
|
|
4
|
+
import { KeyPairUpdateRequest } from './maintenance/KeyPairUpdateRequest';
|
|
5
|
+
import { IccDataOwnerXApi } from './icc-data-owner-x-api';
|
|
6
|
+
import { User } from '../icc-api/model/User';
|
|
7
|
+
/**
|
|
8
|
+
* Api for interpreting maintenance tasks and applying required client-side actions.
|
|
9
|
+
*/
|
|
10
|
+
export declare class IccIcureMaintenanceXApi {
|
|
11
|
+
private readonly crypto;
|
|
12
|
+
private readonly tasksApi;
|
|
13
|
+
private readonly dataOwnerApi;
|
|
14
|
+
constructor(crypto: IccCryptoXApi, tasksApi: IccMaintenanceTaskXApi, dataOwnerApi: IccDataOwnerXApi);
|
|
15
|
+
/**
|
|
16
|
+
* Applies a key pair update request between another data owner and the current data owner to allow the other data owner to access existing exchange
|
|
17
|
+
* keys shared with the current data owner. IMPORTANT: it is your responsibility to verify the authenticity of the public key / update request
|
|
18
|
+
* before calling this method: this method assumes the new public key for the concerned data owner is authentic.
|
|
19
|
+
* @param update a keypair update request to the current data owner.
|
|
20
|
+
*/
|
|
21
|
+
applyKeyPairUpdate(update: KeyPairUpdateRequest): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* @internal This method is intended only for internal use and may be changed without notice.
|
|
24
|
+
* Creates the necessary maintenance tasks to request access to existing exchange keys with the new key pair for the current user.
|
|
25
|
+
* @param user the user which owns the new key pair.
|
|
26
|
+
* @param keypair a new key pair for the current user.
|
|
27
|
+
*/
|
|
28
|
+
createMaintenanceTasksForNewKeypair(user: User, keypair: KeyPair<CryptoKey>): Promise<void>;
|
|
29
|
+
private getExchangeKeysInfosOf;
|
|
30
|
+
private createMaintenanceTask;
|
|
31
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
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.IccIcureMaintenanceXApi = void 0;
|
|
13
|
+
const MaintenanceTask_1 = require("../icc-api/model/MaintenanceTask");
|
|
14
|
+
const utils_1 = require("./utils");
|
|
15
|
+
const PropertyStub_1 = require("../icc-api/model/PropertyStub");
|
|
16
|
+
const PropertyTypeStub_1 = require("../icc-api/model/PropertyTypeStub");
|
|
17
|
+
const TypedValueObject_1 = require("../icc-api/model/TypedValueObject");
|
|
18
|
+
const KeyPairUpdateRequest_1 = require("./maintenance/KeyPairUpdateRequest");
|
|
19
|
+
const icc_data_owner_x_api_1 = require("./icc-data-owner-x-api");
|
|
20
|
+
/**
|
|
21
|
+
* Api for interpreting maintenance tasks and applying required client-side actions.
|
|
22
|
+
*/
|
|
23
|
+
class IccIcureMaintenanceXApi {
|
|
24
|
+
constructor(crypto, tasksApi, dataOwnerApi) {
|
|
25
|
+
this.crypto = crypto;
|
|
26
|
+
this.tasksApi = tasksApi;
|
|
27
|
+
this.dataOwnerApi = dataOwnerApi;
|
|
28
|
+
}
|
|
29
|
+
// TODO api to get all tasks for current owner from owner with id
|
|
30
|
+
/**
|
|
31
|
+
* Applies a key pair update request between another data owner and the current data owner to allow the other data owner to access existing exchange
|
|
32
|
+
* keys shared with the current data owner. IMPORTANT: it is your responsibility to verify the authenticity of the public key / update request
|
|
33
|
+
* before calling this method: this method assumes the new public key for the concerned data owner is authentic.
|
|
34
|
+
* @param update a keypair update request to the current data owner.
|
|
35
|
+
*/
|
|
36
|
+
applyKeyPairUpdate(update) {
|
|
37
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
38
|
+
yield this.crypto.exchangeKeys.base.giveAccessBackTo(update.concernedDataOwnerId, update.newPublicKey, this.crypto.userKeysManager.getDecryptionKeys());
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* @internal This method is intended only for internal use and may be changed without notice.
|
|
43
|
+
* Creates the necessary maintenance tasks to request access to existing exchange keys with the new key pair for the current user.
|
|
44
|
+
* @param user the user which owns the new key pair.
|
|
45
|
+
* @param keypair a new key pair for the current user.
|
|
46
|
+
*/
|
|
47
|
+
createMaintenanceTasksForNewKeypair(user, keypair) {
|
|
48
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
49
|
+
const currentUserType = yield this.dataOwnerApi.getCurrentDataOwnerType();
|
|
50
|
+
if (currentUserType === icc_data_owner_x_api_1.DataOwnerTypeEnum.Device) {
|
|
51
|
+
console.warn('Current data owner is a device and there is no need to create maintenance tasks for updated keypair.');
|
|
52
|
+
}
|
|
53
|
+
else if (currentUserType === icc_data_owner_x_api_1.DataOwnerTypeEnum.Patient || currentUserType === icc_data_owner_x_api_1.DataOwnerTypeEnum.Hcp) {
|
|
54
|
+
const requestsToOwnerTypes = currentUserType === icc_data_owner_x_api_1.DataOwnerTypeEnum.Patient ? [icc_data_owner_x_api_1.DataOwnerTypeEnum.Patient, icc_data_owner_x_api_1.DataOwnerTypeEnum.Hcp] : [icc_data_owner_x_api_1.DataOwnerTypeEnum.Hcp];
|
|
55
|
+
const hexNewPubKey = (0, utils_1.ua2hex)(yield this.crypto.primitives.RSA.exportKey(keypair.publicKey, 'spki'));
|
|
56
|
+
const hexNewPubKeyFp = hexNewPubKey.slice(-32);
|
|
57
|
+
const selfId = yield this.dataOwnerApi.getCurrentDataOwnerId();
|
|
58
|
+
const keysInfo = yield this.getExchangeKeysInfosOf(selfId, requestsToOwnerTypes);
|
|
59
|
+
const requestDataOwners = keysInfo
|
|
60
|
+
.filter((info) => !info.fingerprints.has(hexNewPubKeyFp))
|
|
61
|
+
.flatMap((info) => [info.delegate, info.delegator])
|
|
62
|
+
.filter((dataOwner) => dataOwner !== selfId);
|
|
63
|
+
if (requestDataOwners.length > 0) {
|
|
64
|
+
const tasksToCreate = requestDataOwners.map((dataOwner) => ({
|
|
65
|
+
delegate: dataOwner,
|
|
66
|
+
task: this.createMaintenanceTask(selfId, hexNewPubKey),
|
|
67
|
+
}));
|
|
68
|
+
for (const taskToCreate of tasksToCreate) {
|
|
69
|
+
const instance = yield this.tasksApi.newInstance(user, taskToCreate.task, { additionalDelegates: { [taskToCreate.delegate]: 'WRITE' } });
|
|
70
|
+
if (instance) {
|
|
71
|
+
// TODO create in bulk
|
|
72
|
+
yield this.tasksApi.createMaintenanceTaskWithUser(user, instance);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
else
|
|
78
|
+
throw new Error(`Unknown data owner type for current user ${currentUserType}`);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
getExchangeKeysInfosOf(dataOwnerId, otherOwnerTypes) {
|
|
82
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
83
|
+
const allExchangeKeys = yield this.crypto.exchangeKeys.base.getAllExchangeKeysWith(dataOwnerId, otherOwnerTypes);
|
|
84
|
+
const infoTo = Object.entries(allExchangeKeys.keysToOwner).flatMap(([delegatorId, delegatorFpToKeys]) => Object.values(delegatorFpToKeys).map((encryptedKeys) => ({
|
|
85
|
+
delegator: delegatorId,
|
|
86
|
+
delegate: dataOwnerId,
|
|
87
|
+
fingerprints: new Set(Object.keys(encryptedKeys).map((x) => x.slice(-32))),
|
|
88
|
+
})));
|
|
89
|
+
const infoFrom = Object.values(allExchangeKeys.keysFromOwner).flatMap((delegateIdToKeys) => Object.entries(delegateIdToKeys).map(([delegateId, encryptedKeys]) => ({
|
|
90
|
+
delegator: dataOwnerId,
|
|
91
|
+
delegate: delegateId,
|
|
92
|
+
fingerprints: new Set(Object.keys(encryptedKeys).map((x) => x.slice(-32))),
|
|
93
|
+
})));
|
|
94
|
+
return [...infoFrom, ...infoTo];
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
createMaintenanceTask(ownerId, concernedPubKey) {
|
|
98
|
+
return new MaintenanceTask_1.MaintenanceTask({
|
|
99
|
+
id: this.crypto.primitives.randomUuid(),
|
|
100
|
+
taskType: KeyPairUpdateRequest_1.KeyPairUpdateRequest.TASK_TYPE,
|
|
101
|
+
status: MaintenanceTask_1.MaintenanceTask.StatusEnum.Pending,
|
|
102
|
+
properties: [
|
|
103
|
+
new PropertyStub_1.PropertyStub({
|
|
104
|
+
id: KeyPairUpdateRequest_1.KeyPairUpdateRequest.OWNER_ID_PROP_ID,
|
|
105
|
+
type: new PropertyTypeStub_1.PropertyTypeStub({ type: PropertyTypeStub_1.PropertyTypeStub.TypeEnum.STRING }),
|
|
106
|
+
typedValue: new TypedValueObject_1.TypedValueObject({
|
|
107
|
+
type: TypedValueObject_1.TypedValueObject.TypeEnum.STRING,
|
|
108
|
+
stringValue: ownerId,
|
|
109
|
+
}),
|
|
110
|
+
}),
|
|
111
|
+
new PropertyStub_1.PropertyStub({
|
|
112
|
+
id: KeyPairUpdateRequest_1.KeyPairUpdateRequest.OWNER_PUB_PROP_ID,
|
|
113
|
+
type: new PropertyTypeStub_1.PropertyTypeStub({ type: PropertyTypeStub_1.PropertyTypeStub.TypeEnum.STRING }),
|
|
114
|
+
typedValue: new TypedValueObject_1.TypedValueObject({
|
|
115
|
+
type: TypedValueObject_1.TypedValueObject.TypeEnum.STRING,
|
|
116
|
+
stringValue: concernedPubKey,
|
|
117
|
+
}),
|
|
118
|
+
}),
|
|
119
|
+
],
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
exports.IccIcureMaintenanceXApi = IccIcureMaintenanceXApi;
|
|
124
|
+
//# sourceMappingURL=icc-icure-maintenance-x-api.js.map
|