@icure/api 8.6.12 → 8.6.14

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.
@@ -111,6 +111,15 @@ export declare class IccContactXApi extends IccContactApi implements EncryptedEn
111
111
  * @return a paginated list of decrypted contacts
112
112
  */
113
113
  filterByWithUser(user: models.User, startDocumentId?: string, limit?: number, body?: models.FilterChainContact): Promise<PaginatedListContact | any>;
114
+ /**
115
+ * Filters services using a filter chain and decrypts the results for the given user.
116
+ * @param user the user for decryption
117
+ * @param startDocumentId optional document id to start pagination from
118
+ * @param limit maximum number of results to return
119
+ * @param body the filter chain to apply
120
+ * @return a paginated list of decrypted services
121
+ */
122
+ filterServicesByWithUser(user: models.User, startDocumentId?: string, limit?: number, body?: models.FilterChainService): Promise<PaginatedListContact | any>;
114
123
  /**
115
124
  * Lists contacts by opening date within a date range and decrypts the results for the given user.
116
125
  * @param user the user for decryption
@@ -366,6 +375,12 @@ export declare class IccContactXApi extends IccContactApi implements EncryptedEn
366
375
  * in the returned array, but in case of entity merges there could be multiple values.
367
376
  */
368
377
  decryptPatientIdOf(contact: models.Contact): Promise<string[]>;
378
+ /**
379
+ * @param service a service
380
+ * @return the id of the patient that the service refers to, retrieved from the encrypted metadata. Normally there should only be one element
381
+ * in the returned array, but in case of entity merges there could be multiple values.
382
+ */
383
+ decryptPatientIdOfService(service: models.Service): Promise<string[]>;
369
384
  /**
370
385
  * @return if the logged data owner has write access to the content of the given contact
371
386
  */
@@ -233,6 +233,19 @@ class IccContactXApi extends icc_api_1.IccContactApi {
233
233
  .filterContactsBy(startDocumentId, limit, body)
234
234
  .then((ctcs) => this.decrypt(user.healthcarePartyId || user.patientId, ctcs.rows).then((decryptedRows) => Object.assign(ctcs, { rows: decryptedRows })));
235
235
  }
236
+ /**
237
+ * Filters services using a filter chain and decrypts the results for the given user.
238
+ * @param user the user for decryption
239
+ * @param startDocumentId optional document id to start pagination from
240
+ * @param limit maximum number of results to return
241
+ * @param body the filter chain to apply
242
+ * @return a paginated list of decrypted services
243
+ */
244
+ filterServicesByWithUser(user, startDocumentId, limit, body) {
245
+ return super
246
+ .filterServicesBy(startDocumentId, limit, body)
247
+ .then((svcs) => this.decryptServices(user.healthcarePartyId || user.patientId, svcs.rows).then((decryptedRows) => Object.assign(svcs, { rows: decryptedRows })));
248
+ }
236
249
  /**
237
250
  * Lists contacts by opening date within a date range and decrypts the results for the given user.
238
251
  * @param user the user for decryption
@@ -939,6 +952,16 @@ class IccContactXApi extends icc_api_1.IccContactApi {
939
952
  return this.crypto.xapi.owningEntityIdsOf({ entity: contact, type: utils_1.EntityWithDelegationTypeName.Contact }, undefined);
940
953
  });
941
954
  }
955
+ /**
956
+ * @param service a service
957
+ * @return the id of the patient that the service refers to, retrieved from the encrypted metadata. Normally there should only be one element
958
+ * in the returned array, but in case of entity merges there could be multiple values.
959
+ */
960
+ decryptPatientIdOfService(service) {
961
+ return __awaiter(this, void 0, void 0, function* () {
962
+ return this.crypto.xapi.owningEntityIdsOf({ entity: service, type: utils_1.EntityWithDelegationTypeName.Contact }, undefined);
963
+ });
964
+ }
942
965
  /**
943
966
  * @return if the logged data owner has write access to the content of the given contact
944
967
  */
@@ -1 +1 @@
1
- {"version":3,"file":"icc-contact-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-contact-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAGtD,sDAAsC;AAEtC,iCAAgC;AAChC,4BAA2B;AAC3B,kDAAiD;AACjD,oDAAyF;AAEzF,uDAA+C;AAC/C,qEAAiE;AAEjE,mCASgB;AAChB,0EAAgG;AAChG,wEAAoE;AAQpE,4DAAwE;AACxE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAEzD,kEAA8D;AAE9D,MAAa,cAAe,SAAQ,uBAAa;IAM/C,IAAI,OAAO;QACT,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,C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AAI,CAAC,OAAO,CAAC,WAAW,CAAC,iBAAkB,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA,GAAA,CACnG,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAAC,CAAA;QACxC,CAAC;KAAA;IAED;;;;;OAKG;IACH,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;AAj0CD,wCAi0CC","sourcesContent":["import { IccAuthApi, IccContactApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport i18n from './rsrc/contact.i18n'\n\nimport * as moment from 'moment'\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\nimport { Contact, FilterChainService, ListOfIds, Service } from '../icc-api/model/models'\nimport { PaginatedListContact } from '../icc-api/model/PaginatedListContact'\nimport { utf8_2ua } from './utils/binary-utils'\nimport { ServiceByIdsFilter } from './filters/ServiceByIdsFilter'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport {\n before,\n decryptObject,\n EncryptedFieldsManifest,\n encryptObject,\n EntityWithDelegationTypeName,\n parseEncryptedFields,\n subscribeToEntityEvents,\n SubscriptionOptions,\n} from './utils'\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 { IccUserXApi } from './icc-user-x-api'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { AbstractFilter } from './filters/filters'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\n\nexport class IccContactXApi extends IccContactApi implements EncryptedEntityXApi<models.Contact> {\n i18n: any = i18n\n private readonly contactEncryptedFields: EncryptedFieldsManifest\n private readonly serviceEncryptedFieldsNoContent: EncryptedFieldsManifest | undefined\n private readonly serviceEncryptedFieldsWithContent: EncryptedFieldsManifest\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Contact))\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 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 contactEncryptedKeys: string[] = ['descr'],\n serviceEncryptedKeys: string[] = []\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n if (contactEncryptedKeys.some((key) => key.startsWith('services'))) {\n throw new Error(\"You can't customise encryption of the `services` field of Contact. Use the serviceEncryptedKeys parameter instead.\")\n }\n if (serviceEncryptedKeys.some((key) => key.startsWith('content'))) {\n throw new Error(\"You can't customise encryption of the `content` of a Service. The content values for services is automatically encrypted.\")\n }\n this.crypto = crypto\n this.dataOwnerApi = dataOwnerApi\n this.userApi = userApi\n this.authApi = authApi\n this.contactEncryptedFields = parseEncryptedFields(contactEncryptedKeys, 'Contact.')\n const customServiceEncryptedFields = parseEncryptedFields(serviceEncryptedKeys, 'Service.')\n if (serviceEncryptedKeys.length > 0) {\n this.serviceEncryptedFieldsNoContent = customServiceEncryptedFields\n }\n this.serviceEncryptedFieldsWithContent = {\n ...customServiceEncryptedFields,\n topLevelFields: [...customServiceEncryptedFields.topLevelFields, { fieldName: 'content', fieldPath: 'Service.content' }],\n }\n }\n\n /**\n * Creates a new instance of contact with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this contact refers to.\n * @param c initialised data for the contact. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify other\n * 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 * - sfkOption: specifies which sfk of the owning entity to use.\n * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates\n * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,\n * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.\n * @return a new instance of contact.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient,\n c: any,\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n ignoreAutoDelegations?: boolean // default is considered false\n alternateRootDelegation?: string\n } = {}\n ): Promise<models.Contact> {\n const contact = new models.Contact({\n ...(c ?? {}),\n _type: 'org.taktik.icure.entities.Contact',\n id: c?.id ?? this.crypto.primitives.randomUuid(),\n created: c?.created ?? new Date().getTime(),\n modified: c?.modified ?? new Date().getTime(),\n responsible: c?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: c?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: c?.codes ?? [],\n tags: c?.tags ?? [],\n groupId: c?.groupId ?? this.crypto.primitives.randomUuid(),\n subContacts: c?.subContacts ?? [],\n services: c?.services ?? [],\n openingDate: c?.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 == true\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 contact,\n EntityWithDelegationTypeName.Contact,\n patient.id,\n sfk,\n true,\n extraDelegations,\n options.alternateRootDelegation\n )\n return new models.Contact(initialisationInfo.updatedEntity)\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 contacts with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the contacts of 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) {\n return await this.crypto.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }).then((keysHierarchy) =>\n keysHierarchy && keysHierarchy.length > 0\n ? Promise.all(\n keysHierarchy\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 }\n\n /**\n * Same as {@link findBy} but it will only return the ids of the contacts. It can also filter the contacts where Contact.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 await this.crypto.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }).then((keysHierarchy) =>\n keysHierarchy && keysHierarchy.length > 0\n ? Promise.all(\n keysHierarchy\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.findContactIdsByDataOwnerPatientOpeningDate(hcpartyId, extractedKeys, startDate, endDate, descending)\n )\n ).then((results) => _.uniq(_.flatMap(results)))\n : Promise.resolve([])\n )\n }\n\n /**\n * @deprecated Unused method, bugged: won't work if `hcpartyId` is not the parent hcp and doesn't decrypt contacts.\n * Will be permanently removed in version 8.2.0\n */\n async findByPatientSFKs(hcpartyId: string, patients: Array<models.Patient>): Promise<Array<models.Contact>> {\n const perHcpId: { [key: string]: string[] } = {}\n for (const patient of patients) {\n ;(await this.crypto.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }))\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 .forEach(({ hcpartyId, extractedKeys }) => {\n ;(perHcpId[hcpartyId] || (perHcpId[hcpartyId] = [])).push(...extractedKeys)\n })\n }\n\n return _.uniqBy(\n _.flatMap(\n await Promise.all(\n Object.keys(perHcpId).map((hcpId) =>\n this.findContactsByHCPartyPatientForeignKeys(\n hcpartyId,\n new models.ListOfIds({\n ids: perHcpId[hcpId],\n })\n )\n )\n )\n ),\n (x) => x.id\n )\n }\n\n filterBy(startKey?: string, startDocumentId?: string, limit?: number, body?: models.FilterChainContact): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listContactsByOpeningDate(\n startDate: number,\n endDate: number,\n hcpartyid: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listServices(body?: ListOfIds): Promise<Array<Service>> {\n throw new Error('Cannot call a method that returns services without providing a user for de/encryption')\n }\n\n findByHCPartyFormId(hcPartyId?: string, formId?: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n findByHCPartyFormIds(hcPartyId?: string, body?: models.ListOfIds): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n getContact(contactId: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n getContacts(body?: models.ListOfIds): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n modifyContact(body?: Contact): never {\n throw new Error('Cannot call a method that modify contacts without providing a user for de/encryption')\n }\n\n modifyContacts(body?: Array<Contact>): never {\n throw new Error('Cannot call a method that modify contacts without providing a user for de/encryption')\n }\n\n createContact(body?: Contact): never {\n throw new Error('Cannot call a method that modify contacts without providing a user for de/encryption')\n }\n\n /**\n * @deprecated use {@link findContactIdsByDataOwnerPatientOpeningDate} instead.\n */\n findByHCPartyPatientSecretFKeys(\n hcPartyId: string,\n secretFKeys: string,\n planOfActionIds?: string,\n skipClosedContacts?: boolean\n ): Promise<Array<models.Contact>> {\n return super\n .findByHCPartyPatientSecretFKeys(hcPartyId, secretFKeys, planOfActionIds, skipClosedContacts)\n .then((contacts) => this.decrypt(hcPartyId, contacts))\n }\n\n /**\n * @deprecated use {@link findContactIdsByDataOwnerPatientOpeningDate} instead.\n */\n findByHCPartyPatientSecretFKeysArray(\n hcPartyId: string,\n secretFKeys: string[],\n planOfActionIds?: string,\n skipClosedContacts?: boolean\n ): Promise<Array<models.Contact> | any> {\n return super\n .findByHCPartyPatientSecretFKeysUsingPost(hcPartyId, planOfActionIds, skipClosedContacts, secretFKeys)\n .then((contacts) => this.decrypt(hcPartyId, contacts))\n }\n\n /**\n * Filters contacts using a filter chain and decrypts the results for the given user.\n * @param user the user for decryption\n * @param startDocumentId optional document id to start pagination from\n * @param limit maximum number of results to return\n * @param body the filter chain to apply\n * @return a paginated list of decrypted contacts\n */\n filterByWithUser(\n user: models.User,\n startDocumentId?: string,\n limit?: number,\n body?: models.FilterChainContact\n ): Promise<PaginatedListContact | any> {\n return super\n .filterContactsBy(startDocumentId, limit, body)\n .then((ctcs) =>\n this.decrypt(user.healthcarePartyId! || user.patientId!, ctcs.rows!).then((decryptedRows) => Object.assign(ctcs, { rows: decryptedRows }))\n )\n }\n\n /**\n * Lists contacts by opening date within a date range and decrypts the results for the given user.\n * @param user the user for decryption\n * @param startDate start of the date range (format: YYYYMMDDHHmmss)\n * @param endDate end of the date range (format: YYYYMMDDHHmmss)\n * @param hcpartyid the healthcare party id\n * @param startKey optional start key for pagination\n * @param startDocumentId optional document id to start pagination from\n * @param limit maximum number of results to return\n * @return a paginated list of decrypted contacts\n */\n listContactsByOpeningDateWithUser(\n user: models.User,\n startDate: number,\n endDate: number,\n hcpartyid: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): Promise<PaginatedListContact | any> {\n return super\n .listContactsByOpeningDate(startDate, endDate, hcpartyid, startKey, startDocumentId, limit)\n .then((ctcs) =>\n this.decrypt(user.healthcarePartyId! || user.patientId!, ctcs.rows!).then((decryptedRows) => Object.assign(ctcs, { rows: decryptedRows }))\n )\n }\n\n /**\n * Gets a service by id and decrypts it for the given user.\n * @param user the user for decryption\n * @param serviceId the service id\n * @return the decrypted service\n */\n getServiceWithUser(user: models.User, serviceId: string): Promise<Service> {\n return super\n .getService(serviceId)\n .then((service) => this.decryptServices(user.healthcarePartyId ?? user.patientId ?? user.deviceId!, [service]))\n .then((decrypted) => decrypted[0])\n }\n\n /**\n * Lists services by their ids and decrypts them for the given user.\n * @param user the user for decryption\n * @param serviceIds the list of service ids to retrieve\n * @return an array of decrypted services\n */\n listServicesWithUser(user: models.User, serviceIds: ListOfIds): Promise<Array<Service> | any> {\n return super\n .filterServicesBy(undefined, serviceIds.ids?.length, new FilterChainService({ filter: new ServiceByIdsFilter({ ids: serviceIds.ids }) }))\n .then((paginatedList) => this.decryptServices(user.healthcarePartyId ?? user.patientId ?? user.deviceId!, paginatedList.rows ?? []))\n }\n\n /**\n * Finds contacts by healthcare party and form id and decrypts them for the given user.\n * @param user the user for decryption\n * @param hcPartyId the healthcare party id\n * @param formId the form id\n * @return an array of decrypted contacts\n */\n findByHCPartyFormIdWithUser(user: models.User, hcPartyId: string, formId: string): Promise<Array<models.Contact> | any> {\n return super.findByHCPartyFormId(hcPartyId, formId).then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n }\n\n /**\n * Finds contacts by healthcare party and multiple form ids and decrypts them for the given user.\n * @param user the user for decryption\n * @param hcPartyId the healthcare party id\n * @param body the list of form ids\n * @return an array of decrypted contacts\n */\n findByHCPartyFormIdsWithUser(user: models.User, hcPartyId: string, body: models.ListOfIds): Promise<Array<models.Contact> | any> {\n return super.findByHCPartyFormIds(hcPartyId, body).then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n }\n\n /**\n * Gets a contact by id and decrypts it for the given user.\n * @param user the user for decryption\n * @param contactId the contact id\n * @return the decrypted contact\n */\n getContactWithUser(user: models.User, contactId: string): Promise<models.Contact> {\n return super\n .getContact(contactId)\n .then((ctc) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, [ctc]))\n .then((ctcs) => ctcs[0])\n }\n\n /**\n * Gets multiple contacts by their ids and decrypts them for the given user.\n * @param user the user for decryption\n * @param body the list of contact ids\n * @return an array of decrypted contacts\n */\n getContactsWithUser(user: models.User, body?: models.ListOfIds): Promise<Array<models.Contact> | any> {\n return super.getContacts(body).then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n }\n\n /**\n * Modifies an existing contact by encrypting it and saving it to the database.\n * @param user the user for encryption\n * @param body the contact to modify\n * @return the modified and decrypted contact\n */\n async modifyContactWithUser(user: models.User, body?: models.Contact): Promise<models.Contact | any> {\n return body ? this.modifyContactAs(this.dataOwnerApi.getDataOwnerIdOf(user)!, body) : null\n }\n\n private modifyContactAs(dataOwner: string, body: models.Contact): Promise<models.Contact> {\n return this.encryptAs(dataOwner, [_.cloneDeep(body)])\n .then((ctcs) => super.modifyContact(ctcs[0]))\n .then((ctc) => this.decrypt(dataOwner, [ctc]))\n .then((ctcs) => ctcs[0])\n }\n\n /**\n * Modifies multiple existing contacts by encrypting them and saving them to the database.\n * @param user the user for encryption\n * @param bodies the array of contacts to modify\n * @return an array of modified and decrypted contacts\n */\n async modifyContactsWithUser(user: models.User, bodies?: Array<models.Contact>): Promise<models.Contact[] | any> {\n return bodies\n ? this.encrypt(\n user,\n bodies.map((c) => _.cloneDeep(c))\n )\n .then((ctcs) => super.modifyContacts(ctcs))\n .then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n : null\n }\n\n /**\n * Creates a new contact by encrypting it and saving it to the database.\n * @param user the user for encryption\n * @param body the contact to create\n * @return the created and decrypted contact\n */\n async createContactWithUser(user: models.User, body?: models.Contact): Promise<models.Contact | null> {\n return body\n ? this.encrypt(user, [_.cloneDeep(body)])\n .then((ctcs) => super.createContact(ctcs[0]))\n .then((ctc) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, [ctc]))\n .then((ctcs) => ctcs[0])\n : null\n }\n\n /**\n * Creates multiple new contacts by encrypting them and saving them to the database.\n * @param user the user for encryption\n * @param bodies the array of contacts to create\n * @return an array of created and decrypted contacts\n */\n async createContactsWithUser(user: models.User, bodies?: Array<models.Contact>): Promise<models.Contact[] | null> {\n return bodies\n ? this.encrypt(\n user,\n bodies.map((c) => _.cloneDeep(c))\n )\n .then((ctcs) => super.createContacts(ctcs))\n .then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n : null\n }\n\n /**\n * Encrypts the content and custom encrypted fields of services.\n * Services with compound values are recursively encrypted.\n * @param key the encryption key\n * @param rawKey the raw encryption key as a string\n * @param services the array of services to encrypt\n * @return a promise containing the encrypted services\n */\n encryptServices(key: CryptoKey, rawKey: string, services: Service[]): PromiseLike<Service[]> {\n return Promise.all(\n services.map(async (svc) => {\n if (\n svc.content &&\n Object.values(svc.content).every(\n (c) =>\n c.compoundValue &&\n !c.stringValue &&\n !c.documentId &&\n !c.measureValue &&\n !c.medicationValue &&\n (c.booleanValue === null || c.booleanValue === undefined) &&\n (c.numberValue === null || c.numberValue === undefined) &&\n !c.instantValue &&\n !c.fuzzyDateValue &&\n !c.binaryValue\n )\n ) {\n const recursivelyEncryptedContent = Object.fromEntries(\n await Promise.all(\n Object.entries(svc.content).map(async (p) => {\n if (p[1].compoundValue?.length) {\n return [p[0], { ...p[1], compoundValue: await this.encryptServices(key, rawKey, p[1].compoundValue!) }]\n } else return p\n })\n )\n )\n const copyWithEncryptedContent = { ...svc, content: recursivelyEncryptedContent }\n return this.serviceEncryptedFieldsNoContent\n ? encryptObject(\n copyWithEncryptedContent,\n (obj) => {\n return this.crypto.primitives.AES.encrypt(key, utf8_2ua(JSON.stringify(obj)), rawKey)\n },\n (encryptedSelf) => this.crypto.xapi.tryDecryptJson([{ key, raw: rawKey }], encryptedSelf, false),\n this.serviceEncryptedFieldsNoContent,\n 'service'\n )\n : copyWithEncryptedContent\n } else {\n return encryptObject(\n svc,\n (obj) => {\n return this.crypto.primitives.AES.encrypt(key, utf8_2ua(JSON.stringify(obj)), rawKey)\n },\n (encryptedSelf) => this.crypto.xapi.tryDecryptJson([{ key, raw: rawKey }], encryptedSelf, false),\n this.serviceEncryptedFieldsWithContent,\n 'service'\n )\n }\n })\n )\n }\n\n /**\n * Encrypts contacts for the given user including all services within the contacts.\n * @param user the user for encryption\n * @param ctcs the array of contacts to encrypt\n * @return a promise containing the encrypted contacts\n */\n encrypt(user: models.User, ctcs: Array<models.Contact>) {\n return this.encryptAs(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs)\n }\n\n private async encryptAs(hcpartyId: string, ctcs: Array<models.Contact>): Promise<models.Contact[]> {\n const initializedContacts: models.Contact[] = []\n for (const ctc of ctcs) {\n initializedContacts.push((await this.crypto.xapi.ensureEncryptionKeysInitialised(ctc, EntityWithDelegationTypeName.Contact)) ?? ctc)\n }\n const allEncrypted = await this.crypto.xapi.doManyIncrementallyDecryptingKeys(\n initializedContacts,\n EntityWithDelegationTypeName.Contact,\n async (entity, t, keys) => {\n for (const k of keys) {\n try {\n const encrypted = new Contact(\n await encryptObject(\n {\n ...entity,\n services: entity.services ? await this.encryptServices(k.key, k.raw, entity.services) : [],\n },\n (obj) => {\n return this.crypto.primitives.AES.encrypt(k.key, utf8_2ua(JSON.stringify(obj)), k.raw)\n },\n (encryptedSelf) => this.crypto.xapi.tryDecryptJson(keys, encryptedSelf, false),\n this.contactEncryptedFields,\n EntityWithDelegationTypeName.Contact\n )\n )\n return { success: encrypted }\n } catch (e) {\n console.warn(`Failed to encrypt contact ${entity.id} with key ${k.raw}`)\n }\n }\n return null\n }\n )\n if (ctcs.length != allEncrypted.size) {\n throw new Error(`Couldn't encrypt contacts ${ctcs.flatMap((e) => (allEncrypted.has(e.id!) ? [] : [e.id!]))}`)\n }\n return ctcs.map((e) => allEncrypted.get(e.id!)!)\n }\n\n /**\n * Decrypts contacts and all their encrypted content.\n * @param hcpartyId the healthcare party id (deprecated parameter, kept for compatibility)\n * @param ctcs the array of encrypted contacts\n * @return a promise containing the decrypted contacts\n */\n async decrypt(hcpartyId: string, ctcs: Array<models.Contact>): Promise<Array<models.Contact>> {\n return (await this.crypto.xapi.tryDecryptEntities(ctcs, EntityWithDelegationTypeName.Contact, (x) => new Contact(x))).map(({ entity }) => entity)\n }\n\n /**\n * Decrypts services and all their encrypted content.\n * @param hcpartyId the healthcare party id (deprecated parameter, kept for compatibility)\n * @param svcs the array of encrypted services\n * @return a promise containing the decrypted services\n */\n async decryptServices(hcpartyId: string, svcs: Array<models.Service>): Promise<Array<models.Service>> {\n /*TODO\n * not super efficient, re-decrypts the encryption key metadata of services multiple times, but should mostly rely\n * on cached exchange data after the first decryption and should not do any extra requests to the db.\n * We could ensure to use only cached exchange data by doing limited-size batches of services from the same contact\n * id.\n */\n return (await this.crypto.xapi.tryDecryptEntities(svcs, EntityWithDelegationTypeName.Contact, (x) => new Service(x))).map(({ entity }) => entity)\n }\n\n /**\n * Finds the contact containing the given service id, prioritizing the latest version by valueDate.\n * @param ctcs the array of contacts to search\n * @param svcId the service id to find\n * @return the contact containing the service or undefined if not found\n */\n contactOfService(ctcs: Array<models.Contact>, svcId: string): models.Contact | undefined {\n let latestContact: models.Contact | undefined = undefined\n let latestService: models.Service\n ctcs.forEach((c) => {\n const s: models.Service | undefined = c.services!.find((it) => svcId === it.id)\n if (s && (!latestService || moment(s.valueDate).isAfter(moment(latestService.valueDate)))) {\n latestContact = c\n latestService = s\n }\n })\n return latestContact\n }\n\n /**\n * Extracts and filters services from contacts, keeping only the latest version of each service and excluding deleted services.\n * @param ctcs the array of contacts containing services\n * @param filter a predicate function to filter services: (service, contact) => boolean\n * @return an array of filtered services with contactId set\n */\n filteredServices(ctcs: Array<models.Contact>, filter: any): Array<models.Service> {\n const byIds: { [key: string]: models.Service } = {}\n ctcs.forEach((c) =>\n (c.services || [])\n .filter((s) => filter(s, c))\n .forEach((s) => {\n const ps = byIds[s.id!]\n if (!ps || !ps.modified || (s.modified && ps.modified < s.modified)) {\n byIds[s.id!] = s\n s.contactId = c.id\n }\n })\n )\n return _.values(byIds).filter((s: any) => !s.deleted && !s.endOfLife)\n }\n\n /**\n * Extracts and filters services from contacts, returning a promise. Same as filteredServices but wrapped in a promise.\n * @param ctcs the array of contacts containing services\n * @param filter a predicate function to filter services: (service, contact) => boolean\n * @return a promise containing an array of filtered services\n */\n filterServices(ctcs: Array<models.Contact>, filter: any): Promise<Array<models.Service>> {\n return Promise.resolve(this.filteredServices(ctcs, filter))\n }\n\n /**\n * Gets all services from a contact that have the specified label.\n * @param ctc the contact\n * @param label the service label to filter by\n * @return an array of services with the given label\n */\n services(ctc: models.Contact, label: string) {\n return ctc.services!.filter((s) => s.label === label)\n }\n\n /**\n * Gets the preferred content for a service based on language preference, falling back to French then first available language.\n * @param svc the service\n * @param lng the preferred language code\n * @return the content in the preferred language or null if no content exists\n */\n preferredContent(svc: models.Service, lng: string) {\n return (\n svc && svc.content && (svc.content[lng] || svc.content['fr'] || (Object.keys(svc.content)[0] ? svc.content[Object.keys(svc.content)[0]] : null))\n )\n }\n\n /**\n * Extracts the value from content, prioritizing string, number, measure, medication, and boolean values in that order.\n * @param c the content\n * @return the extracted value or undefined if no value is present\n */\n contentValue(c: models.Content) {\n return (\n c.stringValue ||\n ((c.numberValue || c.numberValue === 0) && c.numberValue) ||\n (c.measureValue && (c.measureValue.value || c.measureValue.value === 0) ? c.measureValue : null) ||\n c.medicationValue ||\n c.booleanValue\n )\n }\n\n /**\n * Gets a short human-readable description of a service in the preferred language.\n * @param svc the service\n * @param lng the preferred language code\n * @return a short description of the service content or empty string\n */\n shortServiceDescription(svc: models.Service, lng: string) {\n const c = this.preferredContent(svc, lng)\n return !c ? '' : this.shortContentDescription(c, lng, svc.label)\n }\n\n /**\n * Gets a short human-readable description of content, formatted appropriately for the content type.\n * @param c the content\n * @param lng the language code for medication formatting\n * @param label optional label used for boolean content display\n * @return a short description of the content\n */\n shortContentDescription(c: models.Content, lng: string, label?: string) {\n return (\n c.stringValue ||\n ((c.numberValue || c.numberValue === 0) && c.numberValue) ||\n (c.measureValue &&\n '' +\n (c.measureValue.value || c.measureValue.value === 0 ? c.measureValue.value : '-') +\n (c.measureValue.unit ? ' ' + c.measureValue.unit : '')) ||\n (c.medicationValue ? this.medication().medicationToString(c.medicationValue, lng) : null) ||\n (c.booleanValue && label) ||\n 'OK'\n )\n }\n\n /**\n * Extracts the medication value from a service's content in the preferred language.\n * @param svc the service\n * @param lng the preferred language code\n * @return the medication value or undefined if not present\n */\n medicationValue(svc: models.Service, lng: string) {\n const c =\n svc && svc.content && (svc.content[lng] || svc.content['fr'] || (Object.keys(svc.content)[0] ? svc.content[Object.keys(svc.content)[0]] : null))\n return c && c.medicationValue\n }\n\n /**\n * Checks if content has any data value set (string, number, measure, boolean, medication, or document).\n * @param c the content to check\n * @return true if content has data, false otherwise\n */\n contentHasData(c: any): boolean {\n return c.stringValue || c.numberValue || c.measureValue || c.booleanValue || c.booleanValue === false || c.medicationValue || c.documentId\n }\n\n /**\n * Localizes a value by selecting the appropriate language from an object, falling back through FR, EN, and NL.\n * @param e the object with language-keyed values or a simple value\n * @param lng the preferred language code\n * @return the localized value or null if e is null/undefined\n */\n localize(e: any, lng: string) {\n if (!e) {\n return null\n }\n return e[lng] || e.fr || e.FR || e.en || e.EN || e.nl || e.NL\n }\n\n /**\n * Modifies the subcontacts this svc belongs to while minimizing the number of references to the svcs inside the subcontacts\n * After the invocation, there is at least one subcontact with provided poaId and heId that contains the svc\n * The svc is not removed from a previous subcontact it would belong to except if the new conditions are compatible\n * Note that undefined and null do not have the same meaning for formId\n * If formId is null: the subcontact which refers svc must have a null formId\n * If formId is undefined, the subcontact can have any value for formId\n *\n * When a svc does not exist yet in the current contact but exists in a previous contact, all the scs it was belonging to are\n * copied in the current contact\n *\n * the svc returned is the one that's inside the ctc\n *\n * @param ctc\n * @param user\n * @param ctcs\n * @param svc\n * @param formId\n * @param poaId aMap {heId2: [poaId11, poaId12], heId2: [poaId21] }\n * @param heId an Array of heIds, equivalent to poaIds = {heId: [], ...}\n * @param init\n * @returns {*}\n */\n\n promoteServiceInContact(\n ctc: models.Contact,\n user: models.User,\n ctcs: Array<models.Contact>,\n svc: models.Service,\n formId: string,\n poaIds?: { [key: string]: string[] },\n heIds?: Array<string>,\n init?: any\n ) {\n if (!ctc) {\n return null\n }\n const existing = ctc.services!.find((s) => s.id === svc.id)\n const promoted = _.extend(_.extend(existing || {}, svc), {\n author: user.id,\n responsible: this.dataOwnerApi.getDataOwnerIdOf(user),\n modified: new Date().getTime(),\n })\n if (!existing) {\n ;(ctc.services || (ctc.services = [])).push(promoted)\n }\n const allSubcontactsInCurrentContactContainingService = (ctc.subContacts || []).filter((csc) =>\n (csc.services || []).some((s) => s.serviceId === svc.id)\n )\n\n //Rearrange poaIds and heIds as a hierarchy\n const hierarchyOfHeAndPoaIds: { [key: string]: Array<any> } = {}\n ;(heIds || []).forEach((id) => (hierarchyOfHeAndPoaIds[id || '_'] = []))\n Object.keys(poaIds || {}).forEach((k: string) => {\n const poas = hierarchyOfHeAndPoaIds[k]\n if (poas) {\n hierarchyOfHeAndPoaIds[k] = _.concat(poas, (poaIds || {})[k])\n } else {\n hierarchyOfHeAndPoaIds[k] = (poaIds || {})[k]\n }\n })\n\n const pastCtc =\n (svc.contactId && svc.contactId !== ctc.id && ctcs.find((c) => c.id === svc.contactId)) ||\n ctcs.reduce(\n (selected: { s: models.Service | null; c: models.Contact | null }, c: models.Contact) => {\n const candidate = (c.services || []).find((s) => s.id === svc.id)\n return ctc.id !== c.id && candidate && (selected.s === null || before(selected.s.modified || 0, candidate.modified || 0))\n ? { s: candidate, c: c }\n : selected\n },\n { s: null, c: null }\n ).c\n //Make sure that all scs the svc was belonging to are copied inside the current contact\n pastCtc &&\n pastCtc\n .subContacts!.filter((psc) => psc.services!.some((s) => s.serviceId === svc.id))\n .forEach((psc) => {\n const sameInCurrent = allSubcontactsInCurrentContactContainingService.find(\n (csc) => csc.formId === psc.formId && csc.planOfActionId === psc.planOfActionId && csc.healthElementId === psc.healthElementId\n )\n if (sameInCurrent) {\n if (!sameInCurrent.services!.some((s) => s.serviceId === svc.id)) {\n sameInCurrent.services!.push({ serviceId: svc.id })\n }\n } else {\n const newSubContact = _.assign(_.assign({}, psc), {\n services: [{ serviceId: svc.id }],\n })\n ctc.subContacts!.push(newSubContact)\n allSubcontactsInCurrentContactContainingService.push(newSubContact)\n }\n })\n\n if (!Object.keys(hierarchyOfHeAndPoaIds).length) {\n hierarchyOfHeAndPoaIds._ = [] //Default is to have at least one option with heId equals to null (represented by _)\n }\n\n Object.keys(hierarchyOfHeAndPoaIds).forEach((heId: string | null) => {\n if (heId === '_') {\n heId = null\n }\n const subPoaIds = heId ? hierarchyOfHeAndPoaIds[heId] : []\n ;((subPoaIds || []).length ? subPoaIds : [null]).forEach((poaId) => {\n //Create or assign subcontacts for all pairs he/poa (can be null/null)\n let destinationSubcontact = ctc.subContacts!.find(\n (sc) =>\n (!formId || sc.formId === formId) &&\n ((!poaId && !sc.planOfActionId) || sc.planOfActionId === poaId) &&\n ((!heId && !sc.healthElementId) || sc.healthElementId === heId)\n )\n if (!destinationSubcontact) {\n ctc.subContacts!.push(\n (destinationSubcontact = new models.SubContact({\n formId: formId || undefined,\n planOfActionId: poaId,\n healthElementId: heId,\n services: [],\n }))\n )\n }\n\n const redundantSubcontact =\n allSubcontactsInCurrentContactContainingService.find((aSc) => destinationSubcontact === aSc) ||\n allSubcontactsInCurrentContactContainingService.find(\n (aSc) =>\n (!aSc.planOfActionId || aSc.planOfActionId === destinationSubcontact!.planOfActionId) &&\n (!aSc.healthElementId || aSc.healthElementId === destinationSubcontact!.healthElementId) &&\n (!aSc.formId || aSc.formId === destinationSubcontact!.formId)\n ) // Find a compatible sc: one that does not contain extra and ≠ information than the destination\n\n if (redundantSubcontact && redundantSubcontact !== destinationSubcontact) {\n redundantSubcontact.services!.splice(\n redundantSubcontact.services!.findIndex((link) => link.serviceId === svc.id),\n 1\n )\n }\n if (!destinationSubcontact.services!.some((s) => s.serviceId === svc.id)) {\n destinationSubcontact.services!.push({ serviceId: svc.id! })\n }\n })\n })\n\n return (init && init(promoted)) || promoted\n }\n\n /**\n * Checks if a service has numeric content (measure or number value) in the preferred language.\n * @param svc the service\n * @param lng the preferred language code\n * @return true if the service has numeric content, false otherwise\n */\n isNumeric(svc: models.Service, lng: string) {\n const c = this.preferredContent(svc, lng)\n return c && (c.measureValue || c.numberValue || c.numberValue == 0)\n }\n\n /**\n * Returns utility functions for working with services.\n * @return an object with helper methods for creating and manipulating services\n */\n service() {\n return {\n newInstance: (user: models.User, s: any) =>\n _.extend(\n {\n id: this.crypto.primitives.randomUuid(),\n _type: 'org.taktik.icure.entities.embed.Service',\n created: new Date().getTime(),\n modified: new Date().getTime(),\n responsible: s?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: s?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: [],\n tags: [],\n content: {},\n valueDate: parseInt(moment().format('YYYYMMDDHHmmss')),\n },\n s\n ),\n }\n }\n\n /**\n * Returns utility functions for working with medication content.\n * @return an object with helper methods for formatting and displaying medication information\n */\n medication() {\n const regimenScores: any = {\n afterwakingup: 63000,\n beforebreakfast: 70000,\n duringbreakfast: 80000,\n afterbreakfast: 90000,\n morning: 100000,\n betweenbreakfastandlunch: 103000,\n beforelunch: 113000,\n midday: 120000,\n duringlunch: 123000,\n afterlunch: 130000,\n afternoon: 140000,\n betweenlunchanddinner: 160000,\n beforedinner: 180000,\n duringdinner: 190000,\n afterdinner: 200000,\n evening: 210000,\n betweendinnerandsleep: 213000,\n thehourofsleep: 220000,\n night: 230000,\n beforemeals: -30000,\n betweenmeals: -20000,\n aftermeals: -10000,\n }\n\n const myself = {\n regimenScores: function () {\n return regimenScores\n },\n medicationNameToString: function (m: any): string {\n return m && m.compoundPrescription\n ? m.compoundPrescription\n : m && m.substanceProduct\n ? myself.productToString(m && m.substanceProduct)\n : myself.productToString(m && m.medicinalProduct)\n },\n reimbursementReasonToString: (m: any, lang: string) => {\n return m && m.reimbursementReason && m.reimbursementReason.label && m.reimbursementReason.label.hasOwnProperty(lang)\n ? m.reimbursementReason.label[lang]\n : ''\n },\n medicationToString: (m: any, lang: string) => {\n let res = `${myself.medicationNameToString(m)}, ${myself.posologyToString(m, lang)}`\n const reason = myself.reimbursementReasonToString(m, lang)\n res = m.numberOfPackages\n ? `${m.numberOfPackages} ${m.numberOfPackages > 1 ? this.i18n[lang].packagesOf : this.i18n[lang].packageOf} ${res}`\n : res\n res = m.duration ? `${res} ${this.i18n[lang].during} ${myself.durationToString(m.duration, lang)}` : res\n res = reason ? `${res} (${reason})` : res\n return res\n },\n productToString: (m: any): string => {\n if (!m) {\n return ''\n }\n return m.intendedname\n },\n posologyToString: (m: any, lang: string) => {\n if (m) {\n if (m.instructionForPatient && m.instructionForPatient.length) {\n return m.instructionForPatient\n }\n if (!m.regimen || !m.regimen.length) {\n return ''\n }\n\n const unit =\n m.regimen[0].administratedQuantity && m.regimen[0].administratedQuantity.administrationUnit\n ? m.regimen[0].administratedQuantity.administrationUnit.code\n : m.regimen[0].administratedQuantity && m.regimen[0].administratedQuantity.unit\n let quantity = m.regimen[0].administratedQuantity && m.regimen[0].administratedQuantity.quantity\n\n m.regimen.slice(1).find((ri: any) => {\n const oUnit =\n ri.administratedQuantity && ri.administratedQuantity.administrationUnit\n ? ri.administratedQuantity.administrationUnit.code\n : ri.administratedQuantity && ri.administratedQuantity.unit\n const oQuantity = ri.administratedQuantity && ri.administratedQuantity.quantity\n\n if (oQuantity !== quantity) {\n quantity = -1\n }\n return oUnit !== unit && oQuantity !== quantity\n })\n\n const cplxRegimen = !unit || quantity < 0\n const quantityUnit = cplxRegimen ? `1 ${this.i18n[lang].take_s_}` : `${quantity} ${unit || this.i18n[lang].take_s_}`\n\n const dayPeriod = m.regimen.find((r: any) => r.weekday !== null && r.weekday !== undefined)\n ? this.i18n[lang].weekly\n : m.regimen.find((r: any) => r.date)\n ? this.i18n[lang].monthly\n : this.i18n[lang].daily\n\n return `${quantityUnit}, ${m.regimen.length} x ${dayPeriod}, ${_.sortBy(\n m.regimen,\n (r) =>\n (r.date ? r.date * 1000000 : 29990000000000) +\n (r.dayNumber || 0) * 1000000 +\n ((r.weekday && r.weekday.weekNumber) || 0) * 7 * 1000000 +\n (r.timeOfDay ? r.timeOfDay : r.dayPeriod && r.dayPeriod.code ? (regimenScores[r.dayPeriod.code] as number) : 0)\n )\n .map((r) => (cplxRegimen ? myself.regimenToExtString(r, lang) : myself.regimenToString(r, lang)))\n .join(', ')}`\n }\n },\n frequencyToString: (m: any, lang: string) => {\n if (m.instructionForPatient && m.instructionForPatient.length) {\n return m.instructionForPatient\n }\n if (!m.regimen || !m.regimen.length) {\n return ''\n }\n\n const dayPeriod = m.regimen.find((r: any) => r.weekday !== null && r.weekday !== undefined)\n ? this.i18n[lang].weekly\n : m.regimen.find((r: any) => r.date)\n ? this.i18n[lang].monthly\n : this.i18n[lang].daily\n\n return `${m.regimen.length} x ${dayPeriod}`\n },\n durationToString: (d: models.Duration, lang: string) => {\n return d.value ? `${d.value} ${this.localize(d.unit!.label, lang)}` : ''\n },\n regimenToExtString: (r: models.RegimenItem, lang: string) => {\n const desc = myself.regimenToString(r, lang)\n return (\n (r.administratedQuantity && r.administratedQuantity.quantity && desc\n ? `${desc} (${r.administratedQuantity.quantity} ${\n (r.administratedQuantity.administrationUnit ? r.administratedQuantity.administrationUnit.code : r.administratedQuantity.unit) ||\n this.i18n[lang].take_s_\n })`\n : desc) || ''\n )\n },\n regimenToString: (r: models.RegimenItem, lang: string) => {\n let res = r.date\n ? `${this.i18n[lang].the} ${moment(r.date).format('DD/MM/YYYY')}`\n : r.dayNumber\n ? `${this.i18n[lang].onDay} ${r.dayNumber}`\n : r.weekday && r.weekday.weekday\n ? `${this.i18n[lang].on} ${r.weekday.weekday}`\n : null\n if (r.dayPeriod && r.dayPeriod.code && r.dayPeriod.code.length) {\n res = res\n ? `${res} ${this.i18n[lang][r.dayPeriod.code] || this.localize(r.dayPeriod.label, lang) || r.dayPeriod.code}`\n : this.i18n[lang][r.dayPeriod.code] || this.localize(r.dayPeriod.label, lang) || r.dayPeriod.code\n }\n if (r.timeOfDay) {\n const timeOfDay =\n r.timeOfDay === 120000\n ? this.i18n[lang].noon\n : `${Math.floor(r.timeOfDay / 10000)}:${('' + (Math.floor(r.timeOfDay / 100) % 100)).replace(/^(.)$/, '0$1')}`\n res = res ? res + ' ' + this.i18n[lang].at + ' ' + timeOfDay : timeOfDay\n }\n return res\n },\n localize: (s: any, lang: string) => {\n if (!s) {\n return s\n }\n return (\n this.i18n[lang][s] ||\n (this.i18n[lang][s.toLowerCase()] &&\n this.i18n[lang][s.toLowerCase()]\n .split('')\n .map((c: string, idx: number) => (idx >= s.length || s[idx].toLocaleLowerCase() === s[idx] ? c : c.toLocaleUpperCase()))\n .join('')) ||\n s\n ) //Applies the (lower/upper)case to the translated lowercase version of the input string (s)\n },\n }\n return myself\n }\n\n /**\n * @param contact a contact\n * @return the id of the patient that the contact 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(contact: models.Contact): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: contact, type: EntityWithDelegationTypeName.Contact }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given contact\n */\n async hasWriteAccess(contact: models.Contact): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: contact, type: EntityWithDelegationTypeName.Contact })\n }\n\n /**\n * Share an existing contact with other data owners, allowing them to access the non-encrypted data of the contact 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 contact.\n * @param contact the contact 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 * contact does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this contact 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 contact: models.Contact,\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.Contact> {\n return this.shareWithMany(contact, { [delegateId]: options })\n }\n\n /**\n * Share an existing contact with other data owners, allowing them to access the non-encrypted data of the contact and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param contact the contact 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 * contact does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this contact 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 contact: models.Contact,\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.Contact> {\n return (await this.tryShareWithMany(contact, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing contact with other data owners, allowing them to access the non-encrypted data of the contact and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param contact the contact 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 * contact does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this contact 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 contact: models.Contact,\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.Contact>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(contact, EntityWithDelegationTypeName.Contact)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyContactAs(self, entityWithEncryptionKey) : contact\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Contact,\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.bulkShareContacts(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])))\n }\n\n /**\n * Gets the data owners that have access to the contact and their permission levels.\n * @param entity the contact\n * @return a promise containing the permissions by data owner id and whether there are unknown anonymous data owners\n */\n getDataOwnersWithAccessTo(\n entity: models.Contact\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Contact })\n }\n\n /**\n * Gets all encryption keys available for the contact.\n * @param entity the contact\n * @return a promise containing an array of encryption key hex strings\n */\n getEncryptionKeysOf(entity: models.Contact): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Contact }, undefined)\n }\n\n /**\n * Subscribes to service events (create, update, delete) and receives decrypted services.\n * @param eventTypes the types of events to subscribe to\n * @param filter optional filter to apply to services\n * @param eventFired callback function invoked when an event occurs, receives the decrypted service\n * @param options optional subscription options\n * @return a connection that can be closed to unsubscribe\n */\n async subscribeToServiceEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Service> | undefined,\n eventFired: (dataSample: Service) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n const currentUser = await this.userApi.getCurrentUser()\n return subscribeToEntityEvents(\n this.host,\n this.authApi,\n 'Service',\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted: Service) => (await this.decryptServices(currentUser.healthcarePartyId!, [encrypted]))[0]\n ).then((ws) => new ConnectionImpl(ws))\n }\n\n /**\n * Subscribes to contact events (create, update, delete) and receives decrypted contacts.\n * @param eventTypes the types of events to subscribe to\n * @param filter optional filter to apply to contacts\n * @param eventFired callback function invoked when an event occurs, receives the decrypted contact\n * @param options optional subscription options\n * @return a connection that can be closed to unsubscribe\n */\n async subscribeToContactEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Contact> | undefined,\n eventFired: (dataSample: Contact) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n const currentUser = await this.userApi.getCurrentUser()\n return subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.Contact,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted: Contact) => (await this.decrypt(currentUser.healthcarePartyId!, [encrypted]))[0]\n ).then((ws) => new ConnectionImpl(ws))\n }\n\n /**\n * Creates or updates de-anonymization metadata for delegations in a contact.\n * @param entity the contact\n * @param delegates the array of delegate ids to create de-anonymization metadata for\n * @return a promise that completes when the metadata is created/updated\n */\n createDelegationDeAnonymizationMetadata(entity: Contact, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Contact }, delegates)\n }\n}\n"]}
1
+ {"version":3,"file":"icc-contact-x-api.js","sourceRoot":"","sources":["../../icc-x-api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AAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAAC,CAAA;QACxC,CAAC;KAAA;IAED;;;;;OAKG;IACH,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;AA/1CD,wCA+1CC","sourcesContent":["import { IccAuthApi, IccContactApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport i18n from './rsrc/contact.i18n'\n\nimport * as moment from 'moment'\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\nimport { Contact, FilterChainService, ListOfIds, Service } from '../icc-api/model/models'\nimport { PaginatedListContact } from '../icc-api/model/PaginatedListContact'\nimport { utf8_2ua } from './utils/binary-utils'\nimport { ServiceByIdsFilter } from './filters/ServiceByIdsFilter'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport {\n before,\n decryptObject,\n EncryptedFieldsManifest,\n encryptObject,\n EntityWithDelegationTypeName,\n parseEncryptedFields,\n subscribeToEntityEvents,\n SubscriptionOptions,\n} from './utils'\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 { IccUserXApi } from './icc-user-x-api'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { AbstractFilter } from './filters/filters'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { SecretIdUseOption } from './crypto/SecretIdUseOption'\n\nexport class IccContactXApi extends IccContactApi implements EncryptedEntityXApi<models.Contact> {\n i18n: any = i18n\n private readonly contactEncryptedFields: EncryptedFieldsManifest\n private readonly serviceEncryptedFieldsNoContent: EncryptedFieldsManifest | undefined\n private readonly serviceEncryptedFieldsWithContent: EncryptedFieldsManifest\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Contact))\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 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 contactEncryptedKeys: string[] = ['descr'],\n serviceEncryptedKeys: string[] = []\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n if (contactEncryptedKeys.some((key) => key.startsWith('services'))) {\n throw new Error(\"You can't customise encryption of the `services` field of Contact. Use the serviceEncryptedKeys parameter instead.\")\n }\n if (serviceEncryptedKeys.some((key) => key.startsWith('content'))) {\n throw new Error(\"You can't customise encryption of the `content` of a Service. The content values for services is automatically encrypted.\")\n }\n this.crypto = crypto\n this.dataOwnerApi = dataOwnerApi\n this.userApi = userApi\n this.authApi = authApi\n this.contactEncryptedFields = parseEncryptedFields(contactEncryptedKeys, 'Contact.')\n const customServiceEncryptedFields = parseEncryptedFields(serviceEncryptedKeys, 'Service.')\n if (serviceEncryptedKeys.length > 0) {\n this.serviceEncryptedFieldsNoContent = customServiceEncryptedFields\n }\n this.serviceEncryptedFieldsWithContent = {\n ...customServiceEncryptedFields,\n topLevelFields: [...customServiceEncryptedFields.topLevelFields, { fieldName: 'content', fieldPath: 'Service.content' }],\n }\n }\n\n /**\n * Creates a new instance of contact with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param patient the patient this contact refers to.\n * @param c initialised data for the contact. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify other\n * 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 * - sfkOption: specifies which sfk of the owning entity to use.\n * - ignoreAutoDelegations: if true the data won't be shared with the autodelegations of the user, but only with additional delegates\n * - alternateRootDelegation: by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,\n * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.\n * @return a new instance of contact.\n */\n async newInstance(\n user: models.User,\n patient: models.Patient,\n c: any,\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n sfkOption?: SecretIdUseOption\n ignoreAutoDelegations?: boolean // default is considered false\n alternateRootDelegation?: string\n } = {}\n ): Promise<models.Contact> {\n const contact = new models.Contact({\n ...(c ?? {}),\n _type: 'org.taktik.icure.entities.Contact',\n id: c?.id ?? this.crypto.primitives.randomUuid(),\n created: c?.created ?? new Date().getTime(),\n modified: c?.modified ?? new Date().getTime(),\n responsible: c?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: c?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: c?.codes ?? [],\n tags: c?.tags ?? [],\n groupId: c?.groupId ?? this.crypto.primitives.randomUuid(),\n subContacts: c?.subContacts ?? [],\n services: c?.services ?? [],\n openingDate: c?.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 == true\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 contact,\n EntityWithDelegationTypeName.Contact,\n patient.id,\n sfk,\n true,\n extraDelegations,\n options.alternateRootDelegation\n )\n return new models.Contact(initialisationInfo.updatedEntity)\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 contacts with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the contacts of 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) {\n return await this.crypto.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }).then((keysHierarchy) =>\n keysHierarchy && keysHierarchy.length > 0\n ? Promise.all(\n keysHierarchy\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 }\n\n /**\n * Same as {@link findBy} but it will only return the ids of the contacts. It can also filter the contacts where Contact.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 await this.crypto.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }).then((keysHierarchy) =>\n keysHierarchy && keysHierarchy.length > 0\n ? Promise.all(\n keysHierarchy\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.findContactIdsByDataOwnerPatientOpeningDate(hcpartyId, extractedKeys, startDate, endDate, descending)\n )\n ).then((results) => _.uniq(_.flatMap(results)))\n : Promise.resolve([])\n )\n }\n\n /**\n * @deprecated Unused method, bugged: won't work if `hcpartyId` is not the parent hcp and doesn't decrypt contacts.\n * Will be permanently removed in version 8.2.0\n */\n async findByPatientSFKs(hcpartyId: string, patients: Array<models.Patient>): Promise<Array<models.Contact>> {\n const perHcpId: { [key: string]: string[] } = {}\n for (const patient of patients) {\n ;(await this.crypto.xapi.secretIdsForHcpHierarchyOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }))\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 .forEach(({ hcpartyId, extractedKeys }) => {\n ;(perHcpId[hcpartyId] || (perHcpId[hcpartyId] = [])).push(...extractedKeys)\n })\n }\n\n return _.uniqBy(\n _.flatMap(\n await Promise.all(\n Object.keys(perHcpId).map((hcpId) =>\n this.findContactsByHCPartyPatientForeignKeys(\n hcpartyId,\n new models.ListOfIds({\n ids: perHcpId[hcpId],\n })\n )\n )\n )\n ),\n (x) => x.id\n )\n }\n\n filterBy(startKey?: string, startDocumentId?: string, limit?: number, body?: models.FilterChainContact): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listContactsByOpeningDate(\n startDate: number,\n endDate: number,\n hcpartyid: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listServices(body?: ListOfIds): Promise<Array<Service>> {\n throw new Error('Cannot call a method that returns services without providing a user for de/encryption')\n }\n\n findByHCPartyFormId(hcPartyId?: string, formId?: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n findByHCPartyFormIds(hcPartyId?: string, body?: models.ListOfIds): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n getContact(contactId: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n getContacts(body?: models.ListOfIds): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n modifyContact(body?: Contact): never {\n throw new Error('Cannot call a method that modify contacts without providing a user for de/encryption')\n }\n\n modifyContacts(body?: Array<Contact>): never {\n throw new Error('Cannot call a method that modify contacts without providing a user for de/encryption')\n }\n\n createContact(body?: Contact): never {\n throw new Error('Cannot call a method that modify contacts without providing a user for de/encryption')\n }\n\n /**\n * @deprecated use {@link findContactIdsByDataOwnerPatientOpeningDate} instead.\n */\n findByHCPartyPatientSecretFKeys(\n hcPartyId: string,\n secretFKeys: string,\n planOfActionIds?: string,\n skipClosedContacts?: boolean\n ): Promise<Array<models.Contact>> {\n return super\n .findByHCPartyPatientSecretFKeys(hcPartyId, secretFKeys, planOfActionIds, skipClosedContacts)\n .then((contacts) => this.decrypt(hcPartyId, contacts))\n }\n\n /**\n * @deprecated use {@link findContactIdsByDataOwnerPatientOpeningDate} instead.\n */\n findByHCPartyPatientSecretFKeysArray(\n hcPartyId: string,\n secretFKeys: string[],\n planOfActionIds?: string,\n skipClosedContacts?: boolean\n ): Promise<Array<models.Contact> | any> {\n return super\n .findByHCPartyPatientSecretFKeysUsingPost(hcPartyId, planOfActionIds, skipClosedContacts, secretFKeys)\n .then((contacts) => this.decrypt(hcPartyId, contacts))\n }\n\n /**\n * Filters contacts using a filter chain and decrypts the results for the given user.\n * @param user the user for decryption\n * @param startDocumentId optional document id to start pagination from\n * @param limit maximum number of results to return\n * @param body the filter chain to apply\n * @return a paginated list of decrypted contacts\n */\n filterByWithUser(\n user: models.User,\n startDocumentId?: string,\n limit?: number,\n body?: models.FilterChainContact\n ): Promise<PaginatedListContact | any> {\n return super\n .filterContactsBy(startDocumentId, limit, body)\n .then((ctcs) =>\n this.decrypt(user.healthcarePartyId! || user.patientId!, ctcs.rows!).then((decryptedRows) => Object.assign(ctcs, { rows: decryptedRows }))\n )\n }\n\n /**\n * Filters services using a filter chain and decrypts the results for the given user.\n * @param user the user for decryption\n * @param startDocumentId optional document id to start pagination from\n * @param limit maximum number of results to return\n * @param body the filter chain to apply\n * @return a paginated list of decrypted services\n */\n filterServicesByWithUser(\n user: models.User,\n startDocumentId?: string,\n limit?: number,\n body?: models.FilterChainService\n ): Promise<PaginatedListContact | any> {\n return super\n .filterServicesBy(startDocumentId, limit, body)\n .then((svcs) =>\n this.decryptServices(user.healthcarePartyId! || user.patientId!, svcs.rows!).then((decryptedRows) => Object.assign(svcs, { rows: decryptedRows }))\n )\n }\n\n /**\n * Lists contacts by opening date within a date range and decrypts the results for the given user.\n * @param user the user for decryption\n * @param startDate start of the date range (format: YYYYMMDDHHmmss)\n * @param endDate end of the date range (format: YYYYMMDDHHmmss)\n * @param hcpartyid the healthcare party id\n * @param startKey optional start key for pagination\n * @param startDocumentId optional document id to start pagination from\n * @param limit maximum number of results to return\n * @return a paginated list of decrypted contacts\n */\n listContactsByOpeningDateWithUser(\n user: models.User,\n startDate: number,\n endDate: number,\n hcpartyid: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): Promise<PaginatedListContact | any> {\n return super\n .listContactsByOpeningDate(startDate, endDate, hcpartyid, startKey, startDocumentId, limit)\n .then((ctcs) =>\n this.decrypt(user.healthcarePartyId! || user.patientId!, ctcs.rows!).then((decryptedRows) => Object.assign(ctcs, { rows: decryptedRows }))\n )\n }\n\n /**\n * Gets a service by id and decrypts it for the given user.\n * @param user the user for decryption\n * @param serviceId the service id\n * @return the decrypted service\n */\n getServiceWithUser(user: models.User, serviceId: string): Promise<Service> {\n return super\n .getService(serviceId)\n .then((service) => this.decryptServices(user.healthcarePartyId ?? user.patientId ?? user.deviceId!, [service]))\n .then((decrypted) => decrypted[0])\n }\n\n /**\n * Lists services by their ids and decrypts them for the given user.\n * @param user the user for decryption\n * @param serviceIds the list of service ids to retrieve\n * @return an array of decrypted services\n */\n listServicesWithUser(user: models.User, serviceIds: ListOfIds): Promise<Array<Service> | any> {\n return super\n .filterServicesBy(undefined, serviceIds.ids?.length, new FilterChainService({ filter: new ServiceByIdsFilter({ ids: serviceIds.ids }) }))\n .then((paginatedList) => this.decryptServices(user.healthcarePartyId ?? user.patientId ?? user.deviceId!, paginatedList.rows ?? []))\n }\n\n /**\n * Finds contacts by healthcare party and form id and decrypts them for the given user.\n * @param user the user for decryption\n * @param hcPartyId the healthcare party id\n * @param formId the form id\n * @return an array of decrypted contacts\n */\n findByHCPartyFormIdWithUser(user: models.User, hcPartyId: string, formId: string): Promise<Array<models.Contact> | any> {\n return super.findByHCPartyFormId(hcPartyId, formId).then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n }\n\n /**\n * Finds contacts by healthcare party and multiple form ids and decrypts them for the given user.\n * @param user the user for decryption\n * @param hcPartyId the healthcare party id\n * @param body the list of form ids\n * @return an array of decrypted contacts\n */\n findByHCPartyFormIdsWithUser(user: models.User, hcPartyId: string, body: models.ListOfIds): Promise<Array<models.Contact> | any> {\n return super.findByHCPartyFormIds(hcPartyId, body).then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n }\n\n /**\n * Gets a contact by id and decrypts it for the given user.\n * @param user the user for decryption\n * @param contactId the contact id\n * @return the decrypted contact\n */\n getContactWithUser(user: models.User, contactId: string): Promise<models.Contact> {\n return super\n .getContact(contactId)\n .then((ctc) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, [ctc]))\n .then((ctcs) => ctcs[0])\n }\n\n /**\n * Gets multiple contacts by their ids and decrypts them for the given user.\n * @param user the user for decryption\n * @param body the list of contact ids\n * @return an array of decrypted contacts\n */\n getContactsWithUser(user: models.User, body?: models.ListOfIds): Promise<Array<models.Contact> | any> {\n return super.getContacts(body).then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n }\n\n /**\n * Modifies an existing contact by encrypting it and saving it to the database.\n * @param user the user for encryption\n * @param body the contact to modify\n * @return the modified and decrypted contact\n */\n async modifyContactWithUser(user: models.User, body?: models.Contact): Promise<models.Contact | any> {\n return body ? this.modifyContactAs(this.dataOwnerApi.getDataOwnerIdOf(user)!, body) : null\n }\n\n private modifyContactAs(dataOwner: string, body: models.Contact): Promise<models.Contact> {\n return this.encryptAs(dataOwner, [_.cloneDeep(body)])\n .then((ctcs) => super.modifyContact(ctcs[0]))\n .then((ctc) => this.decrypt(dataOwner, [ctc]))\n .then((ctcs) => ctcs[0])\n }\n\n /**\n * Modifies multiple existing contacts by encrypting them and saving them to the database.\n * @param user the user for encryption\n * @param bodies the array of contacts to modify\n * @return an array of modified and decrypted contacts\n */\n async modifyContactsWithUser(user: models.User, bodies?: Array<models.Contact>): Promise<models.Contact[] | any> {\n return bodies\n ? this.encrypt(\n user,\n bodies.map((c) => _.cloneDeep(c))\n )\n .then((ctcs) => super.modifyContacts(ctcs))\n .then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n : null\n }\n\n /**\n * Creates a new contact by encrypting it and saving it to the database.\n * @param user the user for encryption\n * @param body the contact to create\n * @return the created and decrypted contact\n */\n async createContactWithUser(user: models.User, body?: models.Contact): Promise<models.Contact | null> {\n return body\n ? this.encrypt(user, [_.cloneDeep(body)])\n .then((ctcs) => super.createContact(ctcs[0]))\n .then((ctc) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, [ctc]))\n .then((ctcs) => ctcs[0])\n : null\n }\n\n /**\n * Creates multiple new contacts by encrypting them and saving them to the database.\n * @param user the user for encryption\n * @param bodies the array of contacts to create\n * @return an array of created and decrypted contacts\n */\n async createContactsWithUser(user: models.User, bodies?: Array<models.Contact>): Promise<models.Contact[] | null> {\n return bodies\n ? this.encrypt(\n user,\n bodies.map((c) => _.cloneDeep(c))\n )\n .then((ctcs) => super.createContacts(ctcs))\n .then((ctcs) => this.decrypt(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs))\n : null\n }\n\n /**\n * Encrypts the content and custom encrypted fields of services.\n * Services with compound values are recursively encrypted.\n * @param key the encryption key\n * @param rawKey the raw encryption key as a string\n * @param services the array of services to encrypt\n * @return a promise containing the encrypted services\n */\n encryptServices(key: CryptoKey, rawKey: string, services: Service[]): PromiseLike<Service[]> {\n return Promise.all(\n services.map(async (svc) => {\n if (\n svc.content &&\n Object.values(svc.content).every(\n (c) =>\n c.compoundValue &&\n !c.stringValue &&\n !c.documentId &&\n !c.measureValue &&\n !c.medicationValue &&\n (c.booleanValue === null || c.booleanValue === undefined) &&\n (c.numberValue === null || c.numberValue === undefined) &&\n !c.instantValue &&\n !c.fuzzyDateValue &&\n !c.binaryValue\n )\n ) {\n const recursivelyEncryptedContent = Object.fromEntries(\n await Promise.all(\n Object.entries(svc.content).map(async (p) => {\n if (p[1].compoundValue?.length) {\n return [p[0], { ...p[1], compoundValue: await this.encryptServices(key, rawKey, p[1].compoundValue!) }]\n } else return p\n })\n )\n )\n const copyWithEncryptedContent = { ...svc, content: recursivelyEncryptedContent }\n return this.serviceEncryptedFieldsNoContent\n ? encryptObject(\n copyWithEncryptedContent,\n (obj) => {\n return this.crypto.primitives.AES.encrypt(key, utf8_2ua(JSON.stringify(obj)), rawKey)\n },\n (encryptedSelf) => this.crypto.xapi.tryDecryptJson([{ key, raw: rawKey }], encryptedSelf, false),\n this.serviceEncryptedFieldsNoContent,\n 'service'\n )\n : copyWithEncryptedContent\n } else {\n return encryptObject(\n svc,\n (obj) => {\n return this.crypto.primitives.AES.encrypt(key, utf8_2ua(JSON.stringify(obj)), rawKey)\n },\n (encryptedSelf) => this.crypto.xapi.tryDecryptJson([{ key, raw: rawKey }], encryptedSelf, false),\n this.serviceEncryptedFieldsWithContent,\n 'service'\n )\n }\n })\n )\n }\n\n /**\n * Encrypts contacts for the given user including all services within the contacts.\n * @param user the user for encryption\n * @param ctcs the array of contacts to encrypt\n * @return a promise containing the encrypted contacts\n */\n encrypt(user: models.User, ctcs: Array<models.Contact>) {\n return this.encryptAs(this.dataOwnerApi.getDataOwnerIdOf(user)!, ctcs)\n }\n\n private async encryptAs(hcpartyId: string, ctcs: Array<models.Contact>): Promise<models.Contact[]> {\n const initializedContacts: models.Contact[] = []\n for (const ctc of ctcs) {\n initializedContacts.push((await this.crypto.xapi.ensureEncryptionKeysInitialised(ctc, EntityWithDelegationTypeName.Contact)) ?? ctc)\n }\n const allEncrypted = await this.crypto.xapi.doManyIncrementallyDecryptingKeys(\n initializedContacts,\n EntityWithDelegationTypeName.Contact,\n async (entity, t, keys) => {\n for (const k of keys) {\n try {\n const encrypted = new Contact(\n await encryptObject(\n {\n ...entity,\n services: entity.services ? await this.encryptServices(k.key, k.raw, entity.services) : [],\n },\n (obj) => {\n return this.crypto.primitives.AES.encrypt(k.key, utf8_2ua(JSON.stringify(obj)), k.raw)\n },\n (encryptedSelf) => this.crypto.xapi.tryDecryptJson(keys, encryptedSelf, false),\n this.contactEncryptedFields,\n EntityWithDelegationTypeName.Contact\n )\n )\n return { success: encrypted }\n } catch (e) {\n console.warn(`Failed to encrypt contact ${entity.id} with key ${k.raw}`)\n }\n }\n return null\n }\n )\n if (ctcs.length != allEncrypted.size) {\n throw new Error(`Couldn't encrypt contacts ${ctcs.flatMap((e) => (allEncrypted.has(e.id!) ? [] : [e.id!]))}`)\n }\n return ctcs.map((e) => allEncrypted.get(e.id!)!)\n }\n\n /**\n * Decrypts contacts and all their encrypted content.\n * @param hcpartyId the healthcare party id (deprecated parameter, kept for compatibility)\n * @param ctcs the array of encrypted contacts\n * @return a promise containing the decrypted contacts\n */\n async decrypt(hcpartyId: string, ctcs: Array<models.Contact>): Promise<Array<models.Contact>> {\n return (await this.crypto.xapi.tryDecryptEntities(ctcs, EntityWithDelegationTypeName.Contact, (x) => new Contact(x))).map(({ entity }) => entity)\n }\n\n /**\n * Decrypts services and all their encrypted content.\n * @param hcpartyId the healthcare party id (deprecated parameter, kept for compatibility)\n * @param svcs the array of encrypted services\n * @return a promise containing the decrypted services\n */\n async decryptServices(hcpartyId: string, svcs: Array<models.Service>): Promise<Array<models.Service>> {\n /*TODO\n * not super efficient, re-decrypts the encryption key metadata of services multiple times, but should mostly rely\n * on cached exchange data after the first decryption and should not do any extra requests to the db.\n * We could ensure to use only cached exchange data by doing limited-size batches of services from the same contact\n * id.\n */\n return (await this.crypto.xapi.tryDecryptEntities(svcs, EntityWithDelegationTypeName.Contact, (x) => new Service(x))).map(({ entity }) => entity)\n }\n\n /**\n * Finds the contact containing the given service id, prioritizing the latest version by valueDate.\n * @param ctcs the array of contacts to search\n * @param svcId the service id to find\n * @return the contact containing the service or undefined if not found\n */\n contactOfService(ctcs: Array<models.Contact>, svcId: string): models.Contact | undefined {\n let latestContact: models.Contact | undefined = undefined\n let latestService: models.Service\n ctcs.forEach((c) => {\n const s: models.Service | undefined = c.services!.find((it) => svcId === it.id)\n if (s && (!latestService || moment(s.valueDate).isAfter(moment(latestService.valueDate)))) {\n latestContact = c\n latestService = s\n }\n })\n return latestContact\n }\n\n /**\n * Extracts and filters services from contacts, keeping only the latest version of each service and excluding deleted services.\n * @param ctcs the array of contacts containing services\n * @param filter a predicate function to filter services: (service, contact) => boolean\n * @return an array of filtered services with contactId set\n */\n filteredServices(ctcs: Array<models.Contact>, filter: any): Array<models.Service> {\n const byIds: { [key: string]: models.Service } = {}\n ctcs.forEach((c) =>\n (c.services || [])\n .filter((s) => filter(s, c))\n .forEach((s) => {\n const ps = byIds[s.id!]\n if (!ps || !ps.modified || (s.modified && ps.modified < s.modified)) {\n byIds[s.id!] = s\n s.contactId = c.id\n }\n })\n )\n return _.values(byIds).filter((s: any) => !s.deleted && !s.endOfLife)\n }\n\n /**\n * Extracts and filters services from contacts, returning a promise. Same as filteredServices but wrapped in a promise.\n * @param ctcs the array of contacts containing services\n * @param filter a predicate function to filter services: (service, contact) => boolean\n * @return a promise containing an array of filtered services\n */\n filterServices(ctcs: Array<models.Contact>, filter: any): Promise<Array<models.Service>> {\n return Promise.resolve(this.filteredServices(ctcs, filter))\n }\n\n /**\n * Gets all services from a contact that have the specified label.\n * @param ctc the contact\n * @param label the service label to filter by\n * @return an array of services with the given label\n */\n services(ctc: models.Contact, label: string) {\n return ctc.services!.filter((s) => s.label === label)\n }\n\n /**\n * Gets the preferred content for a service based on language preference, falling back to French then first available language.\n * @param svc the service\n * @param lng the preferred language code\n * @return the content in the preferred language or null if no content exists\n */\n preferredContent(svc: models.Service, lng: string) {\n return (\n svc && svc.content && (svc.content[lng] || svc.content['fr'] || (Object.keys(svc.content)[0] ? svc.content[Object.keys(svc.content)[0]] : null))\n )\n }\n\n /**\n * Extracts the value from content, prioritizing string, number, measure, medication, and boolean values in that order.\n * @param c the content\n * @return the extracted value or undefined if no value is present\n */\n contentValue(c: models.Content) {\n return (\n c.stringValue ||\n ((c.numberValue || c.numberValue === 0) && c.numberValue) ||\n (c.measureValue && (c.measureValue.value || c.measureValue.value === 0) ? c.measureValue : null) ||\n c.medicationValue ||\n c.booleanValue\n )\n }\n\n /**\n * Gets a short human-readable description of a service in the preferred language.\n * @param svc the service\n * @param lng the preferred language code\n * @return a short description of the service content or empty string\n */\n shortServiceDescription(svc: models.Service, lng: string) {\n const c = this.preferredContent(svc, lng)\n return !c ? '' : this.shortContentDescription(c, lng, svc.label)\n }\n\n /**\n * Gets a short human-readable description of content, formatted appropriately for the content type.\n * @param c the content\n * @param lng the language code for medication formatting\n * @param label optional label used for boolean content display\n * @return a short description of the content\n */\n shortContentDescription(c: models.Content, lng: string, label?: string) {\n return (\n c.stringValue ||\n ((c.numberValue || c.numberValue === 0) && c.numberValue) ||\n (c.measureValue &&\n '' +\n (c.measureValue.value || c.measureValue.value === 0 ? c.measureValue.value : '-') +\n (c.measureValue.unit ? ' ' + c.measureValue.unit : '')) ||\n (c.medicationValue ? this.medication().medicationToString(c.medicationValue, lng) : null) ||\n (c.booleanValue && label) ||\n 'OK'\n )\n }\n\n /**\n * Extracts the medication value from a service's content in the preferred language.\n * @param svc the service\n * @param lng the preferred language code\n * @return the medication value or undefined if not present\n */\n medicationValue(svc: models.Service, lng: string) {\n const c =\n svc && svc.content && (svc.content[lng] || svc.content['fr'] || (Object.keys(svc.content)[0] ? svc.content[Object.keys(svc.content)[0]] : null))\n return c && c.medicationValue\n }\n\n /**\n * Checks if content has any data value set (string, number, measure, boolean, medication, or document).\n * @param c the content to check\n * @return true if content has data, false otherwise\n */\n contentHasData(c: any): boolean {\n return c.stringValue || c.numberValue || c.measureValue || c.booleanValue || c.booleanValue === false || c.medicationValue || c.documentId\n }\n\n /**\n * Localizes a value by selecting the appropriate language from an object, falling back through FR, EN, and NL.\n * @param e the object with language-keyed values or a simple value\n * @param lng the preferred language code\n * @return the localized value or null if e is null/undefined\n */\n localize(e: any, lng: string) {\n if (!e) {\n return null\n }\n return e[lng] || e.fr || e.FR || e.en || e.EN || e.nl || e.NL\n }\n\n /**\n * Modifies the subcontacts this svc belongs to while minimizing the number of references to the svcs inside the subcontacts\n * After the invocation, there is at least one subcontact with provided poaId and heId that contains the svc\n * The svc is not removed from a previous subcontact it would belong to except if the new conditions are compatible\n * Note that undefined and null do not have the same meaning for formId\n * If formId is null: the subcontact which refers svc must have a null formId\n * If formId is undefined, the subcontact can have any value for formId\n *\n * When a svc does not exist yet in the current contact but exists in a previous contact, all the scs it was belonging to are\n * copied in the current contact\n *\n * the svc returned is the one that's inside the ctc\n *\n * @param ctc\n * @param user\n * @param ctcs\n * @param svc\n * @param formId\n * @param poaId aMap {heId2: [poaId11, poaId12], heId2: [poaId21] }\n * @param heId an Array of heIds, equivalent to poaIds = {heId: [], ...}\n * @param init\n * @returns {*}\n */\n\n promoteServiceInContact(\n ctc: models.Contact,\n user: models.User,\n ctcs: Array<models.Contact>,\n svc: models.Service,\n formId: string,\n poaIds?: { [key: string]: string[] },\n heIds?: Array<string>,\n init?: any\n ) {\n if (!ctc) {\n return null\n }\n const existing = ctc.services!.find((s) => s.id === svc.id)\n const promoted = _.extend(_.extend(existing || {}, svc), {\n author: user.id,\n responsible: this.dataOwnerApi.getDataOwnerIdOf(user),\n modified: new Date().getTime(),\n })\n if (!existing) {\n ;(ctc.services || (ctc.services = [])).push(promoted)\n }\n const allSubcontactsInCurrentContactContainingService = (ctc.subContacts || []).filter((csc) =>\n (csc.services || []).some((s) => s.serviceId === svc.id)\n )\n\n //Rearrange poaIds and heIds as a hierarchy\n const hierarchyOfHeAndPoaIds: { [key: string]: Array<any> } = {}\n ;(heIds || []).forEach((id) => (hierarchyOfHeAndPoaIds[id || '_'] = []))\n Object.keys(poaIds || {}).forEach((k: string) => {\n const poas = hierarchyOfHeAndPoaIds[k]\n if (poas) {\n hierarchyOfHeAndPoaIds[k] = _.concat(poas, (poaIds || {})[k])\n } else {\n hierarchyOfHeAndPoaIds[k] = (poaIds || {})[k]\n }\n })\n\n const pastCtc =\n (svc.contactId && svc.contactId !== ctc.id && ctcs.find((c) => c.id === svc.contactId)) ||\n ctcs.reduce(\n (selected: { s: models.Service | null; c: models.Contact | null }, c: models.Contact) => {\n const candidate = (c.services || []).find((s) => s.id === svc.id)\n return ctc.id !== c.id && candidate && (selected.s === null || before(selected.s.modified || 0, candidate.modified || 0))\n ? { s: candidate, c: c }\n : selected\n },\n { s: null, c: null }\n ).c\n //Make sure that all scs the svc was belonging to are copied inside the current contact\n pastCtc &&\n pastCtc\n .subContacts!.filter((psc) => psc.services!.some((s) => s.serviceId === svc.id))\n .forEach((psc) => {\n const sameInCurrent = allSubcontactsInCurrentContactContainingService.find(\n (csc) => csc.formId === psc.formId && csc.planOfActionId === psc.planOfActionId && csc.healthElementId === psc.healthElementId\n )\n if (sameInCurrent) {\n if (!sameInCurrent.services!.some((s) => s.serviceId === svc.id)) {\n sameInCurrent.services!.push({ serviceId: svc.id })\n }\n } else {\n const newSubContact = _.assign(_.assign({}, psc), {\n services: [{ serviceId: svc.id }],\n })\n ctc.subContacts!.push(newSubContact)\n allSubcontactsInCurrentContactContainingService.push(newSubContact)\n }\n })\n\n if (!Object.keys(hierarchyOfHeAndPoaIds).length) {\n hierarchyOfHeAndPoaIds._ = [] //Default is to have at least one option with heId equals to null (represented by _)\n }\n\n Object.keys(hierarchyOfHeAndPoaIds).forEach((heId: string | null) => {\n if (heId === '_') {\n heId = null\n }\n const subPoaIds = heId ? hierarchyOfHeAndPoaIds[heId] : []\n ;((subPoaIds || []).length ? subPoaIds : [null]).forEach((poaId) => {\n //Create or assign subcontacts for all pairs he/poa (can be null/null)\n let destinationSubcontact = ctc.subContacts!.find(\n (sc) =>\n (!formId || sc.formId === formId) &&\n ((!poaId && !sc.planOfActionId) || sc.planOfActionId === poaId) &&\n ((!heId && !sc.healthElementId) || sc.healthElementId === heId)\n )\n if (!destinationSubcontact) {\n ctc.subContacts!.push(\n (destinationSubcontact = new models.SubContact({\n formId: formId || undefined,\n planOfActionId: poaId,\n healthElementId: heId,\n services: [],\n }))\n )\n }\n\n const redundantSubcontact =\n allSubcontactsInCurrentContactContainingService.find((aSc) => destinationSubcontact === aSc) ||\n allSubcontactsInCurrentContactContainingService.find(\n (aSc) =>\n (!aSc.planOfActionId || aSc.planOfActionId === destinationSubcontact!.planOfActionId) &&\n (!aSc.healthElementId || aSc.healthElementId === destinationSubcontact!.healthElementId) &&\n (!aSc.formId || aSc.formId === destinationSubcontact!.formId)\n ) // Find a compatible sc: one that does not contain extra and ≠ information than the destination\n\n if (redundantSubcontact && redundantSubcontact !== destinationSubcontact) {\n redundantSubcontact.services!.splice(\n redundantSubcontact.services!.findIndex((link) => link.serviceId === svc.id),\n 1\n )\n }\n if (!destinationSubcontact.services!.some((s) => s.serviceId === svc.id)) {\n destinationSubcontact.services!.push({ serviceId: svc.id! })\n }\n })\n })\n\n return (init && init(promoted)) || promoted\n }\n\n /**\n * Checks if a service has numeric content (measure or number value) in the preferred language.\n * @param svc the service\n * @param lng the preferred language code\n * @return true if the service has numeric content, false otherwise\n */\n isNumeric(svc: models.Service, lng: string) {\n const c = this.preferredContent(svc, lng)\n return c && (c.measureValue || c.numberValue || c.numberValue == 0)\n }\n\n /**\n * Returns utility functions for working with services.\n * @return an object with helper methods for creating and manipulating services\n */\n service() {\n return {\n newInstance: (user: models.User, s: any) =>\n _.extend(\n {\n id: this.crypto.primitives.randomUuid(),\n _type: 'org.taktik.icure.entities.embed.Service',\n created: new Date().getTime(),\n modified: new Date().getTime(),\n responsible: s?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: s?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: [],\n tags: [],\n content: {},\n valueDate: parseInt(moment().format('YYYYMMDDHHmmss')),\n },\n s\n ),\n }\n }\n\n /**\n * Returns utility functions for working with medication content.\n * @return an object with helper methods for formatting and displaying medication information\n */\n medication() {\n const regimenScores: any = {\n afterwakingup: 63000,\n beforebreakfast: 70000,\n duringbreakfast: 80000,\n afterbreakfast: 90000,\n morning: 100000,\n betweenbreakfastandlunch: 103000,\n beforelunch: 113000,\n midday: 120000,\n duringlunch: 123000,\n afterlunch: 130000,\n afternoon: 140000,\n betweenlunchanddinner: 160000,\n beforedinner: 180000,\n duringdinner: 190000,\n afterdinner: 200000,\n evening: 210000,\n betweendinnerandsleep: 213000,\n thehourofsleep: 220000,\n night: 230000,\n beforemeals: -30000,\n betweenmeals: -20000,\n aftermeals: -10000,\n }\n\n const myself = {\n regimenScores: function () {\n return regimenScores\n },\n medicationNameToString: function (m: any): string {\n return m && m.compoundPrescription\n ? m.compoundPrescription\n : m && m.substanceProduct\n ? myself.productToString(m && m.substanceProduct)\n : myself.productToString(m && m.medicinalProduct)\n },\n reimbursementReasonToString: (m: any, lang: string) => {\n return m && m.reimbursementReason && m.reimbursementReason.label && m.reimbursementReason.label.hasOwnProperty(lang)\n ? m.reimbursementReason.label[lang]\n : ''\n },\n medicationToString: (m: any, lang: string) => {\n let res = `${myself.medicationNameToString(m)}, ${myself.posologyToString(m, lang)}`\n const reason = myself.reimbursementReasonToString(m, lang)\n res = m.numberOfPackages\n ? `${m.numberOfPackages} ${m.numberOfPackages > 1 ? this.i18n[lang].packagesOf : this.i18n[lang].packageOf} ${res}`\n : res\n res = m.duration ? `${res} ${this.i18n[lang].during} ${myself.durationToString(m.duration, lang)}` : res\n res = reason ? `${res} (${reason})` : res\n return res\n },\n productToString: (m: any): string => {\n if (!m) {\n return ''\n }\n return m.intendedname\n },\n posologyToString: (m: any, lang: string) => {\n if (m) {\n if (m.instructionForPatient && m.instructionForPatient.length) {\n return m.instructionForPatient\n }\n if (!m.regimen || !m.regimen.length) {\n return ''\n }\n\n const unit =\n m.regimen[0].administratedQuantity && m.regimen[0].administratedQuantity.administrationUnit\n ? m.regimen[0].administratedQuantity.administrationUnit.code\n : m.regimen[0].administratedQuantity && m.regimen[0].administratedQuantity.unit\n let quantity = m.regimen[0].administratedQuantity && m.regimen[0].administratedQuantity.quantity\n\n m.regimen.slice(1).find((ri: any) => {\n const oUnit =\n ri.administratedQuantity && ri.administratedQuantity.administrationUnit\n ? ri.administratedQuantity.administrationUnit.code\n : ri.administratedQuantity && ri.administratedQuantity.unit\n const oQuantity = ri.administratedQuantity && ri.administratedQuantity.quantity\n\n if (oQuantity !== quantity) {\n quantity = -1\n }\n return oUnit !== unit && oQuantity !== quantity\n })\n\n const cplxRegimen = !unit || quantity < 0\n const quantityUnit = cplxRegimen ? `1 ${this.i18n[lang].take_s_}` : `${quantity} ${unit || this.i18n[lang].take_s_}`\n\n const dayPeriod = m.regimen.find((r: any) => r.weekday !== null && r.weekday !== undefined)\n ? this.i18n[lang].weekly\n : m.regimen.find((r: any) => r.date)\n ? this.i18n[lang].monthly\n : this.i18n[lang].daily\n\n return `${quantityUnit}, ${m.regimen.length} x ${dayPeriod}, ${_.sortBy(\n m.regimen,\n (r) =>\n (r.date ? r.date * 1000000 : 29990000000000) +\n (r.dayNumber || 0) * 1000000 +\n ((r.weekday && r.weekday.weekNumber) || 0) * 7 * 1000000 +\n (r.timeOfDay ? r.timeOfDay : r.dayPeriod && r.dayPeriod.code ? (regimenScores[r.dayPeriod.code] as number) : 0)\n )\n .map((r) => (cplxRegimen ? myself.regimenToExtString(r, lang) : myself.regimenToString(r, lang)))\n .join(', ')}`\n }\n },\n frequencyToString: (m: any, lang: string) => {\n if (m.instructionForPatient && m.instructionForPatient.length) {\n return m.instructionForPatient\n }\n if (!m.regimen || !m.regimen.length) {\n return ''\n }\n\n const dayPeriod = m.regimen.find((r: any) => r.weekday !== null && r.weekday !== undefined)\n ? this.i18n[lang].weekly\n : m.regimen.find((r: any) => r.date)\n ? this.i18n[lang].monthly\n : this.i18n[lang].daily\n\n return `${m.regimen.length} x ${dayPeriod}`\n },\n durationToString: (d: models.Duration, lang: string) => {\n return d.value ? `${d.value} ${this.localize(d.unit!.label, lang)}` : ''\n },\n regimenToExtString: (r: models.RegimenItem, lang: string) => {\n const desc = myself.regimenToString(r, lang)\n return (\n (r.administratedQuantity && r.administratedQuantity.quantity && desc\n ? `${desc} (${r.administratedQuantity.quantity} ${\n (r.administratedQuantity.administrationUnit ? r.administratedQuantity.administrationUnit.code : r.administratedQuantity.unit) ||\n this.i18n[lang].take_s_\n })`\n : desc) || ''\n )\n },\n regimenToString: (r: models.RegimenItem, lang: string) => {\n let res = r.date\n ? `${this.i18n[lang].the} ${moment(r.date).format('DD/MM/YYYY')}`\n : r.dayNumber\n ? `${this.i18n[lang].onDay} ${r.dayNumber}`\n : r.weekday && r.weekday.weekday\n ? `${this.i18n[lang].on} ${r.weekday.weekday}`\n : null\n if (r.dayPeriod && r.dayPeriod.code && r.dayPeriod.code.length) {\n res = res\n ? `${res} ${this.i18n[lang][r.dayPeriod.code] || this.localize(r.dayPeriod.label, lang) || r.dayPeriod.code}`\n : this.i18n[lang][r.dayPeriod.code] || this.localize(r.dayPeriod.label, lang) || r.dayPeriod.code\n }\n if (r.timeOfDay) {\n const timeOfDay =\n r.timeOfDay === 120000\n ? this.i18n[lang].noon\n : `${Math.floor(r.timeOfDay / 10000)}:${('' + (Math.floor(r.timeOfDay / 100) % 100)).replace(/^(.)$/, '0$1')}`\n res = res ? res + ' ' + this.i18n[lang].at + ' ' + timeOfDay : timeOfDay\n }\n return res\n },\n localize: (s: any, lang: string) => {\n if (!s) {\n return s\n }\n return (\n this.i18n[lang][s] ||\n (this.i18n[lang][s.toLowerCase()] &&\n this.i18n[lang][s.toLowerCase()]\n .split('')\n .map((c: string, idx: number) => (idx >= s.length || s[idx].toLocaleLowerCase() === s[idx] ? c : c.toLocaleUpperCase()))\n .join('')) ||\n s\n ) //Applies the (lower/upper)case to the translated lowercase version of the input string (s)\n },\n }\n return myself\n }\n\n /**\n * @param contact a contact\n * @return the id of the patient that the contact 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(contact: models.Contact): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: contact, type: EntityWithDelegationTypeName.Contact }, undefined)\n }\n\n /**\n * @param service a service\n * @return the id of the patient that the service 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 decryptPatientIdOfService(service: models.Service): Promise<string[]> {\n return this.crypto.xapi.owningEntityIdsOf({ entity: service, type: EntityWithDelegationTypeName.Contact }, undefined)\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given contact\n */\n async hasWriteAccess(contact: models.Contact): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: contact, type: EntityWithDelegationTypeName.Contact })\n }\n\n /**\n * Share an existing contact with other data owners, allowing them to access the non-encrypted data of the contact 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 contact.\n * @param contact the contact 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 * contact does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this contact 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 contact: models.Contact,\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.Contact> {\n return this.shareWithMany(contact, { [delegateId]: options })\n }\n\n /**\n * Share an existing contact with other data owners, allowing them to access the non-encrypted data of the contact and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param contact the contact 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 * contact does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this contact 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 contact: models.Contact,\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.Contact> {\n return (await this.tryShareWithMany(contact, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing contact with other data owners, allowing them to access the non-encrypted data of the contact and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param contact the contact 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 * contact does not have encrypted content.\n * - sharePatientId: specifies if the id of the patient that this contact 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 contact: models.Contact,\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.Contact>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(contact, EntityWithDelegationTypeName.Contact)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyContactAs(self, entityWithEncryptionKey) : contact\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Contact,\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.bulkShareContacts(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decrypt(self, [e]).then((es) => es[0])))\n }\n\n /**\n * Gets the data owners that have access to the contact and their permission levels.\n * @param entity the contact\n * @return a promise containing the permissions by data owner id and whether there are unknown anonymous data owners\n */\n getDataOwnersWithAccessTo(\n entity: models.Contact\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Contact })\n }\n\n /**\n * Gets all encryption keys available for the contact.\n * @param entity the contact\n * @return a promise containing an array of encryption key hex strings\n */\n getEncryptionKeysOf(entity: models.Contact): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Contact }, undefined)\n }\n\n /**\n * Subscribes to service events (create, update, delete) and receives decrypted services.\n * @param eventTypes the types of events to subscribe to\n * @param filter optional filter to apply to services\n * @param eventFired callback function invoked when an event occurs, receives the decrypted service\n * @param options optional subscription options\n * @return a connection that can be closed to unsubscribe\n */\n async subscribeToServiceEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Service> | undefined,\n eventFired: (dataSample: Service) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n const currentUser = await this.userApi.getCurrentUser()\n return subscribeToEntityEvents(\n this.host,\n this.authApi,\n 'Service',\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted: Service) => (await this.decryptServices(currentUser.healthcarePartyId!, [encrypted]))[0]\n ).then((ws) => new ConnectionImpl(ws))\n }\n\n /**\n * Subscribes to contact events (create, update, delete) and receives decrypted contacts.\n * @param eventTypes the types of events to subscribe to\n * @param filter optional filter to apply to contacts\n * @param eventFired callback function invoked when an event occurs, receives the decrypted contact\n * @param options optional subscription options\n * @return a connection that can be closed to unsubscribe\n */\n async subscribeToContactEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Contact> | undefined,\n eventFired: (dataSample: Contact) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n const currentUser = await this.userApi.getCurrentUser()\n return subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.Contact,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted: Contact) => (await this.decrypt(currentUser.healthcarePartyId!, [encrypted]))[0]\n ).then((ws) => new ConnectionImpl(ws))\n }\n\n /**\n * Creates or updates de-anonymization metadata for delegations in a contact.\n * @param entity the contact\n * @param delegates the array of delegate ids to create de-anonymization metadata for\n * @return a promise that completes when the metadata is created/updated\n */\n createDelegationDeAnonymizationMetadata(entity: Contact, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Contact }, delegates)\n }\n}\n"]}
@@ -378,6 +378,9 @@ function parseEncryptedFields(encryptedFields, path) {
378
378
  };
379
379
  }
380
380
  function encryptedObjectDeepEqual(l, r) {
381
+ if (l === null || r === null) {
382
+ return l === r;
383
+ }
381
384
  if (Array.isArray(l)) {
382
385
  if (!Array.isArray(r) || l.length !== r.length) {
383
386
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"crypto-utils.js","sourceRoot":"","sources":["../../../icc-x-api/utils/crypto-utils.ts"],"names":[],"mappings":";;;;;;;;;;;AAQA,sCAeC;AAED,8BA2BC;AAED,4BAmBC;AAED,8BA4BC;AAED,gCAiBC;AAmBD,sDAQC;AAQD,oCAKC;AAGD,sBAEC;AAED,wBAEC;AAgID,oDA4FC;AA+CD,sCAyEC;AAoBD,sCAyCC;AAQD,4DAMC;AA1kBD,6BAA4B;AAG5B,wDAA4G;AAC5G,+CAAoC;AACpC,+CAAyC;AAGzC,SAAgB,aAAa,CAAI,cAAmD,EAAE,GAAW,EAAE,IAA0B;IAC3H,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,CAAA;IACpC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,MAAM,GAAG,CAAC,GAAS,EAAE;YACzB,IAAI,CAAC;gBACH,OAAO,MAAM,IAAI,EAAE,CAAA;YACrB,CAAC;oBAAS,CAAC;gBACT,OAAO,cAAc,CAAC,GAAG,CAAC,CAAA;Y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ment'\nimport * as _ from 'lodash'\nimport { a2b, b2a, b64Url2ua, hex2ua, string2ua, ua2b64Url, ua2hex, ua2string } from '../utils/binary-utils'\nimport { pack } from './asn1-packer'\nimport { parseAsn1 } from './asn1-parser'\nimport { KeyPair, ShaVersion } from '../crypto/RSA'\n\nexport function notConcurrent<T>(concurrencyMap: { [key: string]: PromiseLike<any> }, key: string, proc: () => PromiseLike<T>): PromiseLike<T> {\n const inFlight = concurrencyMap[key]\n if (!inFlight) {\n const newJob = (async () => {\n try {\n return await proc()\n } finally {\n delete concurrencyMap[key]\n }\n })()\n concurrencyMap[key] = newJob\n return newJob\n } else {\n return concurrencyMap[key].then(() => notConcurrent(concurrencyMap, key, proc))\n }\n}\n\nexport function jwk2pkcs8(jwk: any): string {\n return pack([\n 0x30,\n [\n [0x02, '00'],\n [0x30, [[0x06, '2a864886f70d010101'], [0x05]]], // pragma: allowlist secret\n [\n 0x04,\n [\n [\n 0x30,\n [\n [0x02, '00'],\n [0x02, ua2hex(b64Url2ua(jwk.n))],\n [0x02, ua2hex(b64Url2ua(jwk.e))],\n [0x02, ua2hex(b64Url2ua(jwk.d))],\n [0x02, ua2hex(b64Url2ua(jwk.p))],\n [0x02, ua2hex(b64Url2ua(jwk.q))],\n [0x02, ua2hex(b64Url2ua(jwk.dp))],\n [0x02, ua2hex(b64Url2ua(jwk.dq))],\n [0x02, ua2hex(b64Url2ua(jwk.qi))],\n ],\n ],\n ],\n ],\n ],\n ])\n}\n\nexport function jwk2spki(jwk: any): string {\n return pack([\n 0x30,\n [\n [0x30, [[0x06, '2a864886f70d010101'], [0x05]]], // pragma: allowlist secret\n [\n 0x03,\n [\n [\n 0x30,\n [\n [0x02, ua2hex(b64Url2ua(jwk.n))],\n [0x02, ua2hex(b64Url2ua(jwk.e))],\n ],\n ],\n ],\n ],\n ],\n ])\n}\n\nexport function spkiToJwk(buf: Uint8Array, shaVersion: ShaVersion): { kty: string; alg: string; n: string; e: string; ext: boolean } {\n const asn1 = parseAsn1(new Uint8Array(buf))\n\n var modulus: Uint8Array | undefined = undefined\n var exponent: Uint8Array | undefined = undefined\n if (\n asn1.type === 0x30 &&\n asn1.children?.[0]?.type === 0x30 &&\n asn1.children?.[0]?.children?.[0]?.type === 0x06 &&\n ua2hex(asn1.children?.[0]?.children?.[0]?.value ?? new Uint8Array(0)) === '2a864886f70d010101' // pragma: allowlist secret\n ) {\n modulus = asn1.children?.[1]?.children?.[0]?.children?.[0]?.value\n exponent = asn1.children?.[1]?.children?.[0]?.children?.[1]?.value\n } else if (asn1.type === 0x30 && asn1.children?.[0]?.type === 0x02 && asn1.children?.[1]?.type === 0x02) {\n modulus = asn1.children?.[0]?.value\n exponent = asn1.children?.[1]?.value\n }\n\n if (!modulus || !exponent) {\n throw new Error('Invalid spki format')\n }\n return {\n kty: 'RSA',\n alg: shaVersion === 'sha-256' ? 'RSA-OAEP-256' : 'RSA-OAEP',\n ext: true,\n n: ua2b64Url(minimalRep(modulus)),\n e: ua2b64Url(minimalRep(exponent)),\n }\n}\n\nexport function pkcs8ToJwk(buf: Uint8Array | ArrayBuffer) {\n const parsed = parseAsn1(new Uint8Array(buf))\n const seq =\n parsed.children?.length === 3 && parsed.children[2].type === 0x04 && parsed.children[2].children?.length === 1\n ? parsed.children[2].children[0]\n : parsed\n return {\n kty: 'RSA',\n n: ua2b64Url(minimalRep(seq.children![1].value as Uint8Array)),\n e: ua2b64Url(minimalRep(seq.children![2].value as Uint8Array)),\n d: ua2b64Url(minimalRep(seq.children![3].value as Uint8Array)),\n p: ua2b64Url(minimalRep(seq.children![4].value as Uint8Array)),\n q: ua2b64Url(minimalRep(seq.children![5].value as Uint8Array)),\n dp: ua2b64Url(minimalRep(seq.children![6].value as Uint8Array)),\n dq: ua2b64Url(minimalRep(seq.children![7].value as Uint8Array)),\n qi: ua2b64Url(minimalRep(seq.children![8].value as Uint8Array)),\n }\n}\n\nfunction minimalRep(b: Uint8Array) {\n let i = 0\n while (b[i] === 0) {\n i++\n }\n return b.slice(i)\n}\n\n/**\n * Provide a view over the given Uint8Array where any trailing null bytes at\n * the end are truncated.\n *\n * This can be used to ignore null bytes at the end of a padded UTF-8 string\n * without needing to copy that string, assuming code point U+0000 is encoded\n * in one null byte according to standards rather than in a multi-byte\n * overlong form.\n */\nexport function truncateTrailingNulls(a: Uint8Array) {\n let end = a.byteLength - 1\n while (a[end] === 0 && end >= 0) {\n end--\n }\n // end is now either the last non-null position in a or -1; in the latter\n // case the returned array will have length 0.\n return a.subarray(0, end + 1)\n}\n\n/**\n *\n * @param buffer1 {Uint8Array}\n * @param buffer2{ Uint8Array}\n * @returns {ArrayBuffer}\n */\nexport function appendBuffer(buffer1: ArrayBuffer, buffer2: ArrayBuffer): ArrayBuffer {\n const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength)\n tmp.set(new Uint8Array(buffer1), 0)\n tmp.set(new Uint8Array(buffer2), buffer1.byteLength)\n return tmp.buffer as ArrayBuffer\n}\n\n//Convenience methods for dates management\nexport function after(d1: number | null | undefined, d2: number | null | undefined): boolean {\n return d1 === null || d2 === null || d1 === undefined || d2 === undefined || moment(d1)!.isAfter(moment(d2)!)\n}\n\nexport function before(d1: number | null | undefined, d2: number | null | undefined): boolean {\n return d1 === null || d2 === null || d1 === undefined || d2 === undefined || moment(d1)!.isBefore(moment(d2)!)\n}\n\nfunction moment(epochOrLongCalendar: number): Moment | null {\n if (!epochOrLongCalendar && epochOrLongCalendar !== 0) {\n return null\n }\n if (epochOrLongCalendar >= 18000101 && epochOrLongCalendar < 25400000) {\n return mm('' + epochOrLongCalendar, 'YYYYMMDD')\n } else if (epochOrLongCalendar >= 18000101000000) {\n return mm('' + epochOrLongCalendar, 'YYYYMMDDHHmmss')\n } else {\n return mm(epochOrLongCalendar)\n }\n}\n\n/**\n * Configuration for the encryption of an object.\n * @param topLevelFields the fields of the object to encrypt. All the fields will be encrypted in a single encryptedSelf field which is added to the\n * object.\n * @param nestedObjectsKeys the name of fields which are expected to contain a nested object (or undefined). Allows to specify\n */\nexport type EncryptedFieldsManifest = {\n topLevelFields: { fieldName: string; fieldPath: string }[]\n nestedObjectsKeys: {\n [objectFieldName: string]: EncryptedFieldsManifest\n }\n mapsValuesKeys: {\n [mapFieldName: string]: EncryptedFieldsManifest\n }\n arraysValuesKeys: {\n [arrayFieldName: string]: EncryptedFieldsManifest\n }\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n *\n * Parse the encrypted fields configuration for a specific entity type.\n *\n * ## Grammar\n *\n * The grammar for each encrypted field is the following:\n * ```\n * fieldName :=\n * regex([a-zA-Z_][a-zA-Z0-9_]+)\n * encryptedField :=\n * fieldName\n * | fieldName + (\".\" | \".*.\" | \"[].\") + encryptedField\n * ```\n *\n * This grammar allows you to specify the fields to encrypt for the object and recursively for nested objects.\n * - A string containing only a single `fieldName` will encrypt the field with the given name.\n * - A string starting with `fieldName.` allows to specify the encrypted fields of a nested object. The encrypted values of the\n * fields in the nested object will be saved in the nested object.\n * - A string starting with `fieldName.*.` treats `fieldName` as a map/dictionary data structure and allows to specify the encrypted fields of the\n * values of the map. Note that the values of the map must be objects as well. The encrypted content of each map value is stored in that value.\n * - A string starting with `fieldName[].` treats `fieldName` as an array and allows to specify the encrypted fields of the values of the array.\n * Note that the values of the array must be objects as well. The encrypted content of each array element is stored in that element.\n *\n * ## Example\n *\n * Consider the following object and encryption keys:\n * ```javascript\n * const obj = {\n * a: { x: 0, y: 1 },\n * b: \"hello\",\n * c: [ { public: \"a\", secret: \"b\" }, { public: \"c\", secret: \"d\" } ],\n * d: \"ok\",\n * e: {\n * info: \"something\",\n * private: \"secret\",\n * dataMap: {\n * \"en\": {\n * a: 1,\n * b: 2\n * },\n * \"fr\": {\n * a: 3,\n * b: 4\n * }\n * }\n * }\n * }\n * const encryptedFields = [\n * \"a\",\n * \"c[].secret\",\n * \"d\",\n * \"e.private\",\n * \"e.datamap.*.a\"\n * ]\n * ```\n * If you use them with the crypt method you will get the following result:\n * ```json\n * {\n * b: \"hello\",\n * c: [\n * { public: \"a\", encryptedSelf: \"...encrypted data of c[0]\" },\n * { public: \"c\", encryptedSelf: \"...encrypted data of c[1]\" }\n * ],\n * e: {\n * info: \"something\",\n * dataMap: {\n * \"en\": { b: 2, encryptedSelf: \"...encrypted data of e.dataMap['en']\" },\n * \"fr\": { b: 4, encryptedSelf: \"...encrypted data of e.dataMap['fr']\" }\n * },\n * encryptedSelf: \"...encrypted data of e\"\n * },\n * encryptedSelf: \"...encrypted data of obj\"\n * }\n * ```\n *\n * ## Shortened representation\n *\n * You can also group encrypted fields having the same prefix by concatenating to the prefix the JSON representation of an array of all the postfixes.\n * For example the following encrypted fields:\n * ```javascript\n * const encryptedFields = [\"a.b.c.d.e.f1\", \"a.b.c.d.e.f2\", \"a.b.c.d.e.f3\", \"a.b.c.d.e.f4\"]\n * ```\n * can be shortened to\n * ```javascript\n * const encryptedFields = ['a.b.c.d.e.[\"f1\",\"f2\",\"f3\",\"f4\"]'] // Note the use of single quotes to avoid escaping the double quotes\n * ```\n * If you use the shortened representation you may need to escape nested json representations. In that case the use of `JSON.stringify` is\n * recommended.\n *\n * @param encryptedFields\n * @param path\n */\nexport function parseEncryptedFields(encryptedFields: string[], path: string): EncryptedFieldsManifest {\n const groupedData = {\n topLevelFields: new Set<string>(),\n nestedObjectsKeys: {} as { [objectFieldName: string]: string[] },\n mapsValuesKeys: {} as { [mapFieldName: string]: string[] },\n arraysValuesKeys: {} as { [arrayFieldName: string]: string[] },\n }\n const encryptedFieldRegex = /^([_a-zA-Z][_a-zA-Z0-9]*)(?:(\\.\\*\\.|\\[]\\.|\\.)(?:[_a-zA-Z].*|\\[.*]))?$/\n const addSubkeyToGroupedData = (\n currFieldName: string,\n currFieldSeparator: string,\n currEncryptedField: string,\n groupedDataKey: 'nestedObjectsKeys' | 'mapsValuesKeys' | 'arraysValuesKeys'\n ) => {\n const existingOrNew = groupedData[groupedDataKey][currFieldName] ?? (groupedData[groupedDataKey][currFieldName] = [])\n const subKey = currEncryptedField.slice(currFieldName.length + currFieldSeparator.length)\n if (subKey.startsWith('[')) {\n let parsedJson: any[]\n try {\n parsedJson = JSON.parse(subKey)\n } catch {\n throw new Error(`Invalid encrypted field ${path}${currEncryptedField} (not a valid JSON subkey)`)\n }\n if (Array.isArray(parsedJson) && parsedJson.every((x) => typeof x == 'string')) {\n parsedJson.forEach((x) => existingOrNew.push(x))\n } else throw new Error(`Invalid encrypted field ${path}${currEncryptedField} (not an array of strings)`)\n } else {\n existingOrNew.push(subKey)\n }\n }\n for (const currEncryptedField of encryptedFields) {\n const currFieldMatch = currEncryptedField.match(encryptedFieldRegex)\n if (!!currFieldMatch) {\n const currFieldName = currFieldMatch[1]\n const currFieldSeparator = currFieldMatch[2]\n if (!currFieldSeparator) {\n if (groupedData.topLevelFields.has(currFieldName)) throw new Error(`Duplicate encrypted field ${path}${currFieldName}`)\n if (\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.mapsValuesKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n groupedData.topLevelFields.add(currFieldName)\n } else if (currFieldSeparator == '.') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.mapsValuesKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'nestedObjectsKeys')\n } else if (currFieldSeparator == '.*.') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'mapsValuesKeys')\n } else if (currFieldSeparator == '[].') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.mapsValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'arraysValuesKeys')\n } else throw new Error(`Internal error: unknown separator ${currFieldSeparator} passed regex validation in ${path}${currEncryptedField}`)\n } else throw new Error(`Invalid encrypted field ${path}${currEncryptedField}`)\n }\n return {\n topLevelFields: Array.from(groupedData.topLevelFields).map((fieldName) => ({ fieldName, fieldPath: path + fieldName })),\n nestedObjectsKeys: Object.fromEntries(\n Object.entries(groupedData.nestedObjectsKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '.'),\n ])\n ),\n mapsValuesKeys: Object.fromEntries(\n Object.entries(groupedData.mapsValuesKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '.*.'),\n ])\n ),\n arraysValuesKeys: Object.fromEntries(\n Object.entries(groupedData.arraysValuesKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '[].'),\n ])\n ),\n }\n}\n\nfunction encryptedObjectDeepEqual(l: any, r: any): boolean {\n if (Array.isArray(l)) {\n if (!Array.isArray(r) || l.length !== r.length) {\n return false\n }\n for (let i = 0; i < l.length; i++) {\n if (!encryptedObjectDeepEqual(l[i], r[i])) {\n return false\n }\n }\n } else if (typeof l === 'object') {\n if (typeof r !== 'object' || Array.isArray(r)) {\n return false\n }\n const toEncryptKeys = Object.keys(l)\n const encryptedSelfContentKeys = Object.keys(r)\n if (toEncryptKeys.length !== encryptedSelfContentKeys.length) {\n return false\n }\n const allKeys = new Set([...toEncryptKeys, ...encryptedSelfContentKeys])\n if (allKeys.size !== toEncryptKeys.length) {\n return false\n }\n for (const key of toEncryptKeys) {\n if (!encryptedObjectDeepEqual(l[key], r[key])) {\n return false\n }\n }\n } else {\n return l === r\n }\n return true\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Encrypt the object graph recursively. Generally return an updated SHALLOW copy, although some fields may be deep copied if they also needed to be\n * recursively encrypted.\n * @param obj the object to encrypt\n * @param cryptor takes in input an object consisting only of the fields to encrypt of obj, and returns the encrypted object.\n * @param decryptor takes in input an \"encrytpedSelf\" value and returns the decrypted content. Can return null or throw exception if the decryption fails.\n * @param keys the keys to encrypt for the\n * @param path path of the current object, used for error messages.\n * @return a shallow copy of the object with a new encryptedSelfField and without the encrypted fields.\n */\nexport async function encryptObject(\n obj: { [key: string]: any },\n cryptor: (obj: { [key: string]: any }) => Promise<ArrayBuffer>,\n decryptor: (encryptedSelf: Uint8Array<ArrayBufferLike>) => Promise<any>,\n keys: EncryptedFieldsManifest,\n path: string = 'obj'\n): Promise<{ [key: string]: any }> {\n const shallowClone = { ...obj }\n const currEncryptedFields: { [key: string]: any } = {}\n for (const { fieldName } of keys.topLevelFields) {\n const fieldValue = shallowClone[fieldName]\n if (fieldValue !== undefined) {\n // we keep null values\n currEncryptedFields[fieldName] = fieldValue\n delete shallowClone[fieldName]\n }\n }\n let existingEncryptedSelfMatch = false\n if (shallowClone.encryptedSelf != undefined) {\n let decrypted = undefined\n try {\n decrypted = await decryptor(string2ua(a2b(shallowClone.encryptedSelf)))\n } catch (e) {\n // ignore\n }\n if (decrypted != undefined /* ignore null and undefined */ && encryptedObjectDeepEqual(currEncryptedFields, decrypted)) {\n existingEncryptedSelfMatch = true\n }\n }\n if (!existingEncryptedSelfMatch) {\n shallowClone['encryptedSelf'] = b2a(ua2string(await cryptor(currEncryptedFields)))\n }\n for (const [fieldName, subKeys] of Object.entries(keys.nestedObjectsKeys)) {\n const fieldValue = shallowClone[fieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!isPojo(fieldValue)) throw new Error(`Expected field ${path}.${fieldName} to be a non-array object`)\n shallowClone[fieldName] = await encryptObject(fieldValue, cryptor, decryptor, subKeys, path + '.' + fieldName)\n }\n }\n for (const [mapFieldName, subKeys] of Object.entries(keys.mapsValuesKeys)) {\n const fieldValue = shallowClone[mapFieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!isPojo(fieldValue)) throw new Error(`Expected field ${path}.${mapFieldName} to be a non-array object`)\n const newMap: { [key: string]: any } = {}\n for (const [key, value] of Object.entries(fieldValue as object)) {\n if (value === null || value === undefined) {\n newMap[key] = value\n } else {\n if (!isPojo(value)) throw new Error(`Expected field ${path}.${mapFieldName}.${key} to be a non-array object`)\n newMap[key] = await encryptObject(value, cryptor, decryptor, subKeys, path + '.' + mapFieldName + '.' + key)\n }\n }\n shallowClone[mapFieldName] = newMap\n }\n }\n for (const [arrayFieldName, subKeys] of Object.entries(keys.arraysValuesKeys)) {\n const fieldValue = shallowClone[arrayFieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!Array.isArray(fieldValue)) throw new Error(`Expected field ${path}.${arrayFieldName} to be an array`)\n const newArray: any[] = Array(fieldValue.length)\n for (let i = 0; i < fieldValue.length; i++) {\n const value = fieldValue[i]\n if (value === null || value === undefined) {\n newArray[i] = value\n } else {\n if (!isPojo(value)) throw new Error(`Expected field ${path}.${arrayFieldName}[${i}] to be a non-array object`)\n newArray[i] = await encryptObject(value, cryptor, decryptor, subKeys, path + '.' + arrayFieldName + '[' + i + ']')\n }\n }\n shallowClone[arrayFieldName] = newArray\n }\n }\n return shallowClone\n}\n\n/**\n * Check if value is a non-null object that is not an array.\n */\nfunction isPojo(value: any): boolean {\n // This break if for some reason we have object versions of String/Number/Boolean\n return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Decrypt object graph recursively.\n *\n * @param obj the object to decrypt\n * @param decryptor the decryptor function (returns a promise); the decryptor returns the decrypted input or null if\n * the decryption fails\n * @return a deep copy of the object with the decrypted fields and removed encryptedSelf field, or null if the\n * decryption failed\n */\nexport async function decryptObject(\n obj: { [key: string]: any },\n decryptor: (obj: Uint8Array) => Promise<{ [key: string]: any } | null>\n): Promise<{ [key: string]: any } | null> {\n const copy: { [key: string]: any } = {}\n for (const [key, value] of Object.entries(obj)) {\n if (key === 'encryptedSelf') {\n copy[key] = value\n } else if (typeof value === 'object' && value !== null) {\n if (Array.isArray(value)) {\n // Note: nested arrays (and primitives) are returned as is, and they aren't recursively decrypted.\n // This is because we currently don't support encryption of elements from arrays in arrays (we only support\n // arrays in objects in arrays).\n // In future this may change.\n const decryptedElements = []\n for (const element of value) {\n if (isPojo(element)) {\n const decrypted = await decryptObject(element, decryptor)\n if (decrypted == null) return null\n decryptedElements.push(decrypted)\n } else {\n decryptedElements.push(element)\n }\n }\n copy[key] = decryptedElements\n } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n copy[key] = value // No direct decryption of array buffer data. Array buffer should be converted to b64 string and encrypted as json data.\n } else {\n const decrypted = await decryptObject(value, decryptor)\n if (decrypted == null) return null\n copy[key] = decrypted\n }\n } else {\n copy[key] = value\n }\n }\n if (obj.encryptedSelf) {\n const decrypted = await decryptor(string2ua(a2b(obj.encryptedSelf)))\n if (decrypted == null) return null\n return { ...copy, ...decrypted }\n } else return copy\n}\n\n/**\n * Extracts the full jwk key pair from the jwk representation of the private key.\n * @param privateKeyJwk private key in jwk representation\n * @param shaVersion the SHA algorithm version\n * @throws if the key is missing the public modulus or public exponent.\n */\nexport function keyPairFromPrivateKeyJwk(privateKeyJwk: JsonWebKey, shaVersion: ShaVersion): KeyPair<JsonWebKey> {\n if (!privateKeyJwk.n || !privateKeyJwk.e) throw new Error('Incomplete private JsonWebKey: missing public modulus and/or exponent')\n return {\n privateKey: privateKeyJwk,\n publicKey: spkiToJwk(hex2ua(jwk2spki(privateKeyJwk)), shaVersion),\n }\n}\n"]}
1
+ {"version":3,"file":"crypto-utils.js","sourceRoot":"","sources":["../../../icc-x-api/utils/cryp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ACnB,CAAC;QACH,CAAC;QACD,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;YACtB,MAAM,SAAS,GAAG,MAAM,SAAS,CAAC,IAAA,wBAAS,EAAC,IAAA,kBAAG,EAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,CAAA;YACpE,IAAI,SAAS,IAAI,IAAI;gBAAE,OAAO,IAAI,CAAA;YAClC,uCAAY,IAAI,GAAK,SAAS,EAAE;QAClC,CAAC;;YAAM,OAAO,IAAI,CAAA;IACpB,CAAC;CAAA;AAED;;;;;GAKG;AACH,SAAgB,wBAAwB,CAAC,aAAyB,EAAE,UAAsB;IACxF,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAA;IAClI,OAAO;QACL,UAAU,EAAE,aAAa;QACzB,SAAS,EAAE,SAAS,CAAC,IAAA,qBAAM,EAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,EAAE,UAAU,CAAC;KAClE,CAAA;AACH,CAAC","sourcesContent":["import * as mm from 'moment'\nimport { Moment } from 'moment'\nimport * as _ from 'lodash'\nimport { a2b, b2a, b64Url2ua, hex2ua, string2ua, ua2b64Url, ua2hex, ua2string } from '../utils/binary-utils'\nimport { pack } from './asn1-packer'\nimport { parseAsn1 } from './asn1-parser'\nimport { KeyPair, ShaVersion } from '../crypto/RSA'\n\nexport function notConcurrent<T>(concurrencyMap: { [key: string]: PromiseLike<any> }, key: string, proc: () => PromiseLike<T>): PromiseLike<T> {\n const inFlight = concurrencyMap[key]\n if (!inFlight) {\n const newJob = (async () => {\n try {\n return await proc()\n } finally {\n delete concurrencyMap[key]\n }\n })()\n concurrencyMap[key] = newJob\n return newJob\n } else {\n return concurrencyMap[key].then(() => notConcurrent(concurrencyMap, key, proc))\n }\n}\n\nexport function jwk2pkcs8(jwk: any): string {\n return pack([\n 0x30,\n [\n [0x02, '00'],\n [0x30, [[0x06, '2a864886f70d010101'], [0x05]]], // pragma: allowlist secret\n [\n 0x04,\n [\n [\n 0x30,\n [\n [0x02, '00'],\n [0x02, ua2hex(b64Url2ua(jwk.n))],\n [0x02, ua2hex(b64Url2ua(jwk.e))],\n [0x02, ua2hex(b64Url2ua(jwk.d))],\n [0x02, ua2hex(b64Url2ua(jwk.p))],\n [0x02, ua2hex(b64Url2ua(jwk.q))],\n [0x02, ua2hex(b64Url2ua(jwk.dp))],\n [0x02, ua2hex(b64Url2ua(jwk.dq))],\n [0x02, ua2hex(b64Url2ua(jwk.qi))],\n ],\n ],\n ],\n ],\n ],\n ])\n}\n\nexport function jwk2spki(jwk: any): string {\n return pack([\n 0x30,\n [\n [0x30, [[0x06, '2a864886f70d010101'], [0x05]]], // pragma: allowlist secret\n [\n 0x03,\n [\n [\n 0x30,\n [\n [0x02, ua2hex(b64Url2ua(jwk.n))],\n [0x02, ua2hex(b64Url2ua(jwk.e))],\n ],\n ],\n ],\n ],\n ],\n ])\n}\n\nexport function spkiToJwk(buf: Uint8Array, shaVersion: ShaVersion): { kty: string; alg: string; n: string; e: string; ext: boolean } {\n const asn1 = parseAsn1(new Uint8Array(buf))\n\n var modulus: Uint8Array | undefined = undefined\n var exponent: Uint8Array | undefined = undefined\n if (\n asn1.type === 0x30 &&\n asn1.children?.[0]?.type === 0x30 &&\n asn1.children?.[0]?.children?.[0]?.type === 0x06 &&\n ua2hex(asn1.children?.[0]?.children?.[0]?.value ?? new Uint8Array(0)) === '2a864886f70d010101' // pragma: allowlist secret\n ) {\n modulus = asn1.children?.[1]?.children?.[0]?.children?.[0]?.value\n exponent = asn1.children?.[1]?.children?.[0]?.children?.[1]?.value\n } else if (asn1.type === 0x30 && asn1.children?.[0]?.type === 0x02 && asn1.children?.[1]?.type === 0x02) {\n modulus = asn1.children?.[0]?.value\n exponent = asn1.children?.[1]?.value\n }\n\n if (!modulus || !exponent) {\n throw new Error('Invalid spki format')\n }\n return {\n kty: 'RSA',\n alg: shaVersion === 'sha-256' ? 'RSA-OAEP-256' : 'RSA-OAEP',\n ext: true,\n n: ua2b64Url(minimalRep(modulus)),\n e: ua2b64Url(minimalRep(exponent)),\n }\n}\n\nexport function pkcs8ToJwk(buf: Uint8Array | ArrayBuffer) {\n const parsed = parseAsn1(new Uint8Array(buf))\n const seq =\n parsed.children?.length === 3 && parsed.children[2].type === 0x04 && parsed.children[2].children?.length === 1\n ? parsed.children[2].children[0]\n : parsed\n return {\n kty: 'RSA',\n n: ua2b64Url(minimalRep(seq.children![1].value as Uint8Array)),\n e: ua2b64Url(minimalRep(seq.children![2].value as Uint8Array)),\n d: ua2b64Url(minimalRep(seq.children![3].value as Uint8Array)),\n p: ua2b64Url(minimalRep(seq.children![4].value as Uint8Array)),\n q: ua2b64Url(minimalRep(seq.children![5].value as Uint8Array)),\n dp: ua2b64Url(minimalRep(seq.children![6].value as Uint8Array)),\n dq: ua2b64Url(minimalRep(seq.children![7].value as Uint8Array)),\n qi: ua2b64Url(minimalRep(seq.children![8].value as Uint8Array)),\n }\n}\n\nfunction minimalRep(b: Uint8Array) {\n let i = 0\n while (b[i] === 0) {\n i++\n }\n return b.slice(i)\n}\n\n/**\n * Provide a view over the given Uint8Array where any trailing null bytes at\n * the end are truncated.\n *\n * This can be used to ignore null bytes at the end of a padded UTF-8 string\n * without needing to copy that string, assuming code point U+0000 is encoded\n * in one null byte according to standards rather than in a multi-byte\n * overlong form.\n */\nexport function truncateTrailingNulls(a: Uint8Array) {\n let end = a.byteLength - 1\n while (a[end] === 0 && end >= 0) {\n end--\n }\n // end is now either the last non-null position in a or -1; in the latter\n // case the returned array will have length 0.\n return a.subarray(0, end + 1)\n}\n\n/**\n *\n * @param buffer1 {Uint8Array}\n * @param buffer2{ Uint8Array}\n * @returns {ArrayBuffer}\n */\nexport function appendBuffer(buffer1: ArrayBuffer, buffer2: ArrayBuffer): ArrayBuffer {\n const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength)\n tmp.set(new Uint8Array(buffer1), 0)\n tmp.set(new Uint8Array(buffer2), buffer1.byteLength)\n return tmp.buffer as ArrayBuffer\n}\n\n//Convenience methods for dates management\nexport function after(d1: number | null | undefined, d2: number | null | undefined): boolean {\n return d1 === null || d2 === null || d1 === undefined || d2 === undefined || moment(d1)!.isAfter(moment(d2)!)\n}\n\nexport function before(d1: number | null | undefined, d2: number | null | undefined): boolean {\n return d1 === null || d2 === null || d1 === undefined || d2 === undefined || moment(d1)!.isBefore(moment(d2)!)\n}\n\nfunction moment(epochOrLongCalendar: number): Moment | null {\n if (!epochOrLongCalendar && epochOrLongCalendar !== 0) {\n return null\n }\n if (epochOrLongCalendar >= 18000101 && epochOrLongCalendar < 25400000) {\n return mm('' + epochOrLongCalendar, 'YYYYMMDD')\n } else if (epochOrLongCalendar >= 18000101000000) {\n return mm('' + epochOrLongCalendar, 'YYYYMMDDHHmmss')\n } else {\n return mm(epochOrLongCalendar)\n }\n}\n\n/**\n * Configuration for the encryption of an object.\n * @param topLevelFields the fields of the object to encrypt. All the fields will be encrypted in a single encryptedSelf field which is added to the\n * object.\n * @param nestedObjectsKeys the name of fields which are expected to contain a nested object (or undefined). Allows to specify\n */\nexport type EncryptedFieldsManifest = {\n topLevelFields: { fieldName: string; fieldPath: string }[]\n nestedObjectsKeys: {\n [objectFieldName: string]: EncryptedFieldsManifest\n }\n mapsValuesKeys: {\n [mapFieldName: string]: EncryptedFieldsManifest\n }\n arraysValuesKeys: {\n [arrayFieldName: string]: EncryptedFieldsManifest\n }\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n *\n * Parse the encrypted fields configuration for a specific entity type.\n *\n * ## Grammar\n *\n * The grammar for each encrypted field is the following:\n * ```\n * fieldName :=\n * regex([a-zA-Z_][a-zA-Z0-9_]+)\n * encryptedField :=\n * fieldName\n * | fieldName + (\".\" | \".*.\" | \"[].\") + encryptedField\n * ```\n *\n * This grammar allows you to specify the fields to encrypt for the object and recursively for nested objects.\n * - A string containing only a single `fieldName` will encrypt the field with the given name.\n * - A string starting with `fieldName.` allows to specify the encrypted fields of a nested object. The encrypted values of the\n * fields in the nested object will be saved in the nested object.\n * - A string starting with `fieldName.*.` treats `fieldName` as a map/dictionary data structure and allows to specify the encrypted fields of the\n * values of the map. Note that the values of the map must be objects as well. The encrypted content of each map value is stored in that value.\n * - A string starting with `fieldName[].` treats `fieldName` as an array and allows to specify the encrypted fields of the values of the array.\n * Note that the values of the array must be objects as well. The encrypted content of each array element is stored in that element.\n *\n * ## Example\n *\n * Consider the following object and encryption keys:\n * ```javascript\n * const obj = {\n * a: { x: 0, y: 1 },\n * b: \"hello\",\n * c: [ { public: \"a\", secret: \"b\" }, { public: \"c\", secret: \"d\" } ],\n * d: \"ok\",\n * e: {\n * info: \"something\",\n * private: \"secret\",\n * dataMap: {\n * \"en\": {\n * a: 1,\n * b: 2\n * },\n * \"fr\": {\n * a: 3,\n * b: 4\n * }\n * }\n * }\n * }\n * const encryptedFields = [\n * \"a\",\n * \"c[].secret\",\n * \"d\",\n * \"e.private\",\n * \"e.datamap.*.a\"\n * ]\n * ```\n * If you use them with the crypt method you will get the following result:\n * ```json\n * {\n * b: \"hello\",\n * c: [\n * { public: \"a\", encryptedSelf: \"...encrypted data of c[0]\" },\n * { public: \"c\", encryptedSelf: \"...encrypted data of c[1]\" }\n * ],\n * e: {\n * info: \"something\",\n * dataMap: {\n * \"en\": { b: 2, encryptedSelf: \"...encrypted data of e.dataMap['en']\" },\n * \"fr\": { b: 4, encryptedSelf: \"...encrypted data of e.dataMap['fr']\" }\n * },\n * encryptedSelf: \"...encrypted data of e\"\n * },\n * encryptedSelf: \"...encrypted data of obj\"\n * }\n * ```\n *\n * ## Shortened representation\n *\n * You can also group encrypted fields having the same prefix by concatenating to the prefix the JSON representation of an array of all the postfixes.\n * For example the following encrypted fields:\n * ```javascript\n * const encryptedFields = [\"a.b.c.d.e.f1\", \"a.b.c.d.e.f2\", \"a.b.c.d.e.f3\", \"a.b.c.d.e.f4\"]\n * ```\n * can be shortened to\n * ```javascript\n * const encryptedFields = ['a.b.c.d.e.[\"f1\",\"f2\",\"f3\",\"f4\"]'] // Note the use of single quotes to avoid escaping the double quotes\n * ```\n * If you use the shortened representation you may need to escape nested json representations. In that case the use of `JSON.stringify` is\n * recommended.\n *\n * @param encryptedFields\n * @param path\n */\nexport function parseEncryptedFields(encryptedFields: string[], path: string): EncryptedFieldsManifest {\n const groupedData = {\n topLevelFields: new Set<string>(),\n nestedObjectsKeys: {} as { [objectFieldName: string]: string[] },\n mapsValuesKeys: {} as { [mapFieldName: string]: string[] },\n arraysValuesKeys: {} as { [arrayFieldName: string]: string[] },\n }\n const encryptedFieldRegex = /^([_a-zA-Z][_a-zA-Z0-9]*)(?:(\\.\\*\\.|\\[]\\.|\\.)(?:[_a-zA-Z].*|\\[.*]))?$/\n const addSubkeyToGroupedData = (\n currFieldName: string,\n currFieldSeparator: string,\n currEncryptedField: string,\n groupedDataKey: 'nestedObjectsKeys' | 'mapsValuesKeys' | 'arraysValuesKeys'\n ) => {\n const existingOrNew = groupedData[groupedDataKey][currFieldName] ?? (groupedData[groupedDataKey][currFieldName] = [])\n const subKey = currEncryptedField.slice(currFieldName.length + currFieldSeparator.length)\n if (subKey.startsWith('[')) {\n let parsedJson: any[]\n try {\n parsedJson = JSON.parse(subKey)\n } catch {\n throw new Error(`Invalid encrypted field ${path}${currEncryptedField} (not a valid JSON subkey)`)\n }\n if (Array.isArray(parsedJson) && parsedJson.every((x) => typeof x == 'string')) {\n parsedJson.forEach((x) => existingOrNew.push(x))\n } else throw new Error(`Invalid encrypted field ${path}${currEncryptedField} (not an array of strings)`)\n } else {\n existingOrNew.push(subKey)\n }\n }\n for (const currEncryptedField of encryptedFields) {\n const currFieldMatch = currEncryptedField.match(encryptedFieldRegex)\n if (!!currFieldMatch) {\n const currFieldName = currFieldMatch[1]\n const currFieldSeparator = currFieldMatch[2]\n if (!currFieldSeparator) {\n if (groupedData.topLevelFields.has(currFieldName)) throw new Error(`Duplicate encrypted field ${path}${currFieldName}`)\n if (\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.mapsValuesKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n groupedData.topLevelFields.add(currFieldName)\n } else if (currFieldSeparator == '.') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.mapsValuesKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'nestedObjectsKeys')\n } else if (currFieldSeparator == '.*.') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.arraysValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'mapsValuesKeys')\n } else if (currFieldSeparator == '[].') {\n if (\n groupedData.topLevelFields.has(currFieldName) ||\n !!groupedData.nestedObjectsKeys[currFieldName] ||\n !!groupedData.mapsValuesKeys[currFieldName]\n )\n throw new Error(`Encrypted field appears multiple times as different nested types and or top-level-field: ${path}${currFieldName}`)\n addSubkeyToGroupedData(currFieldName, currFieldSeparator, currEncryptedField, 'arraysValuesKeys')\n } else throw new Error(`Internal error: unknown separator ${currFieldSeparator} passed regex validation in ${path}${currEncryptedField}`)\n } else throw new Error(`Invalid encrypted field ${path}${currEncryptedField}`)\n }\n return {\n topLevelFields: Array.from(groupedData.topLevelFields).map((fieldName) => ({ fieldName, fieldPath: path + fieldName })),\n nestedObjectsKeys: Object.fromEntries(\n Object.entries(groupedData.nestedObjectsKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '.'),\n ])\n ),\n mapsValuesKeys: Object.fromEntries(\n Object.entries(groupedData.mapsValuesKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '.*.'),\n ])\n ),\n arraysValuesKeys: Object.fromEntries(\n Object.entries(groupedData.arraysValuesKeys).map(([fieldName, fieldNames]) => [\n fieldName,\n parseEncryptedFields(fieldNames, path + fieldName + '[].'),\n ])\n ),\n }\n}\n\nfunction encryptedObjectDeepEqual(l: any, r: any): boolean {\n if (l === null || r === null) {\n return l === r\n }\n if (Array.isArray(l)) {\n if (!Array.isArray(r) || l.length !== r.length) {\n return false\n }\n for (let i = 0; i < l.length; i++) {\n if (!encryptedObjectDeepEqual(l[i], r[i])) {\n return false\n }\n }\n } else if (typeof l === 'object') {\n if (typeof r !== 'object' || Array.isArray(r)) {\n return false\n }\n const toEncryptKeys = Object.keys(l)\n const encryptedSelfContentKeys = Object.keys(r)\n if (toEncryptKeys.length !== encryptedSelfContentKeys.length) {\n return false\n }\n const allKeys = new Set([...toEncryptKeys, ...encryptedSelfContentKeys])\n if (allKeys.size !== toEncryptKeys.length) {\n return false\n }\n for (const key of toEncryptKeys) {\n if (!encryptedObjectDeepEqual(l[key], r[key])) {\n return false\n }\n }\n } else {\n return l === r\n }\n return true\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Encrypt the object graph recursively. Generally return an updated SHALLOW copy, although some fields may be deep copied if they also needed to be\n * recursively encrypted.\n * @param obj the object to encrypt\n * @param cryptor takes in input an object consisting only of the fields to encrypt of obj, and returns the encrypted object.\n * @param decryptor takes in input an \"encrytpedSelf\" value and returns the decrypted content. Can return null or throw exception if the decryption fails.\n * @param keys the keys to encrypt for the\n * @param path path of the current object, used for error messages.\n * @return a shallow copy of the object with a new encryptedSelfField and without the encrypted fields.\n */\nexport async function encryptObject(\n obj: { [key: string]: any },\n cryptor: (obj: { [key: string]: any }) => Promise<ArrayBuffer>,\n decryptor: (encryptedSelf: Uint8Array<ArrayBufferLike>) => Promise<any>,\n keys: EncryptedFieldsManifest,\n path: string = 'obj'\n): Promise<{ [key: string]: any }> {\n const shallowClone = { ...obj }\n const currEncryptedFields: { [key: string]: any } = {}\n for (const { fieldName } of keys.topLevelFields) {\n const fieldValue = shallowClone[fieldName]\n if (fieldValue !== undefined) {\n // we keep null values\n currEncryptedFields[fieldName] = fieldValue\n delete shallowClone[fieldName]\n }\n }\n let existingEncryptedSelfMatch = false\n if (shallowClone.encryptedSelf != undefined) {\n let decrypted = undefined\n try {\n decrypted = await decryptor(string2ua(a2b(shallowClone.encryptedSelf)))\n } catch (e) {\n // ignore\n }\n if (decrypted != undefined /* ignore null and undefined */ && encryptedObjectDeepEqual(currEncryptedFields, decrypted)) {\n existingEncryptedSelfMatch = true\n }\n }\n if (!existingEncryptedSelfMatch) {\n shallowClone['encryptedSelf'] = b2a(ua2string(await cryptor(currEncryptedFields)))\n }\n for (const [fieldName, subKeys] of Object.entries(keys.nestedObjectsKeys)) {\n const fieldValue = shallowClone[fieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!isPojo(fieldValue)) throw new Error(`Expected field ${path}.${fieldName} to be a non-array object`)\n shallowClone[fieldName] = await encryptObject(fieldValue, cryptor, decryptor, subKeys, path + '.' + fieldName)\n }\n }\n for (const [mapFieldName, subKeys] of Object.entries(keys.mapsValuesKeys)) {\n const fieldValue = shallowClone[mapFieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!isPojo(fieldValue)) throw new Error(`Expected field ${path}.${mapFieldName} to be a non-array object`)\n const newMap: { [key: string]: any } = {}\n for (const [key, value] of Object.entries(fieldValue as object)) {\n if (value === null || value === undefined) {\n newMap[key] = value\n } else {\n if (!isPojo(value)) throw new Error(`Expected field ${path}.${mapFieldName}.${key} to be a non-array object`)\n newMap[key] = await encryptObject(value, cryptor, decryptor, subKeys, path + '.' + mapFieldName + '.' + key)\n }\n }\n shallowClone[mapFieldName] = newMap\n }\n }\n for (const [arrayFieldName, subKeys] of Object.entries(keys.arraysValuesKeys)) {\n const fieldValue = shallowClone[arrayFieldName]\n if (fieldValue !== undefined && fieldValue !== null) {\n if (!Array.isArray(fieldValue)) throw new Error(`Expected field ${path}.${arrayFieldName} to be an array`)\n const newArray: any[] = Array(fieldValue.length)\n for (let i = 0; i < fieldValue.length; i++) {\n const value = fieldValue[i]\n if (value === null || value === undefined) {\n newArray[i] = value\n } else {\n if (!isPojo(value)) throw new Error(`Expected field ${path}.${arrayFieldName}[${i}] to be a non-array object`)\n newArray[i] = await encryptObject(value, cryptor, decryptor, subKeys, path + '.' + arrayFieldName + '[' + i + ']')\n }\n }\n shallowClone[arrayFieldName] = newArray\n }\n }\n return shallowClone\n}\n\n/**\n * Check if value is a non-null object that is not an array.\n */\nfunction isPojo(value: any): boolean {\n // This break if for some reason we have object versions of String/Number/Boolean\n return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)\n}\n\n/**\n * @internal this function is for internal use only and may be changed without notice\n * Decrypt object graph recursively.\n *\n * @param obj the object to decrypt\n * @param decryptor the decryptor function (returns a promise); the decryptor returns the decrypted input or null if\n * the decryption fails\n * @return a deep copy of the object with the decrypted fields and removed encryptedSelf field, or null if the\n * decryption failed\n */\nexport async function decryptObject(\n obj: { [key: string]: any },\n decryptor: (obj: Uint8Array) => Promise<{ [key: string]: any } | null>\n): Promise<{ [key: string]: any } | null> {\n const copy: { [key: string]: any } = {}\n for (const [key, value] of Object.entries(obj)) {\n if (key === 'encryptedSelf') {\n copy[key] = value\n } else if (typeof value === 'object' && value !== null) {\n if (Array.isArray(value)) {\n // Note: nested arrays (and primitives) are returned as is, and they aren't recursively decrypted.\n // This is because we currently don't support encryption of elements from arrays in arrays (we only support\n // arrays in objects in arrays).\n // In future this may change.\n const decryptedElements = []\n for (const element of value) {\n if (isPojo(element)) {\n const decrypted = await decryptObject(element, decryptor)\n if (decrypted == null) return null\n decryptedElements.push(decrypted)\n } else {\n decryptedElements.push(element)\n }\n }\n copy[key] = decryptedElements\n } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n copy[key] = value // No direct decryption of array buffer data. Array buffer should be converted to b64 string and encrypted as json data.\n } else {\n const decrypted = await decryptObject(value, decryptor)\n if (decrypted == null) return null\n copy[key] = decrypted\n }\n } else {\n copy[key] = value\n }\n }\n if (obj.encryptedSelf) {\n const decrypted = await decryptor(string2ua(a2b(obj.encryptedSelf)))\n if (decrypted == null) return null\n return { ...copy, ...decrypted }\n } else return copy\n}\n\n/**\n * Extracts the full jwk key pair from the jwk representation of the private key.\n * @param privateKeyJwk private key in jwk representation\n * @param shaVersion the SHA algorithm version\n * @throws if the key is missing the public modulus or public exponent.\n */\nexport function keyPairFromPrivateKeyJwk(privateKeyJwk: JsonWebKey, shaVersion: ShaVersion): KeyPair<JsonWebKey> {\n if (!privateKeyJwk.n || !privateKeyJwk.e) throw new Error('Incomplete private JsonWebKey: missing public modulus and/or exponent')\n return {\n privateKey: privateKeyJwk,\n publicKey: spkiToJwk(hex2ua(jwk2spki(privateKeyJwk)), shaVersion),\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icure/api",
3
- "version": "8.6.12",
3
+ "version": "8.6.14",
4
4
  "description": "Typescript version of iCure standalone API client",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",