@icure/api 8.6.6 → 8.6.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/icc-api/api/IccAccesslogApi.d.ts +14 -0
  2. package/icc-api/api/IccAccesslogApi.js +31 -0
  3. package/icc-api/api/IccAccesslogApi.js.map +1 -1
  4. package/icc-api/api/IccFormApi.d.ts +8 -0
  5. package/icc-api/api/IccFormApi.js +21 -0
  6. package/icc-api/api/IccFormApi.js.map +1 -1
  7. package/icc-api/model/AbstractFilterAccessLog.d.ts +15 -0
  8. package/icc-api/model/AbstractFilterAccessLog.js +21 -0
  9. package/icc-api/model/AbstractFilterAccessLog.js.map +1 -0
  10. package/icc-api/model/ChapterParagraph.d.ts +16 -0
  11. package/icc-api/model/ChapterParagraph.js +21 -0
  12. package/icc-api/model/ChapterParagraph.js.map +1 -0
  13. package/icc-api/model/CryptoActorStub.d.ts +2 -0
  14. package/icc-api/model/CryptoActorStub.js.map +1 -1
  15. package/icc-api/model/Device.d.ts +1 -0
  16. package/icc-api/model/Device.js.map +1 -1
  17. package/icc-api/model/HealthcareParty.d.ts +1 -0
  18. package/icc-api/model/HealthcareParty.js.map +1 -1
  19. package/icc-api/model/Patient.d.ts +1 -0
  20. package/icc-api/model/Patient.js.map +1 -1
  21. package/icc-api/model/Reimbursement.d.ts +2 -0
  22. package/icc-api/model/Reimbursement.js.map +1 -1
  23. package/icc-x-api/crypto/CryptoStrategies.d.ts +2 -1
  24. package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
  25. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +2 -2
  26. package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
  27. package/icc-x-api/crypto/UserEncryptionKeysManager.js +2 -2
  28. package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
  29. package/icc-x-api/filters/AccessLogByDataOwnerPatientDateFilter.d.ts +22 -0
  30. package/icc-x-api/filters/AccessLogByDataOwnerPatientDateFilter.js +24 -0
  31. package/icc-x-api/filters/AccessLogByDataOwnerPatientDateFilter.js.map +1 -0
  32. package/icc-x-api/filters/AccessLogByDateFilter.d.ts +20 -0
  33. package/icc-x-api/filters/AccessLogByDateFilter.js +24 -0
  34. package/icc-x-api/filters/AccessLogByDateFilter.js.map +1 -0
  35. package/icc-x-api/filters/AccessLogByUserIdUserTypeDateFilter.d.ts +21 -0
  36. package/icc-x-api/filters/AccessLogByUserIdUserTypeDateFilter.js +24 -0
  37. package/icc-x-api/filters/AccessLogByUserIdUserTypeDateFilter.js.map +1 -0
  38. package/icc-x-api/icc-contact-x-api.js +3 -3
  39. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  40. package/icc-x-api/utils/crypto-utils.d.ts +2 -1
  41. package/icc-x-api/utils/crypto-utils.js +57 -6
  42. package/icc-x-api/utils/crypto-utils.js.map +1 -1
  43. package/package.json +1 -1
  44. package/test/icc-x-api/crypto/anonymous-delegations-test.js +1 -1
  45. package/test/icc-x-api/crypto/anonymous-delegations-test.js.map +1 -1
  46. package/test/icc-x-api/crypto/cryptoTest.js +99 -1
  47. package/test/icc-x-api/crypto/cryptoTest.js.map +1 -1
  48. package/test/icc-x-api/crypto/legacy-metadata-migration-test.js +3 -3
  49. package/test/icc-x-api/crypto/legacy-metadata-migration-test.js.map +1 -1
  50. package/test/icc-x-api/entity-with-attachments-api-test.js +2 -2
  51. package/test/icc-x-api/entity-with-attachments-api-test.js.map +1 -1
  52. package/test/icc-x-api/icc-form-x-api.js +51 -0
  53. package/test/icc-x-api/icc-form-x-api.js.map +1 -1
  54. package/test/icc-x-api/icc-user-x-api-test.js +1 -1
  55. package/test/icc-x-api/icc-user-x-api-test.js.map +1 -1
  56. package/test/support/CSM-243.js +5 -5
  57. package/test/support/CSM-243.js.map +1 -1
  58. package/test/support/CSM-729.d.ts +1 -0
  59. package/test/support/CSM-729.js +225 -0
  60. package/test/support/CSM-729.js.map +1 -0
@@ -1 +1 @@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I,GAAG,IAAI,GAAG,EAAsB,CAAA;QAC1C,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE;YAC3B,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;gBAAE,OAAO,KAAK,CAAA;YAChC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;YACd,OAAO,IAAI,CAAA;QACb,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAtgCD,sDAsgCC","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 ua2ab,\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: ua2ab(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 let deduplicatedEntities = entities\n if (new Set(deduplicatedEntities.map((e) => e.id)).size != deduplicatedEntities.length) {\n console.error(`Duplicate entries in entities ${deduplicatedEntities.map((x) => x.id)}`)\n deduplicatedEntities = this.deduplicateById(deduplicatedEntities)\n }\n\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const allExtractedKeysForEntities = Object.fromEntries(deduplicatedEntities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const newlyExtractedKeysForEntities = Object.fromEntries(deduplicatedEntities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const results = new Map<string, T>()\n const remainingEntitiesById = Object.fromEntries(deduplicatedEntities.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 private deduplicateById<E extends { id?: string }>(entities: E[]): E[] {\n const seen = new Set<string | undefined>()\n return entities.filter((e) => {\n if (seen.has(e.id)) return false\n seen.add(e.id)\n return true\n })\n }\n}\n"]}
1
+ {"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAYiB;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;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,8BAAyB,GAAzB,yBAAyB,CAA2B;QACpD,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,YAAO,GAAP,OAAO,CAAa;QACpB,kBAAa,GAAb,aAAa,CAAS;IACtC,CA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G,CAAC,CAAC,CAAC,CAAC,CAAA;YACjB,CAAC;iBAAM,IAAI,MAAM,IAAI,qCAAiB,CAAC,sBAAsB,EAAE,CAAC;gBAC9D,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;YACZ,CAAC;iBAAM,IAAI,MAAM,YAAY,qCAAiB,CAAC,GAAG,EAAE,CAAC;gBACnD,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAA;YACvC,CAAC;iBAAM,CAAC;gBACN,MAAM,IAAI,KAAK,CAAC,kCAAkC,MAAM,EAAE,CAAC,CAAA;YAC7D,CAAC;QACH,CAAC;KAAA;IAEO,eAAe,CAA4B,QAAa;QAC9D,MAAM,IAAI,GAAG,IAAI,GAAG,EAAsB,CAAA;QAC1C,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE;YAC3B,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;gBAAE,OAAO,KAAK,CAAA;YAChC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;YACd,OAAO,IAAI,CAAA;QACb,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAxgCD,sDAwgCC","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 ua2ab,\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: ua2ab(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 (encryptedSelf) => this.tryDecryptJson(keys, encryptedSelf, false),\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 () => Promise.resolve(null),\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 let deduplicatedEntities = entities\n if (new Set(deduplicatedEntities.map((e) => e.id)).size != deduplicatedEntities.length) {\n console.error(`Duplicate entries in entities ${deduplicatedEntities.map((x) => x.id)}`)\n deduplicatedEntities = this.deduplicateById(deduplicatedEntities)\n }\n\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const allExtractedKeysForEntities = Object.fromEntries(deduplicatedEntities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const newlyExtractedKeysForEntities = Object.fromEntries(deduplicatedEntities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const results = new Map<string, T>()\n const remainingEntitiesById = Object.fromEntries(deduplicatedEntities.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 private deduplicateById<E extends { id?: string }>(entities: E[]): E[] {\n const seen = new Set<string | undefined>()\n return entities.filter((e) => {\n if (seen.has(e.id)) return false\n seen.add(e.id)\n return true\n })\n }\n}\n"]}
@@ -238,9 +238,9 @@ class UserEncryptionKeysManager {
238
238
  const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id].recoveredKeys);
239
239
  for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {
240
240
  const jwkPair = yield this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk');
241
- yield this.icureStorage.saveKey(keyData.dowt.dataOwner.id, fp, jwkPair, true);
241
+ yield this.icureStorage.saveKey(keyData.dowt.dataOwner.id, fp, jwkPair, currAuthenticity[fp] != undefined ? currAuthenticity[fp] : true);
242
242
  }
243
- const updatedVerifiedMap = yield this.icureStorage.saveSelfVerifiedKeys(keyData.dowt.dataOwner.id, [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce((acc, currFp) => (Object.assign(Object.assign({}, acc), { [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp] })), {}));
243
+ const updatedVerifiedMap = yield this.icureStorage.saveSelfVerifiedKeys(keyData.dowt.dataOwner.id, [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce((acc, currFp) => (Object.assign(Object.assign({}, acc), { [currFp]: currAuthenticity[currFp] != undefined ? currAuthenticity[currFp] : currFp in currExternallyRecovered ? true : undefined })), {}));
244
244
  const keysWithExternallyRecovered = Object.assign(Object.assign({}, keyData.availableKeys), Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])));
245
245
  let parentKeysForRecovery = {};
246
246
  for (let j = 0; j < i; j++) {
@@ -1 +1 @@
1
- {"version":3,"file":"UserEncryptionKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/UserEncryptionKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+BAA2C;AAC3C,oCAAiC;AAEjC,mCAAuC;AAKvC,yEAA8F;AAgB9F,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,C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,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAA,qBAAa,EAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IACvF,CAAC;IAEO,cAAc,CAAC,QAAuC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AA7bD,8DA6bC","sourcesContent":["import { DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair, ShaVersion } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { fingerprintV1 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean | 'keyless'>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class UserEncryptionKeysManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean,\n private readonly keypairRecoverer: KeyPairRecoverer,\n private readonly selfIsAnonymous: boolean\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives, this.keypairRecoverer),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey && fingerprintV1(this.selfLegacyPublicKey)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwnerOrStub): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner),\n ]).filter((key) => {\n const fp = fingerprintV1(key)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = (await this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {\n if (dataOwner.publicKey == '') {\n if (Object.entries(dataOwner.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${dataOwner.id} has \"\" as public key but has non-empty hcPartyKeys`)\n delete dataOwner.publicKey\n }\n return {\n dataOwner,\n type,\n } as DataOwnerWithType\n })\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n const toInit = this.initialiseParentKeys ? hierarchy : [self]\n for (let i = 0; i < toInit.length; i++) {\n const dowt = toInit[i]\n let parentKeysForRecovery: { [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } } = {}\n for (let j = 0; j < i; j++) {\n parentKeysForRecovery = {\n ...keysData[j].availableKeys,\n ...parentKeysForRecovery,\n }\n }\n const availableKeys = await this.loadAndRecoverKeysFor(dowt, parentKeysForRecovery)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = new Set([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dowt.dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dowt.dataOwner),\n ])\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(fingerprintV1(key)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(fingerprintV1(x) in verifiedKeysMap) && !(availableKeys?.[fingerprintV1(x)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (let i = 0; i < keysData.length; i++) {\n const keyData = keysData[i]\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n let parentKeysForRecovery: { [p: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } } = {}\n for (let j = 0; j < i; j++) {\n parentKeysForRecovery = {\n ...keysCache[keysData[j].dowt.dataOwner.id!],\n ...parentKeysForRecovery,\n }\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(\n keyData.dowt,\n this.plainKeysByFingerprint({\n ...keysWithExternallyRecovered,\n ...parentKeysForRecovery,\n })\n )\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else if (typeof whatToDo == 'string' && whatToDo == 'keyless') {\n /*\n * Currently non-anonymous data owners aren't allowed to use keyless mode.\n * Today the delegator is not emitted in views and is not used for access control: an entity without delegation\n * self->self but only a delegation self->other would not be searchable by nor accessible to an explicit data\n * owner.\n * This is not a problem for anonymous data owner, since search and access control use the secure delegation\n * key.\n * Since keyless api was designed for use by patients this is not an issue at the time, but if in future we need\n * to support keyless api for explicit data owner before updating views we can add stubs to legacy delegations.\n */\n if (!this.selfIsAnonymous) throw new Error('Keyless api mode is available only for anonymous data owners.')\n this.keysCache = keysCache\n return undefined\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair(ShaVersion.Sha256))\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const jwKey = await this.primitives.RSA.exportKey(keyPair.publicKey, 'jwk')\n if (jwKey.alg !== 'RSA-OAEP-256') {\n throw new Error('Only keys generated with SHA-256 are currently supported')\n }\n const publicKeyFingerprint = fingerprintV1(publicKeyHex)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const updatedSelf = await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...CryptoActorStub.fromDataOwner(selfDataOwner.dataOwner),\n publicKeysForOaepWithSha256: [...(selfDataOwner.dataOwner.publicKeysForOaepWithSha256 ?? []), publicKeyHex],\n },\n type: selfDataOwner.type,\n })\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: { [key: string]: string[] }\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprintsWithVersion = Object.entries(pubKeysFingerprints).flatMap(([shaVersion, fps]) => {\n return fps.map((fp) => [shaVersion, fp] as [ShaVersion, string])\n })\n return await pubKeysFingerprintsWithVersion.reduce(async (acc, [shaVersion, currentFingerprint]) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (!!storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair(\n 'jwk',\n storedKeypair.pair.privateKey,\n 'jwk',\n storedKeypair.pair.publicKey,\n shaVersion\n )\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(\n dataOwner: DataOwnerWithType,\n ancestorsKeys: { [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }\n ): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprints = {\n 'sha-1': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n 'sha-256': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n }\n const loadedKeys =\n pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (\n loadedKeysFingerprints.length !== pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length &&\n (loadedKeysFingerprints.length > 0 || Object.keys(ancestorsKeys).length > 0)\n ) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint({ ...loadedKeys, ...ancestorsKeys }))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [fingerprintV1(k), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}
1
+ {"version":3,"file":"UserEncryptionKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/UserEncryptionKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+BAA2C;AAC3C,oCAAiC;AAEjC,mCAAuC;AAKvC,yEAA8F;AAgB9F,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAG,CAAC,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE,eAAe,EAAE,EAAE,EAAE,IAA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AA;QACnB,CAAC;KAAA;IAEO,qBAAqB,CAAI,GAAyC;QACxE,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAA,qBAAa,EAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IACvF,CAAC;IAEO,cAAc,CAAC,QAAuC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AA7bD,8DA6bC","sourcesContent":["import { DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair, ShaVersion } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { fingerprintV1 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean | 'keyless'>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class UserEncryptionKeysManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean,\n private readonly keypairRecoverer: KeyPairRecoverer,\n private readonly selfIsAnonymous: boolean\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives, this.keypairRecoverer),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey && fingerprintV1(this.selfLegacyPublicKey)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwnerOrStub): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner),\n ]).filter((key) => {\n const fp = fingerprintV1(key)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = (await this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {\n if (dataOwner.publicKey == '') {\n if (Object.entries(dataOwner.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${dataOwner.id} has \"\" as public key but has non-empty hcPartyKeys`)\n delete dataOwner.publicKey\n }\n return {\n dataOwner,\n type,\n } as DataOwnerWithType\n })\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n const toInit = this.initialiseParentKeys ? hierarchy : [self]\n for (let i = 0; i < toInit.length; i++) {\n const dowt = toInit[i]\n let parentKeysForRecovery: { [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } } = {}\n for (let j = 0; j < i; j++) {\n parentKeysForRecovery = {\n ...keysData[j].availableKeys,\n ...parentKeysForRecovery,\n }\n }\n const availableKeys = await this.loadAndRecoverKeysFor(dowt, parentKeysForRecovery)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = new Set([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dowt.dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dowt.dataOwner),\n ])\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(fingerprintV1(key)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(fingerprintV1(x) in verifiedKeysMap) && !(availableKeys?.[fingerprintV1(x)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (let i = 0; i < keysData.length; i++) {\n const keyData = keysData[i]\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, currAuthenticity[fp] != undefined ? currAuthenticity[fp] : true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currAuthenticity[currFp] != undefined ? currAuthenticity[currFp] : currFp in currExternallyRecovered ? true : undefined,\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n let parentKeysForRecovery: { [p: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } } = {}\n for (let j = 0; j < i; j++) {\n parentKeysForRecovery = {\n ...keysCache[keysData[j].dowt.dataOwner.id!],\n ...parentKeysForRecovery,\n }\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(\n keyData.dowt,\n this.plainKeysByFingerprint({\n ...keysWithExternallyRecovered,\n ...parentKeysForRecovery,\n })\n )\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else if (typeof whatToDo == 'string' && whatToDo == 'keyless') {\n /*\n * Currently non-anonymous data owners aren't allowed to use keyless mode.\n * Today the delegator is not emitted in views and is not used for access control: an entity without delegation\n * self->self but only a delegation self->other would not be searchable by nor accessible to an explicit data\n * owner.\n * This is not a problem for anonymous data owner, since search and access control use the secure delegation\n * key.\n * Since keyless api was designed for use by patients this is not an issue at the time, but if in future we need\n * to support keyless api for explicit data owner before updating views we can add stubs to legacy delegations.\n */\n if (!this.selfIsAnonymous) throw new Error('Keyless api mode is available only for anonymous data owners.')\n this.keysCache = keysCache\n return undefined\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair(ShaVersion.Sha256))\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const jwKey = await this.primitives.RSA.exportKey(keyPair.publicKey, 'jwk')\n if (jwKey.alg !== 'RSA-OAEP-256') {\n throw new Error('Only keys generated with SHA-256 are currently supported')\n }\n const publicKeyFingerprint = fingerprintV1(publicKeyHex)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const updatedSelf = await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...CryptoActorStub.fromDataOwner(selfDataOwner.dataOwner),\n publicKeysForOaepWithSha256: [...(selfDataOwner.dataOwner.publicKeysForOaepWithSha256 ?? []), publicKeyHex],\n },\n type: selfDataOwner.type,\n })\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: { [key: string]: string[] }\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprintsWithVersion = Object.entries(pubKeysFingerprints).flatMap(([shaVersion, fps]) => {\n return fps.map((fp) => [shaVersion, fp] as [ShaVersion, string])\n })\n return await pubKeysFingerprintsWithVersion.reduce(async (acc, [shaVersion, currentFingerprint]) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (!!storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair(\n 'jwk',\n storedKeypair.pair.privateKey,\n 'jwk',\n storedKeypair.pair.publicKey,\n shaVersion\n )\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(\n dataOwner: DataOwnerWithType,\n ancestorsKeys: { [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }\n ): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprints = {\n 'sha-1': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n 'sha-256': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n }\n const loadedKeys =\n pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (\n loadedKeysFingerprints.length !== pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length &&\n (loadedKeysFingerprints.length > 0 || Object.keys(ancestorsKeys).length > 0)\n ) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint({ ...loadedKeys, ...ancestorsKeys }))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [fingerprintV1(k), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}