@icure/api 8.1.8 → 8.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/icc-api/model/RouteOfAdministration.d.ts +0 -1
- package/icc-api/model/RouteOfAdministration.js.map +1 -1
- package/icc-api/model/Vmp.d.ts +0 -2
- package/icc-api/model/Vmp.js.map +1 -1
- package/icc-api/model/VmpGroup.d.ts +0 -2
- package/icc-api/model/VmpGroup.js.map +1 -1
- package/icc-api/model/internal/ExchangeData.d.ts +1 -1
- package/icc-api/model/internal/ExchangeData.js +1 -7
- package/icc-api/model/internal/ExchangeData.js.map +1 -1
- package/icc-x-api/crypto/BaseExchangeDataManager.d.ts +19 -9
- package/icc-x-api/crypto/BaseExchangeDataManager.js +27 -6
- package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/CryptoStrategies.d.ts +2 -1
- package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
- package/icc-x-api/crypto/ExchangeDataManager.d.ts +25 -2
- package/icc-x-api/crypto/ExchangeDataManager.js +98 -5
- package/icc-x-api/crypto/ExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtils.d.ts +3 -1
- package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +3 -3
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/icc-x-api/crypto/SecureDelegationsManager.d.ts +3 -1
- package/icc-x-api/crypto/SecureDelegationsManager.js +10 -6
- package/icc-x-api/crypto/SecureDelegationsManager.js.map +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js +4 -0
- package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
- package/icc-x-api/crypto/utils.js +1 -1
- package/icc-x-api/crypto/utils.js.map +1 -1
- package/icc-x-api/icc-accesslog-x-api.d.ts +6 -0
- package/icc-x-api/icc-accesslog-x-api.js +6 -2
- package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
- package/icc-x-api/icc-bekmehr-x-api.js +1 -1
- package/icc-x-api/icc-bekmehr-x-api.js.map +1 -1
- package/icc-x-api/icc-calendar-item-x-api.d.ts +4 -0
- package/icc-x-api/icc-calendar-item-x-api.js +3 -1
- package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
- package/icc-x-api/icc-classification-x-api.d.ts +3 -0
- package/icc-x-api/icc-classification-x-api.js +3 -1
- package/icc-x-api/icc-classification-x-api.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.d.ts +3 -0
- package/icc-x-api/icc-contact-x-api.js +3 -1
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/icc-crypto-x-api.d.ts +29 -0
- package/icc-x-api/icc-crypto-x-api.js +36 -0
- package/icc-x-api/icc-crypto-x-api.js.map +1 -1
- package/icc-x-api/icc-document-x-api.d.ts +3 -0
- package/icc-x-api/icc-document-x-api.js +3 -1
- package/icc-x-api/icc-document-x-api.js.map +1 -1
- package/icc-x-api/icc-form-x-api.d.ts +3 -0
- package/icc-x-api/icc-form-x-api.js +3 -1
- package/icc-x-api/icc-form-x-api.js.map +1 -1
- package/icc-x-api/icc-helement-x-api.d.ts +3 -0
- package/icc-x-api/icc-helement-x-api.js +3 -1
- package/icc-x-api/icc-helement-x-api.js.map +1 -1
- package/icc-x-api/icc-invoice-x-api.d.ts +3 -0
- package/icc-x-api/icc-invoice-x-api.js +3 -1
- package/icc-x-api/icc-invoice-x-api.js.map +1 -1
- package/icc-x-api/icc-maintenance-task-x-api.d.ts +3 -0
- package/icc-x-api/icc-maintenance-task-x-api.js +3 -1
- package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
- package/icc-x-api/icc-message-x-api.d.ts +3 -0
- package/icc-x-api/icc-message-x-api.js +3 -1
- package/icc-x-api/icc-message-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.d.ts +3 -0
- package/icc-x-api/icc-patient-x-api.js +6 -2
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/icc-x-api/icc-receipt-x-api.d.ts +3 -0
- package/icc-x-api/icc-receipt-x-api.js +3 -1
- package/icc-x-api/icc-receipt-x-api.js.map +1 -1
- package/icc-x-api/icc-recovery-x-api.js +8 -1
- package/icc-x-api/icc-recovery-x-api.js.map +1 -1
- package/icc-x-api/icc-time-table-x-api.d.ts +3 -0
- package/icc-x-api/icc-time-table-x-api.js +3 -1
- package/icc-x-api/icc-time-table-x-api.js.map +1 -1
- package/icc-x-api/icc-topic-x-api.d.ts +3 -0
- package/icc-x-api/icc-topic-x-api.js +3 -1
- package/icc-x-api/icc-topic-x-api.js.map +1 -1
- package/icc-x-api/index.d.ts +16 -0
- package/icc-x-api/index.js +7 -1
- package/icc-x-api/index.js.map +1 -1
- package/icc-x-api/utils/websocket.d.ts +1 -0
- package/package.json +1 -1
- package/test/icc-x-api/autofix-anonymity-test.js +18 -4
- package/test/icc-x-api/autofix-anonymity-test.js.map +1 -1
- package/test/icc-x-api/crypto/exchange-data-manager-test.js +34 -32
- package/test/icc-x-api/crypto/exchange-data-manager-test.js.map +1 -1
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js +2 -2
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js.map +1 -1
- package/test/icc-x-api/icc-hcparty-x-api-test.js +2 -14
- package/test/icc-x-api/icc-hcparty-x-api-test.js.map +1 -1
- package/test/icc-x-api/keyless-api.d.ts +1 -0
- package/test/icc-x-api/keyless-api.js +125 -0
- package/test/icc-x-api/keyless-api.js.map +1 -0
- package/test/utils/FakeExchangeDataManager.d.ts +8 -0
- package/test/utils/FakeExchangeDataManager.js +3 -0
- package/test/utils/FakeExchangeDataManager.js.map +1 -1
- package/test/utils/KeylessCryptoStrategies.d.ts +23 -0
- package/test/utils/KeylessCryptoStrategies.js +26 -0
- package/test/utils/KeylessCryptoStrategies.js.map +1 -0
- package/test/utils/test_utils.d.ts +7 -0
- package/test/utils/test_utils.js +30 -1
- package/test/utils/test_utils.js.map +1 -1
|
@@ -107,12 +107,14 @@ export interface ExtendedApisUtils {
|
|
|
107
107
|
* delegations for access control but don't actually have any encrypted content.
|
|
108
108
|
* HealthcareElement).
|
|
109
109
|
* @param autoDelegations automatically shares the metadata with the provided data owners, with the provided access level.
|
|
110
|
+
* @param alternateRootDelegation by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,
|
|
111
|
+
* and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.
|
|
110
112
|
* @throws if the entity already has non-empty values for encryption metadata.
|
|
111
113
|
* @return an updated copy of the entity.
|
|
112
114
|
*/
|
|
113
115
|
entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, owningEntity: string | undefined, owningEntitySecretIds: string[] | undefined, initialiseEncryptionKey: boolean, autoDelegations: {
|
|
114
116
|
[p: string]: SecureDelegation.AccessLevelEnum;
|
|
115
|
-
}): Promise<{
|
|
117
|
+
}, alternateRootDelegation: string | undefined): Promise<{
|
|
116
118
|
updatedEntity: T;
|
|
117
119
|
rawEncryptionKey: string | undefined;
|
|
118
120
|
secretId: string | undefined;
|
|
@@ -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'\nimport { SecretIdUseOption } from './SecretIdUseOption'\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 resolveSecretIdUseOptions(entity: EncryptedEntityWithType, option: SecretIdUseOption): Promise<string[]>\n\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 owningEntitySecretIds 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 owningEntitySecretIds: 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 tryDecryptEntities<T extends EncryptedEntity>(\n entities: 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(potentialKeys: { key: CryptoKey; raw: string }[], encrypted: Uint8Array, truncateTrailingDecryptedNulls: boolean): Promise<{} | null>\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 tryEncryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T[]>\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\n /**\n * Attempts to do the action providing \"incrementally decrypted\" keys as input; stops the first time the action\n * completes successfully.\n * The method tries to decrypt encryption keys for the entity \"incrementally\", trying first to decrypt keys that\n * require less effort for decryption (e.g. using already cached exchange data or using exchange data for which the\n * id is known without going through the exchange data map). Each time one or more new keys are decrypted the action\n * is called providing ALL keys decrypted up to that point.\n * If no key can be decrypted at all the method returns null without ever attempting the action (the action always\n * receives at least a key in input or is not called).\n * @param entity the entity from which to decrypt the encryption keys.\n * @param entityType the type of entity\n * @param action the action that consumes the encryption key.\n * @return the wrapped result of the first successful action invocation, or null if the action never succeeded or if\n * no key could be decrypted\n */\n doIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entity: E,\n entityType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<{ success: T } | null>\n\n /**\n * Bulk version of {@link doIncrementallyDecryptingKeys}.\n * Differences:\n * - The action is called until it succeeds for all entities or until all decryptable keys have been tried.\n * - For each input the action must return an entry for that entity id with the result if successful or not include\n * the entity id in the result keys if unsuccessful.\n * - An attempt on the action is done only if new keys could be decrypted for all the entities.\n * Additionally, there will be a final attempt after attempting all decryption steps if at least a new key could be\n * decrypted for an entity since the last attempt.\n * In this case entities for which no new key could be decrypted are omitted from the input.\n * @param entities\n * @param entitiesType\n * @param action\n * @return all entities id for which the action completed successfully associated to the result.\n */\n doManyIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entities: E[],\n entitiesType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<Map<string, T>>\n // endregion\n\n // region confidential ids\n\n /**\n * Ensures that the current data owner has access to a confidential secret id for the provided entity: this is an id that is known to the data owner\n * but is not known by any of his parents. If there is currently no confidential secret id for this entity the method returns a copy of the entity\n * with a new confidential secret id for the current data owner (the entity in the database won't be updated), else this method returns undefined.\n * New confidential secret ids will have an appropriate tag, but existing confidential secret ids may not necessarily have it.\n * @param entity an entity which needs to have a confidential secret id for the current data owner\n * @param entityType the type of the entity\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return undefined if the entity already had a confidential secret id for the current user, or the updated AND SAVED entity with the new\n * confidential secret id.\n */\n initialiseConfidentialSecretId<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<T | undefined>\n\n /**\n * Get an existing confidential secret id of the provided entity for the provided data owner (current data owner by default). A confidential secret\n * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.\n * @param entity an entity for which you want to retrieve the confidential secret id.\n * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.\n * @return the confidential secret id or undefined if there is no confidential secret id for the provided data owner.\n */\n getConfidentialSecretId(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string | undefined>\n\n /**\n * Get all existing confidential secret ids of the provided entity for the provided data owner (current data owner by default). A confidential secret\n * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.\n * @param entity an entity for which you want to retrieve the confidential secret id.\n * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.\n * @return the confidential secret ids for the data owner (may be empty).\n */\n getConfidentialSecretIds(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]>\n\n /**\n * Gets a secret id known by the topmost parent of the current data owner hierarchy. If there is multiple secret ids shared with the topmost parent\n * there is no guarantee on which one will be chosen.\n * @param entity an entity.\n * @return a secret id known by the topmost parent of the current data owner hierarchy, or undefined if there is no secret id currently available\n * for the topmost parent.\n */\n getAnySecretIdSharedWithParents(entity: EncryptedEntityWithType): Promise<string | undefined>\n\n /**\n * Gets all secret ids known by the topmost parent of the current data owner hierarchy (or all secret ids known by the current data owner if he is\n * not part of any data owner hierarchy).\n * @param entity an entity.\n * @return all secret ids known by the topmost parent of the current data owner hierarchy, may be empty.\n */\n getSecretIdsSharedWithParents(entity: EncryptedEntityWithType): Promise<string[]>\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'\nimport { SecretIdUseOption } from './SecretIdUseOption'\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 resolveSecretIdUseOptions(entity: EncryptedEntityWithType, option: SecretIdUseOption): Promise<string[]>\n\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 owningEntitySecretIds 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 * @param alternateRootDelegation by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,\n * and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.\n * @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 owningEntitySecretIds: string[] | undefined,\n initialiseEncryptionKey: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum },\n alternateRootDelegation: string | undefined\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 tryDecryptEntities<T extends EncryptedEntity>(\n entities: 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(potentialKeys: { key: CryptoKey; raw: string }[], encrypted: Uint8Array, truncateTrailingDecryptedNulls: boolean): Promise<{} | null>\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 tryEncryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T[]>\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\n /**\n * Attempts to do the action providing \"incrementally decrypted\" keys as input; stops the first time the action\n * completes successfully.\n * The method tries to decrypt encryption keys for the entity \"incrementally\", trying first to decrypt keys that\n * require less effort for decryption (e.g. using already cached exchange data or using exchange data for which the\n * id is known without going through the exchange data map). Each time one or more new keys are decrypted the action\n * is called providing ALL keys decrypted up to that point.\n * If no key can be decrypted at all the method returns null without ever attempting the action (the action always\n * receives at least a key in input or is not called).\n * @param entity the entity from which to decrypt the encryption keys.\n * @param entityType the type of entity\n * @param action the action that consumes the encryption key.\n * @return the wrapped result of the first successful action invocation, or null if the action never succeeded or if\n * no key could be decrypted\n */\n doIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entity: E,\n entityType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<{ success: T } | null>\n\n /**\n * Bulk version of {@link doIncrementallyDecryptingKeys}.\n * Differences:\n * - The action is called until it succeeds for all entities or until all decryptable keys have been tried.\n * - For each input the action must return an entry for that entity id with the result if successful or not include\n * the entity id in the result keys if unsuccessful.\n * - An attempt on the action is done only if new keys could be decrypted for all the entities.\n * Additionally, there will be a final attempt after attempting all decryption steps if at least a new key could be\n * decrypted for an entity since the last attempt.\n * In this case entities for which no new key could be decrypted are omitted from the input.\n * @param entities\n * @param entitiesType\n * @param action\n * @return all entities id for which the action completed successfully associated to the result.\n */\n doManyIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entities: E[],\n entitiesType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<Map<string, T>>\n // endregion\n\n // region confidential ids\n\n /**\n * Ensures that the current data owner has access to a confidential secret id for the provided entity: this is an id that is known to the data owner\n * but is not known by any of his parents. If there is currently no confidential secret id for this entity the method returns a copy of the entity\n * with a new confidential secret id for the current data owner (the entity in the database won't be updated), else this method returns undefined.\n * New confidential secret ids will have an appropriate tag, but existing confidential secret ids may not necessarily have it.\n * @param entity an entity which needs to have a confidential secret id for the current data owner\n * @param entityType the type of the entity\n * @param doRequestBulkShareOrUpdate perform the request to share or update an entity encrypted metadata on the cloud API (and save to DB).\n * @return undefined if the entity already had a confidential secret id for the current user, or the updated AND SAVED entity with the new\n * confidential secret id.\n */\n initialiseConfidentialSecretId<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<T | undefined>\n\n /**\n * Get an existing confidential secret id of the provided entity for the provided data owner (current data owner by default). A confidential secret\n * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.\n * @param entity an entity for which you want to retrieve the confidential secret id.\n * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.\n * @return the confidential secret id or undefined if there is no confidential secret id for the provided data owner.\n */\n getConfidentialSecretId(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string | undefined>\n\n /**\n * Get all existing confidential secret ids of the provided entity for the provided data owner (current data owner by default). A confidential secret\n * id is a secret id known by the data owner but not known by any of his parents: note however that children will know confidential secret ids.\n * @param entity an entity for which you want to retrieve the confidential secret id.\n * @param dataOwnerId (current data owner by default) a data owner for which you want to get a confidential secret id.\n * @return the confidential secret ids for the data owner (may be empty).\n */\n getConfidentialSecretIds(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]>\n\n /**\n * Gets a secret id known by the topmost parent of the current data owner hierarchy. If there is multiple secret ids shared with the topmost parent\n * there is no guarantee on which one will be chosen.\n * @param entity an entity.\n * @return a secret id known by the topmost parent of the current data owner hierarchy, or undefined if there is no secret id currently available\n * for the topmost parent.\n */\n getAnySecretIdSharedWithParents(entity: EncryptedEntityWithType): Promise<string | undefined>\n\n /**\n * Gets all secret ids known by the topmost parent of the current data owner hierarchy (or all secret ids known by the current data owner if he is\n * not part of any data owner hierarchy).\n * @param entity an entity.\n * @return all secret ids known by the topmost parent of the current data owner hierarchy, may be empty.\n */\n getSecretIdsSharedWithParents(entity: EncryptedEntityWithType): Promise<string[]>\n // endregion\n}\n"]}
|
|
@@ -45,7 +45,7 @@ export declare class ExtendedApisUtilsImpl implements ExtendedApisUtils {
|
|
|
45
45
|
hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean>;
|
|
46
46
|
entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName, owningEntity: string | undefined, owningEntitySecretIds: string[] | undefined, initialiseEncryptionKey: boolean, autoDelegations: {
|
|
47
47
|
[p: string]: SecureDelegation.AccessLevelEnum;
|
|
48
|
-
}): Promise<{
|
|
48
|
+
}, alternateRootDelegation: string | undefined): Promise<{
|
|
49
49
|
updatedEntity: T;
|
|
50
50
|
rawEncryptionKey: string | undefined;
|
|
51
51
|
secretId: string;
|
|
@@ -70,14 +70,14 @@ class ExtendedApisUtilsImpl {
|
|
|
70
70
|
AccessLevel.WRITE);
|
|
71
71
|
});
|
|
72
72
|
}
|
|
73
|
-
entityWithInitialisedEncryptedMetadata(entity, entityType, owningEntity, owningEntitySecretIds, initialiseEncryptionKey, autoDelegations) {
|
|
73
|
+
entityWithInitialisedEncryptedMetadata(entity, entityType, owningEntity, owningEntitySecretIds, initialiseEncryptionKey, autoDelegations, alternateRootDelegation) {
|
|
74
74
|
return __awaiter(this, arguments, void 0, function* () {
|
|
75
75
|
this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments);
|
|
76
76
|
this.checkEmptyEncryptionMetadata(entity);
|
|
77
77
|
const newRawKey = initialiseEncryptionKey ? yield this.primitives.AES.generateCryptoKey(true) : undefined;
|
|
78
78
|
const newSecretId = this.primitives.randomUuid();
|
|
79
79
|
return {
|
|
80
|
-
updatedEntity: yield this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(Object.assign(Object.assign({}, entity), { secretForeignKeys: owningEntitySecretIds !== null && owningEntitySecretIds !== void 0 ? owningEntitySecretIds : [] }), entityType, newSecretId ? [newSecretId] : [], !!owningEntity ? [owningEntity] : [], newRawKey ? [newRawKey] : [], autoDelegations),
|
|
80
|
+
updatedEntity: yield this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(Object.assign(Object.assign({}, entity), { secretForeignKeys: owningEntitySecretIds !== null && owningEntitySecretIds !== void 0 ? owningEntitySecretIds : [] }), entityType, newSecretId ? [newSecretId] : [], !!owningEntity ? [owningEntity] : [], newRawKey ? [newRawKey] : [], autoDelegations, alternateRootDelegation),
|
|
81
81
|
rawEncryptionKey: newRawKey,
|
|
82
82
|
secretId: newSecretId,
|
|
83
83
|
};
|
|
@@ -486,7 +486,7 @@ class ExtendedApisUtilsImpl {
|
|
|
486
486
|
.flatMap((x) => x)
|
|
487
487
|
.filter((x) => existingDelegations.has(x))
|
|
488
488
|
.map((x) => [x, AccessLevelEnum.WRITE]));
|
|
489
|
-
return yield this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(Object.assign(Object.assign({}, entity), { secretForeignKeys: (_c = entity.secretForeignKeys) !== null && _c !== void 0 ? _c : [] }), entityType, [], [], [yield this.primitives.AES.generateCryptoKey(true)], usersWithAccessToNewKey);
|
|
489
|
+
return yield this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(Object.assign(Object.assign({}, entity), { secretForeignKeys: (_c = entity.secretForeignKeys) !== null && _c !== void 0 ? _c : [] }), entityType, [], [], [yield this.primitives.AES.generateCryptoKey(true)], usersWithAccessToNewKey, undefined);
|
|
490
490
|
});
|
|
491
491
|
}
|
|
492
492
|
decryptHierarchy(decryptedDataProvider) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAWiB;AAEjB,2EAA6F;AAC7F,2EAAuE;AAIvE,wFAAoF;AAEpF,sDAA0F;AAC1F,qEAAiE;AAKjE,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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AAI,qCAAiB,CAAC,sBAAsB,EAAE;gBAC7D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,6BAA6B,CAAC,MAAM,CAAC,CAAA;gBAC5D,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;gBACtF,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;aAChB;iBAAM,IAAI,MAAM,IAAI,qCAAiB,CAAC,sBAAsB,EAAE;gBAC7D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,6BAA6B,CAAC,MAAM,CAAC,CAAA;gBAC5D,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;gBACtF,OAAO,GAAG,CAAA;aACX;iBAAM,IAAI,MAAM,YAAY,qCAAiB,CAAC,GAAG,EAAE;gBAClD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAA;aACtC;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,kCAAkC,MAAM,EAAE,CAAC,CAAA;aAC5D;QACH,CAAC;KAAA;CACF;AAv/BD,sDAu/BC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport {\n b2a,\n decryptObject,\n EncryptedEntityWithType,\n EncryptedFieldsManifest,\n encryptObject,\n EntityWithDelegationTypeName,\n hex2ua,\n truncateTrailingNulls,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { SecurityMetadataDecryptor, SecurityMetadataType } from './SecurityMetadataDecryptor'\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 { 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 { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\nimport * as _ from 'lodash'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { SecretIdUseOption } from './SecretIdUseOption'\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 constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly securityMetadataDecryptor: SecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {}\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.EncryptionKey)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.EncryptionKey)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.SecretId)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) => this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.SecretId))\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.OwningEntityId)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.OwningEntityId)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.securityMetadataDecryptor.getEntityAccessLevel(entity.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 owningEntitySecretIds: 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: owningEntitySecretIds ?? [],\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 =\n Object.keys(allRequestsByEntityId).length > 0 ? 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.securityMetadataDecryptor.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 this.securityMetadataDecryptor.decryptAllLegacyDelegations(entity.entity, hierarchy, SecurityMetadataType.SecretId)\n const legacyEncryptionKeys = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(\n entity.entity,\n hierarchy,\n SecurityMetadataType.EncryptionKey\n )\n const legacyOwningEntityIds = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(\n entity.entity,\n hierarchy,\n SecurityMetadataType.OwningEntityId\n )\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.securityMetadataDecryptor.getEntityLegacyDelegationAccessLevel(entity.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 this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.SecretId)).map(\n (x) => x.decrypted\n )\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.EncryptionKey)).map(\n (x) => x.decrypted\n )\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.OwningEntityId)).map(\n (x) => x.decrypted\n )\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id &&\n currMemberId === selfId &&\n !(await this.securityMetadataDecryptor.getEntitySecureDelegationAccessLevel(entity.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 triedKeys: Set<string> = new Set()\n const result = await this.doIncrementallyDecryptingKeys(entity.entity, entity.type, async (e, t, keys) => {\n for (const k of keys) {\n if (!triedKeys.has(k.raw)) {\n triedKeys.add(k.raw)\n try {\n const decrypted = await this.primitives.AES.decrypt(k.key, content)\n if (!validator || (await validator(decrypted))) return { success: decrypted }\n } catch (e) {\n console.warn(`Error while attempting to decrypt attachment of ${entity.entity.id} with raw key ${k.raw}: ${e}`)\n }\n }\n }\n return null\n })\n if (result != null) {\n return { data: result.success, wasDecrypted: true }\n } else {\n return { data: content, wasDecrypted: false }\n }\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 const encrypted = await this.doIncrementallyDecryptingKeys(entity, type, async (e, t, keys) => {\n for (const k of keys) {\n try {\n return {\n success: {\n encryptedData: await this.primitives.AES.encrypt(k.key, content),\n updatedEntity: updatedEntity,\n },\n }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${k.raw}: ${e}`)\n }\n }\n return null\n })\n if (encrypted != null) return encrypted.success\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async tryDecryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }[]> {\n const nothingToDecryptResults = new Map<string, T>()\n for (const entity of entities) {\n const nothingToDecrypt = await decryptObject(entity, async (encrypted) => {\n return null\n })\n if (nothingToDecrypt != null) {\n nothingToDecryptResults.set(entity.id!, constructor(nothingToDecrypt))\n }\n }\n const actuallyDecryptedResults = await this.doManyIncrementallyDecryptingKeys(\n entities.filter((e) => !nothingToDecryptResults.has(e.id!)),\n entityType,\n async (entity, t, keys) => {\n // The decrypt object will try all keys on each of the sub-objects; this is intentional because even though it\n // shouldn't happen, but it is still possible that some entity could be accidentally merged badly and the merged\n // entity has multiple encryptedSelf (on different sub-entities) that use different keys.\n const decrypted = await decryptObject(entity, (encrypted) => this.tryDecryptJson(keys, encrypted, false))\n if (decrypted != null) {\n return { success: constructor(decrypted) }\n } else {\n return null\n }\n }\n )\n const res = []\n for (const entity of entities) {\n const decrypted = actuallyDecryptedResults.get(entity.id!) ?? nothingToDecryptResults.get(entity.id!)\n if (!decrypted) {\n res.push({ entity: entity, decrypted: false })\n } else {\n res.push({ entity: decrypted, decrypted: true })\n }\n }\n return res\n }\n\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | null> {\n for (const key of potentialKeys) {\n try {\n const decrypted = await this.primitives.AES.decrypt(key.key, encrypted, key.raw)\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return null\n }\n\n async tryEncryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T[]> {\n const entitiesWithInitialisedEncryptionKeys: T[] = []\n for (const entity of entities) {\n entitiesWithInitialisedEncryptionKeys.push((await this.ensureEncryptionKeysInitialised(entity, entityType)) ?? entity)\n }\n const results = await this.doManyIncrementallyDecryptingKeys(entitiesWithInitialisedEncryptionKeys, entityType, async (e, t, keys) => {\n for (const k of keys) {\n try {\n const encrypted = await encryptObject(\n e,\n (obj) => {\n // TODO 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\n return this.primitives.AES.encrypt(k.key, utf8_2ua(json), k.raw)\n },\n fieldsToEncrypt,\n entityType\n )\n return { success: constructor(encrypted) }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${k.raw}: ${e}`)\n }\n }\n return null\n })\n if (results.size != entitiesWithInitialisedEncryptionKeys.length) {\n if (requireEncryption) {\n throw new Error(\n `Could not encrypt entities ${entitiesWithInitialisedEncryptionKeys.flatMap((e): string[] => (results.has(e.id!) ? [] : [e.id!]))}`\n )\n } else {\n for (const e of entitiesWithInitialisedEncryptionKeys) {\n if (!results.has(e.id!)) {\n await encryptObject(\n e,\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 e\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n results.set(e.id!, e)\n }\n }\n }\n }\n return entitiesWithInitialisedEncryptionKeys.map((e) => results.get(e.id!)!)\n }\n\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.securityMetadataDecryptor.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 decryptedDataProvider: (dataOwners: string[]) => Promise<{ ownerId: string; extracted: string[] }[]>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n return await decryptedDataProvider(canDecryptOwnerIds)\n }\n\n private async decryptAndMergeHierarchy(\n dataOwnerId: string | undefined,\n decryptedDataProvider: (dataOwners: string[]) => Promise<{ ownerId: string; extracted: string[] }[]>\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 decryptedDataProvider(hierarchy)\n const merged = decryptedData.flatMap((x) => x.extracted)\n return this.deduplicate(merged)\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 doIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entity: E,\n entityType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<{ success: T } | null> {\n const res = await this.doManyIncrementallyDecryptingKeys([entity], entityType, (e, t, ks) => action(e, t, ks))\n if (res.has(entity.id!)) {\n return { success: res.get(entity.id!)! }\n } else {\n return null\n }\n }\n\n async doManyIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entities: E[],\n entitiesType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<Map<string, T>> {\n if (entities.length == 0) return new Map()\n if (new Set(entities.map((e) => e.id)).size != entities.length) {\n throw new Error(`Duplicate entries in entities ${entities.map((x) => x.id)}`)\n }\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const allExtractedKeysForEntities = Object.fromEntries(entities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const newlyExtractedKeysForEntities = Object.fromEntries(entities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const results = new Map<string, T>()\n const remainingEntitiesById = Object.fromEntries(entities.map((x) => [x.id!, x] as [string, E]))\n const importedKeysByRaw = new Map<string, CryptoKey>()\n const primitives = this.primitives\n\n async function updateExtractedKeysAndDoActionIfNecessary(\n newKeys: { [entityId: string]: string[] },\n forceUpdateOnEntitiesWithNewExtractedKeys: boolean\n ): Promise<void> {\n for (const [entityId, keys] of Object.entries(newKeys)) {\n const newlyExtractedSet = newlyExtractedKeysForEntities[entityId]\n const alreadyExtractedSet = allExtractedKeysForEntities[entityId]\n for (const k of keys) {\n if (!alreadyExtractedSet.has(k)) {\n newlyExtractedSet.add(k)\n if (!importedKeysByRaw.has(k)) {\n importedKeysByRaw.set(k, await primitives.AES.importKey('raw', hex2ua(k)))\n }\n }\n }\n }\n if (\n forceUpdateOnEntitiesWithNewExtractedKeys ||\n Object.keys(remainingEntitiesById).every((eId) => newlyExtractedKeysForEntities[eId].size > 0)\n ) {\n for (const entity of Object.values(remainingEntitiesById)) {\n const currId = entity.id!\n const currNewlyExtracted = newlyExtractedKeysForEntities[currId]\n if (currNewlyExtracted.size > 0) {\n const currAllExtracted = allExtractedKeysForEntities[currId]\n currNewlyExtracted.forEach((k) => currAllExtracted.add(k))\n currNewlyExtracted.clear()\n const actionResult = await action(\n entity,\n entitiesType,\n [...currAllExtracted].map((raw): { raw: string; key: CryptoKey } => ({\n raw: raw,\n key: importedKeysByRaw.get(raw)!,\n }))\n )\n if (actionResult != null) {\n delete remainingEntitiesById[currId]\n results.set(currId, actionResult.success)\n }\n }\n }\n }\n }\n\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptLegacyDelegations(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingCache(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingKnownExchangeData(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingExchangeDataMap(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary({}, true)\n return results\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 async initialiseConfidentialSecretId<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<T | undefined> {\n if (await this.getConfidentialSecretId({ entity, type: entityType })) return undefined\n const confidentialSecretId = this.primitives.randomUuid()\n return (\n await this.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity, type: entityType },\n {\n [await this.dataOwnerApi.getCurrentDataOwnerId()]: {\n shareEncryptionKeys: ShareMetadataBehaviour.NEVER,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [confidentialSecretId],\n requestedPermissions: RequestedPermissionEnum.MAX_WRITE,\n },\n },\n (request) => doRequestBulkShareOrUpdate(request)\n )\n ).updatedEntityOrThrow\n }\n\n async getConfidentialSecretId(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string | undefined> {\n return this.getConfidentialSecretIds(entity, dataOwnerId).then((x) => x[0])\n }\n\n async getConfidentialSecretIds(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n const chosenDataOwnerId = dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n const dataOwnerHierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(chosenDataOwnerId)\n const hierarchySecretIds = (await this.secretIdsForHcpHierarchyOf(entity)).filter((x) => dataOwnerHierarchy.includes(x.ownerId))\n const keysForDataOwner = hierarchySecretIds.find((x) => x.ownerId === chosenDataOwnerId)\n\n if (!keysForDataOwner) return []\n return keysForDataOwner.extracted.filter((k) => !hierarchySecretIds.some((x) => x.ownerId !== chosenDataOwnerId && x.extracted.includes(k)))\n }\n\n async getAnySecretIdSharedWithParents(entity: EncryptedEntityWithType): Promise<string | undefined> {\n return (await this.getSecretIdsSharedWithParents(entity))[0]\n }\n\n async getSecretIdsSharedWithParents(entity: EncryptedEntityWithType): Promise<string[]> {\n return (await this.secretIdsForHcpHierarchyOf(entity))[0].extracted\n }\n\n async resolveSecretIdUseOptions(entity: EncryptedEntityWithType, option: SecretIdUseOption): Promise<string[]> {\n if (option == SecretIdUseOption.UseNone) {\n return []\n } else if (option == SecretIdUseOption.UseAnyConfidential) {\n const all = await this.getConfidentialSecretIds(entity, undefined)\n if (all.length == 0) throw new Error(\"Couldn't find any confidential secret id\")\n return [all[0]]\n } else if (option == SecretIdUseOption.UseAllConfidential) {\n const all = await this.getConfidentialSecretIds(entity, undefined)\n if (all.length == 0) throw new Error(\"Couldn't find any confidential secret id\")\n return all\n } else if (option == SecretIdUseOption.UseAnySharedWithParent) {\n const all = await this.getSecretIdsSharedWithParents(entity)\n if (all.length == 0) throw new Error(\"Couldn't find any secret id shared with parent\")\n return [all[0]]\n } else if (option == SecretIdUseOption.UseAllSharedWithParent) {\n const all = await this.getSecretIdsSharedWithParents(entity)\n if (all.length == 0) throw new Error(\"Couldn't find any secret id shared with parent\")\n return all\n } else if (option instanceof SecretIdUseOption.Use) {\n return [...new Set(option.secretIds)]\n } else {\n throw new Error(`Unrecognized SecretIdUseOption ${option}`)\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAWiB;AAEjB,2EAA6F;AAC7F,2EAAuE;AAIvE,wFAAoF;AAEpF,sDAA0F;AAC1F,qEAAiE;AAKjE,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;AACzD,2DAAuD;AAEvD;;;GAGG;AACH,MAAa,qBAAqB;IAChC,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,yBAAoD,EACpD,wBAAkD,EAClD,OAAoB,EACpB,aAAsB;QALtB,eAAU,GAAV,UAAU,CAAkB;QAC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IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;gBACtF,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAA;aAChB;iBAAM,IAAI,MAAM,IAAI,qCAAiB,CAAC,sBAAsB,EAAE;gBAC7D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,6BAA6B,CAAC,MAAM,CAAC,CAAA;gBAC5D,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC;oBAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;gBACtF,OAAO,GAAG,CAAA;aACX;iBAAM,IAAI,MAAM,YAAY,qCAAiB,CAAC,GAAG,EAAE;gBAClD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAA;aACtC;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,kCAAkC,MAAM,EAAE,CAAC,CAAA;aAC5D;QACH,CAAC;KAAA;CACF;AA1/BD,sDA0/BC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport {\n b2a,\n decryptObject,\n EncryptedEntityWithType,\n EncryptedFieldsManifest,\n encryptObject,\n EntityWithDelegationTypeName,\n hex2ua,\n truncateTrailingNulls,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { SecurityMetadataDecryptor, SecurityMetadataType } from './SecurityMetadataDecryptor'\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 { 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 { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\nimport * as _ from 'lodash'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { SecretIdUseOption } from './SecretIdUseOption'\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 constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly securityMetadataDecryptor: SecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {}\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.EncryptionKey)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.EncryptionKey)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.SecretId)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) => this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.SecretId))\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.OwningEntityId)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.OwningEntityId)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.securityMetadataDecryptor.getEntityAccessLevel(entity.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 owningEntitySecretIds: string[] | undefined,\n initialiseEncryptionKey: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum },\n alternateRootDelegation: string | undefined\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: owningEntitySecretIds ?? [],\n },\n entityType,\n newSecretId ? [newSecretId] : [],\n !!owningEntity ? [owningEntity] : [],\n newRawKey ? [newRawKey] : [],\n autoDelegations,\n alternateRootDelegation\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 =\n Object.keys(allRequestsByEntityId).length > 0 ? 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.securityMetadataDecryptor.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 this.securityMetadataDecryptor.decryptAllLegacyDelegations(entity.entity, hierarchy, SecurityMetadataType.SecretId)\n const legacyEncryptionKeys = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(\n entity.entity,\n hierarchy,\n SecurityMetadataType.EncryptionKey\n )\n const legacyOwningEntityIds = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(\n entity.entity,\n hierarchy,\n SecurityMetadataType.OwningEntityId\n )\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.securityMetadataDecryptor.getEntityLegacyDelegationAccessLevel(entity.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 this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.SecretId)).map(\n (x) => x.decrypted\n )\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.EncryptionKey)).map(\n (x) => x.decrypted\n )\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.OwningEntityId)).map(\n (x) => x.decrypted\n )\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id &&\n currMemberId === selfId &&\n !(await this.securityMetadataDecryptor.getEntitySecureDelegationAccessLevel(entity.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 triedKeys: Set<string> = new Set()\n const result = await this.doIncrementallyDecryptingKeys(entity.entity, entity.type, async (e, t, keys) => {\n for (const k of keys) {\n if (!triedKeys.has(k.raw)) {\n triedKeys.add(k.raw)\n try {\n const decrypted = await this.primitives.AES.decrypt(k.key, content)\n if (!validator || (await validator(decrypted))) return { success: decrypted }\n } catch (e) {\n console.warn(`Error while attempting to decrypt attachment of ${entity.entity.id} with raw key ${k.raw}: ${e}`)\n }\n }\n }\n return null\n })\n if (result != null) {\n return { data: result.success, wasDecrypted: true }\n } else {\n return { data: content, wasDecrypted: false }\n }\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 const encrypted = await this.doIncrementallyDecryptingKeys(entity, type, async (e, t, keys) => {\n for (const k of keys) {\n try {\n return {\n success: {\n encryptedData: await this.primitives.AES.encrypt(k.key, content),\n updatedEntity: updatedEntity,\n },\n }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${k.raw}: ${e}`)\n }\n }\n return null\n })\n if (encrypted != null) return encrypted.success\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async tryDecryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }[]> {\n const nothingToDecryptResults = new Map<string, T>()\n for (const entity of entities) {\n const nothingToDecrypt = await decryptObject(entity, async (encrypted) => {\n return null\n })\n if (nothingToDecrypt != null) {\n nothingToDecryptResults.set(entity.id!, constructor(nothingToDecrypt))\n }\n }\n const actuallyDecryptedResults = await this.doManyIncrementallyDecryptingKeys(\n entities.filter((e) => !nothingToDecryptResults.has(e.id!)),\n entityType,\n async (entity, t, keys) => {\n // The decrypt object will try all keys on each of the sub-objects; this is intentional because even though it\n // shouldn't happen, but it is still possible that some entity could be accidentally merged badly and the merged\n // entity has multiple encryptedSelf (on different sub-entities) that use different keys.\n const decrypted = await decryptObject(entity, (encrypted) => this.tryDecryptJson(keys, encrypted, false))\n if (decrypted != null) {\n return { success: constructor(decrypted) }\n } else {\n return null\n }\n }\n )\n const res = []\n for (const entity of entities) {\n const decrypted = actuallyDecryptedResults.get(entity.id!) ?? nothingToDecryptResults.get(entity.id!)\n if (!decrypted) {\n res.push({ entity: entity, decrypted: false })\n } else {\n res.push({ entity: decrypted, decrypted: true })\n }\n }\n return res\n }\n\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | null> {\n for (const key of potentialKeys) {\n try {\n const decrypted = await this.primitives.AES.decrypt(key.key, encrypted, key.raw)\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return null\n }\n\n async tryEncryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T[]> {\n const entitiesWithInitialisedEncryptionKeys: T[] = []\n for (const entity of entities) {\n entitiesWithInitialisedEncryptionKeys.push((await this.ensureEncryptionKeysInitialised(entity, entityType)) ?? entity)\n }\n const results = await this.doManyIncrementallyDecryptingKeys(entitiesWithInitialisedEncryptionKeys, entityType, async (e, t, keys) => {\n for (const k of keys) {\n try {\n const encrypted = await encryptObject(\n e,\n (obj) => {\n // TODO 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\n return this.primitives.AES.encrypt(k.key, utf8_2ua(json), k.raw)\n },\n fieldsToEncrypt,\n entityType\n )\n return { success: constructor(encrypted) }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${k.raw}: ${e}`)\n }\n }\n return null\n })\n if (results.size != entitiesWithInitialisedEncryptionKeys.length) {\n if (requireEncryption) {\n throw new Error(\n `Could not encrypt entities ${entitiesWithInitialisedEncryptionKeys.flatMap((e): string[] => (results.has(e.id!) ? [] : [e.id!]))}`\n )\n } else {\n for (const e of entitiesWithInitialisedEncryptionKeys) {\n if (!results.has(e.id!)) {\n await encryptObject(\n e,\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 e\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n results.set(e.id!, e)\n }\n }\n }\n }\n return entitiesWithInitialisedEncryptionKeys.map((e) => results.get(e.id!)!)\n }\n\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.securityMetadataDecryptor.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 undefined\n )\n }\n\n private async decryptHierarchy(\n decryptedDataProvider: (dataOwners: string[]) => Promise<{ ownerId: string; extracted: string[] }[]>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n return await decryptedDataProvider(canDecryptOwnerIds)\n }\n\n private async decryptAndMergeHierarchy(\n dataOwnerId: string | undefined,\n decryptedDataProvider: (dataOwners: string[]) => Promise<{ ownerId: string; extracted: string[] }[]>\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 decryptedDataProvider(hierarchy)\n const merged = decryptedData.flatMap((x) => x.extracted)\n return this.deduplicate(merged)\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 doIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entity: E,\n entityType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<{ success: T } | null> {\n const res = await this.doManyIncrementallyDecryptingKeys([entity], entityType, (e, t, ks) => action(e, t, ks))\n if (res.has(entity.id!)) {\n return { success: res.get(entity.id!)! }\n } else {\n return null\n }\n }\n\n async doManyIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entities: E[],\n entitiesType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<Map<string, T>> {\n if (entities.length == 0) return new Map()\n if (new Set(entities.map((e) => e.id)).size != entities.length) {\n throw new Error(`Duplicate entries in entities ${entities.map((x) => x.id)}`)\n }\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const allExtractedKeysForEntities = Object.fromEntries(entities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const newlyExtractedKeysForEntities = Object.fromEntries(entities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const results = new Map<string, T>()\n const remainingEntitiesById = Object.fromEntries(entities.map((x) => [x.id!, x] as [string, E]))\n const importedKeysByRaw = new Map<string, CryptoKey>()\n const primitives = this.primitives\n\n async function updateExtractedKeysAndDoActionIfNecessary(\n newKeys: { [entityId: string]: string[] },\n forceUpdateOnEntitiesWithNewExtractedKeys: boolean\n ): Promise<void> {\n for (const [entityId, keys] of Object.entries(newKeys)) {\n const newlyExtractedSet = newlyExtractedKeysForEntities[entityId]\n const alreadyExtractedSet = allExtractedKeysForEntities[entityId]\n for (const k of keys) {\n if (!alreadyExtractedSet.has(k)) {\n newlyExtractedSet.add(k)\n if (!importedKeysByRaw.has(k)) {\n importedKeysByRaw.set(k, await primitives.AES.importKey('raw', hex2ua(k)))\n }\n }\n }\n }\n if (\n forceUpdateOnEntitiesWithNewExtractedKeys ||\n Object.keys(remainingEntitiesById).every((eId) => newlyExtractedKeysForEntities[eId].size > 0)\n ) {\n for (const entity of Object.values(remainingEntitiesById)) {\n const currId = entity.id!\n const currNewlyExtracted = newlyExtractedKeysForEntities[currId]\n if (currNewlyExtracted.size > 0) {\n const currAllExtracted = allExtractedKeysForEntities[currId]\n currNewlyExtracted.forEach((k) => currAllExtracted.add(k))\n currNewlyExtracted.clear()\n const actionResult = await action(\n entity,\n entitiesType,\n [...currAllExtracted].map((raw): { raw: string; key: CryptoKey } => ({\n raw: raw,\n key: importedKeysByRaw.get(raw)!,\n }))\n )\n if (actionResult != null) {\n delete remainingEntitiesById[currId]\n results.set(currId, actionResult.success)\n }\n }\n }\n }\n }\n\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptLegacyDelegations(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingCache(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingKnownExchangeData(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingExchangeDataMap(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary({}, true)\n return results\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 async initialiseConfidentialSecretId<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<T | undefined> {\n if (await this.getConfidentialSecretId({ entity, type: entityType })) return undefined\n const confidentialSecretId = this.primitives.randomUuid()\n return (\n await this.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity, type: entityType },\n {\n [await this.dataOwnerApi.getCurrentDataOwnerId()]: {\n shareEncryptionKeys: ShareMetadataBehaviour.NEVER,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [confidentialSecretId],\n requestedPermissions: RequestedPermissionEnum.MAX_WRITE,\n },\n },\n (request) => doRequestBulkShareOrUpdate(request)\n )\n ).updatedEntityOrThrow\n }\n\n async getConfidentialSecretId(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string | undefined> {\n return this.getConfidentialSecretIds(entity, dataOwnerId).then((x) => x[0])\n }\n\n async getConfidentialSecretIds(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n const chosenDataOwnerId = dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n const dataOwnerHierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(chosenDataOwnerId)\n const hierarchySecretIds = (await this.secretIdsForHcpHierarchyOf(entity)).filter((x) => dataOwnerHierarchy.includes(x.ownerId))\n const keysForDataOwner = hierarchySecretIds.find((x) => x.ownerId === chosenDataOwnerId)\n\n if (!keysForDataOwner) return []\n return keysForDataOwner.extracted.filter((k) => !hierarchySecretIds.some((x) => x.ownerId !== chosenDataOwnerId && x.extracted.includes(k)))\n }\n\n async getAnySecretIdSharedWithParents(entity: EncryptedEntityWithType): Promise<string | undefined> {\n return (await this.getSecretIdsSharedWithParents(entity))[0]\n }\n\n async getSecretIdsSharedWithParents(entity: EncryptedEntityWithType): Promise<string[]> {\n return (await this.secretIdsForHcpHierarchyOf(entity))[0].extracted\n }\n\n async resolveSecretIdUseOptions(entity: EncryptedEntityWithType, option: SecretIdUseOption): Promise<string[]> {\n if (option == SecretIdUseOption.UseNone) {\n return []\n } else if (option == SecretIdUseOption.UseAnyConfidential) {\n const all = await this.getConfidentialSecretIds(entity, undefined)\n if (all.length == 0) throw new Error(\"Couldn't find any confidential secret id\")\n return [all[0]]\n } else if (option == SecretIdUseOption.UseAllConfidential) {\n const all = await this.getConfidentialSecretIds(entity, undefined)\n if (all.length == 0) throw new Error(\"Couldn't find any confidential secret id\")\n return all\n } else if (option == SecretIdUseOption.UseAnySharedWithParent) {\n const all = await this.getSecretIdsSharedWithParents(entity)\n if (all.length == 0) throw new Error(\"Couldn't find any secret id shared with parent\")\n return [all[0]]\n } else if (option == SecretIdUseOption.UseAllSharedWithParent) {\n const all = await this.getSecretIdsSharedWithParents(entity)\n if (all.length == 0) throw new Error(\"Couldn't find any secret id shared with parent\")\n return all\n } else if (option instanceof SecretIdUseOption.Use) {\n return [...new Set(option.secretIds)]\n } else {\n throw new Error(`Unrecognized SecretIdUseOption ${option}`)\n }\n }\n}\n"]}
|
|
@@ -32,13 +32,15 @@ export declare class SecureDelegationsManager {
|
|
|
32
32
|
* @param encryptionKeys the initial encryption keys to include and share with the auto-delegations
|
|
33
33
|
* @param autoDelegations the data owners which will initially have access to the entity in addition to the current data owner and the access level
|
|
34
34
|
* they will have on the entity.
|
|
35
|
+
* @param alternateRootDelegation by default a new entity is created with a root delegation from self to self. In keyless mode this is not possible,
|
|
36
|
+
* and instead the root delegation will be from self to another. You have to specify which delegate will be part of the root delegation.
|
|
35
37
|
* @return the entity with the security metadata initialised for the provided parameters.
|
|
36
38
|
*/
|
|
37
39
|
entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(entity: T & {
|
|
38
40
|
secretForeignKeys: string[];
|
|
39
41
|
}, entityType: EntityWithDelegationTypeName, secretIds: string[], owningEntityIds: string[], encryptionKeys: string[], autoDelegations: {
|
|
40
42
|
[delegateId: string]: SecureDelegation.AccessLevelEnum;
|
|
41
|
-
}): Promise<T>;
|
|
43
|
+
}, alternateRootDelegation: string | undefined): Promise<T>;
|
|
42
44
|
/**
|
|
43
45
|
* Make a request for sharing an entity with a delegate or to update existing shared metadata by adding additional secretIds, encryptionKeys or
|
|
44
46
|
* owningEntityIds if there is already some metadata shared between the current data owner and the delegate. In case there is already a delegation
|