@icure/api 8.0.79 → 8.1.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-x-api/crypto/ExtendedApisUtils.d.ts +47 -2
- package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +8 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +81 -2
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/icc-x-api/crypto/SecretIdUseOption.d.ts +60 -0
- package/icc-x-api/crypto/SecretIdUseOption.js +60 -0
- package/icc-x-api/crypto/SecretIdUseOption.js.map +1 -0
- package/icc-x-api/icc-accesslog-x-api.d.ts +2 -1
- package/icc-x-api/icc-accesslog-x-api.js +2 -3
- package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
- package/icc-x-api/icc-calendar-item-x-api.d.ts +26 -3
- package/icc-x-api/icc-calendar-item-x-api.js +51 -16
- package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
- package/icc-x-api/icc-classification-x-api.d.ts +2 -1
- package/icc-x-api/icc-classification-x-api.js +2 -3
- package/icc-x-api/icc-classification-x-api.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.d.ts +3 -2
- package/icc-x-api/icc-contact-x-api.js +5 -8
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/icc-crypto-x-api.d.ts +1 -7
- package/icc-x-api/icc-crypto-x-api.js +1 -8
- package/icc-x-api/icc-crypto-x-api.js.map +1 -1
- package/icc-x-api/icc-document-x-api.d.ts +2 -1
- package/icc-x-api/icc-document-x-api.js +3 -6
- package/icc-x-api/icc-document-x-api.js.map +1 -1
- package/icc-x-api/icc-form-x-api.d.ts +2 -1
- package/icc-x-api/icc-form-x-api.js +2 -3
- package/icc-x-api/icc-form-x-api.js.map +1 -1
- package/icc-x-api/icc-helement-x-api.d.ts +3 -2
- package/icc-x-api/icc-helement-x-api.js +5 -8
- package/icc-x-api/icc-helement-x-api.js.map +1 -1
- package/icc-x-api/icc-invoice-x-api.d.ts +2 -1
- package/icc-x-api/icc-invoice-x-api.js +2 -3
- package/icc-x-api/icc-invoice-x-api.js.map +1 -1
- package/icc-x-api/icc-message-x-api.d.ts +2 -1
- package/icc-x-api/icc-message-x-api.js +2 -3
- package/icc-x-api/icc-message-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.js +4 -6
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/icc-x-api/icc-topic-x-api.d.ts +2 -1
- package/icc-x-api/icc-topic-x-api.js +3 -2
- package/icc-x-api/icc-topic-x-api.js.map +1 -1
- package/icc-x-api/index.js +1 -3
- package/icc-x-api/index.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-x-api/confidential-entities-test.js +49 -6
- package/test/icc-x-api/confidential-entities-test.js.map +1 -1
- package/test/icc-x-api/crypto/cryptoTest.js +5 -3
- package/test/icc-x-api/crypto/cryptoTest.js.map +1 -1
- package/test/icc-x-api/crypto/full-crypto-test.js +0 -2
- package/test/icc-x-api/crypto/full-crypto-test.js.map +1 -1
- package/test/icc-x-api/crypto/shamir.js +3 -1
- package/test/icc-x-api/crypto/shamir.js.map +1 -1
- package/test/icc-x-api/icc-calendar-item-x-api.js +1 -1
- package/test/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
- package/test/icc-x-api/icc-contact-x-api.js +4 -2
- package/test/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/test/icc-x-api/icc-helement-x-api-test.js +3 -1
- package/test/icc-x-api/icc-helement-x-api-test.js.map +1 -1
- package/icc-x-api/crypto/ConfidentialEntities.d.ts +0 -64
- package/icc-x-api/crypto/ConfidentialEntities.js +0 -112
- package/icc-x-api/crypto/ConfidentialEntities.js.map +0 -1
|
@@ -16,6 +16,7 @@ import { SubscriptionOptions } from './utils';
|
|
|
16
16
|
import { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi';
|
|
17
17
|
import { AbstractFilter } from './filters/filters';
|
|
18
18
|
import { Connection } from '../icc-api/model/Connection';
|
|
19
|
+
import { SecretIdUseOption } from './crypto/SecretIdUseOption';
|
|
19
20
|
export declare class IccHelementXApi extends IccHelementApi implements EncryptedEntityXApi<models.HealthElement> {
|
|
20
21
|
private readonly crypto;
|
|
21
22
|
private readonly dataOwnerApi;
|
|
@@ -48,8 +49,8 @@ export declare class IccHelementXApi extends IccHelementApi implements Encrypted
|
|
|
48
49
|
additionalDelegates?: {
|
|
49
50
|
[dataOwnerId: string]: AccessLevelEnum;
|
|
50
51
|
};
|
|
51
|
-
|
|
52
|
-
|
|
52
|
+
sfkOption?: SecretIdUseOption;
|
|
53
|
+
ignoreAutoDelegations?: boolean;
|
|
53
54
|
}): Promise<models.HealthElement>;
|
|
54
55
|
createHealthElement(body?: models.HealthElement): never;
|
|
55
56
|
createHealthElementWithUser(user: models.User, body?: models.HealthElement): Promise<models.HealthElement | any>;
|
|
@@ -19,6 +19,7 @@ const SecureDelegation_1 = require("../icc-api/model/SecureDelegation");
|
|
|
19
19
|
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
|
|
20
20
|
const utils_1 = require("./utils");
|
|
21
21
|
const Connection_1 = require("../icc-api/model/Connection");
|
|
22
|
+
const SecretIdUseOption_1 = require("./crypto/SecretIdUseOption");
|
|
22
23
|
class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
23
24
|
get headers() {
|
|
24
25
|
return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, utils_1.EntityWithDelegationTypeName.HealthElement));
|
|
@@ -54,21 +55,17 @@ class IccHelementXApi extends icc_api_1.IccHelementApi {
|
|
|
54
55
|
* @return a new instance of health element.
|
|
55
56
|
*/
|
|
56
57
|
newInstance(user, patient, h, options = {}) {
|
|
57
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q
|
|
58
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
|
|
58
59
|
return __awaiter(this, void 0, void 0, function* () {
|
|
59
60
|
const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user);
|
|
60
61
|
const helement = Object.assign(Object.assign({}, (h !== null && h !== void 0 ? h : {})), { _type: 'org.taktik.icure.entities.HealthElement', id: (_a = h === null || h === void 0 ? void 0 : h.id) !== null && _a !== void 0 ? _a : this.crypto.primitives.randomUuid(), created: (_b = h === null || h === void 0 ? void 0 : h.created) !== null && _b !== void 0 ? _b : new Date().getTime(), modified: (_c = h === null || h === void 0 ? void 0 : h.modified) !== null && _c !== void 0 ? _c : new Date().getTime(), responsible: (_d = h === null || h === void 0 ? void 0 : h.responsible) !== null && _d !== void 0 ? _d : (this.autofillAuthor ? dataOwnerId : undefined), author: (_e = h === null || h === void 0 ? void 0 : h.author) !== null && _e !== void 0 ? _e : (this.autofillAuthor ? user.id : undefined), codes: (_f = h === null || h === void 0 ? void 0 : h.codes) !== null && _f !== void 0 ? _f : [], tags: (_g = h === null || h === void 0 ? void 0 : h.tags) !== null && _g !== void 0 ? _g : [], healthElementId: (_h = h === null || h === void 0 ? void 0 : h.healthElementId) !== null && _h !== void 0 ? _h : this.crypto.primitives.randomUuid(), openingDate: (_j = h === null || h === void 0 ? void 0 : h.openingDate) !== null && _j !== void 0 ? _j : parseInt(moment().format('YYYYMMDDHHmmss')) });
|
|
61
62
|
const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user);
|
|
62
63
|
if (ownerId !== (yield this.dataOwnerApi.getCurrentDataOwnerId()))
|
|
63
64
|
throw new Error('Can only initialise entities as current data owner.');
|
|
64
|
-
const sfk = (_k = options.
|
|
65
|
-
|
|
66
|
-
: yield this.crypto.confidential.getAnySecretIdSharedWithParents({ entity: patient, type: utils_1.EntityWithDelegationTypeName.Patient }));
|
|
67
|
-
if (!sfk)
|
|
68
|
-
throw new Error(`Couldn't find any sfk of parent patient ${patient.id} for confidential=${(_l = options === null || options === void 0 ? void 0 : options.confidential) !== null && _l !== void 0 ? _l : false}`);
|
|
69
|
-
const extraDelegations = Object.assign(Object.assign({}, (options.confidential
|
|
65
|
+
const sfk = yield this.crypto.xapi.resolveSecretIdUseOptions({ entity: patient, type: utils_1.EntityWithDelegationTypeName.Patient }, (_k = options.sfkOption) !== null && _k !== void 0 ? _k : SecretIdUseOption_1.SecretIdUseOption.UseAnySharedWithParent);
|
|
66
|
+
const extraDelegations = Object.assign(Object.assign({}, (options.ignoreAutoDelegations
|
|
70
67
|
? {}
|
|
71
|
-
: Object.fromEntries([...((
|
|
68
|
+
: Object.fromEntries([...((_m = (_l = user.autoDelegations) === null || _l === void 0 ? void 0 : _l.all) !== null && _m !== void 0 ? _m : []), ...((_p = (_o = user.autoDelegations) === null || _o === void 0 ? void 0 : _o.medicalInformation) !== null && _p !== void 0 ? _p : [])].map((d) => [d, AccessLevelEnum.WRITE])))), ((_q = options === null || options === void 0 ? void 0 : options.additionalDelegates) !== null && _q !== void 0 ? _q : {}));
|
|
72
69
|
const initialisationInfo = yield this.crypto.xapi.entityWithInitialisedEncryptedMetadata(helement, utils_1.EntityWithDelegationTypeName.HealthElement, patient.id, sfk, true, extraDelegations);
|
|
73
70
|
return new models.HealthElement(initialisationInfo.updatedEntity);
|
|
74
71
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icc-helement-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-helement-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAuD;AAGvD,kDAAiD;AAEjD,4BAA2B;AAC3B,iCAAgC;AAGhC,0EAAgG;AAChG,wEAAoE;AACpE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAOzD,mCAAmJ;AAGnJ,4DAAwE;AAExE,MAAa,eAAgB,SAAQ,wBAAc;IAGjD,IAAI,OAAO;QACT,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EA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E,IAAI,EAAE,oCAA4B,CAAC,aAAa,EAAE,EAAE,SAAS,CAAC,CAAA;IACnH,CAAC;IAEK,8BAA8B,CAClC,UAA8C,EAC9C,MAAiD,EACjD,UAA2D,EAC3D,UAA+B,EAAE;;YAEjC,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,CAAA;YAEvD,OAAO,MAAM,IAAA,+BAAuB,EAClC,IAAI,CAAC,IAAI,EACT,IAAI,CAAC,OAAO,EACZ,oCAA4B,CAAC,aAAa,EAC1C,UAAU,EACV,MAAM,EACN,UAAU,EACV,OAAO,EACP,CAAO,SAAS,EAAE,EAAE,gDAAC,OAAA,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,WAAW,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA,GAAA,CAC3G,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAAC,CAAA;QACxC,CAAC;KAAA;IAED,uCAAuC,CAAC,MAAqB,EAAE,SAAmB;QAChF,OAAO,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAC,iCAAiC,CAC7E,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,aAAa,EAAE,EAC5D,SAAS,CACV,CAAA;IACH,CAAC;CACF;AAxhBD,0CAwhBC","sourcesContent":["import { IccAuthApi, 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 { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { XHR } from '../icc-api/api/XHR'\nimport { IccUserXApi } from './icc-user-x-api'\nimport { EncryptedFieldsManifest, EntityWithDelegationTypeName, parseEncryptedFields, subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { AbstractFilter } from './filters/filters'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\n\nexport class IccHelementXApi extends IccHelementApi implements EncryptedEntityXApi<models.HealthElement> {\n private readonly encryptedFields: EncryptedFieldsManifest\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.HealthElement))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly userApi: IccUserXApi,\n private readonly authApi: IccAuthApi,\n private readonly autofillAuthor: boolean,\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.encryptedFields = parseEncryptedFields(encryptedKeys, 'HealthElement.')\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.\n * - preferredSfk: secret id of the patient to use as the secret foreign key to use for the health element. The default value will be a\n * secret id of patient known by the topmost parent in the current data owner hierarchy if the confidential is set to false, else a secret id that\n * the data owner did not share with any of his parents.\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]: AccessLevelEnum }\n preferredSfk?: string\n confidential?: boolean\n } = {}\n ) {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n const helement = {\n ...(h ?? {}),\n _type: 'org.taktik.icure.entities.HealthElement',\n id: h?.id ?? this.crypto.primitives.randomUuid(),\n created: h?.created ?? new Date().getTime(),\n modified: h?.modified ?? new Date().getTime(),\n responsible: h?.responsible ?? (this.autofillAuthor ? dataOwnerId : undefined),\n author: h?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: h?.codes ?? [],\n tags: h?.tags ?? [],\n healthElementId: h?.healthElementId ?? this.crypto.primitives.randomUuid(),\n openingDate: h?.openingDate ?? parseInt(moment().format('YYYYMMDDHHmmss')),\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({ entity: patient, type: EntityWithDelegationTypeName.Patient })\n : await this.crypto.confidential.getAnySecretIdSharedWithParents({ entity: patient, type: EntityWithDelegationTypeName.Patient }))\n if (!sfk) throw new Error(`Couldn't find any sfk of parent patient ${patient.id} for confidential=${options?.confidential ?? false}`)\n const extraDelegations = {\n ...(options.confidential\n ? {}\n : Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n )),\n ...(options?.additionalDelegates ?? {}),\n }\n const initialisationInfo = await this.crypto.xapi.entityWithInitialisedEncryptedMetadata(\n helement,\n EntityWithDelegationTypeName.HealthElement,\n patient.id,\n sfk,\n true,\n extraDelegations\n )\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 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.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.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.modifyHealthElementAs(this.dataOwnerApi.getDataOwnerIdOf(user), body) : Promise.resolve(null)\n }\n private modifyHealthElementAs(dataOwner: string, body: HealthElement): Promise<HealthElement> {\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 * @deprecated use {@link findIdsBy}.\n * @param hcpartyId\n * @param patient (Promise)\n * @param keepObsoleteVersions\n * @param usingPost\n */\n findBy(hcpartyId: string, patient: models.Patient, keepObsoleteVersions = false, usingPost = false) {\n return this.crypto.xapi\n .secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.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 /**\n * Same as {@link findBy} but it will only return the ids of the health elements. It can also filter the health elements where HealthElement.openingDate is between\n * startDate and endDate in ascending or descending order by that field. (default: ascending).\n */\n async findIdsBy(hcpartyId: string, patient: models.Patient, startDate?: number, endDate?: number, descending?: boolean) {\n return this.crypto.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }).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 this.findHealthElementIdsByDataOwnerPatientOpeningDate(hcpartyId, extractedKeys, startDate, endDate, descending)\n )\n ).then((results) => _.uniq(_.flatMap(results)))\n : Promise.resolve([])\n )\n }\n\n /**\n * @deprecated use {@link findHealthElementIdsByDataOwnerPatientOpeningDate} instead.\n */\n findByHCPartyPatientSecretFKeys(hcPartyId: string, secretFKeys: string): Promise<Array<models.HealthElement> | any> {\n return super.findHealthElementsByHCPartyPatientForeignKeys(hcPartyId, secretFKeys).then((helements) => this.decrypt(hcPartyId, helements))\n }\n\n /**\n * @deprecated use {@link findHealthElementIdsByDataOwnerPatientOpeningDate} instead.\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 this.crypto.xapi.tryEncryptEntities(\n healthElements,\n EntityWithDelegationTypeName.HealthElement,\n this.encryptedFields,\n false,\n false,\n (x) => new models.HealthElement(x)\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 async decrypt(dataOwnerId: string, hes: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n return (await this.crypto.xapi.tryDecryptEntities(hes, EntityWithDelegationTypeName.HealthElement, (x) => new models.HealthElement(x))).map(\n ({ 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.xapi.owningEntityIdsOf({ entity: healthElement, type: EntityWithDelegationTypeName.HealthElement }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given health element\n */\n async hasWriteAccess(healthElement: models.HealthElement): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: healthElement, type: EntityWithDelegationTypeName.HealthElement })\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 * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n healthElement: models.HealthElement,\n options: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.HealthElement> {\n return this.shareWithMany(healthElement, { [delegateId]: options })\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 delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n healthElement: models.HealthElement,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.HealthElement> {\n return (await this.tryShareWithMany(healthElement, delegates)).updatedEntityOrThrow\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 healthElement the health element to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n healthElement: models.HealthElement,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.HealthElement>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(healthElement, EntityWithDelegationTypeName.HealthElement)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyHealthElementAs(self, entityWithEncryptionKey) : healthElement\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.HealthElement,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareHealthElements(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])))\n }\n\n getDataOwnersWithAccessTo(\n entity: models.HealthElement\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.HealthElement })\n }\n\n getEncryptionKeysOf(entity: models.HealthElement): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.HealthElement }, undefined)\n }\n\n async subscribeToHealthElementEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<HealthElement> | undefined,\n eventFired: (healthElement: HealthElement) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n const currentUser = await this.userApi.getCurrentUser()\n\n return await subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.HealthElement,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted) => (await this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(currentUser), [encrypted]))[0]\n ).then((rs) => new ConnectionImpl(rs))\n }\n\n createDelegationDeAnonymizationMetadata(entity: HealthElement, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo(\n { entity, type: EntityWithDelegationTypeName.HealthElement },\n delegates\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,wCAAuD;AAGvD,kDAAiD;AAEjD,4BAA2B;AAC3B,iCAAgC;AAGhC,0EAAgG;AAChG,wEAAoE;AACpE,IAAO,eAAe,GA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,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,CAAA;YAEvD,OAAO,MAAM,IAAA,+BAAuB,EAClC,IAAI,CAAC,IAAI,EACT,IAAI,CAAC,OAAO,EACZ,oCAA4B,CAAC,aAAa,EAC1C,UAAU,EACV,MAAM,EACN,UAAU,EACV,OAAO,EACP,CAAO,SAAS,EAAE,EAAE,gDAAC,OAAA,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,gBAAgB,CAAC,WAAW,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA,GAAA,CAC3G,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAAC,CAAA;QACxC,CAAC;KAAA;IAED,uCAAuC,CAAC,MAAqB,EAAE,SAAmB;QAChF,OAAO,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAC,iCAAiC,CAC7E,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,aAAa,EAAE,EAC5D,SAAS,CACV,CAAA;IACH,CAAC;CACF;AAthBD,0CAshBC","sourcesContent":["import { IccAuthApi, 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 { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { XHR } from '../icc-api/api/XHR'\nimport { IccUserXApi } from './icc-user-x-api'\nimport { EncryptedFieldsManifest, EntityWithDelegationTypeName, parseEncryptedFields, subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { AbstractFilter } from './filters/filters'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\n\nexport class IccHelementXApi extends IccHelementApi implements EncryptedEntityXApi<models.HealthElement> {\n private readonly encryptedFields: EncryptedFieldsManifest\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.HealthElement))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly userApi: IccUserXApi,\n private readonly authApi: IccAuthApi,\n private readonly autofillAuthor: boolean,\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.encryptedFields = parseEncryptedFields(encryptedKeys, 'HealthElement.')\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.\n * - preferredSfk: secret id of the patient to use as the secret foreign key to use for the health element. The default value will be a\n * secret id of patient known by the topmost parent in the current data owner hierarchy if the confidential is set to false, else a secret id that\n * the data owner did not share with any of his parents.\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]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n ignoreAutoDelegations?: boolean\n } = {}\n ) {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n const helement = {\n ...(h ?? {}),\n _type: 'org.taktik.icure.entities.HealthElement',\n id: h?.id ?? this.crypto.primitives.randomUuid(),\n created: h?.created ?? new Date().getTime(),\n modified: h?.modified ?? new Date().getTime(),\n responsible: h?.responsible ?? (this.autofillAuthor ? dataOwnerId : undefined),\n author: h?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: h?.codes ?? [],\n tags: h?.tags ?? [],\n healthElementId: h?.healthElementId ?? this.crypto.primitives.randomUuid(),\n openingDate: h?.openingDate ?? parseInt(moment().format('YYYYMMDDHHmmss')),\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 = await this.crypto.xapi.resolveSecretIdUseOptions(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n options.sfkOption ?? SecretIdUseOption.UseAnySharedWithParent\n )\n const extraDelegations = {\n ...(options.ignoreAutoDelegations\n ? {}\n : Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n )),\n ...(options?.additionalDelegates ?? {}),\n }\n const initialisationInfo = await this.crypto.xapi.entityWithInitialisedEncryptedMetadata(\n helement,\n EntityWithDelegationTypeName.HealthElement,\n patient.id,\n sfk,\n true,\n extraDelegations\n )\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 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.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.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.modifyHealthElementAs(this.dataOwnerApi.getDataOwnerIdOf(user), body) : Promise.resolve(null)\n }\n private modifyHealthElementAs(dataOwner: string, body: HealthElement): Promise<HealthElement> {\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 * @deprecated use {@link findIdsBy}.\n * @param hcpartyId\n * @param patient (Promise)\n * @param keepObsoleteVersions\n * @param usingPost\n */\n findBy(hcpartyId: string, patient: models.Patient, keepObsoleteVersions = false, usingPost = false) {\n return this.crypto.xapi\n .secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.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 /**\n * Same as {@link findBy} but it will only return the ids of the health elements. It can also filter the health elements where HealthElement.openingDate is between\n * startDate and endDate in ascending or descending order by that field. (default: ascending).\n */\n async findIdsBy(hcpartyId: string, patient: models.Patient, startDate?: number, endDate?: number, descending?: boolean) {\n return this.crypto.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }).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 this.findHealthElementIdsByDataOwnerPatientOpeningDate(hcpartyId, extractedKeys, startDate, endDate, descending)\n )\n ).then((results) => _.uniq(_.flatMap(results)))\n : Promise.resolve([])\n )\n }\n\n /**\n * @deprecated use {@link findHealthElementIdsByDataOwnerPatientOpeningDate} instead.\n */\n findByHCPartyPatientSecretFKeys(hcPartyId: string, secretFKeys: string): Promise<Array<models.HealthElement> | any> {\n return super.findHealthElementsByHCPartyPatientForeignKeys(hcPartyId, secretFKeys).then((helements) => this.decrypt(hcPartyId, helements))\n }\n\n /**\n * @deprecated use {@link findHealthElementIdsByDataOwnerPatientOpeningDate} instead.\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 this.crypto.xapi.tryEncryptEntities(\n healthElements,\n EntityWithDelegationTypeName.HealthElement,\n this.encryptedFields,\n false,\n false,\n (x) => new models.HealthElement(x)\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 async decrypt(dataOwnerId: string, hes: Array<models.HealthElement>): Promise<Array<models.HealthElement>> {\n return (await this.crypto.xapi.tryDecryptEntities(hes, EntityWithDelegationTypeName.HealthElement, (x) => new models.HealthElement(x))).map(\n ({ 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.xapi.owningEntityIdsOf({ entity: healthElement, type: EntityWithDelegationTypeName.HealthElement }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given health element\n */\n async hasWriteAccess(healthElement: models.HealthElement): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: healthElement, type: EntityWithDelegationTypeName.HealthElement })\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 * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n healthElement: models.HealthElement,\n options: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.HealthElement> {\n return this.shareWithMany(healthElement, { [delegateId]: options })\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 delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n healthElement: models.HealthElement,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.HealthElement> {\n return (await this.tryShareWithMany(healthElement, delegates)).updatedEntityOrThrow\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 healthElement the health element to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n healthElement: models.HealthElement,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.HealthElement>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(healthElement, EntityWithDelegationTypeName.HealthElement)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyHealthElementAs(self, entityWithEncryptionKey) : healthElement\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.HealthElement,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareHealthElements(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])))\n }\n\n getDataOwnersWithAccessTo(\n entity: models.HealthElement\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.HealthElement })\n }\n\n getEncryptionKeysOf(entity: models.HealthElement): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.HealthElement }, undefined)\n }\n\n async subscribeToHealthElementEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<HealthElement> | undefined,\n eventFired: (healthElement: HealthElement) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n const currentUser = await this.userApi.getCurrentUser()\n\n return await subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.HealthElement,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted) => (await this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(currentUser), [encrypted]))[0]\n ).then((rs) => new ConnectionImpl(rs))\n }\n\n createDelegationDeAnonymizationMetadata(entity: HealthElement, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo(\n { entity, type: EntityWithDelegationTypeName.HealthElement },\n delegates\n )\n }\n}\n"]}
|
|
@@ -12,6 +12,7 @@ import { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest
|
|
|
12
12
|
import RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum;
|
|
13
13
|
import { XHR } from '../icc-api/api/XHR';
|
|
14
14
|
import { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi';
|
|
15
|
+
import { SecretIdUseOption } from './crypto/SecretIdUseOption';
|
|
15
16
|
export declare class IccInvoiceXApi extends IccInvoiceApi implements EncryptedEntityXApi<models.Invoice> {
|
|
16
17
|
private readonly crypto;
|
|
17
18
|
private readonly entityrefApi;
|
|
@@ -39,7 +40,7 @@ export declare class IccInvoiceXApi extends IccInvoiceApi implements EncryptedEn
|
|
|
39
40
|
additionalDelegates?: {
|
|
40
41
|
[dataOwnerId: string]: AccessLevelEnum;
|
|
41
42
|
};
|
|
42
|
-
|
|
43
|
+
sfkOption?: SecretIdUseOption;
|
|
43
44
|
}): Promise<models.Invoice>;
|
|
44
45
|
createInvoice(invoice: Invoice, prefix?: string): Promise<Invoice>;
|
|
45
46
|
getNextInvoiceReference(prefix: string, entityrefApi: IccEntityrefApi): Promise<number>;
|
|
@@ -17,6 +17,7 @@ const AuthenticationProvider_1 = require("./auth/AuthenticationProvider");
|
|
|
17
17
|
const SecureDelegation_1 = require("../icc-api/model/SecureDelegation");
|
|
18
18
|
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
|
|
19
19
|
const utils_1 = require("./utils");
|
|
20
|
+
const SecretIdUseOption_1 = require("./crypto/SecretIdUseOption");
|
|
20
21
|
class IccInvoiceXApi extends icc_api_1.IccInvoiceApi {
|
|
21
22
|
get headers() {
|
|
22
23
|
return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, utils_1.EntityWithDelegationTypeName.Invoice));
|
|
@@ -53,9 +54,7 @@ class IccInvoiceXApi extends icc_api_1.IccInvoiceApi {
|
|
|
53
54
|
const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user);
|
|
54
55
|
if (ownerId !== (yield this.dataOwnerApi.getCurrentDataOwnerId()))
|
|
55
56
|
throw new Error('Can only initialise entities as current data owner.');
|
|
56
|
-
const sfk = (_k = options.
|
|
57
|
-
if (!sfk)
|
|
58
|
-
throw new Error(`Couldn't find any sfk of parent patient ${patient.id}`);
|
|
57
|
+
const sfk = yield this.crypto.xapi.resolveSecretIdUseOptions({ entity: patient, type: utils_1.EntityWithDelegationTypeName.Patient }, (_k = options.sfkOption) !== null && _k !== void 0 ? _k : SecretIdUseOption_1.SecretIdUseOption.UseAnySharedWithParent);
|
|
59
58
|
const extraDelegations = Object.assign(Object.assign({}, Object.fromEntries([...((_m = (_l = user.autoDelegations) === null || _l === void 0 ? void 0 : _l.all) !== null && _m !== void 0 ? _m : []), ...((_p = (_o = user.autoDelegations) === null || _o === void 0 ? void 0 : _o.financialInformation) !== null && _p !== void 0 ? _p : [])].map((d) => [d, AccessLevelEnum.WRITE]))), ((_q = options === null || options === void 0 ? void 0 : options.additionalDelegates) !== null && _q !== void 0 ? _q : {}));
|
|
60
59
|
return new models.Invoice(yield this.crypto.xapi
|
|
61
60
|
.entityWithInitialisedEncryptedMetadata(invoice, utils_1.EntityWithDelegationTypeName.Invoice, patient.id, sfk, true, extraDelegations)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icc-invoice-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-invoice-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAA2D;AAG3D,4BAA2B;AAC3B,kDAAiD;AAGjD,0EAAgG;AAChG,wEAAoE;AACpE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAOzD,mCAAsD;AAEtD,MAAa,cAAe,SAAQ,uBAAa;IAC/C,IAAI,OAAO;QACT,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,EAAE,oCAA4B,CAAC,OAAO,CAAC,CAAC,CAAA;IAC7I,CAAC;IAED,YACE,IAAY,EACZ,OAAkC,EACjB,MAAqB,EACrB,YAA6B,EAC7B,YAA8B,EAC9B,cAAuB,EACxC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,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EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAA;IACpJ,CAAC;CACF;AA5SD,wCA4SC","sourcesContent":["import { IccEntityrefApi, IccInvoiceApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\nimport { Invoice } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { EntityWithDelegationTypeName } from './utils'\n\nexport class IccInvoiceXApi extends IccInvoiceApi implements EncryptedEntityXApi<models.Invoice> {\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Invoice))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly entityrefApi: IccEntityrefApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly autofillAuthor: boolean,\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 }\n\n /**\n * Creates a new instance of invoice with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this invoice refers to.\n * @param inv initialised data for the invoice. 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.\n * - preferredSfk: secret id of the patient to use as the secret foreign key to use for the invoice. The default value will be a\n * secret id of patient known by the topmost parent in the current data owner hierarchy.\n * @return a new instance of invoice.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient,\n inv: any = {},\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n preferredSfk?: string\n } = {}\n ): Promise<models.Invoice> {\n const invoice = new models.Invoice({\n ...(inv ?? {}),\n _type: 'org.taktik.icure.entities.Invoice',\n id: inv?.id ?? this.crypto.primitives.randomUuid(),\n groupId: inv?.groupId ?? this.crypto.primitives.randomUuid(),\n created: inv?.created ?? new Date().getTime(),\n modified: inv?.modified ?? new Date().getTime(),\n responsible: inv?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: inv?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: inv?.codes ?? [],\n tags: inv?.tags ?? [],\n invoicingCodes: inv?.invoicingCodes ?? [],\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 (await this.crypto.confidential.getAnySecretIdSharedWithParents({ entity: patient, type: EntityWithDelegationTypeName.Patient }))\n if (!sfk) throw new Error(`Couldn't find any sfk of parent patient ${patient.id}`)\n const extraDelegations = {\n ...Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.financialInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n ),\n ...(options?.additionalDelegates ?? {}),\n }\n return new models.Invoice(\n await this.crypto.xapi\n .entityWithInitialisedEncryptedMetadata(invoice, EntityWithDelegationTypeName.Invoice, patient.id, sfk, true, extraDelegations)\n .then((x) => x.updatedEntity)\n )\n }\n\n createInvoice(invoice: Invoice, prefix?: string): Promise<Invoice> {\n if (!prefix) {\n return super.createInvoice(invoice)\n }\n if (!invoice.id) {\n invoice.id = this.crypto.primitives.randomUuid()\n }\n return this.getNextInvoiceReference(prefix, this.entityrefApi)\n .then((reference) => this.createInvoiceReference(reference, invoice.id!, prefix, this.entityrefApi))\n .then((entityReference) => {\n if (!entityReference.id) {\n throw new Error('Cannot create invoice')\n }\n\n if (invoice.internshipNihii) {\n invoice.invoiceReference = entityReference.id.substring(prefix.length).replace('0', '1')\n } else {\n invoice.invoiceReference = entityReference.id.substring(prefix.length)\n }\n return super.createInvoice(invoice)\n })\n }\n\n getNextInvoiceReference(prefix: string, entityrefApi: IccEntityrefApi): Promise<number> {\n return entityrefApi.getLatest(prefix).then((entRef: models.EntityReference) => {\n if (!entRef || !entRef.id || !entRef.id!.startsWith(prefix)) return 1\n const sequenceNumber = entRef.id!.split(':').pop() || 0\n return Number(sequenceNumber) + 1\n })\n }\n\n createInvoiceReference(nextReference: number, docId: string, prefix: string, entityrefApi: IccEntityrefApi): Promise<models.EntityReference> {\n return entityrefApi\n .createEntityReference(\n new models.EntityReference({\n id: prefix + nextReference.toString().padStart(6, '0'),\n docId,\n })\n )\n .catch((err) => {\n console.log(err)\n return this.createInvoiceReference(nextReference + 1, docId, prefix, entityrefApi)\n })\n }\n\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 invoices with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the invoices for the patient.\n *\n * @deprecated use {@link findIdsBy} instead\n * @param hcpartyId\n * @param patient (Promise)\n * @param usingPost\n */\n async findBy(hcpartyId: string, patient: models.Patient, usingPost: boolean = false): Promise<Array<models.Invoice>> {\n const extractedKeys = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, hcpartyId)\n const topmostParentId = (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0]\n let invoices: Array<Invoice> = usingPost\n ? await this.findInvoicesByHCPartyPatientForeignKeysUsingPost(hcpartyId!, _.uniq(extractedKeys))\n : await this.findInvoicesByHCPartyPatientForeignKeys(hcpartyId!, _.uniq(extractedKeys).join(','))\n return await this.decrypt(hcpartyId, invoices)\n }\n\n async findIdsBy(hcpartyId: string, patient: models.Patient, startDate?: number, endDate?: number, descending?: boolean): Promise<string[]> {\n const extractedKeys = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, hcpartyId)\n const topmostParentId = (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0]\n return this.findInvoiceIdsByDataOwnerPatientInvoiceDate(hcpartyId!, _.uniq(extractedKeys), startDate, endDate, descending)\n }\n\n encrypt(user: models.User, invoices: Array<models.Invoice>) {\n return Promise.resolve(invoices)\n }\n\n decrypt(hcpartyId: string, invoices: Array<models.Invoice>): Promise<Array<models.Invoice>> {\n return Promise.resolve(invoices)\n }\n\n /**\n * @param invoice a invoice\n * @return the id of the patient that the invoice 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(invoice: models.Invoice): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: invoice, type: EntityWithDelegationTypeName.Invoice }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given invoice\n */\n async hasWriteAccess(invoice: models.Invoice): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: invoice, type: EntityWithDelegationTypeName.Invoice })\n }\n\n /**\n * Share an existing invoice with other data owners, allowing them to access the non-encrypted data of the invoice 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 invoice.\n * @param invoice the invoice to share.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * invoice does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this invoice refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n invoice: models.Invoice,\n options: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Invoice> {\n return this.shareWithMany(invoice, { [delegateId]: options })\n }\n\n /**\n * Share an existing invoice with other data owners, allowing them to access the non-encrypted data of the invoice and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param invoice the invoice to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * invoice does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this invoice refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n invoice: models.Invoice,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Invoice> {\n return (await this.tryShareWithMany(invoice, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing invoice with other data owners, allowing them to access the non-encrypted data of the invoice and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param invoice the invoice to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * invoice does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this invoice refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n invoice: models.Invoice,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Invoice>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(invoice, EntityWithDelegationTypeName.Invoice)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyInvoice(entityWithEncryptionKey) : invoice\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Invoice,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareInvoices(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])))\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Invoice\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Invoice })\n }\n\n getEncryptionKeysOf(entity: models.Invoice): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Invoice }, undefined)\n }\n\n createDelegationDeAnonymizationMetadata(entity: models.Invoice, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Invoice }, delegates)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"icc-invoice-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-invoice-x-api.ts"],"names":[],"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AAE,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QACvF,CAAC;KAAA;IAED,yBAAyB,CACvB,MAAsB;QAEtB,OAAO,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAC,yBAAyB,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,OAAO,EAAE,CAAC,CAAA;IACjI,CAAC;IAED,mBAAmB,CAAC,MAAsB;QACxC,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAA;IAC7G,CAAC;IAED,uCAAuC,CAAC,MAAsB,EAAE,SAAmB;QACjF,OAAO,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAC,iCAAiC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAA;IACpJ,CAAC;CACF;AA5SD,wCA4SC","sourcesContent":["import { IccEntityrefApi, IccInvoiceApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\nimport { Invoice } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { EntityWithDelegationTypeName } from './utils'\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\n\nexport class IccInvoiceXApi extends IccInvoiceApi implements EncryptedEntityXApi<models.Invoice> {\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Invoice))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly entityrefApi: IccEntityrefApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly autofillAuthor: boolean,\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 }\n\n /**\n * Creates a new instance of invoice with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this invoice refers to.\n * @param inv initialised data for the invoice. 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.\n * - preferredSfk: secret id of the patient to use as the secret foreign key to use for the invoice. The default value will be a\n * secret id of patient known by the topmost parent in the current data owner hierarchy.\n * @return a new instance of invoice.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient,\n inv: any = {},\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n } = {}\n ): Promise<models.Invoice> {\n const invoice = new models.Invoice({\n ...(inv ?? {}),\n _type: 'org.taktik.icure.entities.Invoice',\n id: inv?.id ?? this.crypto.primitives.randomUuid(),\n groupId: inv?.groupId ?? this.crypto.primitives.randomUuid(),\n created: inv?.created ?? new Date().getTime(),\n modified: inv?.modified ?? new Date().getTime(),\n responsible: inv?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: inv?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: inv?.codes ?? [],\n tags: inv?.tags ?? [],\n invoicingCodes: inv?.invoicingCodes ?? [],\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 = await this.crypto.xapi.resolveSecretIdUseOptions(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n options.sfkOption ?? SecretIdUseOption.UseAnySharedWithParent\n )\n const extraDelegations = {\n ...Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.financialInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n ),\n ...(options?.additionalDelegates ?? {}),\n }\n return new models.Invoice(\n await this.crypto.xapi\n .entityWithInitialisedEncryptedMetadata(invoice, EntityWithDelegationTypeName.Invoice, patient.id, sfk, true, extraDelegations)\n .then((x) => x.updatedEntity)\n )\n }\n\n createInvoice(invoice: Invoice, prefix?: string): Promise<Invoice> {\n if (!prefix) {\n return super.createInvoice(invoice)\n }\n if (!invoice.id) {\n invoice.id = this.crypto.primitives.randomUuid()\n }\n return this.getNextInvoiceReference(prefix, this.entityrefApi)\n .then((reference) => this.createInvoiceReference(reference, invoice.id!, prefix, this.entityrefApi))\n .then((entityReference) => {\n if (!entityReference.id) {\n throw new Error('Cannot create invoice')\n }\n\n if (invoice.internshipNihii) {\n invoice.invoiceReference = entityReference.id.substring(prefix.length).replace('0', '1')\n } else {\n invoice.invoiceReference = entityReference.id.substring(prefix.length)\n }\n return super.createInvoice(invoice)\n })\n }\n\n getNextInvoiceReference(prefix: string, entityrefApi: IccEntityrefApi): Promise<number> {\n return entityrefApi.getLatest(prefix).then((entRef: models.EntityReference) => {\n if (!entRef || !entRef.id || !entRef.id!.startsWith(prefix)) return 1\n const sequenceNumber = entRef.id!.split(':').pop() || 0\n return Number(sequenceNumber) + 1\n })\n }\n\n createInvoiceReference(nextReference: number, docId: string, prefix: string, entityrefApi: IccEntityrefApi): Promise<models.EntityReference> {\n return entityrefApi\n .createEntityReference(\n new models.EntityReference({\n id: prefix + nextReference.toString().padStart(6, '0'),\n docId,\n })\n )\n .catch((err) => {\n console.log(err)\n return this.createInvoiceReference(nextReference + 1, docId, prefix, entityrefApi)\n })\n }\n\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 invoices with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the invoices for the patient.\n *\n * @deprecated use {@link findIdsBy} instead\n * @param hcpartyId\n * @param patient (Promise)\n * @param usingPost\n */\n async findBy(hcpartyId: string, patient: models.Patient, usingPost: boolean = false): Promise<Array<models.Invoice>> {\n const extractedKeys = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, hcpartyId)\n const topmostParentId = (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0]\n let invoices: Array<Invoice> = usingPost\n ? await this.findInvoicesByHCPartyPatientForeignKeysUsingPost(hcpartyId!, _.uniq(extractedKeys))\n : await this.findInvoicesByHCPartyPatientForeignKeys(hcpartyId!, _.uniq(extractedKeys).join(','))\n return await this.decrypt(hcpartyId, invoices)\n }\n\n async findIdsBy(hcpartyId: string, patient: models.Patient, startDate?: number, endDate?: number, descending?: boolean): Promise<string[]> {\n const extractedKeys = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, hcpartyId)\n const topmostParentId = (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())[0]\n return this.findInvoiceIdsByDataOwnerPatientInvoiceDate(hcpartyId!, _.uniq(extractedKeys), startDate, endDate, descending)\n }\n\n encrypt(user: models.User, invoices: Array<models.Invoice>) {\n return Promise.resolve(invoices)\n }\n\n decrypt(hcpartyId: string, invoices: Array<models.Invoice>): Promise<Array<models.Invoice>> {\n return Promise.resolve(invoices)\n }\n\n /**\n * @param invoice a invoice\n * @return the id of the patient that the invoice 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(invoice: models.Invoice): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: invoice, type: EntityWithDelegationTypeName.Invoice }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given invoice\n */\n async hasWriteAccess(invoice: models.Invoice): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: invoice, type: EntityWithDelegationTypeName.Invoice })\n }\n\n /**\n * Share an existing invoice with other data owners, allowing them to access the non-encrypted data of the invoice 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 invoice.\n * @param invoice the invoice to share.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * invoice does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this invoice refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n invoice: models.Invoice,\n options: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Invoice> {\n return this.shareWithMany(invoice, { [delegateId]: options })\n }\n\n /**\n * Share an existing invoice with other data owners, allowing them to access the non-encrypted data of the invoice and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param invoice the invoice to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * invoice does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this invoice refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n invoice: models.Invoice,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Invoice> {\n return (await this.tryShareWithMany(invoice, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing invoice with other data owners, allowing them to access the non-encrypted data of the invoice and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param invoice the invoice to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds: specifies which secret ids of the entity should be shared. If not provided all secret ids available to the current user will be shared\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 * invoice does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this invoice refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n invoice: models.Invoice,\n delegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Invoice>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(invoice, EntityWithDelegationTypeName.Invoice)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyInvoice(entityWithEncryptionKey) : invoice\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Invoice,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareInvoices(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])))\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Invoice\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Invoice })\n }\n\n getEncryptionKeysOf(entity: models.Invoice): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Invoice }, undefined)\n }\n\n createDelegationDeAnonymizationMetadata(entity: models.Invoice, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Invoice }, delegates)\n }\n}\n"]}
|
|
@@ -16,6 +16,7 @@ import RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum;
|
|
|
16
16
|
import { AbstractFilter } from './filters/filters';
|
|
17
17
|
import { SubscriptionOptions } from './utils';
|
|
18
18
|
import { Connection } from '../icc-api/model/Connection';
|
|
19
|
+
import { SecretIdUseOption } from './crypto/SecretIdUseOption';
|
|
19
20
|
export declare class IccMessageXApi extends IccMessageApi implements EncryptedEntityXApi<models.Message> {
|
|
20
21
|
private readonly crypto;
|
|
21
22
|
private readonly dataOwnerApi;
|
|
@@ -45,7 +46,7 @@ export declare class IccMessageXApi extends IccMessageApi implements EncryptedEn
|
|
|
45
46
|
additionalDelegates?: {
|
|
46
47
|
[dataOwnerId: string]: AccessLevelEnum;
|
|
47
48
|
};
|
|
48
|
-
|
|
49
|
+
sfkOption?: SecretIdUseOption;
|
|
49
50
|
}): Promise<models.Message>;
|
|
50
51
|
decrypt(messages: Array<models.Message>): Promise<{
|
|
51
52
|
entity: models.Message;
|
|
@@ -17,6 +17,7 @@ const SecureDelegation_1 = require("../icc-api/model/SecureDelegation");
|
|
|
17
17
|
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
|
|
18
18
|
const utils_1 = require("./utils");
|
|
19
19
|
const Connection_1 = require("../icc-api/model/Connection");
|
|
20
|
+
const SecretIdUseOption_1 = require("./crypto/SecretIdUseOption");
|
|
20
21
|
class IccMessageXApi extends icc_api_1.IccMessageApi {
|
|
21
22
|
get headers() {
|
|
22
23
|
return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, utils_1.EntityWithDelegationTypeName.Message));
|
|
@@ -54,14 +55,12 @@ class IccMessageXApi extends icc_api_1.IccMessageApi {
|
|
|
54
55
|
newInstanceWithPatient(user, patient, m = {}, options = {}) {
|
|
55
56
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
56
57
|
return __awaiter(this, void 0, void 0, function* () {
|
|
57
|
-
if (!patient && options.preferredSfk)
|
|
58
|
-
throw new Error('You need to specify parent patient in order to use secret foreign keys.');
|
|
59
58
|
const message = Object.assign(Object.assign({}, (m !== null && m !== void 0 ? m : {})), { _type: 'org.taktik.icure.entities.Message', id: (_a = m === null || m === void 0 ? void 0 : m.id) !== null && _a !== void 0 ? _a : this.crypto.primitives.randomUuid(), created: (_b = m === null || m === void 0 ? void 0 : m.created) !== null && _b !== void 0 ? _b : new Date().getTime(), modified: (_c = m === null || m === void 0 ? void 0 : m.modified) !== null && _c !== void 0 ? _c : new Date().getTime(), responsible: (_d = m === null || m === void 0 ? void 0 : m.responsible) !== null && _d !== void 0 ? _d : (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined), author: (_e = m === null || m === void 0 ? void 0 : m.author) !== null && _e !== void 0 ? _e : (this.autofillAuthor ? user.id : undefined), codes: (_f = m === null || m === void 0 ? void 0 : m.codes) !== null && _f !== void 0 ? _f : [], tags: (_g = m === null || m === void 0 ? void 0 : m.tags) !== null && _g !== void 0 ? _g : [] });
|
|
60
59
|
const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user);
|
|
61
60
|
if (ownerId !== (yield this.dataOwnerApi.getCurrentDataOwnerId()))
|
|
62
61
|
throw new Error('Can only initialise entities as current data owner.');
|
|
63
62
|
const sfk = patient
|
|
64
|
-
? (_h = options.
|
|
63
|
+
? yield this.crypto.xapi.resolveSecretIdUseOptions({ entity: patient, type: utils_1.EntityWithDelegationTypeName.Patient }, (_h = options.sfkOption) !== null && _h !== void 0 ? _h : SecretIdUseOption_1.SecretIdUseOption.UseAnySharedWithParent)
|
|
65
64
|
: undefined;
|
|
66
65
|
if (patient && !sfk)
|
|
67
66
|
throw new Error(`Couldn't find any sfk of parent patient ${patient.id}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icc-message-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-message-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAGtD,kDAAiD;AAGjD,0EAAgG;AAChG,wEAAoE;AAOpE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAGzD,mCAAmJ;AACnJ,4DAAwE;AAExE,MAAa,cAAe,SAAQ,uBAAa;IAG/C,IAAI,OAAO;QACT,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,EAAE,oCAA4B,CAAC,OAAO,CAAC,CAAC,CAAA;IAC7I,CAAC;IAED,YACE,IAAY,EACZ,OAAkC,EACjB,MAAqB,EACrB,YAA8B,EAC9B,OAAmB,EACnB,cAAuB,EACxC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,gBAA+B,EAAE,EACjC,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAA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3C,UAA+C,EAC/C,UAA+B,EAAE;;YAEjC,OAAO,MAAM,IAAA,+BAAuB,EAClC,IAAI,CAAC,IAAI,EACT,IAAI,CAAC,OAAO,EACZ,oCAA4B,CAAC,OAAO,EACpC,UAAU,EACV,MAAM,EACN,UAAU,EACV,OAAO,EACP,CAAO,SAAS,EAAE,EAAE,gDAAC,OAAA,CAAC,MAAM,IAAI,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAA,GAAA,CACjE,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAAC,CAAA;QACxC,CAAC;KAAA;IAED,uCAAuC,CAAC,MAAe,EAAE,SAAmB;QAC1E,OAAO,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAC,iCAAiC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,oCAA4B,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAA;IACpJ,CAAC;CACF;AArSD,wCAqSC","sourcesContent":["import { IccAuthApi, IccMessageApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as models from '../icc-api/model/models'\nimport { Message, MessagesReadStatusUpdate, PaginatedListMessage, Patient, User } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { FilterChainMessage } from '../icc-api/model/FilterChainMessage'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { AbstractFilter } from './filters/filters'\nimport { EncryptedFieldsManifest, EntityWithDelegationTypeName, parseEncryptedFields, subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\n\nexport class IccMessageXApi extends IccMessageApi implements EncryptedEntityXApi<models.Message> {\n private readonly encryptedFields: EncryptedFieldsManifest\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Message))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly authApi: IccAuthApi,\n private readonly autofillAuthor: boolean,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n encryptedKeys: Array<string> = [],\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.encryptedFields = parseEncryptedFields(encryptedKeys, 'Message.')\n }\n\n // noinspection JSUnusedGlobalSymbols\n newInstance(user: User, m: any) {\n return this.newInstanceWithPatient(user, null, m)\n }\n\n /**\n * Creates a new instance of message with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this message refers to.\n * @param m initialised data for the message. 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.\n * - preferredSfk: secret id of the patient to use as the secret foreign key to use for the message. The default value will be a\n * secret id of patient known by the topmost parent in the current data owner hierarchy.\n * @return a new instance of message.\n */\n async newInstanceWithPatient(\n user: User,\n patient: Patient | null,\n m: any = {},\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n preferredSfk?: string\n } = {}\n ) {\n if (!patient && options.preferredSfk) throw new Error('You need to specify parent patient in order to use secret foreign keys.')\n const message = {\n ...(m ?? {}),\n _type: 'org.taktik.icure.entities.Message',\n id: m?.id ?? this.crypto.primitives.randomUuid(),\n created: m?.created ?? new Date().getTime(),\n modified: m?.modified ?? new Date().getTime(),\n responsible: m?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: m?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: m?.codes ?? [],\n tags: m?.tags ?? [],\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 = patient\n ? options.preferredSfk ??\n (await this.crypto.confidential.getAnySecretIdSharedWithParents({ entity: patient, type: EntityWithDelegationTypeName.Patient }))\n : undefined\n if (patient && !sfk) throw new Error(`Couldn't find any sfk of parent patient ${patient.id}`)\n const extraDelegations = {\n ...Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n ),\n ...(options?.additionalDelegates ?? {}),\n }\n return new models.Message(\n await this.crypto.xapi\n .entityWithInitialisedEncryptedMetadata(message, EntityWithDelegationTypeName.Message, patient?.id, sfk, true, extraDelegations)\n .then((x) => x.updatedEntity)\n )\n }\n\n async decrypt(messages: Array<models.Message>) {\n return await this.crypto.xapi.tryDecryptEntities(messages, EntityWithDelegationTypeName.Message, (x) => new models.Message(x))\n }\n\n encrypt(messages: Array<models.Message>): Promise<Array<models.Message>> {\n return this.crypto.xapi.tryEncryptEntities(\n messages,\n EntityWithDelegationTypeName.Message,\n this.encryptedFields,\n true,\n false,\n (x) => new models.Message(x)\n )\n }\n\n /**\n * @param message a message\n * @return the id of the patient that the message 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(message: models.Message): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: message, type: EntityWithDelegationTypeName.Message }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given message\n */\n async hasWriteAccess(message: models.Message): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: message, type: EntityWithDelegationTypeName.Message })\n }\n\n /**\n * Share an existing message with other data owners, allowing them to access the non-encrypted data of the message 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 message.\n * @param message the message to share.\n * @param shareSecretIds the secret ids of the Message that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Message is the owning entity id.\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 * message does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this message refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n message: models.Message,\n shareSecretIds: string[],\n options: {\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Message> {\n return this.shareWithMany(message, { [delegateId]: { ...options, shareSecretIds } })\n }\n\n /**\n * Share an existing message with other data owners, allowing them to access the non-encrypted data of the message and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param message the message to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds the secret ids of the Message that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Message is the owning entity id. Mandatory.\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 * message does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this message refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n message: models.Message,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Message> {\n return (await this.tryShareWithMany(message, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing message with other data owners, allowing them to access the non-encrypted data of the message and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param message the message to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds the secret ids of the Message that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Message is the owning entity id. Mandatory.\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 * message does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this message refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n message: models.Message,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Message>> {\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(message, EntityWithDelegationTypeName.Message)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyMessage(entityWithEncryptionKey) : message\n return this.crypto.xapi.simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Message,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareMessages(x)\n )\n }\n\n /**\n * @param message a message\n * @return the secret ids of the message, retrieved from the encrypted metadata. The result may be used to find entities where the message is\n * the 'owning entity', or in the {@link shareWith} method in order to share it with other data owners.\n */\n decryptSecretIdsOf(message: models.Message): Promise<string[]> {\n return this.crypto.xapi.secretIdsOf({ entity: message, type: EntityWithDelegationTypeName.Message }, undefined)\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Message\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Message })\n }\n\n getEncryptionKeysOf(entity: models.Message): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Message }, undefined)\n }\n\n override async filterMessagesBy(body: FilterChainMessage, startDocumentId?: string, limit?: number): Promise<PaginatedListMessage> {\n const page = await super.filterMessagesBy(body, startDocumentId, limit)\n const decryptedMessages = await this.decrypt(page.rows ?? [])\n if (decryptedMessages.some((m) => !m.decrypted)) throw new Error('Some messages could not be decrypted')\n return {\n ...page,\n rows: decryptedMessages.map((m) => m.entity),\n }\n }\n\n async encryptAndCreateMessageInTopic(body: Message): Promise<Message> {\n const encryptedMessage = await this.encrypt([body])\n const createdMessage = await super.createMessageInTopic(encryptedMessage[0])\n return (await this.decrypt([createdMessage]))[0].entity\n }\n\n async setMessagesReadStatus(body?: MessagesReadStatusUpdate): Promise<Array<Message>> {\n return (await this.decrypt(await super.setMessagesReadStatus(body))).map((m) => m.entity)\n }\n\n async getAndDecryptMessage(messageId: string): Promise<Message> {\n const encryptedMessage = await super.getMessage(messageId)\n const decryptedMessage = await this.decrypt([encryptedMessage])\n if (!decryptedMessage[0].decrypted) throw new Error('Message could not be decrypted')\n return decryptedMessage[0].entity\n }\n\n async subscribeToMessageEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Message> | undefined,\n eventFired: (message: Message) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n return await subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.Message,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted) => (await this.decrypt([encrypted]))[0].entity\n ).then((rs) => new ConnectionImpl(rs))\n }\n\n createDelegationDeAnonymizationMetadata(entity: Message, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Message }, delegates)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"icc-message-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-message-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAGtD,kDAAiD;AA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'./icc-crypto-x-api'\n\nimport * as models from '../icc-api/model/models'\nimport { Message, MessagesReadStatusUpdate, PaginatedListMessage, Patient, User } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { FilterChainMessage } from '../icc-api/model/FilterChainMessage'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { AbstractFilter } from './filters/filters'\nimport { EncryptedFieldsManifest, EntityWithDelegationTypeName, parseEncryptedFields, subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\n\nexport class IccMessageXApi extends IccMessageApi implements EncryptedEntityXApi<models.Message> {\n private readonly encryptedFields: EncryptedFieldsManifest\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Message))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly authApi: IccAuthApi,\n private readonly autofillAuthor: boolean,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n encryptedKeys: Array<string> = [],\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.encryptedFields = parseEncryptedFields(encryptedKeys, 'Message.')\n }\n\n // noinspection JSUnusedGlobalSymbols\n newInstance(user: User, m: any) {\n return this.newInstanceWithPatient(user, null, m)\n }\n\n /**\n * Creates a new instance of message with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this message refers to.\n * @param m initialised data for the message. 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.\n * - preferredSfk: secret id of the patient to use as the secret foreign key to use for the message. The default value will be a\n * secret id of patient known by the topmost parent in the current data owner hierarchy.\n * @return a new instance of message.\n */\n async newInstanceWithPatient(\n user: User,\n patient: Patient | null,\n m: any = {},\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n } = {}\n ) {\n const message = {\n ...(m ?? {}),\n _type: 'org.taktik.icure.entities.Message',\n id: m?.id ?? this.crypto.primitives.randomUuid(),\n created: m?.created ?? new Date().getTime(),\n modified: m?.modified ?? new Date().getTime(),\n responsible: m?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: m?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: m?.codes ?? [],\n tags: m?.tags ?? [],\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 = patient\n ? await this.crypto.xapi.resolveSecretIdUseOptions(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n options.sfkOption ?? SecretIdUseOption.UseAnySharedWithParent\n )\n : undefined\n if (patient && !sfk) throw new Error(`Couldn't find any sfk of parent patient ${patient.id}`)\n const extraDelegations = {\n ...Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n ),\n ...(options?.additionalDelegates ?? {}),\n }\n return new models.Message(\n await this.crypto.xapi\n .entityWithInitialisedEncryptedMetadata(message, EntityWithDelegationTypeName.Message, patient?.id, sfk, true, extraDelegations)\n .then((x) => x.updatedEntity)\n )\n }\n\n async decrypt(messages: Array<models.Message>) {\n return await this.crypto.xapi.tryDecryptEntities(messages, EntityWithDelegationTypeName.Message, (x) => new models.Message(x))\n }\n\n encrypt(messages: Array<models.Message>): Promise<Array<models.Message>> {\n return this.crypto.xapi.tryEncryptEntities(\n messages,\n EntityWithDelegationTypeName.Message,\n this.encryptedFields,\n true,\n false,\n (x) => new models.Message(x)\n )\n }\n\n /**\n * @param message a message\n * @return the id of the patient that the message 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(message: models.Message): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: message, type: EntityWithDelegationTypeName.Message }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given message\n */\n async hasWriteAccess(message: models.Message): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: message, type: EntityWithDelegationTypeName.Message })\n }\n\n /**\n * Share an existing message with other data owners, allowing them to access the non-encrypted data of the message 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 message.\n * @param message the message to share.\n * @param shareSecretIds the secret ids of the Message that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Message is the owning entity id.\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 * message does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this message refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n message: models.Message,\n shareSecretIds: string[],\n options: {\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Message> {\n return this.shareWithMany(message, { [delegateId]: { ...options, shareSecretIds } })\n }\n\n /**\n * Share an existing message with other data owners, allowing them to access the non-encrypted data of the message and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param message the message to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds the secret ids of the Message that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Message is the owning entity id. Mandatory.\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 * message does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this message refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n message: models.Message,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Message> {\n return (await this.tryShareWithMany(message, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing message with other data owners, allowing them to access the non-encrypted data of the message and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param message the message to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds the secret ids of the Message that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Message is the owning entity id. Mandatory.\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 * message does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this message refers to should be shared with the delegate (defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n message: models.Message,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n sharePatientId?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Message>> {\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(message, EntityWithDelegationTypeName.Message)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyMessage(entityWithEncryptionKey) : message\n return this.crypto.xapi.simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Message,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: options.sharePatientId,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkShareMessages(x)\n )\n }\n\n /**\n * @param message a message\n * @return the secret ids of the message, retrieved from the encrypted metadata. The result may be used to find entities where the message is\n * the 'owning entity', or in the {@link shareWith} method in order to share it with other data owners.\n */\n decryptSecretIdsOf(message: models.Message): Promise<string[]> {\n return this.crypto.xapi.secretIdsOf({ entity: message, type: EntityWithDelegationTypeName.Message }, undefined)\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Message\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Message })\n }\n\n getEncryptionKeysOf(entity: models.Message): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Message }, undefined)\n }\n\n override async filterMessagesBy(body: FilterChainMessage, startDocumentId?: string, limit?: number): Promise<PaginatedListMessage> {\n const page = await super.filterMessagesBy(body, startDocumentId, limit)\n const decryptedMessages = await this.decrypt(page.rows ?? [])\n if (decryptedMessages.some((m) => !m.decrypted)) throw new Error('Some messages could not be decrypted')\n return {\n ...page,\n rows: decryptedMessages.map((m) => m.entity),\n }\n }\n\n async encryptAndCreateMessageInTopic(body: Message): Promise<Message> {\n const encryptedMessage = await this.encrypt([body])\n const createdMessage = await super.createMessageInTopic(encryptedMessage[0])\n return (await this.decrypt([createdMessage]))[0].entity\n }\n\n async setMessagesReadStatus(body?: MessagesReadStatusUpdate): Promise<Array<Message>> {\n return (await this.decrypt(await super.setMessagesReadStatus(body))).map((m) => m.entity)\n }\n\n async getAndDecryptMessage(messageId: string): Promise<Message> {\n const encryptedMessage = await super.getMessage(messageId)\n const decryptedMessage = await this.decrypt([encryptedMessage])\n if (!decryptedMessage[0].decrypted) throw new Error('Message could not be decrypted')\n return decryptedMessage[0].entity\n }\n\n async subscribeToMessageEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Message> | undefined,\n eventFired: (message: Message) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n return await subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.Message,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted) => (await this.decrypt([encrypted]))[0].entity\n ).then((rs) => new ConnectionImpl(rs))\n }\n\n createDelegationDeAnonymizationMetadata(entity: Message, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Message }, delegates)\n }\n}\n"]}
|