@icure/api 7.0.0-beta.4 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/icc-api/api/IccDocumentApi.d.ts +6 -4
  2. package/icc-api/api/IccDocumentApi.js +8 -5
  3. package/icc-api/api/IccDocumentApi.js.map +1 -1
  4. package/icc-api/model/Address.d.ts +6 -0
  5. package/icc-api/model/Address.js.map +1 -1
  6. package/icc-api/model/Annotation.d.ts +18 -0
  7. package/icc-api/model/Annotation.js.map +1 -1
  8. package/icc-api/model/Connection.d.ts +16 -0
  9. package/icc-api/model/Connection.js +38 -0
  10. package/icc-api/model/Connection.js.map +1 -0
  11. package/icc-api/model/Content.js +1 -1
  12. package/icc-api/model/Content.js.map +1 -1
  13. package/icc-api/model/CryptoActorStub.d.ts +5 -0
  14. package/icc-api/model/CryptoActorStub.js +1 -0
  15. package/icc-api/model/CryptoActorStub.js.map +1 -1
  16. package/icc-api/model/Delegation.d.ts +3 -0
  17. package/icc-api/model/Delegation.js.map +1 -1
  18. package/icc-api/model/HealthElement.d.ts +6 -0
  19. package/icc-api/model/HealthElement.js.map +1 -1
  20. package/icc-api/model/HealthcareParty.js +1 -1
  21. package/icc-api/model/HealthcareParty.js.map +1 -1
  22. package/icc-api/model/ISO639_1.d.ts +8 -0
  23. package/icc-api/model/ISO639_1.js +3 -0
  24. package/icc-api/model/ISO639_1.js.map +1 -0
  25. package/icc-api/model/Patient.d.ts +7 -0
  26. package/icc-api/model/Patient.js +1 -1
  27. package/icc-api/model/Patient.js.map +1 -1
  28. package/icc-api/model/models.d.ts +2 -0
  29. package/icc-api/model/models.js +1 -0
  30. package/icc-api/model/models.js.map +1 -1
  31. package/icc-x-api/crypto/EntitiesEncryption.d.ts +2 -1
  32. package/icc-x-api/crypto/EntitiesEncryption.js +13 -11
  33. package/icc-x-api/crypto/EntitiesEncryption.js.map +1 -1
  34. package/icc-x-api/filters/filters.d.ts +4 -0
  35. package/icc-x-api/filters/filters.js +4 -0
  36. package/icc-x-api/filters/filters.js.map +1 -1
  37. package/icc-x-api/icc-accesslog-x-api.d.ts +1 -1
  38. package/icc-x-api/icc-accesslog-x-api.js +9 -21
  39. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  40. package/icc-x-api/icc-calendar-item-x-api.d.ts +1 -1
  41. package/icc-x-api/icc-calendar-item-x-api.js +9 -18
  42. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  43. package/icc-x-api/icc-classification-x-api.js +6 -17
  44. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  45. package/icc-x-api/icc-contact-x-api.d.ts +30 -2
  46. package/icc-x-api/icc-contact-x-api.js +82 -96
  47. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  48. package/icc-x-api/icc-device-x-api.d.ts +17 -0
  49. package/icc-x-api/icc-device-x-api.js +35 -0
  50. package/icc-x-api/icc-device-x-api.js.map +1 -0
  51. package/icc-x-api/icc-doctemplate-x-api.js +2 -13
  52. package/icc-x-api/icc-doctemplate-x-api.js.map +1 -1
  53. package/icc-x-api/icc-document-x-api.d.ts +12 -4
  54. package/icc-x-api/icc-document-x-api.js +22 -23
  55. package/icc-x-api/icc-document-x-api.js.map +1 -1
  56. package/icc-x-api/icc-form-x-api.js +6 -15
  57. package/icc-x-api/icc-form-x-api.js.map +1 -1
  58. package/icc-x-api/icc-hcparty-x-api.d.ts +9 -2
  59. package/icc-x-api/icc-hcparty-x-api.js +9 -1
  60. package/icc-x-api/icc-hcparty-x-api.js.map +1 -1
  61. package/icc-x-api/icc-helement-x-api.d.ts +12 -3
  62. package/icc-x-api/icc-helement-x-api.js +19 -19
  63. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  64. package/icc-x-api/icc-invoice-x-api.js +6 -17
  65. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  66. package/icc-x-api/icc-maintenance-task-x-api.d.ts +12 -2
  67. package/icc-x-api/icc-maintenance-task-x-api.js +17 -13
  68. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  69. package/icc-x-api/icc-message-x-api.js +6 -16
  70. package/icc-x-api/icc-message-x-api.js.map +1 -1
  71. package/icc-x-api/icc-patient-x-api.d.ts +12 -3
  72. package/icc-x-api/icc-patient-x-api.js +21 -18
  73. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  74. package/icc-x-api/icc-receipt-x-api.js +5 -15
  75. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  76. package/icc-x-api/icc-time-table-x-api.js +5 -15
  77. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  78. package/icc-x-api/icc-user-x-api.d.ts +10 -1
  79. package/icc-x-api/icc-user-x-api.js +8 -1
  80. package/icc-x-api/icc-user-x-api.js.map +1 -1
  81. package/icc-x-api/index.d.ts +110 -4
  82. package/icc-x-api/index.js +17 -15
  83. package/icc-x-api/index.js.map +1 -1
  84. package/icc-x-api/utils/crypto-utils.d.ts +140 -11
  85. package/icc-x-api/utils/crypto-utils.js +285 -36
  86. package/icc-x-api/utils/crypto-utils.js.map +1 -1
  87. package/icc-x-api/utils/index.d.ts +1 -0
  88. package/icc-x-api/utils/index.js +1 -0
  89. package/icc-x-api/utils/index.js.map +1 -1
  90. package/icc-x-api/utils/websocket.d.ts +61 -0
  91. package/icc-x-api/utils/websocket.js +351 -0
  92. package/icc-x-api/utils/websocket.js.map +1 -0
  93. package/package.json +5 -2
@@ -1 +1 @@
1
- {"version":3,"file":"EntitiesEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/EntitiesEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAA8H;AAC9H,4BAA2B;AAE3B,gEAAuD;AACvD,qEAAiE;AAGjE;;;GAGG;AACH,MAAa,kBAAkB;IAK7B,YAAY,UAA4B,EAAE,YAA8B,EAAE,mBAAwC;QAChH,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,YAAY,GAAG,YAAY,CAA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iB,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;QAC3G,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;gBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;SACF;IACH,CAAC;CACF;AA/5BD,gDA+5BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport { b2a, crypt, decrypt, hex2ua, string2ua, truncateTrailingNulls, ua2hex, ua2string, ua2utf8, utf8_2ua } from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly exchangeKeysManager: ExchangeKeysManager\n\n constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, exchangeKeysManager: ExchangeKeysManager) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.exchangeKeysManager = exchangeKeysManager\n }\n\n /**\n * Get the data owners which can access the entity\n * @param entity an entity.\n */\n async getDataOwnersWithAccessTo(entity: EncryptedEntity): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: 'WRITE' }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entity.delegations ?? {}).map((x) => [x, 'WRITE'])),\n hasUnknownAnonymousDataOwners: false,\n }\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n autoShareSecretIds: boolean,\n delegatesShareInfo: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKey?: ShareMetadataBehaviour\n shareOwningEntityIds?: ShareMetadataBehaviour\n }\n }\n ): Promise<T | undefined> {\n if (!Object.keys(delegatesShareInfo).length) {\n throw new Error('Must specify at least a delegate')\n }\n let defaultSecretIds: string[] | undefined\n if (autoShareSecretIds) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n defaultSecretIds = availableSecretIds\n } else {\n defaultSecretIds = [this.primitives.randomUuid()]\n }\n }\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let updatedEntity = undefined\n for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {\n let shareSecretIds: string[] = autoShareSecretIds ? defaultSecretIds! : requests.shareSecretIds ?? []\n let actualShareEncryptionKeys: string[] = []\n if (requests.shareEncryptionKey !== ShareMetadataBehaviour.NEVER) {\n if (!availableEncryptionKeys.length && requests.shareEncryptionKey === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (requests.shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n if (!availableOwningEntityIds.length && requests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n updatedEntity =\n (await this.entityWithExtendedEncryptedMetadata(\n updatedEntity ?? entity,\n delegateId,\n shareSecretIds,\n actualShareEncryptionKeys,\n actualShareOwningEntityIds\n )) ?? updatedEntity\n }\n return updatedEntity\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T | undefined> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return undefined\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf((await this.ensureEncryptionKeysInitialised(entity)) ?? entity, dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async tryDecryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n /* ignore */\n }\n }\n return { data: content, wasDecrypted: false }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string | undefined,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decrypt(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n const text = ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted)\n return JSON.parse(text)\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string | undefined,\n cryptedKeys: string[],\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await crypt(\n entityWithInitialisedEncryptionKeys,\n (obj) => {\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || v instanceof Uint8Array\n ? b2a(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n cryptedKeys\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n const cryptedCopyWithRandomKey = await crypt(\n _.cloneDeep(entity),\n async (obj: { [key: string]: string }) => Promise.resolve(new ArrayBuffer(1)),\n cryptedKeys\n )\n if (\n !_.isEqual(\n _.omitBy({ ...cryptedCopyWithRandomKey, encryptedSelf: undefined }, _.isNil),\n _.omitBy({ ...entity, encryptedSelf: undefined }, _.isNil)\n )\n ) {\n throw new Error(`Impossible to modify encrypted value of an entity if no encryption key is known.\\n${entity}`)\n }\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T | undefined> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) return entity\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return Promise.all(\n (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const hierarchy = dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as CryptoActorStubWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.stub?.id\n ? {\n ...entity,\n rev: updatedDelegator!.stub.rev,\n hcPartyKeys: updatedDelegator!.stub.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.stub.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (existingMetadata.length > 0) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n }\n }\n}\n"]}
1
+ {"version":3,"file":"EntitiesEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/EntitiesEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAaiB;AACjB,4BAA2B;AAE3B,gEAAuD;AACvD,qEAAiE;AAGjE;;;GAGG;A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,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAA;QAC3H,IAAI,MAAM,CAAC,cAAc,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;QAC/G,IAAI,MAAM,CAAC,iBAAiB,IAAI,MAAM,CAAC,iBAAiB,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;QAC3G,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;gBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;SACF;IACH,CAAC;CACF;AAr6BD,gDAq6BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport {\n b2a,\n encryptObject,\n decryptObject,\n EncryptedFieldsManifest,\n hex2ua,\n parseEncryptedFields,\n string2ua,\n truncateTrailingNulls,\n ua2hex,\n ua2string,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n private readonly primitives: CryptoPrimitives\n private readonly dataOwnerApi: IccDataOwnerXApi\n private readonly exchangeKeysManager: ExchangeKeysManager\n\n constructor(primitives: CryptoPrimitives, dataOwnerApi: IccDataOwnerXApi, exchangeKeysManager: ExchangeKeysManager) {\n this.primitives = primitives\n this.dataOwnerApi = dataOwnerApi\n this.exchangeKeysManager = exchangeKeysManager\n }\n\n /**\n * Get the data owners which can access the entity\n * @param entity an entity.\n */\n async getDataOwnersWithAccessTo(entity: EncryptedEntity): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: 'WRITE' }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entity.delegations ?? {}).map((x) => [x, 'WRITE'])),\n hasUnknownAnonymousDataOwners: false,\n }\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n autoShareSecretIds: boolean,\n delegatesShareInfo: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKey?: ShareMetadataBehaviour\n shareOwningEntityIds?: ShareMetadataBehaviour\n }\n }\n ): Promise<T | undefined> {\n if (!Object.keys(delegatesShareInfo).length) {\n throw new Error('Must specify at least a delegate')\n }\n let defaultSecretIds: string[] | undefined\n if (autoShareSecretIds) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n defaultSecretIds = availableSecretIds\n } else {\n defaultSecretIds = [this.primitives.randomUuid()]\n }\n }\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let updatedEntity = undefined\n for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {\n let shareSecretIds: string[] = autoShareSecretIds ? defaultSecretIds! : requests.shareSecretIds ?? []\n let actualShareEncryptionKeys: string[] = []\n if (requests.shareEncryptionKey !== ShareMetadataBehaviour.NEVER) {\n if (!availableEncryptionKeys.length && requests.shareEncryptionKey === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (requests.shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n if (!availableOwningEntityIds.length && requests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n updatedEntity =\n (await this.entityWithExtendedEncryptedMetadata(\n updatedEntity ?? entity,\n delegateId,\n shareSecretIds,\n actualShareEncryptionKeys,\n actualShareOwningEntityIds\n )) ?? updatedEntity\n }\n return updatedEntity\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T | undefined> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return undefined\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf((await this.ensureEncryptionKeysInitialised(entity)) ?? entity, dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async tryDecryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n /* ignore */\n }\n }\n return { data: content, wasDecrypted: false }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string | undefined,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n const text = ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted)\n return JSON.parse(text)\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string | undefined,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n entityWithInitialisedEncryptionKeys ?? entity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || v instanceof Uint8Array\n ? b2a(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n 'entity'\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T | undefined> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return Promise.all(\n (await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()).map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const hierarchy = dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as CryptoActorStubWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.stub?.id\n ? {\n ...entity,\n rev: updatedDelegator!.stub.rev,\n hcPartyKeys: updatedDelegator!.stub.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.stub.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n _.each(argsArray, (arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (existingMetadata.length > 0) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n }\n }\n}\n"]}
@@ -55,6 +55,10 @@ export * from './ServiceByIdsFilter';
55
55
  export * from './ServiceBySecretForeignKeys';
56
56
  export * from './UnionFilter';
57
57
  export * from './UserByIdsFilter';
58
+ export * from './MaintenanceTaskByHcPartyAndIdentifiersFilter';
59
+ export * from './MaintenanceTaskByHcPartyAndTypeFilter';
60
+ export * from './MaintenanceTaskByIdsFilter';
61
+ export * from './MaintenanceTaskAfterDateFilter';
58
62
  export declare class Filter {
59
63
  static patient(): PatientFilterBuilder;
60
64
  }
@@ -77,6 +77,10 @@ __exportStar(require("./ServiceByIdsFilter"), exports);
77
77
  __exportStar(require("./ServiceBySecretForeignKeys"), exports);
78
78
  __exportStar(require("./UnionFilter"), exports);
79
79
  __exportStar(require("./UserByIdsFilter"), exports);
80
+ __exportStar(require("./MaintenanceTaskByHcPartyAndIdentifiersFilter"), exports);
81
+ __exportStar(require("./MaintenanceTaskByHcPartyAndTypeFilter"), exports);
82
+ __exportStar(require("./MaintenanceTaskByIdsFilter"), exports);
83
+ __exportStar(require("./MaintenanceTaskAfterDateFilter"), exports);
80
84
  class Filter {
81
85
  static patient() {
82
86
  return new PatientFilterBuilder();
@@ -1 +1 @@
1
- {"version":3,"file":"filters.js","sourceRoot":"","sources":["../../../icc-x-api/filters/filters.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,qDAAiD;AAOjD,6DAAyD;AACzD,+CAA2C;AAC3C,yDAAqD;AACrD,uFAAmF;AACnF,yFAAqF;AACrF,+FAA2F;AAC3F,qFAAiF;AACjF,yGAAqG;AACrG,2FAAuF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,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAyB,CAAA;IACtI,CAAC;IAED,YAAY,CAAC,IAAY;QACvB,OAAO,IAAI,CAAC,QAAQ,CAClB,IAAI,EACJ,IAAI,oBAAoB,CACtB,GAAG,EAAE,CACH,IAAI,iFAAuC,CAAC;YAC1C,iBAAiB,EAAE,IAAI,CAAC,KAAK;YAC7B,YAAY,EAAE,IAAI;SACnB,CAAC,EACJ,IAAI,CAAC,KAAK,CACX,CACsB,CAAA;IAC3B,CAAC;IAED,KAAK;;QACH,OAAO,CAAA,MAAA,IAAI,CAAC,cAAc,oDAAI,KAAI,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,EAAE,CAAA;IACtD,CAAC;CACF","sourcesContent":["import { ConstantFilter } from './ConstantFilter'\nimport { Patient } from '../../icc-api/model/Patient'\nimport { AbstractFilterPatient } from '../../icc-api/model/AbstractFilterPatient'\nimport { AbstractFilterContact } from '../../icc-api/model/AbstractFilterContact'\nimport { AbstractFilterService } from '../../icc-api/model/AbstractFilterService'\nimport { Service } from '../../icc-api/model/Service'\nimport { Contact } from '../../icc-api/model/Contact'\nimport { IntersectionFilter } from './IntersectionFilter'\nimport { UnionFilter } from './UnionFilter'\nimport { ComplementFilter } from './ComplementFilter'\nimport { PatientByHcPartyAndActiveFilter } from './PatientByHcPartyAndActiveFilter'\nimport { PatientByHcPartyAndAddressFilter } from './PatientByHcPartyAndAddressFilter'\nimport { PatientByHcPartyAndExternalIdFilter } from './PatientByHcPartyAndExternalIdFilter'\nimport { PatientByHcPartyAndSsinsFilter } from './PatientByHcPartyAndSsinsFilter'\nimport { PatientByHcPartyDateOfBirthBetweenFilter } from './PatientByHcPartyDateOfBirthBetweenFilter'\nimport { PatientByHcPartyDateOfBirthFilter } from './PatientByHcPartyDateOfBirthFilter'\n\nimport { add, format } from 'date-fns'\nimport { PatientByHcPartyFilter } from './PatientByHcPartyFilter'\nimport { PatientByHcPartyGenderEducationProfession } from './PatientByHcPartyGenderEducationProfession'\nimport { PatientByIdsFilter } from './PatientByIdsFilter'\nimport { PatientByHcPartyNameContainsFuzzyFilter } from './PatientByHcPartyNameContainsFuzzyFilter'\n\nimport GenderEnum = Patient.GenderEnum\nimport { ContactByHcPartyFilter } from './ContactByHcPartyFilter'\n\nexport * from './AllCodesFilter'\nexport * from './AllDevicesFilter'\nexport * from './AllHealthcarePartiesFilter'\nexport * from './AllUsersFilter'\nexport * from './CodeByIdsFilter'\nexport * from './CodeByRegionTypeLabelLanguageFilter'\nexport * from './ComplementFilter'\nexport * from './ConstantFilter'\nexport * from './ContactByHcPartyFilter'\nexport * from './ContactByHcPartyPatientTagCodeDateFilter'\nexport * from './ContactByHcPartyTagCodeDateFilter'\nexport * from './ContactByServiceIdsFilter'\nexport * from './DeviceByHcPartyFilter'\nexport * from './DeviceByIdsFilter'\nexport * from './HealthElementByHcPartyFilter'\nexport * from './HealthElementByHcPartyIdentifiersFilter'\nexport * from './HealthElementByHcPartySecretForeignKeysFilter'\nexport * from './HealthElementByHcPartyTagCodeFilter'\nexport * from './HealthElementByIdsFilter'\nexport * from './HealthcarePartyByIdsFilter'\nexport * from './HealthcarePartyByNameFilter'\nexport * from './HealthcarePartyByTagCodeFilter'\nexport * from './IntersectionFilter'\nexport * from './InvoiceByHcPartyCodeDateFilter'\nexport * from './PatientByHcPartyAndActiveFilter'\nexport * from './PatientByHcPartyAndAddressFilter'\nexport * from './PatientByHcPartyAndExternalIdFilter'\nexport * from './PatientByHcPartyAndIdentifiersFilter'\nexport * from './PatientByHcPartyAndSsinFilter'\nexport * from './PatientByHcPartyAndSsinsFilter'\nexport * from './PatientByHcPartyDateOfBirthBetweenFilter'\nexport * from './PatientByHcPartyDateOfBirthFilter'\nexport * from './PatientByHcPartyFilter'\nexport * from './PatientByHcPartyGenderEducationProfession'\nexport * from './PatientByHcPartyNameContainsFuzzyFilter'\nexport * from './PatientByHcPartyNameFilter'\nexport * from './PatientByIdsFilter'\nexport * from './ServiceByContactsAndSubcontactsFilter'\nexport * from './ServiceByHcPartyFilter'\nexport * from './ServiceByHcPartyIdentifiersFilter'\nexport * from './ServiceByHcPartyHealthElementIdsFilter'\nexport * from './ServiceByHcPartyTagCodeDateFilter'\nexport * from './ServiceByIdsFilter'\nexport * from './ServiceBySecretForeignKeys'\nexport * from './UnionFilter'\nexport * from './UserByIdsFilter'\n\nexport class Filter {\n public static patient(): PatientFilterBuilder {\n return new PatientFilterBuilder()\n }\n}\n\nexport type AbstractFilter<T> = T extends Patient\n ? AbstractFilterPatient | ConstantFilter<Patient> | IntersectionFilter<Patient> | UnionFilter<Patient> | ComplementFilter<Patient>\n : T extends Contact\n ? AbstractFilterContact | ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T>\n : T extends Service\n ? AbstractFilterService | ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T>\n : ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T>\n\nconst f: AbstractFilterContact = new ComplementFilter<Contact>(new ContactByHcPartyFilter({}), new ContactByHcPartyFilter({}))\n\nabstract class FilterBuilder<T> {\n // This is the current generator for the filter, when we call build(), filterProvider() is going to be called\n filterProvider?: () => AbstractFilter<T>\n // This is the method that is called each time we chain a filter to another filter. The default behaviour is to\n // return a FilterBuilder with the provider set to the last element in the chain, except when we use combination\n // operators like or()/and()/… . After one of those, the composer is set to a function that will return a FilterBuilder\n // that combines the existing filterBuilder with the filter definition we just added.\n composer: (thisFilterBuilder: FilterBuilder<T>, otherFilterBuilder: FilterBuilder<T>) => FilterBuilder<T> = (\n thisFilterBuilder: FilterBuilder<T>,\n otherFilterBuilder: FilterBuilder<T>\n ) => otherFilterBuilder\n\n protected constructor(\n filterProvider?: () => AbstractFilter<T>,\n composer?: (thisFilterBuilder: FilterBuilder<T>, otherFilterBuilder: FilterBuilder<T>) => FilterBuilder<T>\n ) {\n this.filterProvider = filterProvider\n composer && (this.composer = composer)\n }\n\n abstract build(): AbstractFilter<T>\n\n abstract clone(\n filterProvider?: () => AbstractFilter<T>,\n composer?: (thisFilterBuilder: FilterBuilder<T>, otherFilterBuilder: FilterBuilder<T>) => FilterBuilder<T>\n ): FilterBuilder<T>\n\n listOf(elements: T[]): FilterBuilder<T> {\n return this.clone(() => new ConstantFilter<T>(elements) as AbstractFilter<T>)\n }\n\n private makeLazyLeftRightFilterBuilder(\n leftHandRightHandFiltersCombiner: (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () => AbstractFilter<T>\n ) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const leftHandFilterBuilder: FilterBuilder<T> = this\n const leftHandFilter = leftHandFilterBuilder.build() // Freeze the leftHand filter\n\n return leftHandFilterBuilder.filterProvider\n ? this.clone(\n undefined, //filter provider is indeterminate until we have performed a composition\n (unused: FilterBuilder<T>, rightHandFilterBuilder: FilterBuilder<T>) => {\n // because we freeze the leftHand in the state it is right now, we are not going to use its value when the composition occurs\n const rightHandFilter = rightHandFilterBuilder.build()\n\n return rightHandFilter\n ? this.clone(leftHandRightHandFiltersCombiner(leftHandFilter, rightHandFilter), rightHandFilterBuilder.composer)\n : rightHandFilterBuilder //Can this happen ?\n }\n )\n : this\n }\n\n private makeEagerLeftRightFilterBuilder(\n rightHandFilterBuilderFactory: (it: FilterBuilder<T>) => FilterBuilder<T>,\n leftHandRightHandFiltersCombiner: (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () => AbstractFilter<T>\n ) {\n const rightHandFilterBuilder = rightHandFilterBuilderFactory(this)\n return this.filterProvider ? this.clone(leftHandRightHandFiltersCombiner(this.build(), rightHandFilterBuilder.build())) : this\n }\n\n /**\n * There are two ways of doing and, or, …\n *\n * 1) for (...) or (...) we use the syntax ... .or((builder) => builder...)\n * ex: youngerThan(65).or((b) => b.olderThan(18).and().gender(M)) means any gender < 65 or male > 18\n * 2) for ((...) or ...) we use the syntax ... .or().…\n * ex: youngerThan(65).or().olderThan(18).and().gender(M) means males between 18 and 65\n *\n * When 1) is used we do not have to wait for anything to provide a resolved builder that can later be combined with extra elements in the chain.\n * In other words, we can build the current filter chain up to the or/and/… and we can build what is inside the or/and/… brackets and we can set\n * the filterProvider of the returned Builder to () => UnionFilter([leftHand.build(), innerBrackets.build()]).\n *\n * When 2) is used, things get more tricky because we will have to do an or/and/… between what we have on the leftHand and with what we do not have\n * yet on the right hand. What we do in that situation is to set the filterProvider() to undefined because calling build() without having provided a\n * rightHand doesn't make sense. We set a composer that is going to be called the next time we chain a filter.\n *\n * @param filterBuilderFactory\n */\n\n and(filterBuilderFactory?: (it: FilterBuilder<T>) => FilterBuilder<T>): FilterBuilder<T> {\n const combiner = (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () =>\n new IntersectionFilter<T>([leftHandFilter, rightHandFilter]) as AbstractFilter<T>\n\n return filterBuilderFactory ? this.makeEagerLeftRightFilterBuilder(filterBuilderFactory, combiner) : this.makeLazyLeftRightFilterBuilder(combiner)\n }\n\n or(filterBuilderFactory?: (it: FilterBuilder<T>) => FilterBuilder<T>): FilterBuilder<T> {\n const combiner = (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () =>\n new UnionFilter<T>([leftHandFilter, rightHandFilter]) as AbstractFilter<T>\n\n return filterBuilderFactory ? this.makeEagerLeftRightFilterBuilder(filterBuilderFactory, combiner) : this.makeLazyLeftRightFilterBuilder(combiner)\n }\n\n minus(filterBuilderFactory?: (it: FilterBuilder<T>) => FilterBuilder<T>): FilterBuilder<T> {\n const combiner = (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () =>\n new ComplementFilter<T>(leftHandFilter, rightHandFilter) as AbstractFilter<T>\n\n return filterBuilderFactory ? this.makeEagerLeftRightFilterBuilder(filterBuilderFactory, combiner) : this.makeLazyLeftRightFilterBuilder(combiner)\n }\n}\n\nclass PatientFilterBuilder extends FilterBuilder<Patient> {\n hcpId?: string\n\n constructor(\n filterProvider?: () => AbstractFilter<Patient>,\n hcpId?: string,\n composer?: (thisFilterBuilder: FilterBuilder<Patient>, otherFilterBuilder: FilterBuilder<Patient>) => FilterBuilder<Patient>\n ) {\n super(filterProvider, composer)\n this.hcpId = hcpId\n }\n\n clone(\n filterProvider?: () => AbstractFilter<Patient>,\n composer?: (thisFilterBuilder: FilterBuilder<Patient>, otherFilterBuilder: FilterBuilder<Patient>) => FilterBuilder<Patient>\n ): FilterBuilder<Patient> {\n return new PatientFilterBuilder(filterProvider, this.hcpId, composer)\n }\n\n listOf(elements: Patient[]): PatientFilterBuilder {\n return new PatientFilterBuilder(() => new ConstantFilter<Patient>(elements) as AbstractFilter<Patient>)\n }\n\n and(filterBuilderFactory?: (it: PatientFilterBuilder) => PatientFilterBuilder): PatientFilterBuilder {\n return super.and(filterBuilderFactory as any) as PatientFilterBuilder\n }\n\n or(filterBuilderFactory?: (it: PatientFilterBuilder) => PatientFilterBuilder): PatientFilterBuilder {\n return super.or(filterBuilderFactory as any) as PatientFilterBuilder\n }\n\n minus(filterBuilderFactory?: (it: PatientFilterBuilder) => PatientFilterBuilder): PatientFilterBuilder {\n return super.minus(filterBuilderFactory as any) as PatientFilterBuilder\n }\n\n forHcp(hcpId: string): PatientFilterBuilder {\n return this.composer(this, new PatientFilterBuilder(this.filterProvider, hcpId)) as PatientFilterBuilder\n }\n\n all(): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(() => new PatientByHcPartyFilter({ healthcarePartyId: this.hcpId }), this.hcpId)\n ) as PatientFilterBuilder\n }\n\n activePatients(): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(() => new PatientByHcPartyAndActiveFilter({ healthcarePartyId: this.hcpId, active: true }), this.hcpId)\n ) as PatientFilterBuilder\n }\n\n inactivePatients(): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(() => new PatientByHcPartyAndActiveFilter({ healthcarePartyId: this.hcpId, active: false }), this.hcpId)\n ) as PatientFilterBuilder\n }\n\n byAddress(searchString?: string, postalCode?: string, houseNumber?: string): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyAndAddressFilter({\n healthcarePartyId: this.hcpId,\n searchString,\n postalCode,\n houseNumber,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n withExternalId(externalId: string): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyAndExternalIdFilter({\n healthcarePartyId: this.hcpId,\n externalId: externalId,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n withSsins(ssins: string[]): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(() => new PatientByHcPartyAndSsinsFilter({ healthcarePartyId: this.hcpId, ssins: ssins }), this.hcpId)\n ) as PatientFilterBuilder\n }\n\n withDateOfBirthBetween(from?: number, to?: number): PatientFilterBuilder {\n return this.composer(\n this,\n this.clone(\n () =>\n new PatientByHcPartyDateOfBirthBetweenFilter({\n healthcarePartyId: this.hcpId,\n minDateOfBirth: from,\n maxDateOfBirth: to,\n })\n )\n ) as PatientFilterBuilder\n }\n\n byDateOfBirth(dateOfBirth: number): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyDateOfBirthFilter({\n healthcarePartyId: this.hcpId,\n dateOfBirth: dateOfBirth,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n olderThan(age: number): PatientFilterBuilder {\n return this.withDateOfBirthBetween(10000101, parseInt(format(add(new Date(), { years: -age }), 'yyyyMMdd')))\n }\n\n youngerThan(age: number): PatientFilterBuilder {\n return this.withDateOfBirthBetween(parseInt(format(add(new Date(), { years: -age }), 'yyyyMMdd')), 99991231)\n }\n\n byGenderEducationProfession(gender?: GenderEnum, education?: string, profession?: string): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyGenderEducationProfession({\n healthcarePartyId: this.hcpId,\n gender: gender,\n education: education,\n profession: profession,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n byIds(ids: string[]): PatientFilterBuilder {\n return this.composer(this, new PatientFilterBuilder(() => new PatientByIdsFilter({ ids: ids }), this.hcpId)) as PatientFilterBuilder\n }\n\n searchByName(name: string): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyNameContainsFuzzyFilter({\n healthcarePartyId: this.hcpId,\n searchString: name,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n build(): AbstractFilter<Patient> {\n return this.filterProvider?.() || this.all().build()\n }\n}\n"]}
1
+ {"version":3,"file":"filters.js","sourceRoot":"","sources":["../../../icc-x-api/filters/filters.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,qDAAiD;AAOjD,6DAAyD;AACzD,+CAA2C;AAC3C,yDAAqD;AACrD,uFAAmF;AACnF,yFAAqF;AACrF,+FAA2F;AAC3F,qFAAiF;AACjF,yGAAqG;AACrG,2FAAuF;AAEvF,uCAAsC;AACtC,qEAAiE;AACjE,2GAAuG;AACvG,6DAAyD;AACzD,uGAAmG;AAGnG,qEAAiE;AAEjE,mDAAgC;AAChC,qDAAkC;AAClC,+DAA4C;AAC5C,mDAAgC;AAChC,oDAAiC;AACjC,wEAAqD;AACrD,qDAAkC;AAClC,mDAAgC;AAChC,2DAAwC;AACxC,6EAA0D;AAC1D,sEAAmD;AACnD,8DAA2C;AAC3C,0DAAuC;AACvC,sDAAmC;AACnC,iEAA8C;AAC9C,4EAAyD;AACzD,kFAA+D;AAC/D,wEAAqD;AACrD,6DAA0C;AAC1C,+DAA4C;AAC5C,gEAA6C;AAC7C,mEAAgD;AAChD,uDAAoC;AACpC,mEAAgD;AAChD,oEAAiD;AACjD,qEAAkD;AAClD,wEAAqD;AACrD,yEAAsD;AACtD,kEAA+C;AAC/C,mEAAgD;AACh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sourcesContent":["import { ConstantFilter } from './ConstantFilter'\nimport { Patient } from '../../icc-api/model/Patient'\nimport { AbstractFilterPatient } from '../../icc-api/model/AbstractFilterPatient'\nimport { AbstractFilterContact } from '../../icc-api/model/AbstractFilterContact'\nimport { AbstractFilterService } from '../../icc-api/model/AbstractFilterService'\nimport { Service } from '../../icc-api/model/Service'\nimport { Contact } from '../../icc-api/model/Contact'\nimport { IntersectionFilter } from './IntersectionFilter'\nimport { UnionFilter } from './UnionFilter'\nimport { ComplementFilter } from './ComplementFilter'\nimport { PatientByHcPartyAndActiveFilter } from './PatientByHcPartyAndActiveFilter'\nimport { PatientByHcPartyAndAddressFilter } from './PatientByHcPartyAndAddressFilter'\nimport { PatientByHcPartyAndExternalIdFilter } from './PatientByHcPartyAndExternalIdFilter'\nimport { PatientByHcPartyAndSsinsFilter } from './PatientByHcPartyAndSsinsFilter'\nimport { PatientByHcPartyDateOfBirthBetweenFilter } from './PatientByHcPartyDateOfBirthBetweenFilter'\nimport { PatientByHcPartyDateOfBirthFilter } from './PatientByHcPartyDateOfBirthFilter'\n\nimport { add, format } from 'date-fns'\nimport { PatientByHcPartyFilter } from './PatientByHcPartyFilter'\nimport { PatientByHcPartyGenderEducationProfession } from './PatientByHcPartyGenderEducationProfession'\nimport { PatientByIdsFilter } from './PatientByIdsFilter'\nimport { PatientByHcPartyNameContainsFuzzyFilter } from './PatientByHcPartyNameContainsFuzzyFilter'\n\nimport GenderEnum = Patient.GenderEnum\nimport { ContactByHcPartyFilter } from './ContactByHcPartyFilter'\n\nexport * from './AllCodesFilter'\nexport * from './AllDevicesFilter'\nexport * from './AllHealthcarePartiesFilter'\nexport * from './AllUsersFilter'\nexport * from './CodeByIdsFilter'\nexport * from './CodeByRegionTypeLabelLanguageFilter'\nexport * from './ComplementFilter'\nexport * from './ConstantFilter'\nexport * from './ContactByHcPartyFilter'\nexport * from './ContactByHcPartyPatientTagCodeDateFilter'\nexport * from './ContactByHcPartyTagCodeDateFilter'\nexport * from './ContactByServiceIdsFilter'\nexport * from './DeviceByHcPartyFilter'\nexport * from './DeviceByIdsFilter'\nexport * from './HealthElementByHcPartyFilter'\nexport * from './HealthElementByHcPartyIdentifiersFilter'\nexport * from './HealthElementByHcPartySecretForeignKeysFilter'\nexport * from './HealthElementByHcPartyTagCodeFilter'\nexport * from './HealthElementByIdsFilter'\nexport * from './HealthcarePartyByIdsFilter'\nexport * from './HealthcarePartyByNameFilter'\nexport * from './HealthcarePartyByTagCodeFilter'\nexport * from './IntersectionFilter'\nexport * from './InvoiceByHcPartyCodeDateFilter'\nexport * from './PatientByHcPartyAndActiveFilter'\nexport * from './PatientByHcPartyAndAddressFilter'\nexport * from './PatientByHcPartyAndExternalIdFilter'\nexport * from './PatientByHcPartyAndIdentifiersFilter'\nexport * from './PatientByHcPartyAndSsinFilter'\nexport * from './PatientByHcPartyAndSsinsFilter'\nexport * from './PatientByHcPartyDateOfBirthBetweenFilter'\nexport * from './PatientByHcPartyDateOfBirthFilter'\nexport * from './PatientByHcPartyFilter'\nexport * from './PatientByHcPartyGenderEducationProfession'\nexport * from './PatientByHcPartyNameContainsFuzzyFilter'\nexport * from './PatientByHcPartyNameFilter'\nexport * from './PatientByIdsFilter'\nexport * from './ServiceByContactsAndSubcontactsFilter'\nexport * from './ServiceByHcPartyFilter'\nexport * from './ServiceByHcPartyIdentifiersFilter'\nexport * from './ServiceByHcPartyHealthElementIdsFilter'\nexport * from './ServiceByHcPartyTagCodeDateFilter'\nexport * from './ServiceByIdsFilter'\nexport * from './ServiceBySecretForeignKeys'\nexport * from './UnionFilter'\nexport * from './UserByIdsFilter'\nexport * from './MaintenanceTaskByHcPartyAndIdentifiersFilter'\nexport * from './MaintenanceTaskByHcPartyAndTypeFilter'\nexport * from './MaintenanceTaskByIdsFilter'\nexport * from './MaintenanceTaskAfterDateFilter'\n\nexport class Filter {\n public static patient(): PatientFilterBuilder {\n return new PatientFilterBuilder()\n }\n}\n\nexport type AbstractFilter<T> = T extends Patient\n ? AbstractFilterPatient | ConstantFilter<Patient> | IntersectionFilter<Patient> | UnionFilter<Patient> | ComplementFilter<Patient>\n : T extends Contact\n ? AbstractFilterContact | ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T>\n : T extends Service\n ? AbstractFilterService | ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T>\n : ConstantFilter<T> | IntersectionFilter<T> | UnionFilter<T> | ComplementFilter<T>\n\nconst f: AbstractFilterContact = new ComplementFilter<Contact>(new ContactByHcPartyFilter({}), new ContactByHcPartyFilter({}))\n\nabstract class FilterBuilder<T> {\n // This is the current generator for the filter, when we call build(), filterProvider() is going to be called\n filterProvider?: () => AbstractFilter<T>\n // This is the method that is called each time we chain a filter to another filter. The default behaviour is to\n // return a FilterBuilder with the provider set to the last element in the chain, except when we use combination\n // operators like or()/and()/… . After one of those, the composer is set to a function that will return a FilterBuilder\n // that combines the existing filterBuilder with the filter definition we just added.\n composer: (thisFilterBuilder: FilterBuilder<T>, otherFilterBuilder: FilterBuilder<T>) => FilterBuilder<T> = (\n thisFilterBuilder: FilterBuilder<T>,\n otherFilterBuilder: FilterBuilder<T>\n ) => otherFilterBuilder\n\n protected constructor(\n filterProvider?: () => AbstractFilter<T>,\n composer?: (thisFilterBuilder: FilterBuilder<T>, otherFilterBuilder: FilterBuilder<T>) => FilterBuilder<T>\n ) {\n this.filterProvider = filterProvider\n composer && (this.composer = composer)\n }\n\n abstract build(): AbstractFilter<T>\n\n abstract clone(\n filterProvider?: () => AbstractFilter<T>,\n composer?: (thisFilterBuilder: FilterBuilder<T>, otherFilterBuilder: FilterBuilder<T>) => FilterBuilder<T>\n ): FilterBuilder<T>\n\n listOf(elements: T[]): FilterBuilder<T> {\n return this.clone(() => new ConstantFilter<T>(elements) as AbstractFilter<T>)\n }\n\n private makeLazyLeftRightFilterBuilder(\n leftHandRightHandFiltersCombiner: (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () => AbstractFilter<T>\n ) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const leftHandFilterBuilder: FilterBuilder<T> = this\n const leftHandFilter = leftHandFilterBuilder.build() // Freeze the leftHand filter\n\n return leftHandFilterBuilder.filterProvider\n ? this.clone(\n undefined, //filter provider is indeterminate until we have performed a composition\n (unused: FilterBuilder<T>, rightHandFilterBuilder: FilterBuilder<T>) => {\n // because we freeze the leftHand in the state it is right now, we are not going to use its value when the composition occurs\n const rightHandFilter = rightHandFilterBuilder.build()\n\n return rightHandFilter\n ? this.clone(leftHandRightHandFiltersCombiner(leftHandFilter, rightHandFilter), rightHandFilterBuilder.composer)\n : rightHandFilterBuilder //Can this happen ?\n }\n )\n : this\n }\n\n private makeEagerLeftRightFilterBuilder(\n rightHandFilterBuilderFactory: (it: FilterBuilder<T>) => FilterBuilder<T>,\n leftHandRightHandFiltersCombiner: (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () => AbstractFilter<T>\n ) {\n const rightHandFilterBuilder = rightHandFilterBuilderFactory(this)\n return this.filterProvider ? this.clone(leftHandRightHandFiltersCombiner(this.build(), rightHandFilterBuilder.build())) : this\n }\n\n /**\n * There are two ways of doing and, or, …\n *\n * 1) for (...) or (...) we use the syntax ... .or((builder) => builder...)\n * ex: youngerThan(65).or((b) => b.olderThan(18).and().gender(M)) means any gender < 65 or male > 18\n * 2) for ((...) or ...) we use the syntax ... .or().…\n * ex: youngerThan(65).or().olderThan(18).and().gender(M) means males between 18 and 65\n *\n * When 1) is used we do not have to wait for anything to provide a resolved builder that can later be combined with extra elements in the chain.\n * In other words, we can build the current filter chain up to the or/and/… and we can build what is inside the or/and/… brackets and we can set\n * the filterProvider of the returned Builder to () => UnionFilter([leftHand.build(), innerBrackets.build()]).\n *\n * When 2) is used, things get more tricky because we will have to do an or/and/… between what we have on the leftHand and with what we do not have\n * yet on the right hand. What we do in that situation is to set the filterProvider() to undefined because calling build() without having provided a\n * rightHand doesn't make sense. We set a composer that is going to be called the next time we chain a filter.\n *\n * @param filterBuilderFactory\n */\n\n and(filterBuilderFactory?: (it: FilterBuilder<T>) => FilterBuilder<T>): FilterBuilder<T> {\n const combiner = (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () =>\n new IntersectionFilter<T>([leftHandFilter, rightHandFilter]) as AbstractFilter<T>\n\n return filterBuilderFactory ? this.makeEagerLeftRightFilterBuilder(filterBuilderFactory, combiner) : this.makeLazyLeftRightFilterBuilder(combiner)\n }\n\n or(filterBuilderFactory?: (it: FilterBuilder<T>) => FilterBuilder<T>): FilterBuilder<T> {\n const combiner = (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () =>\n new UnionFilter<T>([leftHandFilter, rightHandFilter]) as AbstractFilter<T>\n\n return filterBuilderFactory ? this.makeEagerLeftRightFilterBuilder(filterBuilderFactory, combiner) : this.makeLazyLeftRightFilterBuilder(combiner)\n }\n\n minus(filterBuilderFactory?: (it: FilterBuilder<T>) => FilterBuilder<T>): FilterBuilder<T> {\n const combiner = (leftHandFilter: AbstractFilter<T>, rightHandFilter: AbstractFilter<T>) => () =>\n new ComplementFilter<T>(leftHandFilter, rightHandFilter) as AbstractFilter<T>\n\n return filterBuilderFactory ? this.makeEagerLeftRightFilterBuilder(filterBuilderFactory, combiner) : this.makeLazyLeftRightFilterBuilder(combiner)\n }\n}\n\nclass PatientFilterBuilder extends FilterBuilder<Patient> {\n hcpId?: string\n\n constructor(\n filterProvider?: () => AbstractFilter<Patient>,\n hcpId?: string,\n composer?: (thisFilterBuilder: FilterBuilder<Patient>, otherFilterBuilder: FilterBuilder<Patient>) => FilterBuilder<Patient>\n ) {\n super(filterProvider, composer)\n this.hcpId = hcpId\n }\n\n clone(\n filterProvider?: () => AbstractFilter<Patient>,\n composer?: (thisFilterBuilder: FilterBuilder<Patient>, otherFilterBuilder: FilterBuilder<Patient>) => FilterBuilder<Patient>\n ): FilterBuilder<Patient> {\n return new PatientFilterBuilder(filterProvider, this.hcpId, composer)\n }\n\n listOf(elements: Patient[]): PatientFilterBuilder {\n return new PatientFilterBuilder(() => new ConstantFilter<Patient>(elements) as AbstractFilter<Patient>)\n }\n\n and(filterBuilderFactory?: (it: PatientFilterBuilder) => PatientFilterBuilder): PatientFilterBuilder {\n return super.and(filterBuilderFactory as any) as PatientFilterBuilder\n }\n\n or(filterBuilderFactory?: (it: PatientFilterBuilder) => PatientFilterBuilder): PatientFilterBuilder {\n return super.or(filterBuilderFactory as any) as PatientFilterBuilder\n }\n\n minus(filterBuilderFactory?: (it: PatientFilterBuilder) => PatientFilterBuilder): PatientFilterBuilder {\n return super.minus(filterBuilderFactory as any) as PatientFilterBuilder\n }\n\n forHcp(hcpId: string): PatientFilterBuilder {\n return this.composer(this, new PatientFilterBuilder(this.filterProvider, hcpId)) as PatientFilterBuilder\n }\n\n all(): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(() => new PatientByHcPartyFilter({ healthcarePartyId: this.hcpId }), this.hcpId)\n ) as PatientFilterBuilder\n }\n\n activePatients(): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(() => new PatientByHcPartyAndActiveFilter({ healthcarePartyId: this.hcpId, active: true }), this.hcpId)\n ) as PatientFilterBuilder\n }\n\n inactivePatients(): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(() => new PatientByHcPartyAndActiveFilter({ healthcarePartyId: this.hcpId, active: false }), this.hcpId)\n ) as PatientFilterBuilder\n }\n\n byAddress(searchString?: string, postalCode?: string, houseNumber?: string): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyAndAddressFilter({\n healthcarePartyId: this.hcpId,\n searchString,\n postalCode,\n houseNumber,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n withExternalId(externalId: string): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyAndExternalIdFilter({\n healthcarePartyId: this.hcpId,\n externalId: externalId,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n withSsins(ssins: string[]): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(() => new PatientByHcPartyAndSsinsFilter({ healthcarePartyId: this.hcpId, ssins: ssins }), this.hcpId)\n ) as PatientFilterBuilder\n }\n\n withDateOfBirthBetween(from?: number, to?: number): PatientFilterBuilder {\n return this.composer(\n this,\n this.clone(\n () =>\n new PatientByHcPartyDateOfBirthBetweenFilter({\n healthcarePartyId: this.hcpId,\n minDateOfBirth: from,\n maxDateOfBirth: to,\n })\n )\n ) as PatientFilterBuilder\n }\n\n byDateOfBirth(dateOfBirth: number): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyDateOfBirthFilter({\n healthcarePartyId: this.hcpId,\n dateOfBirth: dateOfBirth,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n olderThan(age: number): PatientFilterBuilder {\n return this.withDateOfBirthBetween(10000101, parseInt(format(add(new Date(), { years: -age }), 'yyyyMMdd')))\n }\n\n youngerThan(age: number): PatientFilterBuilder {\n return this.withDateOfBirthBetween(parseInt(format(add(new Date(), { years: -age }), 'yyyyMMdd')), 99991231)\n }\n\n byGenderEducationProfession(gender?: GenderEnum, education?: string, profession?: string): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyGenderEducationProfession({\n healthcarePartyId: this.hcpId,\n gender: gender,\n education: education,\n profession: profession,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n byIds(ids: string[]): PatientFilterBuilder {\n return this.composer(this, new PatientFilterBuilder(() => new PatientByIdsFilter({ ids: ids }), this.hcpId)) as PatientFilterBuilder\n }\n\n searchByName(name: string): PatientFilterBuilder {\n return this.composer(\n this,\n new PatientFilterBuilder(\n () =>\n new PatientByHcPartyNameContainsFuzzyFilter({\n healthcarePartyId: this.hcpId,\n searchString: name,\n }),\n this.hcpId\n )\n ) as PatientFilterBuilder\n }\n\n build(): AbstractFilter<Patient> {\n return this.filterProvider?.() || this.all().build()\n }\n}\n"]}
@@ -10,7 +10,7 @@ export interface AccessLogWithPatientId extends AccessLog {
10
10
  patientId: string;
11
11
  }
12
12
  export declare class IccAccesslogXApi extends IccAccesslogApi implements EncryptedEntityXApi<models.AccessLog> {
13
- private readonly cryptedKeys;
13
+ private readonly encryptedFields;
14
14
  crypto: IccCryptoXApi;
15
15
  dataOwnerApi: IccDataOwnerXApi;
16
16
  constructor(host: string, headers: {
@@ -14,6 +14,7 @@ const icc_api_1 = require("../icc-api");
14
14
  const models_1 = require("../icc-api/model/models");
15
15
  const _ = require("lodash");
16
16
  const AuthenticationProvider_1 = require("./auth/AuthenticationProvider");
17
+ const utils_1 = require("./utils");
17
18
  class IccAccesslogXApi extends icc_api_1.IccAccesslogApi {
18
19
  constructor(host, headers, crypto, dataOwnerApi, cryptedKeys = ['detail', 'objectId'], authenticationProvider = new AuthenticationProvider_1.NoAuthenticationProvider(), fetchImpl = typeof window !== 'undefined'
19
20
  ? window.fetch
@@ -21,9 +22,9 @@ class IccAccesslogXApi extends icc_api_1.IccAccesslogApi {
21
22
  ? self.fetch
22
23
  : fetch) {
23
24
  super(host, headers, authenticationProvider, fetchImpl);
24
- this.cryptedKeys = cryptedKeys;
25
25
  this.crypto = crypto;
26
26
  this.dataOwnerApi = dataOwnerApi;
27
+ this.encryptedFields = (0, utils_1.parseEncryptedFields)(cryptedKeys, 'AccessLog.');
27
28
  }
28
29
  /**
29
30
  * Creates a new instance of access log with initialised encryption metadata (not in the database).
@@ -41,33 +42,20 @@ class IccAccesslogXApi extends icc_api_1.IccAccesslogApi {
41
42
  * @return a new instance of access log.
42
43
  */
43
44
  newInstance(user, patient, h, options = {}) {
44
- var _a, _b, _c, _d, _e, _f;
45
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
45
46
  return __awaiter(this, void 0, void 0, function* () {
46
47
  const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user);
47
- const accessLog = _.assign({
48
- id: this.crypto.primitives.randomUuid(),
49
- _type: 'org.taktik.icure.entities.AccessLog',
50
- created: new Date().getTime(),
51
- modified: new Date().getTime(),
52
- date: +new Date(),
53
- responsible: dataOwnerId,
54
- author: user.id,
55
- codes: [],
56
- tags: [],
57
- user: user.id,
58
- patientId: patient.id,
59
- accessType: 'USER_ACCESS',
60
- }, h || {});
48
+ const accessLog = Object.assign(Object.assign({}, (h !== null && h !== void 0 ? h : {})), { _type: 'org.taktik.icure.entities.AccessLog', id: (_a = h === null || h === void 0 ? void 0 : h.id) !== null && _a !== void 0 ? _a : this.crypto.primitives.randomUuid(), created: (_b = h === null || h === void 0 ? void 0 : h.created) !== null && _b !== void 0 ? _b : new Date().getTime(), modified: (_c = h === null || h === void 0 ? void 0 : h.modified) !== null && _c !== void 0 ? _c : new Date().getTime(), date: (_d = h === null || h === void 0 ? void 0 : h.date) !== null && _d !== void 0 ? _d : new Date().getTime(), responsible: (_e = h === null || h === void 0 ? void 0 : h.responsible) !== null && _e !== void 0 ? _e : dataOwnerId, author: (_f = h === null || h === void 0 ? void 0 : h.author) !== null && _f !== void 0 ? _f : user.id, codes: (_g = h === null || h === void 0 ? void 0 : h.codes) !== null && _g !== void 0 ? _g : [], tags: (_h = h === null || h === void 0 ? void 0 : h.tags) !== null && _h !== void 0 ? _h : [], user: (_j = h === null || h === void 0 ? void 0 : h.user) !== null && _j !== void 0 ? _j : user.id, patientId: (_k = h === null || h === void 0 ? void 0 : h.patientId) !== null && _k !== void 0 ? _k : patient.id, accessType: (_l = h === null || h === void 0 ? void 0 : h.accessType) !== null && _l !== void 0 ? _l : 'USER_ACCESS' });
61
49
  const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user);
62
50
  if (ownerId !== (yield this.dataOwnerApi.getCurrentDataOwnerId()))
63
51
  throw new Error('Can only initialise entities as current data owner.');
64
- const sfk = (_a = options.preferredSfk) !== null && _a !== void 0 ? _a : (yield this.crypto.confidential.getAnySecretIdSharedWithParents(patient));
52
+ const sfk = (_m = options.preferredSfk) !== null && _m !== void 0 ? _m : (yield this.crypto.confidential.getAnySecretIdSharedWithParents(patient));
65
53
  if (!sfk)
66
54
  throw new Error(`Couldn't find any sfk of parent patient ${patient.id}`);
67
55
  const extraDelegations = [
68
- ...Object.keys((_b = options.additionalDelegates) !== null && _b !== void 0 ? _b : {}),
69
- ...((_d = (_c = user.autoDelegations) === null || _c === void 0 ? void 0 : _c.all) !== null && _d !== void 0 ? _d : []),
70
- ...((_f = (_e = user.autoDelegations) === null || _e === void 0 ? void 0 : _e.administrativeData) !== null && _f !== void 0 ? _f : []),
56
+ ...Object.keys((_o = options.additionalDelegates) !== null && _o !== void 0 ? _o : {}),
57
+ ...((_q = (_p = user.autoDelegations) === null || _p === void 0 ? void 0 : _p.all) !== null && _q !== void 0 ? _q : []),
58
+ ...((_s = (_r = user.autoDelegations) === null || _r === void 0 ? void 0 : _r.administrativeData) !== null && _s !== void 0 ? _s : []),
71
59
  ];
72
60
  return new models_1.AccessLog(yield this.crypto.entities
73
61
  .entityWithInitialisedEncryptedMetadata(accessLog, patient.id, sfk, true, extraDelegations)
@@ -122,7 +110,7 @@ class IccAccesslogXApi extends icc_api_1.IccAccesslogApi {
122
110
  return this.encryptAs(this.dataOwnerApi.getDataOwnerIdOf(user), accessLogs);
123
111
  }
124
112
  encryptAs(dataOwner, accessLogs) {
125
- return Promise.all(accessLogs.map((x) => this.crypto.entities.tryEncryptEntity(x, dataOwner, this.cryptedKeys, false, true, (json) => new models_1.AccessLog(json))));
113
+ return Promise.all(accessLogs.map((x) => this.crypto.entities.tryEncryptEntity(x, dataOwner, this.encryptedFields, false, true, (json) => new models_1.AccessLog(json))));
126
114
  }
127
115
  createAccessLog(body) {
128
116
  throw new Error('Cannot call a method that returns access logs without providing a user for de/encryption');