@icure/api 8.0.48 → 8.0.50

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 (61) hide show
  1. package/icc-api/api/IccContactApi.js +1 -1
  2. package/icc-api/api/IccContactApi.js.map +1 -1
  3. package/icc-x-api/crypto/ConfidentialEntities.js +1 -1
  4. package/icc-x-api/crypto/ConfidentialEntities.js.map +1 -1
  5. package/icc-x-api/crypto/DelegationsDeAnonymization.js +5 -2
  6. package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
  7. package/icc-x-api/crypto/ExtendedApisUtils.d.ts +5 -8
  8. package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -1
  9. package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +5 -5
  10. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +4 -14
  11. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
  12. package/icc-x-api/crypto/utils.js +5 -2
  13. package/icc-x-api/crypto/utils.js.map +1 -1
  14. package/icc-x-api/filters/HealthElementByHcPartyTagCodeFilter.d.ts +1 -1
  15. package/icc-x-api/filters/HealthElementByHcPartyTagCodeFilter.js.map +1 -1
  16. package/icc-x-api/icc-accesslog-x-api.d.ts +6 -0
  17. package/icc-x-api/icc-accesslog-x-api.js +9 -3
  18. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  19. package/icc-x-api/icc-calendar-item-x-api.d.ts +6 -0
  20. package/icc-x-api/icc-calendar-item-x-api.js +9 -3
  21. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  22. package/icc-x-api/icc-classification-x-api.d.ts +6 -0
  23. package/icc-x-api/icc-classification-x-api.js +9 -3
  24. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  25. package/icc-x-api/icc-contact-x-api.d.ts +6 -0
  26. package/icc-x-api/icc-contact-x-api.js +9 -3
  27. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  28. package/icc-x-api/icc-document-x-api.d.ts +6 -0
  29. package/icc-x-api/icc-document-x-api.js +9 -3
  30. package/icc-x-api/icc-document-x-api.js.map +1 -1
  31. package/icc-x-api/icc-form-x-api.d.ts +6 -0
  32. package/icc-x-api/icc-form-x-api.js +9 -3
  33. package/icc-x-api/icc-form-x-api.js.map +1 -1
  34. package/icc-x-api/icc-helement-x-api.d.ts +6 -0
  35. package/icc-x-api/icc-helement-x-api.js +9 -3
  36. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  37. package/icc-x-api/icc-invoice-x-api.d.ts +6 -0
  38. package/icc-x-api/icc-invoice-x-api.js +9 -3
  39. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  40. package/icc-x-api/icc-maintenance-task-x-api.d.ts +6 -0
  41. package/icc-x-api/icc-maintenance-task-x-api.js +9 -3
  42. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  43. package/icc-x-api/icc-message-x-api.js +5 -2
  44. package/icc-x-api/icc-message-x-api.js.map +1 -1
  45. package/icc-x-api/icc-patient-x-api.js +5 -2
  46. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  47. package/icc-x-api/icc-receipt-x-api.d.ts +6 -0
  48. package/icc-x-api/icc-receipt-x-api.js +9 -3
  49. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  50. package/icc-x-api/icc-time-table-x-api.d.ts +6 -0
  51. package/icc-x-api/icc-time-table-x-api.js +9 -3
  52. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  53. package/icc-x-api/icc-topic-x-api.d.ts +6 -0
  54. package/icc-x-api/icc-topic-x-api.js +9 -3
  55. package/icc-x-api/icc-topic-x-api.js.map +1 -1
  56. package/package.json +1 -1
  57. package/test/icc-x-api/help-meddi.d.ts +1 -0
  58. package/test/icc-x-api/help-meddi.js +53 -0
  59. package/test/icc-x-api/help-meddi.js.map +1 -0
  60. package/test/icc-x-api/icc-recovery-x-api.js +5 -0
  61. package/test/icc-x-api/icc-recovery-x-api.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ExtendedApisUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtils.ts"],"names":[],"mappings":"","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { ShareResult } from '../utils/ShareResult'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { EncryptedFieldsManifest } from '../utils'\nimport { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this interface is meant only for internal use and may be changed without notice.\n * Gives access to several functions to access encrypted entities metadata.\n */\nexport interface ExtendedApisUtils {\n // region metadata decryption\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 * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\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 * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\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 * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get if the current data owner has write access to the content of the entity.\n * @param entity an entity\n * @return if the current data owner (or one of his parents) has write access to the content of the entity.\n */\n hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>\n\n /**\n * @param entity an entity\n * @return if the entity has no encryption metadata and can be safely initialised using .\n */\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean\n // endregion\n\n // region metadata initialisation and share\n /**\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, 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 and DOES NOT SAVE the entity to the cloud/DB: you will have to save the entity manually.\n * @param entity entity which requires encryption metadata initialisation.\n * @param entityType type of the entity.\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 initialiseEncryptionKey if false this method will not initialize an encryption key for the entity. Use only for entities which use\n * delegations for access control but don't actually have any encrypted content.\n * @param initialiseSecretId if false this method will not initialize any secret id, use it for entities which can not be 'owning entities' (e.g.\n * HealthcareElement).\n * @param autoDelegations automatically shares the metadata with the provided data owners, with the provided access level.\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n initialiseSecretId: boolean,\n autoDelegations: { [dataOwnerId: string]: AccessLevelEnum }\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string | undefined\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 updates the entity in the cloud/DB (the updated entities in the returned promise are already saved in the DB). NOTE: this method can only\n * be used with entities which already exist in the cloud (the entities must have been saved).\n * @param entitiesType type of entities to update\n * @param entitiesUpdates share/update requests for each entity. An array of objects containing:\n * - The entity to share/update (or at least its encrypted metadata)\n * - The data to share/update for each delegate. An object associating to each delegate id the data to share/update for that delegate, and the\n * permissions requested for the delegate (ignored if the request will only update already existing shared metadata).\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @throws if there are duplicate entities in the requested updates.\n * @return a promise which will be completed with an object containing:\n * - the updated entities, only for entities were at least one update was successful\n * - information on the individual requests failed, containing the id of the entity, id of the delegate that the request was for, the content,\n * an error code mirroring an http status code, and a human-friendly description of the error (but not necessarily end-user friendly).\n */\n bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n /**\n * Simplified version of {@link bulkShareOrUpdateEncryptedEntityMetadata} for a single entity and with automatic retrieval of the encryption keys\n * and owning entity ids if requested. NOTE: this method can only be used with entities which already exist in the cloud (the entity must have\n * been saved).\n * @param entity an entity.\n * @param unusedSecretIds specifies if the entity should not actually use secret ids but may have some if it was created using older iCure sdk\n * versions. If true the method expects `shareSecretIds` options to always be undefined and will always share any available secret ids. If false\n * it expects `shareSecretIds` options to always be defined and will only share the secret ids specified in the options.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareEncryptionKeys specifies if the encryption keys of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareOwningEntityIds specifies if the owning entity ids of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareSecretIds specifies which secret ids of the entity should be shared. Should be defined only if {@link unusedSecretIds} is false.\n * - requestedPermissions requested permissions for the delegate. Defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return a promise which will be completed with the result of the operation\n * @throws if shareEncryptionKeys or shareOwningEntityIds is {@link ShareMetadataBehaviour.REQUIRED} and the current data owner can't access any\n * value for the required metadata.\n */\n simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n unusedSecretIds: boolean,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>>\n // endregion\n\n // region content encryption and decryption\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 type type of the entity.\n * @param content data of the entity which you want to encrypt.\n * @param saveEntity a function which saves the entity to the cloud/DB. Used only if a new encryption key needed to be initialised for the entity.\n * @return the encrypted data and, if a new encryption key was initialised for the entity, the updated entity.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }>\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 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 * @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 tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }>\n\n /**\n * TODO work on this\n * Decrypts the content of an encrypted entity.\n */\n decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }>\n\n /**\n * Tries to decrypt data to a json object using the provided keys.\n */\n tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined>\n\n /**\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 using the default configuration). If the entity specifies\n * a value for any field which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T>\n\n /**\n * Returns the first encryption key which could be properly decrypted from the entity using the current data owner.\n * @throws if no key could be decrypted.\n */\n decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }>\n\n /**\n * Returns all encryption keys which could be properly decrypted from the entity using the current data owner. The keys returned by this method\n * should not be used for encryption of the entity, but only for decryption.\n * This is because this for data from pre-2018 users this method may return also keys from old formats of entities which are not safe anymore for\n * encryption.\n */\n decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]>\n\n /**\n * Verifies if the entity has valid encryption keys (regardless of whether the current data owner has access to them or not). If not this method\n * will throw an error, otherwise it will return undefined. For pre-2018 users there are some cases where the data may have been encrypted with a\n * key not safe for encryption anymore, in which case this method will return the entity with a new and safe encryption key.\n * After this method is called, if it returns an entity it should also be re-encrypted (using the new key) and saved to the cloud.\n */\n ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined>\n // endregion\n}\n"]}
1
+ {"version":3,"file":"ExtendedApisUtils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtils.ts"],"names":[],"mappings":"","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { ShareResult } from '../utils/ShareResult'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { EncryptedFieldsManifest } from '../utils'\nimport { BulkShareOrUpdateMetadataParams } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this interface is meant only for internal use and may be changed without notice.\n * Gives access to several functions to access encrypted entities metadata.\n */\nexport interface ExtendedApisUtils {\n // region metadata decryption\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 * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\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 * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\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 * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId: string | undefined): Promise<string[]>\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 * @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 owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]>\n\n /**\n * Get if the current data owner has write access to the content of the entity.\n * @param entity an entity\n * @return if the current data owner (or one of his parents) has write access to the content of the entity.\n */\n hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>\n\n /**\n * @param entity an entity\n * @return if the entity has no encryption metadata and can be safely initialised using .\n */\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean\n // endregion\n\n // region metadata initialisation and share\n /**\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, 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 and DOES NOT SAVE the entity to the cloud/DB: you will have to save the entity manually.\n * @param entity entity which requires encryption metadata initialisation.\n * @param entityType type of the entity.\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 initialiseEncryptionKey if false this method will not initialize an encryption key for the entity. Use only for entities which use\n * delegations for access control but don't actually have any encrypted content.\n * HealthcareElement).\n * @param autoDelegations automatically shares the metadata with the provided data owners, with the provided access level.\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<{ updatedEntity: T; rawEncryptionKey: string | undefined; secretId: string | undefined }>\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 updates the entity in the cloud/DB (the updated entities in the returned promise are already saved in the DB). NOTE: this method can only\n * be used with entities which already exist in the cloud (the entities must have been saved).\n * @param entitiesType type of entities to update\n * @param entitiesUpdates share/update requests for each entity. An array of objects containing:\n * - The entity to share/update (or at least its encrypted metadata)\n * - The data to share/update for each delegate. An object associating to each delegate id the data to share/update for that delegate, and the\n * permissions requested for the delegate (ignored if the request will only update already existing shared metadata).\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @throws if there are duplicate entities in the requested updates.\n * @return a promise which will be completed with an object containing:\n * - the updated entities, only for entities were at least one update was successful\n * - information on the individual requests failed, containing the id of the entity, id of the delegate that the request was for, the content,\n * an error code mirroring an http status code, and a human-friendly description of the error (but not necessarily end-user friendly).\n */\n bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }>\n\n /**\n * Simplified version of {@link bulkShareOrUpdateEncryptedEntityMetadata} for a single entity and with automatic retrieval of the encryption keys\n * and owning entity ids if requested. NOTE: this method can only be used with entities which already exist in the cloud (the entity must have\n * been saved).\n * @param entity an entity.\n * versions. If true the method expects `shareSecretIds` options to always be undefined and will always share any available secret ids. If false\n * it expects `shareSecretIds` options to always be defined and will only share the secret ids specified in the options.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareEncryptionKeys specifies if the encryption keys of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareOwningEntityIds specifies if the owning entity ids of the entity should be shared. Defaults to\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}.\n * - shareSecretIds specifies which secret ids of the entity should be shared. Should be defined only if {@link unusedSecretIds} is false.\n * - requestedPermissions requested permissions for the delegate. Defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return a promise which will be completed with the result of the operation\n * @throws if shareEncryptionKeys or shareOwningEntityIds is {@link ShareMetadataBehaviour.REQUIRED} and the current data owner can't access any\n * value for the required metadata.\n */\n simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n delegates: {\n [p: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>>\n // endregion\n\n // region content encryption and decryption\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 type type of the entity.\n * @param content data of the entity which you want to encrypt.\n * @param saveEntity a function which saves the entity to the cloud/DB. Used only if a new encryption key needed to be initialised for the entity.\n * @return the encrypted data and, if a new encryption key was initialised for the entity, the updated entity.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }>\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 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 * @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 tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }>\n\n /**\n * TODO work on this\n * Decrypts the content of an encrypted entity.\n */\n decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }>\n\n /**\n * Tries to decrypt data to a json object using the provided keys.\n */\n tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined>\n\n /**\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 using the default configuration). If the entity specifies\n * a value for any field which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T>\n\n /**\n * Returns the first encryption key which could be properly decrypted from the entity using the current data owner.\n * @throws if no key could be decrypted.\n */\n decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }>\n\n /**\n * Returns all encryption keys which could be properly decrypted from the entity using the current data owner. The keys returned by this method\n * should not be used for encryption of the entity, but only for decryption.\n * This is because this for data from pre-2018 users this method may return also keys from old formats of entities which are not safe anymore for\n * encryption.\n */\n decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]>\n\n /**\n * Verifies if the entity has valid encryption keys (regardless of whether the current data owner has access to them or not). If not this method\n * will throw an error, otherwise it will return undefined. For pre-2018 users there are some cases where the data may have been encrypted with a\n * key not safe for encryption anymore, in which case this method will return the entity with a new and safe encryption key.\n * After this method is called, if it returns an entity it should also be re-encrypted (using the new key) and saved to the cloud.\n */\n ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined>\n // endregion\n}\n"]}
@@ -46,12 +46,12 @@ export declare class ExtendedApisUtilsImpl implements ExtendedApisUtils {
46
46
  extracted: string[];
47
47
  }[]>;
48
48
  hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>;
49
- entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, owningEntity: string | undefined, owningEntitySecretId: string | undefined, initialiseEncryptionKey: boolean, initialiseSecretId: boolean, autoDelegations: {
49
+ entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, owningEntity: string | undefined, owningEntitySecretId: string | undefined, initialiseEncryptionKey: boolean, autoDelegations: {
50
50
  [p: string]: SecureDelegation.AccessLevelEnum;
51
51
  }): Promise<{
52
52
  updatedEntity: T;
53
53
  rawEncryptionKey: string | undefined;
54
- secretId: string | undefined;
54
+ secretId: string;
55
55
  }>;
56
56
  bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(entitiesType: EntityWithDelegationTypeName, entitiesUpdates: {
57
57
  entity: EncryptedEntityStub;
@@ -114,12 +114,12 @@ export declare class ExtendedApisUtilsImpl implements ExtendedApisUtils {
114
114
  simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(entity: {
115
115
  entity: T;
116
116
  type: EntityWithDelegationTypeName;
117
- }, unusedSecretIds: boolean, delegates: {
118
- [delegateId: string]: {
117
+ }, delegates: {
118
+ [p: string]: {
119
119
  shareSecretIds: string[] | undefined;
120
120
  shareEncryptionKeys: ShareMetadataBehaviour | undefined;
121
121
  shareOwningEntityIds: ShareMetadataBehaviour | undefined;
122
- requestedPermissions: RequestedPermissionEnum | undefined;
122
+ requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined;
123
123
  };
124
124
  }, doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>): Promise<ShareResult<T>>;
125
125
  private makeMigrationRequestsIfNeeded;
@@ -72,12 +72,12 @@ class ExtendedApisUtilsImpl {
72
72
  AccessLevel.WRITE);
73
73
  });
74
74
  }
75
- entityWithInitialisedEncryptedMetadata(entity, entityType, owningEntity, owningEntitySecretId, initialiseEncryptionKey, initialiseSecretId, autoDelegations) {
75
+ entityWithInitialisedEncryptedMetadata(entity, entityType, owningEntity, owningEntitySecretId, initialiseEncryptionKey, autoDelegations) {
76
76
  return __awaiter(this, arguments, void 0, function* () {
77
77
  this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments);
78
78
  this.checkEmptyEncryptionMetadata(entity);
79
79
  const newRawKey = initialiseEncryptionKey ? yield this.primitives.AES.generateCryptoKey(true) : undefined;
80
- const newSecretId = initialiseSecretId ? this.primitives.randomUuid() : undefined;
80
+ const newSecretId = this.primitives.randomUuid();
81
81
  return {
82
82
  updatedEntity: yield this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(Object.assign(Object.assign({}, entity), { secretForeignKeys: owningEntitySecretId ? [owningEntitySecretId] : [] }), entityType, newSecretId ? [newSecretId] : [], !!owningEntity ? [owningEntity] : [], newRawKey ? [newRawKey] : [], autoDelegations),
83
83
  rawEncryptionKey: newRawKey,
@@ -205,15 +205,11 @@ class ExtendedApisUtilsImpl {
205
205
  return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId };
206
206
  });
207
207
  }
208
- simpleShareOrUpdateEncryptedEntityMetadata(entity, unusedSecretIds, delegates, doRequestBulkShareOrUpdate) {
208
+ simpleShareOrUpdateEncryptedEntityMetadata(entity, delegates, doRequestBulkShareOrUpdate) {
209
209
  var _a, _b;
210
210
  return __awaiter(this, void 0, void 0, function* () {
211
211
  const availableEncryptionKeys = yield this.encryptionKeysOf(entity);
212
212
  const availableOwningEntityIds = yield this.owningEntityIdsOf(entity);
213
- let availableSecretIds;
214
- if (unusedSecretIds) {
215
- availableSecretIds = yield this.secretIdsOf(entity);
216
- }
217
213
  const dataForDelegates = {};
218
214
  for (const [delegateId, delegateRequests] of Object.entries(delegates)) {
219
215
  if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour_1.ShareMetadataBehaviour.REQUIRED) {
@@ -222,14 +218,8 @@ class ExtendedApisUtilsImpl {
222
218
  if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour_1.ShareMetadataBehaviour.REQUIRED) {
223
219
  throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`);
224
220
  }
225
- if (!delegateRequests.shareSecretIds && !unusedSecretIds) {
226
- throw new Error(`Share secret ids parameter is mandatory for entities of type ${entity.type}.`);
227
- }
228
- else if (delegateRequests.shareSecretIds && unusedSecretIds) {
229
- throw new Error(`Share secret ids parameter must not be unused with entities of type ${entity.type}.`);
230
- }
231
221
  dataForDelegates[delegateId] = {
232
- shareSecretIds: (_a = delegateRequests.shareSecretIds) !== null && _a !== void 0 ? _a : availableSecretIds,
222
+ shareSecretIds: (_a = delegateRequests.shareSecretIds) !== null && _a !== void 0 ? _a : (yield this.secretIdsOf(entity)),
233
223
  shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,
234
224
  shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,
235
225
  requestedPermissions: (_b = delegateRequests.requestedPermissions) !== null && _b !== void 0 ? _b : RequestedPermissionEnum.MAX_WRITE,
@@ -1 +1 @@
1
- {"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAuI;AAEvI,gEAAiE;AACjE,2EAAuG;AAEvG,2EAAuE;AAIvE,wFAAoF;AAIpF,sDAA0F;AAC1F,qEAAiE;AAGjE,IAAO,WAAW,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACrD,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAC3E,IAAO,2BAA2B,GAAG,uCAAkB,CAAC,2BAA2B,CAAA;AACnF,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAGzD;;;GAGG;AACH,MAAa,qBAAqB;IAGhC,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,0BAAqE,EACrE,uBAAmE,EACnE,wBAAkD,EAClD,OAAoB,EACpB,aAAsB;QANtB,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,+BAA0B,GAA1B,0BAA0B,CAA2C;QACrE,4BAAuB,GAAvB,uBAAuB,CAA4C;QACnE,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,YAAO,GAAP,OAAO,CAAa;QACpB,kBAAa,GAAb,aAAa,CAAS;QAEvC,IAAI,CAAC,4BAA4B,GAAG,IAAI,0DAA8B,CAAC,CAAC,0BAA0B,EAAE,uBAAuB,CAAC,CAAC,CAAA;IAC/H,CAAC;IAEK,gBAAgB,CAAC,MAA+B,EAAE,WAAoB;;YAC1E,OAAO,MAAM,IAAI,CAAC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,iBAAiB,IAAI,MAAM,CAAC,iBAAiB,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;QAC3G,IAAI,MAAM,CAAC,gBAAgB,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;QACrH,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,IAAI,oBAAoB,EAAE;gBACxB,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;oBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;aACF;;gBAAM,OAAO,KAAK,CAAA;SACpB;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAr0BD,sDAq0BC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { b2a, encryptObject, decryptObject, hex2ua, truncateTrailingNulls, ua2utf8, utf8_2ua, EncryptedFieldsManifest } from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { asyncGeneratorToArray } from '../utils/collection-utils'\nimport { SecurityMetadataDecryptor, SecurityMetadataDecryptorChain } from './SecurityMetadataDecryptor'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { SecureDelegationsManager } from './SecureDelegationsManager'\nimport { LegacyDelegationSecurityMetadataDecryptor } from './LegacyDelegationSecurityMetadataDecryptor'\nimport { SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { ShareResult, ShareResultFailure, ShareResultSuccess } from '../utils/ShareResult'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { IccUserXApi } from '../icc-user-x-api'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this class is for internal use only and may be changed without notice.\n * Methods to support extended apis.\n */\nexport class ExtendedApisUtilsImpl implements ExtendedApisUtils {\n private readonly allSecurityMetadataDecryptor: SecurityMetadataDecryptor\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly legacyDelMetadataDecryptor: LegacyDelegationSecurityMetadataDecryptor,\n private readonly secDelMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {\n this.allSecurityMetadataDecryptor = new SecurityMetadataDecryptorChain([legacyDelMetadataDecryptor, secDelMetadataDecryptor])\n }\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.allSecurityMetadataDecryptor.getEntityAccessLevel(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())) ===\n AccessLevel.WRITE\n )\n }\n\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n initialiseSecretId: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<{ updatedEntity: T; rawEncryptionKey: string | undefined; secretId: string | undefined }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const newRawKey = initialiseEncryptionKey ? await this.primitives.AES.generateCryptoKey(true) : undefined\n const newSecretId = initialiseSecretId ? this.primitives.randomUuid() : undefined\n return {\n updatedEntity: await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: owningEntitySecretId ? [owningEntitySecretId] : [],\n },\n entityType,\n newSecretId ? [newSecretId] : [],\n !!owningEntity ? [owningEntity] : [],\n newRawKey ? [newRawKey] : [],\n autoDelegations\n ),\n rawEncryptionKey: newRawKey,\n secretId: newSecretId,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updatedEntities: T[] = []\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n if (result.updatedEntity) {\n updatedEntities.push(result.updatedEntity)\n }\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n // TODO implement auto-retry for failed requests if the shouldRetry flag in result.rejectedRequests is set to true\n return {\n updatedEntities,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n const successfulRequests = Object.entries(allRequestsByEntityId)\n .flatMap(([entityId, requests]) => Object.keys(requests).map((delegateId) => ({ entityId, delegateId })))\n .filter(({ entityId, delegateId }) => !updateErrors.some((error) => error.entityId === entityId && error.delegateId === delegateId))\n return {\n successfulUpdates: successfulRequests,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n private async prepareBulkShareRequests(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[]\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n allRequestsByEntityId: { [entityId: string]: EntityRequestInformation }\n orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n }\n }> {\n if (new Set(entitiesUpdates.map((e) => e.entity.id)).size !== entitiesUpdates.length) {\n throw new Error('Duplicate requests: the same entity id is present more than once in the input')\n }\n const allRequestsByEntityId = {} as { [entityId: string]: EntityRequestInformation }\n const orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n } = {}\n const unmodifiedEntitiesIds: string[] = []\n for (const { entity, dataForDelegates } of entitiesUpdates) {\n const entityId = entity.id\n if (!entityId) throw new Error('Share of an entity requires for the entity to already exist and have an id')\n const entityWithType = { entity, type: entitiesType }\n const currentRequests = {} as { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n const currentOrderedRequests: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[] = []\n const migrationRequests = await this.makeMigrationRequestsIfNeeded(entityWithType, dataForDelegates)\n for (const [delegate, request] of Object.entries(migrationRequests)) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: dataForDelegates[delegate],\n updatedForMigration: true,\n })\n }\n for (const [delegate, userRequest] of Object.entries(dataForDelegates)) {\n if (!migrationRequests[delegate]) {\n const request = await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entityWithType,\n delegate,\n userRequest.shareSecretIds ?? [],\n userRequest.shareEncryptionKeys ?? [],\n userRequest.shareOwningEntityIds ?? [],\n userRequest.requestedPermissions\n )\n if (request) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: userRequest,\n updatedForMigration: false,\n })\n }\n }\n }\n if (Object.keys(currentRequests).length > 0) {\n const existingDelegationMembersDetails = await this.secDelMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const accessibleMembers = new Set(\n this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n )\n const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {\n if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {\n return [k]\n } else return []\n })\n allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations }\n orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests\n } else {\n unmodifiedEntitiesIds.push(entityId)\n }\n }\n return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId }\n }\n\n async simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n unusedSecretIds: boolean,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>> {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let availableSecretIds: string[] | undefined\n if (unusedSecretIds) {\n availableSecretIds = await this.secretIdsOf(entity)\n }\n const dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n for (const [delegateId, delegateRequests] of Object.entries(delegates)) {\n if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no encryption keys or the current data owner can't access any encryption keys, but sharing is required.`\n )\n }\n if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`\n )\n }\n if (!delegateRequests.shareSecretIds && !unusedSecretIds) {\n throw new Error(`Share secret ids parameter is mandatory for entities of type ${entity.type}.`)\n } else if (delegateRequests.shareSecretIds && unusedSecretIds) {\n throw new Error(`Share secret ids parameter must not be unused with entities of type ${entity.type}.`)\n }\n dataForDelegates[delegateId] = {\n shareSecretIds: delegateRequests.shareSecretIds ?? availableSecretIds!,\n shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,\n shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,\n requestedPermissions: delegateRequests.requestedPermissions ?? RequestedPermissionEnum.MAX_WRITE,\n }\n }\n const shareResult = await this.bulkShareOrUpdateEncryptedEntityMetadata(\n entity.type,\n [\n {\n entity: entity.entity,\n dataForDelegates,\n },\n ],\n (x) => doRequestBulkShareOrUpdate(x)\n )\n if (shareResult.unmodifiedEntitiesIds.includes(entity.entity.id!)) {\n return new ShareResultSuccess(entity.entity)\n }\n if (!shareResult.updateErrors.length && shareResult.updatedEntities.length === 1) {\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n const requestedDelegates = new Set(Object.keys(delegates))\n const errorsOfRequestedDelegates = shareResult.updateErrors.filter((x) => requestedDelegates.has(x.delegateId))\n if (errorsOfRequestedDelegates.length === 0 && shareResult.updatedEntities.length === 1) {\n console.warn(`Errors with migration of encrypted metadata ${JSON.stringify(shareResult.updateErrors)}.`)\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n return new ShareResultFailure(\n shareResult.updateErrors,\n `There was an error sharing entity with id ${entity.entity.id}. Check the logs for more details.`\n )\n }\n\n private async makeMigrationRequestsIfNeeded(\n entity: EncryptedEntityWithType,\n userRequestsForEntity: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n ): Promise<{ [delegateId: string]: EntityShareOrMetadataUpdateRequest }> {\n const hierarchy = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const legacySecretIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, hierarchy))\n const legacyEncryptionKeys = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptEncryptionKeysOf(entity, hierarchy))\n const legacyOwningEntityIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, hierarchy))\n const res = {} as { [delegateId: string]: EntityShareOrMetadataUpdateRequest }\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n for (const hierarchyMember of hierarchy) {\n const hierarchyMemberMigration = await this.makeMigrationRequestForMemberOfHierarchy(\n entity,\n selfId,\n hierarchyMember,\n userRequestsForEntity[hierarchyMember],\n legacySecretIds,\n legacyEncryptionKeys,\n legacyOwningEntityIds\n )\n if (hierarchyMemberMigration) {\n res[hierarchyMember] = hierarchyMemberMigration\n }\n }\n return res\n }\n\n private async makeMigrationRequestForMemberOfHierarchy(\n entity: EncryptedEntityWithType,\n selfId: string,\n currMemberId: string,\n userRequestForDelegate:\n | {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n | undefined,\n legacySecretIds: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyEncryptionKeys: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyOwningEntityIds: { decrypted: string; dataOwnersWithAccess: string[] }[]\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n // This implementation is very specific from migration from delegations to secure delegations. If in future we will have to migrate from secure delegations to something else, this method may need significant changes in its logic.\n const subHierarchy = this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(currMemberId) : [currMemberId]\n const subHierarchySet = new Set(subHierarchy)\n const legacyAccess =\n selfId === entity.entity.id && currMemberId === selfId\n ? AccessLevel.WRITE\n : await this.legacyDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy)\n if (!legacyAccess) return undefined\n const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d))).map((x) => x.decrypted)\n const selfLegacyEncryptionKeys = legacyEncryptionKeys\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n const selfLegacyOwningEntityIds = legacyOwningEntityIds\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n let missingSecretIds: string[] = []\n let missingEncryptionKeys: string[] = []\n let missingOwningEntityIds: string[] = []\n if (selfLegacySecretIds.length > 0) {\n const currentSecretIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptSecretIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptEncryptionKeysOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id && currMemberId === selfId && !(await this.secDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy))\n if (missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0 || mustCreateRootDelegation) {\n let requestedPermissions: RequestedPermissionInternal\n if (currMemberId === selfId) {\n requestedPermissions = RequestedPermissionInternal.ROOT\n } else {\n requestedPermissions = RequestedPermissionInternal.FULL_WRITE // Legacy permission if present is always write\n }\n return await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entity,\n currMemberId,\n Array.from(new Set([...missingSecretIds, ...(userRequestForDelegate?.shareSecretIds ?? [])])),\n Array.from(new Set([...missingEncryptionKeys, ...(userRequestForDelegate?.shareEncryptionKeys ?? [])])),\n Array.from(new Set([...missingOwningEntityIds, ...(userRequestForDelegate?.shareOwningEntityIds ?? [])])),\n requestedPermissions\n )\n } else return undefined\n }\n\n async tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n const triedKeys: Set<string> = new Set()\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n if (!triedKeys.has(latest.value.decrypted)) {\n triedKeys.add(latest.value.decrypted)\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(latest.value.decrypted, content)\n if (!validator || (await validator(decrypted))) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n console.warn(`Error while decrypting with raw key ${latest.value}: ${e}`)\n }\n }\n latest = await decryptedKeys.next()\n }\n return { data: content, wasDecrypted: false }\n }\n\n async encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }> {\n const ensureInitialisedKeysResult = await this.ensureEncryptionKeysInitialised(entity, type)\n let updatedEntity: T | undefined\n if (!!ensureInitialisedKeysResult) {\n updatedEntity = await saveEntity(ensureInitialisedKeysResult)\n }\n\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf({ entity: updatedEntity ?? entity, type }, dataOwnerIds)\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n try {\n return { encryptedData: await this.primitives.AES.encryptWithRawKey(latest.value.decrypted, content), updatedEntity: updatedEntity }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${latest.value}: ${e}`)\n }\n latest = await decryptedKeys.next()\n }\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.decryptAndImportAllDecryptionKeys({ entity: entity, type: entityType })\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 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 return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return undefined\n }\n\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity, entityType)\n const updatedEntity = entityWithInitialisedEncryptionKeys ? entityWithInitialisedEncryptionKeys : entity\n const encryptionKey = await this.tryImportFirstValidKey({ entity, type: entityType })\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n updatedEntity,\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 || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).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 entityType\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 async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity)) 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 * Add encryption key and share with all auto-delegates already in legacy delegations.\n * TODO disable this logic and simply throw error for post-2018 customers.\n */\n const existingDelegations = new Set(Object.keys(entity.delegations ?? {}))\n const usersWithAccessToNewKey = Object.fromEntries(\n Object.values((await this.userApi.getCurrentUser()).autoDelegations ?? {})\n .flatMap((x) => x)\n .filter((x) => existingDelegations.has(x))\n .map((x) => [x, AccessLevelEnum.WRITE])\n )\n return await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: entity.secretForeignKeys ?? [],\n },\n entityType,\n [],\n [],\n [await this.primitives.AES.generateCryptoKey(true)],\n usersWithAccessToNewKey\n )\n }\n\n private async decryptHierarchy(\n entity: EncryptedEntityWithType,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, canDecryptOwnerIds))\n return canDecryptOwnerIds.map((ownerId) => {\n const extracted = this.deduplicate(decryptedData.filter((x) => x.dataOwnersWithAccess.some((o) => o === ownerId)).map((x) => x.decrypted))\n return { ownerId, extracted }\n })\n }\n\n private async decryptAndMergeHierarchy(\n entity: EncryptedEntityWithType,\n dataOwnerId: string | undefined,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, hierarchy))\n return this.deduplicate(decryptedData.map((x) => x.decrypted))\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 async decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]> {\n const keys = this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity.entity)\n ? await this.encryptionKeysOf(entity)\n : this.deduplicate(\n await asyncGeneratorToArray(\n this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())\n ).then((secretIdsInfo) => secretIdsInfo.map(({ decrypted }) => decrypted))\n )\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 async decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(entity)\n if (!res) throw new Error(`Could not find any valid key for entity ${entity.entity.id} (${entity.type}).`)\n return res\n }\n\n private async tryImportFirstValidKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string } | undefined> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const generator = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n let latest = await generator.next()\n while (!latest.done) {\n const imported = await this.tryImportKey(latest.value.decrypted)\n if (imported) return { key: imported, raw: latest.value.decrypted }\n latest = await generator.next()\n }\n return undefined\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 argsArray.forEach((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 this.doCheckEmptyEncryptionMetadata(entity, true)\n }\n\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean {\n return this.doCheckEmptyEncryptionMetadata(entity, false)\n }\n\n private doCheckEmptyEncryptionMetadata(entity: EncryptedEntity, throwErrorIfNonEmpty: boolean): boolean {\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 (entity.securityMetadata && Object.keys(entity.securityMetadata).length) existingMetadata.push('securityMetadata')\n if (existingMetadata.length > 0) {\n if (throwErrorIfNonEmpty) {\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 } else return false\n }\n return true\n }\n}\n"]}
1
+ {"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAuI;AAEvI,gEAAiE;AACjE,2EAAuG;AAEvG,2EAAuE;AAIvE,wFAAoF;AAIpF,sDAA0F;AAC1F,qEAAiE;AAGjE,IAAO,WAAW,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACrD,IAAO,uBAAuB,GAA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AAM,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,MAAM,CAAC,gBAAgB,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;QACrH,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,IAAI,oBAAoB,EAAE;gBACxB,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;oBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;aACF;;gBAAM,OAAO,KAAK,CAAA;SACpB;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA1zBD,sDA0zBC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { b2a, encryptObject, decryptObject, hex2ua, truncateTrailingNulls, ua2utf8, utf8_2ua, EncryptedFieldsManifest } from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { asyncGeneratorToArray } from '../utils/collection-utils'\nimport { SecurityMetadataDecryptor, SecurityMetadataDecryptorChain } from './SecurityMetadataDecryptor'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { SecureDelegationsManager } from './SecureDelegationsManager'\nimport { LegacyDelegationSecurityMetadataDecryptor } from './LegacyDelegationSecurityMetadataDecryptor'\nimport { SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { ShareResult, ShareResultFailure, ShareResultSuccess } from '../utils/ShareResult'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { IccUserXApi } from '../icc-user-x-api'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this class is for internal use only and may be changed without notice.\n * Methods to support extended apis.\n */\nexport class ExtendedApisUtilsImpl implements ExtendedApisUtils {\n private readonly allSecurityMetadataDecryptor: SecurityMetadataDecryptor\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly legacyDelMetadataDecryptor: LegacyDelegationSecurityMetadataDecryptor,\n private readonly secDelMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {\n this.allSecurityMetadataDecryptor = new SecurityMetadataDecryptorChain([legacyDelMetadataDecryptor, secDelMetadataDecryptor])\n }\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.allSecurityMetadataDecryptor.getEntityAccessLevel(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())) ===\n AccessLevel.WRITE\n )\n }\n\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<{ updatedEntity: T; rawEncryptionKey: string | undefined; secretId: string }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const newRawKey = initialiseEncryptionKey ? await this.primitives.AES.generateCryptoKey(true) : undefined\n const newSecretId = this.primitives.randomUuid()\n return {\n updatedEntity: await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: owningEntitySecretId ? [owningEntitySecretId] : [],\n },\n entityType,\n newSecretId ? [newSecretId] : [],\n !!owningEntity ? [owningEntity] : [],\n newRawKey ? [newRawKey] : [],\n autoDelegations\n ),\n rawEncryptionKey: newRawKey,\n secretId: newSecretId,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updatedEntities: T[] = []\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n if (result.updatedEntity) {\n updatedEntities.push(result.updatedEntity)\n }\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n // TODO implement auto-retry for failed requests if the shouldRetry flag in result.rejectedRequests is set to true\n return {\n updatedEntities,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n const successfulRequests = Object.entries(allRequestsByEntityId)\n .flatMap(([entityId, requests]) => Object.keys(requests).map((delegateId) => ({ entityId, delegateId })))\n .filter(({ entityId, delegateId }) => !updateErrors.some((error) => error.entityId === entityId && error.delegateId === delegateId))\n return {\n successfulUpdates: successfulRequests,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n private async prepareBulkShareRequests(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[]\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n allRequestsByEntityId: { [entityId: string]: EntityRequestInformation }\n orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n }\n }> {\n if (new Set(entitiesUpdates.map((e) => e.entity.id)).size !== entitiesUpdates.length) {\n throw new Error('Duplicate requests: the same entity id is present more than once in the input')\n }\n const allRequestsByEntityId = {} as { [entityId: string]: EntityRequestInformation }\n const orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n } = {}\n const unmodifiedEntitiesIds: string[] = []\n for (const { entity, dataForDelegates } of entitiesUpdates) {\n const entityId = entity.id\n if (!entityId) throw new Error('Share of an entity requires for the entity to already exist and have an id')\n const entityWithType = { entity, type: entitiesType }\n const currentRequests = {} as { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n const currentOrderedRequests: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[] = []\n const migrationRequests = await this.makeMigrationRequestsIfNeeded(entityWithType, dataForDelegates)\n for (const [delegate, request] of Object.entries(migrationRequests)) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: dataForDelegates[delegate],\n updatedForMigration: true,\n })\n }\n for (const [delegate, userRequest] of Object.entries(dataForDelegates)) {\n if (!migrationRequests[delegate]) {\n const request = await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entityWithType,\n delegate,\n userRequest.shareSecretIds ?? [],\n userRequest.shareEncryptionKeys ?? [],\n userRequest.shareOwningEntityIds ?? [],\n userRequest.requestedPermissions\n )\n if (request) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: userRequest,\n updatedForMigration: false,\n })\n }\n }\n }\n if (Object.keys(currentRequests).length > 0) {\n const existingDelegationMembersDetails = await this.secDelMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const accessibleMembers = new Set(\n this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n )\n const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {\n if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {\n return [k]\n } else return []\n })\n allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations }\n orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests\n } else {\n unmodifiedEntitiesIds.push(entityId)\n }\n }\n return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId }\n }\n\n async simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n delegates: {\n [p: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>> {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n const dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n for (const [delegateId, delegateRequests] of Object.entries(delegates)) {\n if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no encryption keys or the current data owner can't access any encryption keys, but sharing is required.`\n )\n }\n if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`\n )\n }\n dataForDelegates[delegateId] = {\n shareSecretIds: delegateRequests.shareSecretIds ?? (await this.secretIdsOf(entity)),\n shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,\n shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,\n requestedPermissions: delegateRequests.requestedPermissions ?? RequestedPermissionEnum.MAX_WRITE,\n }\n }\n const shareResult = await this.bulkShareOrUpdateEncryptedEntityMetadata(\n entity.type,\n [\n {\n entity: entity.entity,\n dataForDelegates,\n },\n ],\n (x) => doRequestBulkShareOrUpdate(x)\n )\n if (shareResult.unmodifiedEntitiesIds.includes(entity.entity.id!)) {\n return new ShareResultSuccess(entity.entity)\n }\n if (!shareResult.updateErrors.length && shareResult.updatedEntities.length === 1) {\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n const requestedDelegates = new Set(Object.keys(delegates))\n const errorsOfRequestedDelegates = shareResult.updateErrors.filter((x) => requestedDelegates.has(x.delegateId))\n if (errorsOfRequestedDelegates.length === 0 && shareResult.updatedEntities.length === 1) {\n console.warn(`Errors with migration of encrypted metadata ${JSON.stringify(shareResult.updateErrors)}.`)\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n return new ShareResultFailure(\n shareResult.updateErrors,\n `There was an error sharing entity with id ${entity.entity.id}. Check the logs for more details.`\n )\n }\n\n private async makeMigrationRequestsIfNeeded(\n entity: EncryptedEntityWithType,\n userRequestsForEntity: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n ): Promise<{ [delegateId: string]: EntityShareOrMetadataUpdateRequest }> {\n const hierarchy = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const legacySecretIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, hierarchy))\n const legacyEncryptionKeys = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptEncryptionKeysOf(entity, hierarchy))\n const legacyOwningEntityIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, hierarchy))\n const res = {} as { [delegateId: string]: EntityShareOrMetadataUpdateRequest }\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n for (const hierarchyMember of hierarchy) {\n const hierarchyMemberMigration = await this.makeMigrationRequestForMemberOfHierarchy(\n entity,\n selfId,\n hierarchyMember,\n userRequestsForEntity[hierarchyMember],\n legacySecretIds,\n legacyEncryptionKeys,\n legacyOwningEntityIds\n )\n if (hierarchyMemberMigration) {\n res[hierarchyMember] = hierarchyMemberMigration\n }\n }\n return res\n }\n\n private async makeMigrationRequestForMemberOfHierarchy(\n entity: EncryptedEntityWithType,\n selfId: string,\n currMemberId: string,\n userRequestForDelegate:\n | {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n | undefined,\n legacySecretIds: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyEncryptionKeys: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyOwningEntityIds: { decrypted: string; dataOwnersWithAccess: string[] }[]\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n // This implementation is very specific from migration from delegations to secure delegations. If in future we will have to migrate from secure delegations to something else, this method may need significant changes in its logic.\n const subHierarchy = this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(currMemberId) : [currMemberId]\n const subHierarchySet = new Set(subHierarchy)\n const legacyAccess =\n selfId === entity.entity.id && currMemberId === selfId\n ? AccessLevel.WRITE\n : await this.legacyDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy)\n if (!legacyAccess) return undefined\n const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d))).map((x) => x.decrypted)\n const selfLegacyEncryptionKeys = legacyEncryptionKeys\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n const selfLegacyOwningEntityIds = legacyOwningEntityIds\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n let missingSecretIds: string[] = []\n let missingEncryptionKeys: string[] = []\n let missingOwningEntityIds: string[] = []\n if (selfLegacySecretIds.length > 0) {\n const currentSecretIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptSecretIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptEncryptionKeysOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id && currMemberId === selfId && !(await this.secDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy))\n if (missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0 || mustCreateRootDelegation) {\n let requestedPermissions: RequestedPermissionInternal\n if (currMemberId === selfId) {\n requestedPermissions = RequestedPermissionInternal.ROOT\n } else {\n requestedPermissions = RequestedPermissionInternal.FULL_WRITE // Legacy permission if present is always write\n }\n return await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entity,\n currMemberId,\n Array.from(new Set([...missingSecretIds, ...(userRequestForDelegate?.shareSecretIds ?? [])])),\n Array.from(new Set([...missingEncryptionKeys, ...(userRequestForDelegate?.shareEncryptionKeys ?? [])])),\n Array.from(new Set([...missingOwningEntityIds, ...(userRequestForDelegate?.shareOwningEntityIds ?? [])])),\n requestedPermissions\n )\n } else return undefined\n }\n\n async tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n const triedKeys: Set<string> = new Set()\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n if (!triedKeys.has(latest.value.decrypted)) {\n triedKeys.add(latest.value.decrypted)\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(latest.value.decrypted, content)\n if (!validator || (await validator(decrypted))) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n console.warn(`Error while decrypting with raw key ${latest.value}: ${e}`)\n }\n }\n latest = await decryptedKeys.next()\n }\n return { data: content, wasDecrypted: false }\n }\n\n async encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }> {\n const ensureInitialisedKeysResult = await this.ensureEncryptionKeysInitialised(entity, type)\n let updatedEntity: T | undefined\n if (!!ensureInitialisedKeysResult) {\n updatedEntity = await saveEntity(ensureInitialisedKeysResult)\n }\n\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf({ entity: updatedEntity ?? entity, type }, dataOwnerIds)\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n try {\n return { encryptedData: await this.primitives.AES.encryptWithRawKey(latest.value.decrypted, content), updatedEntity: updatedEntity }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${latest.value}: ${e}`)\n }\n latest = await decryptedKeys.next()\n }\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.decryptAndImportAllDecryptionKeys({ entity: entity, type: entityType })\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 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 return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return undefined\n }\n\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity, entityType)\n const updatedEntity = entityWithInitialisedEncryptionKeys ? entityWithInitialisedEncryptionKeys : entity\n const encryptionKey = await this.tryImportFirstValidKey({ entity, type: entityType })\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n updatedEntity,\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 || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).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 entityType\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 async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity)) 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 * Add encryption key and share with all auto-delegates already in legacy delegations.\n * TODO disable this logic and simply throw error for post-2018 customers.\n */\n const existingDelegations = new Set(Object.keys(entity.delegations ?? {}))\n const usersWithAccessToNewKey = Object.fromEntries(\n Object.values((await this.userApi.getCurrentUser()).autoDelegations ?? {})\n .flatMap((x) => x)\n .filter((x) => existingDelegations.has(x))\n .map((x) => [x, AccessLevelEnum.WRITE])\n )\n return await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: entity.secretForeignKeys ?? [],\n },\n entityType,\n [],\n [],\n [await this.primitives.AES.generateCryptoKey(true)],\n usersWithAccessToNewKey\n )\n }\n\n private async decryptHierarchy(\n entity: EncryptedEntityWithType,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, canDecryptOwnerIds))\n return canDecryptOwnerIds.map((ownerId) => {\n const extracted = this.deduplicate(decryptedData.filter((x) => x.dataOwnersWithAccess.some((o) => o === ownerId)).map((x) => x.decrypted))\n return { ownerId, extracted }\n })\n }\n\n private async decryptAndMergeHierarchy(\n entity: EncryptedEntityWithType,\n dataOwnerId: string | undefined,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, hierarchy))\n return this.deduplicate(decryptedData.map((x) => x.decrypted))\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 async decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]> {\n const keys = this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity.entity)\n ? await this.encryptionKeysOf(entity)\n : this.deduplicate(\n await asyncGeneratorToArray(\n this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())\n ).then((secretIdsInfo) => secretIdsInfo.map(({ decrypted }) => decrypted))\n )\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 async decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(entity)\n if (!res) throw new Error(`Could not find any valid key for entity ${entity.entity.id} (${entity.type}).`)\n return res\n }\n\n private async tryImportFirstValidKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string } | undefined> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const generator = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n let latest = await generator.next()\n while (!latest.done) {\n const imported = await this.tryImportKey(latest.value.decrypted)\n if (imported) return { key: imported, raw: latest.value.decrypted }\n latest = await generator.next()\n }\n return undefined\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 argsArray.forEach((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 this.doCheckEmptyEncryptionMetadata(entity, true)\n }\n\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean {\n return this.doCheckEmptyEncryptionMetadata(entity, false)\n }\n\n private doCheckEmptyEncryptionMetadata(entity: EncryptedEntity, throwErrorIfNonEmpty: boolean): boolean {\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 (entity.securityMetadata && Object.keys(entity.securityMetadata).length) existingMetadata.push('securityMetadata')\n if (existingMetadata.length > 0) {\n if (throwErrorIfNonEmpty) {\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 } else return false\n }\n return true\n }\n}\n"]}
@@ -104,11 +104,14 @@ function ensureDelegationForSelf(dataOwnerApi, xapi, patientApi, cryptoPrimitive
104
104
  else {
105
105
  if (xapi.hasEmptyEncryptionMetadata(patient)) {
106
106
  // This should not really happen, usually some user will have already initialised the patient and its encryption metadata.
107
- const updatedPatient = yield xapi.entityWithInitialisedEncryptedMetadata(patient, utils_1.EntityWithDelegationTypeName.Patient, undefined, undefined, true, true, {});
107
+ const updatedPatient = yield xapi.entityWithInitialisedEncryptedMetadata(patient, utils_1.EntityWithDelegationTypeName.Patient, undefined, undefined, true, {});
108
108
  return { dataOwner: yield patientApi.modifyPatient(updatedPatient.updatedEntity), type: DataOwnerTypeEnum_1.DataOwnerTypeEnum.Patient };
109
109
  }
110
110
  else {
111
- const updatedPatient = yield xapi.simpleShareOrUpdateEncryptedEntityMetadata({ entity: patient, type: utils_1.EntityWithDelegationTypeName.Patient }, false, {
111
+ const updatedPatient = yield xapi.simpleShareOrUpdateEncryptedEntityMetadata({
112
+ entity: patient,
113
+ type: utils_1.EntityWithDelegationTypeName.Patient,
114
+ }, {
112
115
  [patient.id]: {
113
116
  shareEncryptionKeys: ShareMetadataBehaviour_1.ShareMetadataBehaviour.IF_AVAILABLE,
114
117
  shareOwningEntityIds: ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER,
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wBAAwB;AACxB,sDAAsF;AAEtF,+BAA4C;AAC5C,oCAA+D;AAC/D,yDAAqD;AAKrD,qEAAiE;AACjE,wFAAoF;AAEpF,6EAAyE;AACzE,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,SAAoB;;IAC5D,OAAO,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,MAAA,SAAS,CAAC,2BAA2B,mCAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAa,CAAC,CAAA;AAC7G,CAAC;AAFD,8DAEC;AAED;;;GAGG;AACH,SAAgB,uBAAuB,CAAC,SAAoB;;IAC1D,OAAO,IAAI,GAAG,CAAC,CAAC,SAAS,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,MAAA,SAAS,CAAC,eAAe,mCAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC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,CAAC,2BAA2B,0CAAE,QAAQ,CAAC,SAAS,CAAC,CAAA;YAC9D,CAAC,CAAC,gBAAU,CAAC,MAAM;YACnB,CAAC,CAAC,SAAS,CAAA;AACf,CAAC;AAND,kDAMC;AAED;;;;;;GAMG;AACH,SAAgB,aAAa,CAAC,GAAW;IACvC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAA;AACvB,CAAC;AAFD,sCAEC;AAED;;;;;;GAMG;AACH,SAAgB,aAAa,CAAC,GAAW;IACvC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAA;AAC5B,CAAC;AAFD,sCAEC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,EAAU;IAC1C,0GAA0G;IAC1G,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;AACxB,CAAC;AAHD,8CAGC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,yBAAyB,CAAC,EAAU;IAClD,OAAO,EAAE,GAAG,YAAY,CAAA;AAC1B,CAAC;AAFD,8DAEC;AAED;;;;GAIG;AACH,SAAgB,0BAA0B,CAAC,eAAuB;IAChE,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,IAAI,YAAY,EAAE;QAC9C,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAA;KAClF;AACH,CAAC;AAJD,gEAIC","sourcesContent":["// Uses fp as node names\nimport { acyclic, graphFromEdges, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { DataOwner, DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { RSAUtils, ShaVersion } from './RSA'\nimport { EntityWithDelegationTypeName, hex2ua } from '../utils'\nimport { Patient } from '../../icc-api/model/Patient'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedEntityWithType } from '../utils/EntityWithDelegationTypeName'\nimport { IccPatientApi } from '../../icc-api'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha256.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha256Of(dataOwner: DataOwner) {\n return new Set([...(dataOwner.publicKeysForOaepWithSha256 ?? [])].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha1.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha1Of(dataOwner: DataOwner) {\n return new Set([dataOwner.publicKey, ...Object.keys(dataOwner.aesExchangeKeys ?? {})].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get the transfer key graph for a data owner. Node names are the public key fingerprints of the data owner's keys, and an edge represents a key\n * which can be retrieved from another key using the transfer keys.\n * @param dataOwner a data owner.\n * @return a graph representing the possible key recovery paths using transfer keys for hte provided data owner.\n */\nexport function transferKeysFpGraphOf(dataOwner: DataOwner): StronglyConnectedGraph {\n const publicKeys = Array.from([...hexPublicKeysWithSha1Of(dataOwner), ...hexPublicKeysWithSha256Of(dataOwner)])\n const edges: [string, string][] = []\n Object.entries(dataOwner.transferKeys ?? {}).forEach(([from, tos]) => {\n Object.keys(tos).forEach((to) => {\n edges.push([fingerprintV1(from), fingerprintV1(to)])\n })\n })\n return acyclic(\n graphFromEdges(\n edges,\n publicKeys.map((x) => fingerprintV1(x))\n )\n )\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get a map for converting public keys fingerprint to full public keys for the provided data owner.\n * @param dataOwner a data owner.\n * @param shaVersion gets only the keys that are generated with this SHA version (default: 'sha-1').\n * @return a map to convert fingerprints of the data owner into full public keys.\n */\nexport function fingerprintToPublicKeysMapOf(dataOwner: DataOwner, shaVersion: ShaVersion): { [fp: string]: string } {\n const publicKeys = shaVersion === 'sha-1' ? Array.from(hexPublicKeysWithSha1Of(dataOwner)) : Array.from(hexPublicKeysWithSha256Of(dataOwner))\n const res: { [fp: string]: string } = {}\n publicKeys.forEach((pk) => {\n res[fingerprintV1(pk)] = pk\n })\n return res\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Load many public keys in spki format.\n * @param rsa the rsa service\n * @param publicKeysSpkiHex public keys in spki format, hex encoded.\n * @param shaVersion the version of the Sha algorithm used in the keys generations. ()\n * @return public keys as crypto keys by their fingerprint.\n */\nexport async function loadPublicKeys(\n rsa: RSAUtils,\n publicKeysSpkiHex: string[],\n shaVersion: ShaVersion\n): Promise<{ [publicKeyFingerprint: string]: CryptoKey }> {\n return Object.fromEntries(\n await Promise.all(publicKeysSpkiHex.map(async (x) => [fingerprintV1(x), await rsa.importKey('spki', hex2ua(x), ['encrypt'], shaVersion)]))\n )\n}\n\n/**\n * @internal This method is intended only for internal use and may be changed without notice.\n * Creates a delegation for the current data owner if the data owner is an encrypted entity and there is no delegation to himself.\n * @return the updated self.\n */\nexport async function ensureDelegationForSelf(\n dataOwnerApi: IccDataOwnerXApi,\n xapi: ExtendedApisUtils,\n patientApi: IccPatientApi,\n cryptoPrimitives: CryptoPrimitives\n): Promise<DataOwnerWithType> {\n const self = await dataOwnerApi.getCurrentDataOwner()\n if (self.type === 'patient') {\n const patient = new Patient(self.dataOwner)\n const patientWithType: EncryptedEntityWithType = { entity: patient, type: EntityWithDelegationTypeName.Patient }\n const availableSecretIds = await xapi.secretIdsOf(patientWithType, undefined)\n if (availableSecretIds.length) {\n return self\n } else {\n if (xapi.hasEmptyEncryptionMetadata(patient)) {\n // This should not really happen, usually some user will have already initialised the patient and its encryption metadata.\n const updatedPatient = await xapi.entityWithInitialisedEncryptedMetadata(\n patient,\n EntityWithDelegationTypeName.Patient,\n undefined,\n undefined,\n true,\n true,\n {}\n )\n return { dataOwner: await patientApi.modifyPatient(updatedPatient.updatedEntity), type: DataOwnerTypeEnum.Patient }\n } else {\n const updatedPatient = await xapi.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n false,\n {\n [patient.id!]: {\n shareEncryptionKeys: ShareMetadataBehaviour.IF_AVAILABLE,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [cryptoPrimitives.randomUuid()],\n requestedPermissions: RequestedPermissionEnum.FULL_WRITE,\n },\n },\n (x) => patientApi.bulkSharePatients(x)\n )\n return { dataOwner: updatedPatient.updatedEntityOrThrow, type: DataOwnerTypeEnum.Patient }\n }\n }\n } else {\n return self\n }\n}\n\n/**\n * Search a public key in the data owner and returns the corresponding SHA version used to generate it or undefined if not found.\n * @param dataOwner the data owner.\n * @param publicKey the public key.\n * @return 'sha-1', 'sha-256', undefined\n */\nexport function getShaVersionForKey(dataOwner: DataOwnerOrStub, publicKey: string): ShaVersion | undefined {\n return dataOwner.publicKey === publicKey || Object.keys(dataOwner.aesExchangeKeys ?? {}).includes(publicKey)\n ? ShaVersion.Sha1\n : !!dataOwner.publicKeysForOaepWithSha256?.includes(publicKey)\n ? ShaVersion.Sha256\n : undefined\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters)\n * of the SPKI key.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV1(key: string): string {\n return key.slice(-32)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters) from which the\n * last 5 (10 characters) are removed because they are a constant of the SPKI format.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV2(key: string): string {\n return key.slice(-32, -10)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Converts the fingerprint of a key from a V1 format to a V2 format.\n * @param fp the fingerprint of the key in the V1 format.\n * @return the fingerprint of the key in the v2 format.\n */\nexport function fingerprintV1toV2(fp: string): string {\n // Conversion resilient to mistakes: if the fingerprint is already in V2 format it will be returned as is.\n return fp.slice(0, 22)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V1 format, false otherwise.\n */\nexport function fingerprintIsV1(fp: string): boolean {\n return fp.length === 32\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V2 format, false otherwise.\n */\nexport function fingerprintIsV2(fp: string): boolean {\n return fp.length === 22\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint v2.\n * @return the fingerprint v1 using the standard tail.\n */\nexport function fingerprintV2ToStandardV1(fp: string): string {\n return fp + '0203010001'\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param publicKeyOrFpv1 a public key in spki format or a public key fp v1\n * @throws if the input does not terminate with 0203010001\n */\nexport function checkStandardPublicKeyTail(publicKeyOrFpv1: string) {\n if (publicKeyOrFpv1.slice(-10) != '0203010001') {\n throw new Error('Illegal state: generated public key should end with 0203010001')\n }\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;A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,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,yBAAyB,CAAC,EAAU;IAClD,OAAO,EAAE,GAAG,YAAY,CAAA;AAC1B,CAAC;AAFD,8DAEC;AAED;;;;GAIG;AACH,SAAgB,0BAA0B,CAAC,eAAuB;IAChE,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,IAAI,YAAY,EAAE;QAC9C,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAA;KAClF;AACH,CAAC;AAJD,gEAIC","sourcesContent":["// Uses fp as node names\nimport { acyclic, graphFromEdges, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { DataOwner, DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { RSAUtils, ShaVersion } from './RSA'\nimport { EntityWithDelegationTypeName, hex2ua } from '../utils'\nimport { Patient } from '../../icc-api/model/Patient'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedEntityWithType } from '../utils/EntityWithDelegationTypeName'\nimport { IccPatientApi } from '../../icc-api'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha256.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha256Of(dataOwner: DataOwner) {\n return new Set([...(dataOwner.publicKeysForOaepWithSha256 ?? [])].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha1.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha1Of(dataOwner: DataOwner) {\n return new Set([dataOwner.publicKey, ...Object.keys(dataOwner.aesExchangeKeys ?? {})].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get the transfer key graph for a data owner. Node names are the public key fingerprints of the data owner's keys, and an edge represents a key\n * which can be retrieved from another key using the transfer keys.\n * @param dataOwner a data owner.\n * @return a graph representing the possible key recovery paths using transfer keys for hte provided data owner.\n */\nexport function transferKeysFpGraphOf(dataOwner: DataOwner): StronglyConnectedGraph {\n const publicKeys = Array.from([...hexPublicKeysWithSha1Of(dataOwner), ...hexPublicKeysWithSha256Of(dataOwner)])\n const edges: [string, string][] = []\n Object.entries(dataOwner.transferKeys ?? {}).forEach(([from, tos]) => {\n Object.keys(tos).forEach((to) => {\n edges.push([fingerprintV1(from), fingerprintV1(to)])\n })\n })\n return acyclic(\n graphFromEdges(\n edges,\n publicKeys.map((x) => fingerprintV1(x))\n )\n )\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get a map for converting public keys fingerprint to full public keys for the provided data owner.\n * @param dataOwner a data owner.\n * @param shaVersion gets only the keys that are generated with this SHA version (default: 'sha-1').\n * @return a map to convert fingerprints of the data owner into full public keys.\n */\nexport function fingerprintToPublicKeysMapOf(dataOwner: DataOwner, shaVersion: ShaVersion): { [fp: string]: string } {\n const publicKeys = shaVersion === 'sha-1' ? Array.from(hexPublicKeysWithSha1Of(dataOwner)) : Array.from(hexPublicKeysWithSha256Of(dataOwner))\n const res: { [fp: string]: string } = {}\n publicKeys.forEach((pk) => {\n res[fingerprintV1(pk)] = pk\n })\n return res\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Load many public keys in spki format.\n * @param rsa the rsa service\n * @param publicKeysSpkiHex public keys in spki format, hex encoded.\n * @param shaVersion the version of the Sha algorithm used in the keys generations. ()\n * @return public keys as crypto keys by their fingerprint.\n */\nexport async function loadPublicKeys(\n rsa: RSAUtils,\n publicKeysSpkiHex: string[],\n shaVersion: ShaVersion\n): Promise<{ [publicKeyFingerprint: string]: CryptoKey }> {\n return Object.fromEntries(\n await Promise.all(publicKeysSpkiHex.map(async (x) => [fingerprintV1(x), await rsa.importKey('spki', hex2ua(x), ['encrypt'], shaVersion)]))\n )\n}\n\n/**\n * @internal This method is intended only for internal use and may be changed without notice.\n * Creates a delegation for the current data owner if the data owner is an encrypted entity and there is no delegation to himself.\n * @return the updated self.\n */\nexport async function ensureDelegationForSelf(\n dataOwnerApi: IccDataOwnerXApi,\n xapi: ExtendedApisUtils,\n patientApi: IccPatientApi,\n cryptoPrimitives: CryptoPrimitives\n): Promise<DataOwnerWithType> {\n const self = await dataOwnerApi.getCurrentDataOwner()\n if (self.type === 'patient') {\n const patient = new Patient(self.dataOwner)\n const patientWithType: EncryptedEntityWithType = { entity: patient, type: EntityWithDelegationTypeName.Patient }\n const availableSecretIds = await xapi.secretIdsOf(patientWithType, undefined)\n if (availableSecretIds.length) {\n return self\n } else {\n if (xapi.hasEmptyEncryptionMetadata(patient)) {\n // This should not really happen, usually some user will have already initialised the patient and its encryption metadata.\n const updatedPatient = await xapi.entityWithInitialisedEncryptedMetadata(\n patient,\n EntityWithDelegationTypeName.Patient,\n undefined,\n undefined,\n true,\n {}\n )\n return { dataOwner: await patientApi.modifyPatient(updatedPatient.updatedEntity), type: DataOwnerTypeEnum.Patient }\n } else {\n const updatedPatient = await xapi.simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: patient,\n type: EntityWithDelegationTypeName.Patient,\n },\n {\n [patient.id!]: {\n shareEncryptionKeys: ShareMetadataBehaviour.IF_AVAILABLE,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [cryptoPrimitives.randomUuid()],\n requestedPermissions: RequestedPermissionEnum.FULL_WRITE,\n },\n },\n (x) => patientApi.bulkSharePatients(x)\n )\n return { dataOwner: updatedPatient.updatedEntityOrThrow, type: DataOwnerTypeEnum.Patient }\n }\n }\n } else {\n return self\n }\n}\n\n/**\n * Search a public key in the data owner and returns the corresponding SHA version used to generate it or undefined if not found.\n * @param dataOwner the data owner.\n * @param publicKey the public key.\n * @return 'sha-1', 'sha-256', undefined\n */\nexport function getShaVersionForKey(dataOwner: DataOwnerOrStub, publicKey: string): ShaVersion | undefined {\n return dataOwner.publicKey === publicKey || Object.keys(dataOwner.aesExchangeKeys ?? {}).includes(publicKey)\n ? ShaVersion.Sha1\n : !!dataOwner.publicKeysForOaepWithSha256?.includes(publicKey)\n ? ShaVersion.Sha256\n : undefined\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters)\n * of the SPKI key.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV1(key: string): string {\n return key.slice(-32)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters) from which the\n * last 5 (10 characters) are removed because they are a constant of the SPKI format.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV2(key: string): string {\n return key.slice(-32, -10)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Converts the fingerprint of a key from a V1 format to a V2 format.\n * @param fp the fingerprint of the key in the V1 format.\n * @return the fingerprint of the key in the v2 format.\n */\nexport function fingerprintV1toV2(fp: string): string {\n // Conversion resilient to mistakes: if the fingerprint is already in V2 format it will be returned as is.\n return fp.slice(0, 22)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V1 format, false otherwise.\n */\nexport function fingerprintIsV1(fp: string): boolean {\n return fp.length === 32\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V2 format, false otherwise.\n */\nexport function fingerprintIsV2(fp: string): boolean {\n return fp.length === 22\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint v2.\n * @return the fingerprint v1 using the standard tail.\n */\nexport function fingerprintV2ToStandardV1(fp: string): string {\n return fp + '0203010001'\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param publicKeyOrFpv1 a public key in spki format or a public key fp v1\n * @throws if the input does not terminate with 0203010001\n */\nexport function checkStandardPublicKeyTail(publicKeyOrFpv1: string) {\n if (publicKeyOrFpv1.slice(-10) != '0203010001') {\n throw new Error('Illegal state: generated public key should end with 0203010001')\n }\n}\n"]}
@@ -14,7 +14,7 @@ export declare class HealthElementByHcPartyTagCodeFilter extends AbstractFilterH
14
14
  $type: string;
15
15
  constructor(json: JSON | any);
16
16
  desc?: string;
17
- healthCarePartyId?: string;
17
+ healthcarePartyId?: string;
18
18
  codeType?: string;
19
19
  codeCode?: string;
20
20
  tagType?: string;