@icure/api 8.0.49 → 8.0.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/icc-api/model/ExternalFilterKey.d.ts +10 -0
- package/icc-api/model/ExternalFilterKey.js +3 -0
- package/icc-api/model/ExternalFilterKey.js.map +1 -0
- package/icc-x-api/crypto/ConfidentialEntities.js +1 -1
- package/icc-x-api/crypto/ConfidentialEntities.js.map +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js +5 -2
- package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtils.d.ts +5 -8
- package/icc-x-api/crypto/ExtendedApisUtils.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.d.ts +5 -5
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +4 -14
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/icc-x-api/crypto/utils.js +5 -2
- package/icc-x-api/crypto/utils.js.map +1 -1
- package/icc-x-api/filters/ExternalViewFilterCode.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterCode.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterCode.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterContact.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterContact.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterContact.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterDevice.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterDevice.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterDevice.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterHealthElement.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterHealthElement.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterHealthElement.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterHealthcareParty.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterHealthcareParty.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterHealthcareParty.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterInvoice.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterInvoice.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterInvoice.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterMaintenanceTask.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterMaintenanceTask.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterMaintenanceTask.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterMessage.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterMessage.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterMessage.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterPatient.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterPatient.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterPatient.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterService.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterService.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterService.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterTopic.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterTopic.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterTopic.js.map +1 -0
- package/icc-x-api/filters/ExternalViewFilterUser.d.ts +12 -0
- package/icc-x-api/filters/ExternalViewFilterUser.js +14 -0
- package/icc-x-api/filters/ExternalViewFilterUser.js.map +1 -0
- package/icc-x-api/icc-accesslog-x-api.d.ts +6 -0
- package/icc-x-api/icc-accesslog-x-api.js +9 -3
- package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
- package/icc-x-api/icc-calendar-item-x-api.d.ts +6 -0
- package/icc-x-api/icc-calendar-item-x-api.js +9 -3
- package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
- package/icc-x-api/icc-classification-x-api.d.ts +6 -0
- package/icc-x-api/icc-classification-x-api.js +9 -3
- package/icc-x-api/icc-classification-x-api.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.d.ts +6 -0
- package/icc-x-api/icc-contact-x-api.js +9 -3
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/icc-document-x-api.d.ts +6 -0
- package/icc-x-api/icc-document-x-api.js +9 -3
- package/icc-x-api/icc-document-x-api.js.map +1 -1
- package/icc-x-api/icc-form-x-api.d.ts +6 -0
- package/icc-x-api/icc-form-x-api.js +9 -3
- package/icc-x-api/icc-form-x-api.js.map +1 -1
- package/icc-x-api/icc-helement-x-api.d.ts +6 -0
- package/icc-x-api/icc-helement-x-api.js +9 -3
- package/icc-x-api/icc-helement-x-api.js.map +1 -1
- package/icc-x-api/icc-invoice-x-api.d.ts +6 -0
- package/icc-x-api/icc-invoice-x-api.js +9 -3
- package/icc-x-api/icc-invoice-x-api.js.map +1 -1
- package/icc-x-api/icc-maintenance-task-x-api.d.ts +6 -0
- package/icc-x-api/icc-maintenance-task-x-api.js +9 -3
- package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
- package/icc-x-api/icc-message-x-api.js +5 -2
- package/icc-x-api/icc-message-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.js +5 -2
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/icc-x-api/icc-receipt-x-api.d.ts +6 -0
- package/icc-x-api/icc-receipt-x-api.js +9 -3
- package/icc-x-api/icc-receipt-x-api.js.map +1 -1
- package/icc-x-api/icc-time-table-x-api.d.ts +6 -0
- package/icc-x-api/icc-time-table-x-api.js +9 -3
- package/icc-x-api/icc-time-table-x-api.js.map +1 -1
- package/icc-x-api/icc-topic-x-api.d.ts +6 -0
- package/icc-x-api/icc-topic-x-api.js +9 -3
- package/icc-x-api/icc-topic-x-api.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/cryp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AG,CAAC,EAAE;YAC/B,IAAI,oBAAoB,EAAE;gBACxB,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;oBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;aACF;;gBAAM,OAAO,KAAK,CAAA;SACpB;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AAr0BD,sDAq0BC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { b2a, encryptObject, decryptObject, hex2ua, truncateTrailingNulls, ua2utf8, utf8_2ua, EncryptedFieldsManifest } from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { asyncGeneratorToArray } from '../utils/collection-utils'\nimport { SecurityMetadataDecryptor, SecurityMetadataDecryptorChain } from './SecurityMetadataDecryptor'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { SecureDelegationsManager } from './SecureDelegationsManager'\nimport { LegacyDelegationSecurityMetadataDecryptor } from './LegacyDelegationSecurityMetadataDecryptor'\nimport { SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { ShareResult, ShareResultFailure, ShareResultSuccess } from '../utils/ShareResult'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { IccUserXApi } from '../icc-user-x-api'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this class is for internal use only and may be changed without notice.\n * Methods to support extended apis.\n */\nexport class ExtendedApisUtilsImpl implements ExtendedApisUtils {\n private readonly allSecurityMetadataDecryptor: SecurityMetadataDecryptor\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly legacyDelMetadataDecryptor: LegacyDelegationSecurityMetadataDecryptor,\n private readonly secDelMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {\n this.allSecurityMetadataDecryptor = new SecurityMetadataDecryptorChain([legacyDelMetadataDecryptor, secDelMetadataDecryptor])\n }\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.allSecurityMetadataDecryptor.getEntityAccessLevel(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())) ===\n AccessLevel.WRITE\n )\n }\n\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n initialiseSecretId: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<{ updatedEntity: T; rawEncryptionKey: string | undefined; secretId: string | undefined }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const newRawKey = initialiseEncryptionKey ? await this.primitives.AES.generateCryptoKey(true) : undefined\n const newSecretId = initialiseSecretId ? this.primitives.randomUuid() : undefined\n return {\n updatedEntity: await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: owningEntitySecretId ? [owningEntitySecretId] : [],\n },\n entityType,\n newSecretId ? [newSecretId] : [],\n !!owningEntity ? [owningEntity] : [],\n newRawKey ? [newRawKey] : [],\n autoDelegations\n ),\n rawEncryptionKey: newRawKey,\n secretId: newSecretId,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updatedEntities: T[] = []\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n if (result.updatedEntity) {\n updatedEntities.push(result.updatedEntity)\n }\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n // TODO implement auto-retry for failed requests if the shouldRetry flag in result.rejectedRequests is set to true\n return {\n updatedEntities,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n const successfulRequests = Object.entries(allRequestsByEntityId)\n .flatMap(([entityId, requests]) => Object.keys(requests).map((delegateId) => ({ entityId, delegateId })))\n .filter(({ entityId, delegateId }) => !updateErrors.some((error) => error.entityId === entityId && error.delegateId === delegateId))\n return {\n successfulUpdates: successfulRequests,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n private async prepareBulkShareRequests(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[]\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n allRequestsByEntityId: { [entityId: string]: EntityRequestInformation }\n orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n }\n }> {\n if (new Set(entitiesUpdates.map((e) => e.entity.id)).size !== entitiesUpdates.length) {\n throw new Error('Duplicate requests: the same entity id is present more than once in the input')\n }\n const allRequestsByEntityId = {} as { [entityId: string]: EntityRequestInformation }\n const orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n } = {}\n const unmodifiedEntitiesIds: string[] = []\n for (const { entity, dataForDelegates } of entitiesUpdates) {\n const entityId = entity.id\n if (!entityId) throw new Error('Share of an entity requires for the entity to already exist and have an id')\n const entityWithType = { entity, type: entitiesType }\n const currentRequests = {} as { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n const currentOrderedRequests: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[] = []\n const migrationRequests = await this.makeMigrationRequestsIfNeeded(entityWithType, dataForDelegates)\n for (const [delegate, request] of Object.entries(migrationRequests)) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: dataForDelegates[delegate],\n updatedForMigration: true,\n })\n }\n for (const [delegate, userRequest] of Object.entries(dataForDelegates)) {\n if (!migrationRequests[delegate]) {\n const request = await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entityWithType,\n delegate,\n userRequest.shareSecretIds ?? [],\n userRequest.shareEncryptionKeys ?? [],\n userRequest.shareOwningEntityIds ?? [],\n userRequest.requestedPermissions\n )\n if (request) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: userRequest,\n updatedForMigration: false,\n })\n }\n }\n }\n if (Object.keys(currentRequests).length > 0) {\n const existingDelegationMembersDetails = await this.secDelMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const accessibleMembers = new Set(\n this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n )\n const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {\n if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {\n return [k]\n } else return []\n })\n allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations }\n orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests\n } else {\n unmodifiedEntitiesIds.push(entityId)\n }\n }\n return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId }\n }\n\n async simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n unusedSecretIds: boolean,\n delegates: {\n [delegateId: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>> {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let availableSecretIds: string[] | undefined\n if (unusedSecretIds) {\n availableSecretIds = await this.secretIdsOf(entity)\n }\n const dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n for (const [delegateId, delegateRequests] of Object.entries(delegates)) {\n if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no encryption keys or the current data owner can't access any encryption keys, but sharing is required.`\n )\n }\n if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`\n )\n }\n if (!delegateRequests.shareSecretIds && !unusedSecretIds) {\n throw new Error(`Share secret ids parameter is mandatory for entities of type ${entity.type}.`)\n } else if (delegateRequests.shareSecretIds && unusedSecretIds) {\n throw new Error(`Share secret ids parameter must not be unused with entities of type ${entity.type}.`)\n }\n dataForDelegates[delegateId] = {\n shareSecretIds: delegateRequests.shareSecretIds ?? availableSecretIds!,\n shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,\n shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,\n requestedPermissions: delegateRequests.requestedPermissions ?? RequestedPermissionEnum.MAX_WRITE,\n }\n }\n const shareResult = await this.bulkShareOrUpdateEncryptedEntityMetadata(\n entity.type,\n [\n {\n entity: entity.entity,\n dataForDelegates,\n },\n ],\n (x) => doRequestBulkShareOrUpdate(x)\n )\n if (shareResult.unmodifiedEntitiesIds.includes(entity.entity.id!)) {\n return new ShareResultSuccess(entity.entity)\n }\n if (!shareResult.updateErrors.length && shareResult.updatedEntities.length === 1) {\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n const requestedDelegates = new Set(Object.keys(delegates))\n const errorsOfRequestedDelegates = shareResult.updateErrors.filter((x) => requestedDelegates.has(x.delegateId))\n if (errorsOfRequestedDelegates.length === 0 && shareResult.updatedEntities.length === 1) {\n console.warn(`Errors with migration of encrypted metadata ${JSON.stringify(shareResult.updateErrors)}.`)\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n return new ShareResultFailure(\n shareResult.updateErrors,\n `There was an error sharing entity with id ${entity.entity.id}. Check the logs for more details.`\n )\n }\n\n private async makeMigrationRequestsIfNeeded(\n entity: EncryptedEntityWithType,\n userRequestsForEntity: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n ): Promise<{ [delegateId: string]: EntityShareOrMetadataUpdateRequest }> {\n const hierarchy = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const legacySecretIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, hierarchy))\n const legacyEncryptionKeys = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptEncryptionKeysOf(entity, hierarchy))\n const legacyOwningEntityIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, hierarchy))\n const res = {} as { [delegateId: string]: EntityShareOrMetadataUpdateRequest }\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n for (const hierarchyMember of hierarchy) {\n const hierarchyMemberMigration = await this.makeMigrationRequestForMemberOfHierarchy(\n entity,\n selfId,\n hierarchyMember,\n userRequestsForEntity[hierarchyMember],\n legacySecretIds,\n legacyEncryptionKeys,\n legacyOwningEntityIds\n )\n if (hierarchyMemberMigration) {\n res[hierarchyMember] = hierarchyMemberMigration\n }\n }\n return res\n }\n\n private async makeMigrationRequestForMemberOfHierarchy(\n entity: EncryptedEntityWithType,\n selfId: string,\n currMemberId: string,\n userRequestForDelegate:\n | {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n | undefined,\n legacySecretIds: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyEncryptionKeys: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyOwningEntityIds: { decrypted: string; dataOwnersWithAccess: string[] }[]\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n // This implementation is very specific from migration from delegations to secure delegations. If in future we will have to migrate from secure delegations to something else, this method may need significant changes in its logic.\n const subHierarchy = this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(currMemberId) : [currMemberId]\n const subHierarchySet = new Set(subHierarchy)\n const legacyAccess =\n selfId === entity.entity.id && currMemberId === selfId\n ? AccessLevel.WRITE\n : await this.legacyDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy)\n if (!legacyAccess) return undefined\n const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d))).map((x) => x.decrypted)\n const selfLegacyEncryptionKeys = legacyEncryptionKeys\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n const selfLegacyOwningEntityIds = legacyOwningEntityIds\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n let missingSecretIds: string[] = []\n let missingEncryptionKeys: string[] = []\n let missingOwningEntityIds: string[] = []\n if (selfLegacySecretIds.length > 0) {\n const currentSecretIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptSecretIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptEncryptionKeysOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id && currMemberId === selfId && !(await this.secDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy))\n if (missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0 || mustCreateRootDelegation) {\n let requestedPermissions: RequestedPermissionInternal\n if (currMemberId === selfId) {\n requestedPermissions = RequestedPermissionInternal.ROOT\n } else {\n requestedPermissions = RequestedPermissionInternal.FULL_WRITE // Legacy permission if present is always write\n }\n return await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entity,\n currMemberId,\n Array.from(new Set([...missingSecretIds, ...(userRequestForDelegate?.shareSecretIds ?? [])])),\n Array.from(new Set([...missingEncryptionKeys, ...(userRequestForDelegate?.shareEncryptionKeys ?? [])])),\n Array.from(new Set([...missingOwningEntityIds, ...(userRequestForDelegate?.shareOwningEntityIds ?? [])])),\n requestedPermissions\n )\n } else return undefined\n }\n\n async tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n const triedKeys: Set<string> = new Set()\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n if (!triedKeys.has(latest.value.decrypted)) {\n triedKeys.add(latest.value.decrypted)\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(latest.value.decrypted, content)\n if (!validator || (await validator(decrypted))) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n console.warn(`Error while decrypting with raw key ${latest.value}: ${e}`)\n }\n }\n latest = await decryptedKeys.next()\n }\n return { data: content, wasDecrypted: false }\n }\n\n async encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }> {\n const ensureInitialisedKeysResult = await this.ensureEncryptionKeysInitialised(entity, type)\n let updatedEntity: T | undefined\n if (!!ensureInitialisedKeysResult) {\n updatedEntity = await saveEntity(ensureInitialisedKeysResult)\n }\n\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf({ entity: updatedEntity ?? entity, type }, dataOwnerIds)\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n try {\n return { encryptedData: await this.primitives.AES.encryptWithRawKey(latest.value.decrypted, content), updatedEntity: updatedEntity }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${latest.value}: ${e}`)\n }\n latest = await decryptedKeys.next()\n }\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.decryptAndImportAllDecryptionKeys({ entity: entity, type: entityType })\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return undefined\n }\n\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity, entityType)\n const updatedEntity = entityWithInitialisedEncryptionKeys ? entityWithInitialisedEncryptionKeys : entity\n const encryptionKey = await this.tryImportFirstValidKey({ entity, type: entityType })\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n updatedEntity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n entityType\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity)) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * Add encryption key and share with all auto-delegates already in legacy delegations.\n * TODO disable this logic and simply throw error for post-2018 customers.\n */\n const existingDelegations = new Set(Object.keys(entity.delegations ?? {}))\n const usersWithAccessToNewKey = Object.fromEntries(\n Object.values((await this.userApi.getCurrentUser()).autoDelegations ?? {})\n .flatMap((x) => x)\n .filter((x) => existingDelegations.has(x))\n .map((x) => [x, AccessLevelEnum.WRITE])\n )\n return await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: entity.secretForeignKeys ?? [],\n },\n entityType,\n [],\n [],\n [await this.primitives.AES.generateCryptoKey(true)],\n usersWithAccessToNewKey\n )\n }\n\n private async decryptHierarchy(\n entity: EncryptedEntityWithType,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, canDecryptOwnerIds))\n return canDecryptOwnerIds.map((ownerId) => {\n const extracted = this.deduplicate(decryptedData.filter((x) => x.dataOwnersWithAccess.some((o) => o === ownerId)).map((x) => x.decrypted))\n return { ownerId, extracted }\n })\n }\n\n private async decryptAndMergeHierarchy(\n entity: EncryptedEntityWithType,\n dataOwnerId: string | undefined,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, hierarchy))\n return this.deduplicate(decryptedData.map((x) => x.decrypted))\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n async decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]> {\n const keys = this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity.entity)\n ? await this.encryptionKeysOf(entity)\n : this.deduplicate(\n await asyncGeneratorToArray(\n this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())\n ).then((secretIdsInfo) => secretIdsInfo.map(({ decrypted }) => decrypted))\n )\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n async decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(entity)\n if (!res) throw new Error(`Could not find any valid key for entity ${entity.entity.id} (${entity.type}).`)\n return res\n }\n\n private async tryImportFirstValidKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string } | undefined> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const generator = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n let latest = await generator.next()\n while (!latest.done) {\n const imported = await this.tryImportKey(latest.value.decrypted)\n if (imported) return { key: imported, raw: latest.value.decrypted }\n latest = await generator.next()\n }\n return undefined\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n argsArray.forEach((arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n this.doCheckEmptyEncryptionMetadata(entity, true)\n }\n\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean {\n return this.doCheckEmptyEncryptionMetadata(entity, false)\n }\n\n private doCheckEmptyEncryptionMetadata(entity: EncryptedEntity, throwErrorIfNonEmpty: boolean): boolean {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (entity.securityMetadata && Object.keys(entity.securityMetadata).length) existingMetadata.push('securityMetadata')\n if (existingMetadata.length > 0) {\n if (throwErrorIfNonEmpty) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n } else return false\n }\n return true\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAAuI;AAEvI,gEAAiE;AACjE,2EAAuG;AAEvG,2EAAuE;AAIvE,wFAAoF;AAIpF,sDAA0F;AAC1F,qEAAiE;AAGjE,IAAO,WAAW,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACrD,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAC3E,IAAO,2BAA2B,GAAG,uCAAkB,CAAC,2BAA2B,CAAA;AACnF,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAGzD;;;GAGG;AACH,MAAa,qBAAqB;IAGhC,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,0BAAqE,EACrE,uBAAmE,EACnE,wBAAkD,EAClD,OAAoB,EACpB,aAAsB;QANtB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M,CAAC,iBAAiB,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;QAC3G,IAAI,MAAM,CAAC,gBAAgB,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;QACrH,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,IAAI,oBAAoB,EAAE;gBACxB,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;oBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;aACF;;gBAAM,OAAO,KAAK,CAAA;SACpB;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA1zBD,sDA0zBC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { b2a, encryptObject, decryptObject, hex2ua, truncateTrailingNulls, ua2utf8, utf8_2ua, EncryptedFieldsManifest } from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { asyncGeneratorToArray } from '../utils/collection-utils'\nimport { SecurityMetadataDecryptor, SecurityMetadataDecryptorChain } from './SecurityMetadataDecryptor'\nimport { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { SecureDelegationsManager } from './SecureDelegationsManager'\nimport { LegacyDelegationSecurityMetadataDecryptor } from './LegacyDelegationSecurityMetadataDecryptor'\nimport { SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { ShareResult, ShareResultFailure, ShareResultSuccess } from '../utils/ShareResult'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { IccUserXApi } from '../icc-user-x-api'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n/**\n * @internal this class is for internal use only and may be changed without notice.\n * Methods to support extended apis.\n */\nexport class ExtendedApisUtilsImpl implements ExtendedApisUtils {\n private readonly allSecurityMetadataDecryptor: SecurityMetadataDecryptor\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly legacyDelMetadataDecryptor: LegacyDelegationSecurityMetadataDecryptor,\n private readonly secDelMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {\n this.allSecurityMetadataDecryptor = new SecurityMetadataDecryptorChain([legacyDelMetadataDecryptor, secDelMetadataDecryptor])\n }\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptSecretIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(entity, dataOwnerId, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy(entity, (entityWithType, hierarchy) =>\n this.allSecurityMetadataDecryptor.decryptOwningEntityIdsOf(entityWithType, hierarchy)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.allSecurityMetadataDecryptor.getEntityAccessLevel(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())) ===\n AccessLevel.WRITE\n )\n }\n\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKey: boolean,\n autoDelegations: { [p: string]: SecureDelegation.AccessLevelEnum }\n ): Promise<{ updatedEntity: T; rawEncryptionKey: string | undefined; secretId: string }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const newRawKey = initialiseEncryptionKey ? await this.primitives.AES.generateCryptoKey(true) : undefined\n const newSecretId = this.primitives.randomUuid()\n return {\n updatedEntity: await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: owningEntitySecretId ? [owningEntitySecretId] : [],\n },\n entityType,\n newSecretId ? [newSecretId] : [],\n !!owningEntity ? [owningEntity] : [],\n newRawKey ? [newRawKey] : [],\n autoDelegations\n ),\n rawEncryptionKey: newRawKey,\n secretId: newSecretId,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<{\n updatedEntities: T[]\n unmodifiedEntitiesIds: string[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updatedEntities: T[] = []\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n if (result.updatedEntity) {\n updatedEntities.push(result.updatedEntity)\n }\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n // TODO implement auto-retry for failed requests if the shouldRetry flag in result.rejectedRequests is set to true\n return {\n updatedEntities,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n const successfulRequests = Object.entries(allRequestsByEntityId)\n .flatMap(([entityId, requests]) => Object.keys(requests).map((delegateId) => ({ entityId, delegateId })))\n .filter(({ entityId, delegateId }) => !updateErrors.some((error) => error.entityId === entityId && error.delegateId === delegateId))\n return {\n successfulUpdates: successfulRequests,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n private async prepareBulkShareRequests(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[]\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n allRequestsByEntityId: { [entityId: string]: EntityRequestInformation }\n orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n }\n }> {\n if (new Set(entitiesUpdates.map((e) => e.entity.id)).size !== entitiesUpdates.length) {\n throw new Error('Duplicate requests: the same entity id is present more than once in the input')\n }\n const allRequestsByEntityId = {} as { [entityId: string]: EntityRequestInformation }\n const orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n } = {}\n const unmodifiedEntitiesIds: string[] = []\n for (const { entity, dataForDelegates } of entitiesUpdates) {\n const entityId = entity.id\n if (!entityId) throw new Error('Share of an entity requires for the entity to already exist and have an id')\n const entityWithType = { entity, type: entitiesType }\n const currentRequests = {} as { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n const currentOrderedRequests: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[] = []\n const migrationRequests = await this.makeMigrationRequestsIfNeeded(entityWithType, dataForDelegates)\n for (const [delegate, request] of Object.entries(migrationRequests)) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: dataForDelegates[delegate],\n updatedForMigration: true,\n })\n }\n for (const [delegate, userRequest] of Object.entries(dataForDelegates)) {\n if (!migrationRequests[delegate]) {\n const request = await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entityWithType,\n delegate,\n userRequest.shareSecretIds ?? [],\n userRequest.shareEncryptionKeys ?? [],\n userRequest.shareOwningEntityIds ?? [],\n userRequest.requestedPermissions\n )\n if (request) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: userRequest,\n updatedForMigration: false,\n })\n }\n }\n }\n if (Object.keys(currentRequests).length > 0) {\n const existingDelegationMembersDetails = await this.secDelMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const accessibleMembers = new Set(\n this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n )\n const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {\n if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {\n return [k]\n } else return []\n })\n allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations }\n orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests\n } else {\n unmodifiedEntitiesIds.push(entityId)\n }\n }\n return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId }\n }\n\n async simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n delegates: {\n [p: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>> {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n const dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n for (const [delegateId, delegateRequests] of Object.entries(delegates)) {\n if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no encryption keys or the current data owner can't access any encryption keys, but sharing is required.`\n )\n }\n if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`\n )\n }\n dataForDelegates[delegateId] = {\n shareSecretIds: delegateRequests.shareSecretIds ?? (await this.secretIdsOf(entity)),\n shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,\n shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,\n requestedPermissions: delegateRequests.requestedPermissions ?? RequestedPermissionEnum.MAX_WRITE,\n }\n }\n const shareResult = await this.bulkShareOrUpdateEncryptedEntityMetadata(\n entity.type,\n [\n {\n entity: entity.entity,\n dataForDelegates,\n },\n ],\n (x) => doRequestBulkShareOrUpdate(x)\n )\n if (shareResult.unmodifiedEntitiesIds.includes(entity.entity.id!)) {\n return new ShareResultSuccess(entity.entity)\n }\n if (!shareResult.updateErrors.length && shareResult.updatedEntities.length === 1) {\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n const requestedDelegates = new Set(Object.keys(delegates))\n const errorsOfRequestedDelegates = shareResult.updateErrors.filter((x) => requestedDelegates.has(x.delegateId))\n if (errorsOfRequestedDelegates.length === 0 && shareResult.updatedEntities.length === 1) {\n console.warn(`Errors with migration of encrypted metadata ${JSON.stringify(shareResult.updateErrors)}.`)\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n return new ShareResultFailure(\n shareResult.updateErrors,\n `There was an error sharing entity with id ${entity.entity.id}. Check the logs for more details.`\n )\n }\n\n private async makeMigrationRequestsIfNeeded(\n entity: EncryptedEntityWithType,\n userRequestsForEntity: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n ): Promise<{ [delegateId: string]: EntityShareOrMetadataUpdateRequest }> {\n const hierarchy = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const legacySecretIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, hierarchy))\n const legacyEncryptionKeys = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptEncryptionKeysOf(entity, hierarchy))\n const legacyOwningEntityIds = await asyncGeneratorToArray(this.legacyDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, hierarchy))\n const res = {} as { [delegateId: string]: EntityShareOrMetadataUpdateRequest }\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n for (const hierarchyMember of hierarchy) {\n const hierarchyMemberMigration = await this.makeMigrationRequestForMemberOfHierarchy(\n entity,\n selfId,\n hierarchyMember,\n userRequestsForEntity[hierarchyMember],\n legacySecretIds,\n legacyEncryptionKeys,\n legacyOwningEntityIds\n )\n if (hierarchyMemberMigration) {\n res[hierarchyMember] = hierarchyMemberMigration\n }\n }\n return res\n }\n\n private async makeMigrationRequestForMemberOfHierarchy(\n entity: EncryptedEntityWithType,\n selfId: string,\n currMemberId: string,\n userRequestForDelegate:\n | {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n | undefined,\n legacySecretIds: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyEncryptionKeys: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyOwningEntityIds: { decrypted: string; dataOwnersWithAccess: string[] }[]\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n // This implementation is very specific from migration from delegations to secure delegations. If in future we will have to migrate from secure delegations to something else, this method may need significant changes in its logic.\n const subHierarchy = this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(currMemberId) : [currMemberId]\n const subHierarchySet = new Set(subHierarchy)\n const legacyAccess =\n selfId === entity.entity.id && currMemberId === selfId\n ? AccessLevel.WRITE\n : await this.legacyDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy)\n if (!legacyAccess) return undefined\n const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d))).map((x) => x.decrypted)\n const selfLegacyEncryptionKeys = legacyEncryptionKeys\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n const selfLegacyOwningEntityIds = legacyOwningEntityIds\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n let missingSecretIds: string[] = []\n let missingEncryptionKeys: string[] = []\n let missingOwningEntityIds: string[] = []\n if (selfLegacySecretIds.length > 0) {\n const currentSecretIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptSecretIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptEncryptionKeysOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await asyncGeneratorToArray(this.secDelMetadataDecryptor.decryptOwningEntityIdsOf(entity, [currMemberId]))).map((x) => x.decrypted)\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id && currMemberId === selfId && !(await this.secDelMetadataDecryptor.getEntityAccessLevel(entity, subHierarchy))\n if (missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0 || mustCreateRootDelegation) {\n let requestedPermissions: RequestedPermissionInternal\n if (currMemberId === selfId) {\n requestedPermissions = RequestedPermissionInternal.ROOT\n } else {\n requestedPermissions = RequestedPermissionInternal.FULL_WRITE // Legacy permission if present is always write\n }\n return await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entity,\n currMemberId,\n Array.from(new Set([...missingSecretIds, ...(userRequestForDelegate?.shareSecretIds ?? [])])),\n Array.from(new Set([...missingEncryptionKeys, ...(userRequestForDelegate?.shareEncryptionKeys ?? [])])),\n Array.from(new Set([...missingOwningEntityIds, ...(userRequestForDelegate?.shareOwningEntityIds ?? [])])),\n requestedPermissions\n )\n } else return undefined\n }\n\n async tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n const triedKeys: Set<string> = new Set()\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n if (!triedKeys.has(latest.value.decrypted)) {\n triedKeys.add(latest.value.decrypted)\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(latest.value.decrypted, content)\n if (!validator || (await validator(decrypted))) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n console.warn(`Error while decrypting with raw key ${latest.value}: ${e}`)\n }\n }\n latest = await decryptedKeys.next()\n }\n return { data: content, wasDecrypted: false }\n }\n\n async encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }> {\n const ensureInitialisedKeysResult = await this.ensureEncryptionKeysInitialised(entity, type)\n let updatedEntity: T | undefined\n if (!!ensureInitialisedKeysResult) {\n updatedEntity = await saveEntity(ensureInitialisedKeysResult)\n }\n\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const decryptedKeys = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf({ entity: updatedEntity ?? entity, type }, dataOwnerIds)\n let latest = await decryptedKeys.next()\n while (!latest.done) {\n try {\n return { encryptedData: await this.primitives.AES.encryptWithRawKey(latest.value.decrypted, content), updatedEntity: updatedEntity }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${latest.value}: ${e}`)\n }\n latest = await decryptedKeys.next()\n }\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n if (!entity.encryptedSelf) return { entity, decrypted: true }\n const encryptionKeys = await this.decryptAndImportAllDecryptionKeys({ entity: entity, type: entityType })\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return undefined\n }\n\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity, entityType)\n const updatedEntity = entityWithInitialisedEncryptionKeys ? entityWithInitialisedEncryptionKeys : entity\n const encryptionKey = await this.tryImportFirstValidKey({ entity, type: entityType })\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n updatedEntity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n entityType\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity)) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * Add encryption key and share with all auto-delegates already in legacy delegations.\n * TODO disable this logic and simply throw error for post-2018 customers.\n */\n const existingDelegations = new Set(Object.keys(entity.delegations ?? {}))\n const usersWithAccessToNewKey = Object.fromEntries(\n Object.values((await this.userApi.getCurrentUser()).autoDelegations ?? {})\n .flatMap((x) => x)\n .filter((x) => existingDelegations.has(x))\n .map((x) => [x, AccessLevelEnum.WRITE])\n )\n return await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: entity.secretForeignKeys ?? [],\n },\n entityType,\n [],\n [],\n [await this.primitives.AES.generateCryptoKey(true)],\n usersWithAccessToNewKey\n )\n }\n\n private async decryptHierarchy(\n entity: EncryptedEntityWithType,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, canDecryptOwnerIds))\n return canDecryptOwnerIds.map((ownerId) => {\n const extracted = this.deduplicate(decryptedData.filter((x) => x.dataOwnersWithAccess.some((o) => o === ownerId)).map((x) => x.decrypted))\n return { ownerId, extracted }\n })\n }\n\n private async decryptAndMergeHierarchy(\n entity: EncryptedEntityWithType,\n dataOwnerId: string | undefined,\n decryptedDataGeneratorProvider: (\n entityWithType: EncryptedEntityWithType,\n dataOwners: string[]\n ) => AsyncGenerator<{ decrypted: string; dataOwnersWithAccess: string[] }, void, never>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const decryptedData = await asyncGeneratorToArray(decryptedDataGeneratorProvider(entity, hierarchy))\n return this.deduplicate(decryptedData.map((x) => x.decrypted))\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n async decryptAndImportAllDecryptionKeys(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }[]> {\n const keys = this.allSecurityMetadataDecryptor.hasAnyEncryptionKeys(entity.entity)\n ? await this.encryptionKeysOf(entity)\n : this.deduplicate(\n await asyncGeneratorToArray(\n this.legacyDelMetadataDecryptor.decryptSecretIdsOf(entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())\n ).then((secretIdsInfo) => secretIdsInfo.map(({ decrypted }) => decrypted))\n )\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n async decryptAndImportAnyEncryptionKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(entity)\n if (!res) throw new Error(`Could not find any valid key for entity ${entity.entity.id} (${entity.type}).`)\n return res\n }\n\n private async tryImportFirstValidKey(entity: EncryptedEntityWithType): Promise<{ key: CryptoKey; raw: string } | undefined> {\n const dataOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n\n const generator = this.allSecurityMetadataDecryptor.decryptEncryptionKeysOf(entity, dataOwnerIds)\n let latest = await generator.next()\n while (!latest.done) {\n const imported = await this.tryImportKey(latest.value.decrypted)\n if (imported) return { key: imported, raw: latest.value.decrypted }\n latest = await generator.next()\n }\n return undefined\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n argsArray.forEach((arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n this.doCheckEmptyEncryptionMetadata(entity, true)\n }\n\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean {\n return this.doCheckEmptyEncryptionMetadata(entity, false)\n }\n\n private doCheckEmptyEncryptionMetadata(entity: EncryptedEntity, throwErrorIfNonEmpty: boolean): boolean {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (entity.securityMetadata && Object.keys(entity.securityMetadata).length) existingMetadata.push('securityMetadata')\n if (existingMetadata.length > 0) {\n if (throwErrorIfNonEmpty) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n } else return false\n }\n return true\n }\n}\n"]}
|
|
@@ -104,11 +104,14 @@ function ensureDelegationForSelf(dataOwnerApi, xapi, patientApi, cryptoPrimitive
|
|
|
104
104
|
else {
|
|
105
105
|
if (xapi.hasEmptyEncryptionMetadata(patient)) {
|
|
106
106
|
// This should not really happen, usually some user will have already initialised the patient and its encryption metadata.
|
|
107
|
-
const updatedPatient = yield xapi.entityWithInitialisedEncryptedMetadata(patient, utils_1.EntityWithDelegationTypeName.Patient, undefined, undefined, true,
|
|
107
|
+
const updatedPatient = yield xapi.entityWithInitialisedEncryptedMetadata(patient, utils_1.EntityWithDelegationTypeName.Patient, undefined, undefined, true, {});
|
|
108
108
|
return { dataOwner: yield patientApi.modifyPatient(updatedPatient.updatedEntity), type: DataOwnerTypeEnum_1.DataOwnerTypeEnum.Patient };
|
|
109
109
|
}
|
|
110
110
|
else {
|
|
111
|
-
const updatedPatient = yield xapi.simpleShareOrUpdateEncryptedEntityMetadata({
|
|
111
|
+
const updatedPatient = yield xapi.simpleShareOrUpdateEncryptedEntityMetadata({
|
|
112
|
+
entity: patient,
|
|
113
|
+
type: utils_1.EntityWithDelegationTypeName.Patient,
|
|
114
|
+
}, {
|
|
112
115
|
[patient.id]: {
|
|
113
116
|
shareEncryptionKeys: ShareMetadataBehaviour_1.ShareMetadataBehaviour.IF_AVAILABLE,
|
|
114
117
|
shareOwningEntityIds: ShareMetadataBehaviour_1.ShareMetadataBehaviour.NEVER,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wBAAwB;AACxB,sDAAsF;AAEtF,+BAA4C;AAC5C,oCAA+D;AAC/D,yDAAqD;AAKrD,qEAAiE;AACjE,wFAAoF;AAEpF,6EAAyE;AACzE,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,SAAoB;;IAC5D,OAAO,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,MAAA,SAAS,CAAC,2BAA2B,mCAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAa,CAAC,CAAA;AAC7G,CAAC;AAFD,8DAEC;AAED;;;GAGG;AACH,SAAgB,uBAAuB,CAAC,SAAoB;;IAC1D,OAAO,IAAI,GAAG,CAAC,CAAC,SAAS,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,MAAA,SAAS,CAAC,eAAe,mCAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAa,CAAC,CAAA;AACjI,CAAC;AAFD,0DAEC;AAED;;;;;;GAMG;AACH,SAAgB,qBAAqB,CAAC,SAAoB;;IACxD,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,GAA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O,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAA;AACvB,CAAC;AAFD,sCAEC;AAED;;;;;;GAMG;AACH,SAAgB,aAAa,CAAC,GAAW;IACvC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAA;AAC5B,CAAC;AAFD,sCAEC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,EAAU;IAC1C,0GAA0G;IAC1G,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;AACxB,CAAC;AAHD,8CAGC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,yBAAyB,CAAC,EAAU;IAClD,OAAO,EAAE,GAAG,YAAY,CAAA;AAC1B,CAAC;AAFD,8DAEC;AAED;;;;GAIG;AACH,SAAgB,0BAA0B,CAAC,eAAuB;IAChE,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,IAAI,YAAY,EAAE;QAC9C,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAA;KAClF;AACH,CAAC;AAJD,gEAIC","sourcesContent":["// Uses fp as node names\nimport { acyclic, graphFromEdges, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { DataOwner, DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { RSAUtils, ShaVersion } from './RSA'\nimport { EntityWithDelegationTypeName, hex2ua } from '../utils'\nimport { Patient } from '../../icc-api/model/Patient'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedEntityWithType } from '../utils/EntityWithDelegationTypeName'\nimport { IccPatientApi } from '../../icc-api'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha256.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha256Of(dataOwner: DataOwner) {\n return new Set([...(dataOwner.publicKeysForOaepWithSha256 ?? [])].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha1.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha1Of(dataOwner: DataOwner) {\n return new Set([dataOwner.publicKey, ...Object.keys(dataOwner.aesExchangeKeys ?? {})].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get the transfer key graph for a data owner. Node names are the public key fingerprints of the data owner's keys, and an edge represents a key\n * which can be retrieved from another key using the transfer keys.\n * @param dataOwner a data owner.\n * @return a graph representing the possible key recovery paths using transfer keys for hte provided data owner.\n */\nexport function transferKeysFpGraphOf(dataOwner: DataOwner): StronglyConnectedGraph {\n const publicKeys = Array.from([...hexPublicKeysWithSha1Of(dataOwner), ...hexPublicKeysWithSha256Of(dataOwner)])\n const edges: [string, string][] = []\n Object.entries(dataOwner.transferKeys ?? {}).forEach(([from, tos]) => {\n Object.keys(tos).forEach((to) => {\n edges.push([fingerprintV1(from), fingerprintV1(to)])\n })\n })\n return acyclic(\n graphFromEdges(\n edges,\n publicKeys.map((x) => fingerprintV1(x))\n )\n )\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get a map for converting public keys fingerprint to full public keys for the provided data owner.\n * @param dataOwner a data owner.\n * @param shaVersion gets only the keys that are generated with this SHA version (default: 'sha-1').\n * @return a map to convert fingerprints of the data owner into full public keys.\n */\nexport function fingerprintToPublicKeysMapOf(dataOwner: DataOwner, shaVersion: ShaVersion): { [fp: string]: string } {\n const publicKeys = shaVersion === 'sha-1' ? Array.from(hexPublicKeysWithSha1Of(dataOwner)) : Array.from(hexPublicKeysWithSha256Of(dataOwner))\n const res: { [fp: string]: string } = {}\n publicKeys.forEach((pk) => {\n res[fingerprintV1(pk)] = pk\n })\n return res\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Load many public keys in spki format.\n * @param rsa the rsa service\n * @param publicKeysSpkiHex public keys in spki format, hex encoded.\n * @param shaVersion the version of the Sha algorithm used in the keys generations. ()\n * @return public keys as crypto keys by their fingerprint.\n */\nexport async function loadPublicKeys(\n rsa: RSAUtils,\n publicKeysSpkiHex: string[],\n shaVersion: ShaVersion\n): Promise<{ [publicKeyFingerprint: string]: CryptoKey }> {\n return Object.fromEntries(\n await Promise.all(publicKeysSpkiHex.map(async (x) => [fingerprintV1(x), await rsa.importKey('spki', hex2ua(x), ['encrypt'], shaVersion)]))\n )\n}\n\n/**\n * @internal This method is intended only for internal use and may be changed without notice.\n * Creates a delegation for the current data owner if the data owner is an encrypted entity and there is no delegation to himself.\n * @return the updated self.\n */\nexport async function ensureDelegationForSelf(\n dataOwnerApi: IccDataOwnerXApi,\n xapi: ExtendedApisUtils,\n patientApi: IccPatientApi,\n cryptoPrimitives: CryptoPrimitives\n): Promise<DataOwnerWithType> {\n const self = await dataOwnerApi.getCurrentDataOwner()\n if (self.type === 'patient') {\n const patient = new Patient(self.dataOwner)\n const patientWithType: EncryptedEntityWithType = { entity: patient, type: EntityWithDelegationTypeName.Patient }\n const availableSecretIds = await xapi.secretIdsOf(patientWithType, undefined)\n if (availableSecretIds.length) {\n return self\n } else {\n if (xapi.hasEmptyEncryptionMetadata(patient)) {\n // This should not really happen, usually some user will have already initialised the patient and its encryption metadata.\n const updatedPatient = await xapi.entityWithInitialisedEncryptedMetadata(\n patient,\n EntityWithDelegationTypeName.Patient,\n undefined,\n undefined,\n true,\n true,\n {}\n )\n return { dataOwner: await patientApi.modifyPatient(updatedPatient.updatedEntity), type: DataOwnerTypeEnum.Patient }\n } else {\n const updatedPatient = await xapi.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n false,\n {\n [patient.id!]: {\n shareEncryptionKeys: ShareMetadataBehaviour.IF_AVAILABLE,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [cryptoPrimitives.randomUuid()],\n requestedPermissions: RequestedPermissionEnum.FULL_WRITE,\n },\n },\n (x) => patientApi.bulkSharePatients(x)\n )\n return { dataOwner: updatedPatient.updatedEntityOrThrow, type: DataOwnerTypeEnum.Patient }\n }\n }\n } else {\n return self\n }\n}\n\n/**\n * Search a public key in the data owner and returns the corresponding SHA version used to generate it or undefined if not found.\n * @param dataOwner the data owner.\n * @param publicKey the public key.\n * @return 'sha-1', 'sha-256', undefined\n */\nexport function getShaVersionForKey(dataOwner: DataOwnerOrStub, publicKey: string): ShaVersion | undefined {\n return dataOwner.publicKey === publicKey || Object.keys(dataOwner.aesExchangeKeys ?? {}).includes(publicKey)\n ? ShaVersion.Sha1\n : !!dataOwner.publicKeysForOaepWithSha256?.includes(publicKey)\n ? ShaVersion.Sha256\n : undefined\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters)\n * of the SPKI key.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV1(key: string): string {\n return key.slice(-32)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters) from which the\n * last 5 (10 characters) are removed because they are a constant of the SPKI format.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV2(key: string): string {\n return key.slice(-32, -10)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Converts the fingerprint of a key from a V1 format to a V2 format.\n * @param fp the fingerprint of the key in the V1 format.\n * @return the fingerprint of the key in the v2 format.\n */\nexport function fingerprintV1toV2(fp: string): string {\n // Conversion resilient to mistakes: if the fingerprint is already in V2 format it will be returned as is.\n return fp.slice(0, 22)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V1 format, false otherwise.\n */\nexport function fingerprintIsV1(fp: string): boolean {\n return fp.length === 32\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V2 format, false otherwise.\n */\nexport function fingerprintIsV2(fp: string): boolean {\n return fp.length === 22\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint v2.\n * @return the fingerprint v1 using the standard tail.\n */\nexport function fingerprintV2ToStandardV1(fp: string): string {\n return fp + '0203010001'\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param publicKeyOrFpv1 a public key in spki format or a public key fp v1\n * @throws if the input does not terminate with 0203010001\n */\nexport function checkStandardPublicKeyTail(publicKeyOrFpv1: string) {\n if (publicKeyOrFpv1.slice(-10) != '0203010001') {\n throw new Error('Illegal state: generated public key should end with 0203010001')\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wBAAwB;AACxB,sDAAsF;AAEtF,+BAA4C;AAC5C,oCAA+D;AAC/D,yDAAqD;AAKrD,qEAAiE;AACjE,wFAAoF;AAEpF,6EAAyE;AACzE,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E;;;GAGG;AACH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C;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,yBAAyB,CAAC,EAAU;IAClD,OAAO,EAAE,GAAG,YAAY,CAAA;AAC1B,CAAC;AAFD,8DAEC;AAED;;;;GAIG;AACH,SAAgB,0BAA0B,CAAC,eAAuB;IAChE,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,IAAI,YAAY,EAAE;QAC9C,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAA;KAClF;AACH,CAAC;AAJD,gEAIC","sourcesContent":["// Uses fp as node names\nimport { acyclic, graphFromEdges, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { DataOwner, DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { RSAUtils, ShaVersion } from './RSA'\nimport { EntityWithDelegationTypeName, hex2ua } from '../utils'\nimport { Patient } from '../../icc-api/model/Patient'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedEntityWithType } from '../utils/EntityWithDelegationTypeName'\nimport { IccPatientApi } from '../../icc-api'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha256.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha256Of(dataOwner: DataOwner) {\n return new Set([...(dataOwner.publicKeysForOaepWithSha256 ?? [])].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha1.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha1Of(dataOwner: DataOwner) {\n return new Set([dataOwner.publicKey, ...Object.keys(dataOwner.aesExchangeKeys ?? {})].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get the transfer key graph for a data owner. Node names are the public key fingerprints of the data owner's keys, and an edge represents a key\n * which can be retrieved from another key using the transfer keys.\n * @param dataOwner a data owner.\n * @return a graph representing the possible key recovery paths using transfer keys for hte provided data owner.\n */\nexport function transferKeysFpGraphOf(dataOwner: DataOwner): StronglyConnectedGraph {\n const publicKeys = Array.from([...hexPublicKeysWithSha1Of(dataOwner), ...hexPublicKeysWithSha256Of(dataOwner)])\n const edges: [string, string][] = []\n Object.entries(dataOwner.transferKeys ?? {}).forEach(([from, tos]) => {\n Object.keys(tos).forEach((to) => {\n edges.push([fingerprintV1(from), fingerprintV1(to)])\n })\n })\n return acyclic(\n graphFromEdges(\n edges,\n publicKeys.map((x) => fingerprintV1(x))\n )\n )\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get a map for converting public keys fingerprint to full public keys for the provided data owner.\n * @param dataOwner a data owner.\n * @param shaVersion gets only the keys that are generated with this SHA version (default: 'sha-1').\n * @return a map to convert fingerprints of the data owner into full public keys.\n */\nexport function fingerprintToPublicKeysMapOf(dataOwner: DataOwner, shaVersion: ShaVersion): { [fp: string]: string } {\n const publicKeys = shaVersion === 'sha-1' ? Array.from(hexPublicKeysWithSha1Of(dataOwner)) : Array.from(hexPublicKeysWithSha256Of(dataOwner))\n const res: { [fp: string]: string } = {}\n publicKeys.forEach((pk) => {\n res[fingerprintV1(pk)] = pk\n })\n return res\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Load many public keys in spki format.\n * @param rsa the rsa service\n * @param publicKeysSpkiHex public keys in spki format, hex encoded.\n * @param shaVersion the version of the Sha algorithm used in the keys generations. ()\n * @return public keys as crypto keys by their fingerprint.\n */\nexport async function loadPublicKeys(\n rsa: RSAUtils,\n publicKeysSpkiHex: string[],\n shaVersion: ShaVersion\n): Promise<{ [publicKeyFingerprint: string]: CryptoKey }> {\n return Object.fromEntries(\n await Promise.all(publicKeysSpkiHex.map(async (x) => [fingerprintV1(x), await rsa.importKey('spki', hex2ua(x), ['encrypt'], shaVersion)]))\n )\n}\n\n/**\n * @internal This method is intended only for internal use and may be changed without notice.\n * Creates a delegation for the current data owner if the data owner is an encrypted entity and there is no delegation to himself.\n * @return the updated self.\n */\nexport async function ensureDelegationForSelf(\n dataOwnerApi: IccDataOwnerXApi,\n xapi: ExtendedApisUtils,\n patientApi: IccPatientApi,\n cryptoPrimitives: CryptoPrimitives\n): Promise<DataOwnerWithType> {\n const self = await dataOwnerApi.getCurrentDataOwner()\n if (self.type === 'patient') {\n const patient = new Patient(self.dataOwner)\n const patientWithType: EncryptedEntityWithType = { entity: patient, type: EntityWithDelegationTypeName.Patient }\n const availableSecretIds = await xapi.secretIdsOf(patientWithType, undefined)\n if (availableSecretIds.length) {\n return self\n } else {\n if (xapi.hasEmptyEncryptionMetadata(patient)) {\n // This should not really happen, usually some user will have already initialised the patient and its encryption metadata.\n const updatedPatient = await xapi.entityWithInitialisedEncryptedMetadata(\n patient,\n EntityWithDelegationTypeName.Patient,\n undefined,\n undefined,\n true,\n {}\n )\n return { dataOwner: await patientApi.modifyPatient(updatedPatient.updatedEntity), type: DataOwnerTypeEnum.Patient }\n } else {\n const updatedPatient = await xapi.simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: patient,\n type: EntityWithDelegationTypeName.Patient,\n },\n {\n [patient.id!]: {\n shareEncryptionKeys: ShareMetadataBehaviour.IF_AVAILABLE,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [cryptoPrimitives.randomUuid()],\n requestedPermissions: RequestedPermissionEnum.FULL_WRITE,\n },\n },\n (x) => patientApi.bulkSharePatients(x)\n )\n return { dataOwner: updatedPatient.updatedEntityOrThrow, type: DataOwnerTypeEnum.Patient }\n }\n }\n } else {\n return self\n }\n}\n\n/**\n * Search a public key in the data owner and returns the corresponding SHA version used to generate it or undefined if not found.\n * @param dataOwner the data owner.\n * @param publicKey the public key.\n * @return 'sha-1', 'sha-256', undefined\n */\nexport function getShaVersionForKey(dataOwner: DataOwnerOrStub, publicKey: string): ShaVersion | undefined {\n return dataOwner.publicKey === publicKey || Object.keys(dataOwner.aesExchangeKeys ?? {}).includes(publicKey)\n ? ShaVersion.Sha1\n : !!dataOwner.publicKeysForOaepWithSha256?.includes(publicKey)\n ? ShaVersion.Sha256\n : undefined\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters)\n * of the SPKI key.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV1(key: string): string {\n return key.slice(-32)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters) from which the\n * last 5 (10 characters) are removed because they are a constant of the SPKI format.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV2(key: string): string {\n return key.slice(-32, -10)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Converts the fingerprint of a key from a V1 format to a V2 format.\n * @param fp the fingerprint of the key in the V1 format.\n * @return the fingerprint of the key in the v2 format.\n */\nexport function fingerprintV1toV2(fp: string): string {\n // Conversion resilient to mistakes: if the fingerprint is already in V2 format it will be returned as is.\n return fp.slice(0, 22)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V1 format, false otherwise.\n */\nexport function fingerprintIsV1(fp: string): boolean {\n return fp.length === 32\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V2 format, false otherwise.\n */\nexport function fingerprintIsV2(fp: string): boolean {\n return fp.length === 22\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint v2.\n * @return the fingerprint v1 using the standard tail.\n */\nexport function fingerprintV2ToStandardV1(fp: string): string {\n return fp + '0203010001'\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param publicKeyOrFpv1 a public key in spki format or a public key fp v1\n * @throws if the input does not terminate with 0203010001\n */\nexport function checkStandardPublicKeyTail(publicKeyOrFpv1: string) {\n if (publicKeyOrFpv1.slice(-10) != '0203010001') {\n throw new Error('Illegal state: generated public key should end with 0203010001')\n }\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { AbstractFilterCode } from '../../icc-api/model/AbstractFilterCode';
|
|
2
|
+
import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey';
|
|
3
|
+
export declare class ExternalViewFilterCode extends AbstractFilterCode {
|
|
4
|
+
$type: string;
|
|
5
|
+
entityQualifiedName: string;
|
|
6
|
+
constructor(json: JSON | any);
|
|
7
|
+
view?: string;
|
|
8
|
+
partition?: string;
|
|
9
|
+
startKey?: ExternalFilterKey;
|
|
10
|
+
endKey?: ExternalFilterKey;
|
|
11
|
+
desc?: string;
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExternalViewFilterCode = void 0;
|
|
4
|
+
const AbstractFilterCode_1 = require("../../icc-api/model/AbstractFilterCode");
|
|
5
|
+
class ExternalViewFilterCode extends AbstractFilterCode_1.AbstractFilterCode {
|
|
6
|
+
constructor(json) {
|
|
7
|
+
super(json);
|
|
8
|
+
this.$type = 'ExternalViewFilter';
|
|
9
|
+
this.entityQualifiedName = 'org.taktik.icure.entities.base.Code';
|
|
10
|
+
Object.assign(this, json);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.ExternalViewFilterCode = ExternalViewFilterCode;
|
|
14
|
+
//# sourceMappingURL=ExternalViewFilterCode.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ExternalViewFilterCode.js","sourceRoot":"","sources":["../../../icc-x-api/filters/ExternalViewFilterCode.ts"],"names":[],"mappings":";;;AAAA,+EAA2E;AAG3E,MAAa,sBAAuB,SAAQ,uCAAkB;IAG5D,YAAY,IAAgB;QAC1B,KAAK,CAAC,IAAI,CAAC,CAAA;QAHb,UAAK,GAAW,oBAAoB,CAAA;QACpC,wBAAmB,GAAW,qCAAqC,CAAA;QAIjE,MAAM,CAAC,MAAM,CAAC,IAA8B,EAAE,IAAI,CAAC,CAAA;IACrD,CAAC;CAOF;AAdD,wDAcC","sourcesContent":["import { AbstractFilterCode } from '../../icc-api/model/AbstractFilterCode'\nimport { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey'\n\nexport class ExternalViewFilterCode extends AbstractFilterCode {\n $type: string = 'ExternalViewFilter'\n entityQualifiedName: string = 'org.taktik.icure.entities.base.Code'\n constructor(json: JSON | any) {\n super(json)\n\n Object.assign(this as ExternalViewFilterCode, json)\n }\n\n view?: string\n partition?: string\n startKey?: ExternalFilterKey\n endKey?: ExternalFilterKey\n desc?: string\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey';
|
|
2
|
+
import { AbstractFilterContact } from '../../icc-api/model/AbstractFilterContact';
|
|
3
|
+
export declare class ExternalViewFilterContact extends AbstractFilterContact {
|
|
4
|
+
$type: string;
|
|
5
|
+
entityQualifiedName: string;
|
|
6
|
+
constructor(json: JSON | any);
|
|
7
|
+
view?: string;
|
|
8
|
+
partition?: string;
|
|
9
|
+
startKey?: ExternalFilterKey;
|
|
10
|
+
endKey?: ExternalFilterKey;
|
|
11
|
+
desc?: string;
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExternalViewFilterContact = void 0;
|
|
4
|
+
const AbstractFilterContact_1 = require("../../icc-api/model/AbstractFilterContact");
|
|
5
|
+
class ExternalViewFilterContact extends AbstractFilterContact_1.AbstractFilterContact {
|
|
6
|
+
constructor(json) {
|
|
7
|
+
super(json);
|
|
8
|
+
this.$type = 'ExternalViewFilter';
|
|
9
|
+
this.entityQualifiedName = 'org.taktik.icure.entities.Contact';
|
|
10
|
+
Object.assign(this, json);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.ExternalViewFilterContact = ExternalViewFilterContact;
|
|
14
|
+
//# sourceMappingURL=ExternalViewFilterContact.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ExternalViewFilterContact.js","sourceRoot":"","sources":["../../../icc-x-api/filters/ExternalViewFilterContact.ts"],"names":[],"mappings":";;;AACA,qFAAiF;AAEjF,MAAa,yBAA0B,SAAQ,6CAAqB;IAGlE,YAAY,IAAgB;QAC1B,KAAK,CAAC,IAAI,CAAC,CAAA;QAHb,UAAK,GAAW,oBAAoB,CAAA;QACpC,wBAAmB,GAAW,mCAAmC,CAAA;QAI/D,MAAM,CAAC,MAAM,CAAC,IAAiC,EAAE,IAAI,CAAC,CAAA;IACxD,CAAC;CAOF;AAdD,8DAcC","sourcesContent":["import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey'\nimport { AbstractFilterContact } from '../../icc-api/model/AbstractFilterContact'\n\nexport class ExternalViewFilterContact extends AbstractFilterContact {\n $type: string = 'ExternalViewFilter'\n entityQualifiedName: string = 'org.taktik.icure.entities.Contact'\n constructor(json: JSON | any) {\n super(json)\n\n Object.assign(this as ExternalViewFilterContact, json)\n }\n\n view?: string\n partition?: string\n startKey?: ExternalFilterKey\n endKey?: ExternalFilterKey\n desc?: string\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey';
|
|
2
|
+
import { AbstractFilterDevice } from '../../icc-api/model/AbstractFilterDevice';
|
|
3
|
+
export declare class ExternalViewFilterDevice extends AbstractFilterDevice {
|
|
4
|
+
$type: string;
|
|
5
|
+
entityQualifiedName: string;
|
|
6
|
+
constructor(json: JSON | any);
|
|
7
|
+
view?: string;
|
|
8
|
+
partition?: string;
|
|
9
|
+
startKey?: ExternalFilterKey;
|
|
10
|
+
endKey?: ExternalFilterKey;
|
|
11
|
+
desc?: string;
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExternalViewFilterDevice = void 0;
|
|
4
|
+
const AbstractFilterDevice_1 = require("../../icc-api/model/AbstractFilterDevice");
|
|
5
|
+
class ExternalViewFilterDevice extends AbstractFilterDevice_1.AbstractFilterDevice {
|
|
6
|
+
constructor(json) {
|
|
7
|
+
super(json);
|
|
8
|
+
this.$type = 'ExternalViewFilter';
|
|
9
|
+
this.entityQualifiedName = 'org.taktik.icure.entities.Device';
|
|
10
|
+
Object.assign(this, json);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.ExternalViewFilterDevice = ExternalViewFilterDevice;
|
|
14
|
+
//# sourceMappingURL=ExternalViewFilterDevice.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ExternalViewFilterDevice.js","sourceRoot":"","sources":["../../../icc-x-api/filters/ExternalViewFilterDevice.ts"],"names":[],"mappings":";;;AACA,mFAA+E;AAE/E,MAAa,wBAAyB,SAAQ,2CAAoB;IAGhE,YAAY,IAAgB;QAC1B,KAAK,CAAC,IAAI,CAAC,CAAA;QAHb,UAAK,GAAW,oBAAoB,CAAA;QACpC,wBAAmB,GAAW,kCAAkC,CAAA;QAI9D,MAAM,CAAC,MAAM,CAAC,IAAgC,EAAE,IAAI,CAAC,CAAA;IACvD,CAAC;CAOF;AAdD,4DAcC","sourcesContent":["import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey'\nimport { AbstractFilterDevice } from '../../icc-api/model/AbstractFilterDevice'\n\nexport class ExternalViewFilterDevice extends AbstractFilterDevice {\n $type: string = 'ExternalViewFilter'\n entityQualifiedName: string = 'org.taktik.icure.entities.Device'\n constructor(json: JSON | any) {\n super(json)\n\n Object.assign(this as ExternalViewFilterDevice, json)\n }\n\n view?: string\n partition?: string\n startKey?: ExternalFilterKey\n endKey?: ExternalFilterKey\n desc?: string\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey';
|
|
2
|
+
import { AbstractFilterHealthElement } from '../../icc-api/model/AbstractFilterHealthElement';
|
|
3
|
+
export declare class ExternalViewFilterHealthElement extends AbstractFilterHealthElement {
|
|
4
|
+
$type: string;
|
|
5
|
+
entityQualifiedName: string;
|
|
6
|
+
constructor(json: JSON | any);
|
|
7
|
+
view?: string;
|
|
8
|
+
partition?: string;
|
|
9
|
+
startKey?: ExternalFilterKey;
|
|
10
|
+
endKey?: ExternalFilterKey;
|
|
11
|
+
desc?: string;
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExternalViewFilterHealthElement = void 0;
|
|
4
|
+
const AbstractFilterHealthElement_1 = require("../../icc-api/model/AbstractFilterHealthElement");
|
|
5
|
+
class ExternalViewFilterHealthElement extends AbstractFilterHealthElement_1.AbstractFilterHealthElement {
|
|
6
|
+
constructor(json) {
|
|
7
|
+
super(json);
|
|
8
|
+
this.$type = 'ExternalViewFilter';
|
|
9
|
+
this.entityQualifiedName = 'org.taktik.icure.entities.HealthElement';
|
|
10
|
+
Object.assign(this, json);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.ExternalViewFilterHealthElement = ExternalViewFilterHealthElement;
|
|
14
|
+
//# sourceMappingURL=ExternalViewFilterHealthElement.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ExternalViewFilterHealthElement.js","sourceRoot":"","sources":["../../../icc-x-api/filters/ExternalViewFilterHealthElement.ts"],"names":[],"mappings":";;;AACA,iGAA6F;AAE7F,MAAa,+BAAgC,SAAQ,yDAA2B;IAG9E,YAAY,IAAgB;QAC1B,KAAK,CAAC,IAAI,CAAC,CAAA;QAHb,UAAK,GAAW,oBAAoB,CAAA;QACpC,wBAAmB,GAAW,yCAAyC,CAAA;QAIrE,MAAM,CAAC,MAAM,CAAC,IAAuC,EAAE,IAAI,CAAC,CAAA;IAC9D,CAAC;CAOF;AAdD,0EAcC","sourcesContent":["import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey'\nimport { AbstractFilterHealthElement } from '../../icc-api/model/AbstractFilterHealthElement'\n\nexport class ExternalViewFilterHealthElement extends AbstractFilterHealthElement {\n $type: string = 'ExternalViewFilter'\n entityQualifiedName: string = 'org.taktik.icure.entities.HealthElement'\n constructor(json: JSON | any) {\n super(json)\n\n Object.assign(this as ExternalViewFilterHealthElement, json)\n }\n\n view?: string\n partition?: string\n startKey?: ExternalFilterKey\n endKey?: ExternalFilterKey\n desc?: string\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey';
|
|
2
|
+
import { AbstractFilterHealthcareParty } from '../../icc-api/model/AbstractFilterHealthcareParty';
|
|
3
|
+
export declare class ExternalViewFilterHealthcareParty extends AbstractFilterHealthcareParty {
|
|
4
|
+
$type: string;
|
|
5
|
+
entityQualifiedName: string;
|
|
6
|
+
constructor(json: JSON | any);
|
|
7
|
+
view?: string;
|
|
8
|
+
partition?: string;
|
|
9
|
+
startKey?: ExternalFilterKey;
|
|
10
|
+
endKey?: ExternalFilterKey;
|
|
11
|
+
desc?: string;
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExternalViewFilterHealthcareParty = void 0;
|
|
4
|
+
const AbstractFilterHealthcareParty_1 = require("../../icc-api/model/AbstractFilterHealthcareParty");
|
|
5
|
+
class ExternalViewFilterHealthcareParty extends AbstractFilterHealthcareParty_1.AbstractFilterHealthcareParty {
|
|
6
|
+
constructor(json) {
|
|
7
|
+
super(json);
|
|
8
|
+
this.$type = 'ExternalViewFilter';
|
|
9
|
+
this.entityQualifiedName = 'org.taktik.icure.entities.HealthcareParty';
|
|
10
|
+
Object.assign(this, json);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.ExternalViewFilterHealthcareParty = ExternalViewFilterHealthcareParty;
|
|
14
|
+
//# sourceMappingURL=ExternalViewFilterHealthcareParty.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ExternalViewFilterHealthcareParty.js","sourceRoot":"","sources":["../../../icc-x-api/filters/ExternalViewFilterHealthcareParty.ts"],"names":[],"mappings":";;;AACA,qGAAiG;AAEjG,MAAa,iCAAkC,SAAQ,6DAA6B;IAGlF,YAAY,IAAgB;QAC1B,KAAK,CAAC,IAAI,CAAC,CAAA;QAHb,UAAK,GAAW,oBAAoB,CAAA;QACpC,wBAAmB,GAAW,2CAA2C,CAAA;QAIvE,MAAM,CAAC,MAAM,CAAC,IAAyC,EAAE,IAAI,CAAC,CAAA;IAChE,CAAC;CAOF;AAdD,8EAcC","sourcesContent":["import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey'\nimport { AbstractFilterHealthcareParty } from '../../icc-api/model/AbstractFilterHealthcareParty'\n\nexport class ExternalViewFilterHealthcareParty extends AbstractFilterHealthcareParty {\n $type: string = 'ExternalViewFilter'\n entityQualifiedName: string = 'org.taktik.icure.entities.HealthcareParty'\n constructor(json: JSON | any) {\n super(json)\n\n Object.assign(this as ExternalViewFilterHealthcareParty, json)\n }\n\n view?: string\n partition?: string\n startKey?: ExternalFilterKey\n endKey?: ExternalFilterKey\n desc?: string\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ExternalFilterKey } from '../../icc-api/model/ExternalFilterKey';
|
|
2
|
+
import { AbstractFilterInvoice } from '../../icc-api/model/AbstractFilterInvoice';
|
|
3
|
+
export declare class ExternalViewFilterInvoice extends AbstractFilterInvoice {
|
|
4
|
+
$type: string;
|
|
5
|
+
entityQualifiedName: string;
|
|
6
|
+
constructor(json: JSON | any);
|
|
7
|
+
view?: string;
|
|
8
|
+
partition?: string;
|
|
9
|
+
startKey?: ExternalFilterKey;
|
|
10
|
+
endKey?: ExternalFilterKey;
|
|
11
|
+
desc?: string;
|
|
12
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExternalViewFilterInvoice = void 0;
|
|
4
|
+
const AbstractFilterInvoice_1 = require("../../icc-api/model/AbstractFilterInvoice");
|
|
5
|
+
class ExternalViewFilterInvoice extends AbstractFilterInvoice_1.AbstractFilterInvoice {
|
|
6
|
+
constructor(json) {
|
|
7
|
+
super(json);
|
|
8
|
+
this.$type = 'ExternalViewFilter';
|
|
9
|
+
this.entityQualifiedName = 'org.taktik.icure.entities.Invoice';
|
|
10
|
+
Object.assign(this, json);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.ExternalViewFilterInvoice = ExternalViewFilterInvoice;
|
|
14
|
+
//# sourceMappingURL=ExternalViewFilterInvoice.js.map
|