@icure/api 8.0.72 → 8.0.74
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/Content.js +13 -1
- package/icc-api/model/Content.js.map +1 -1
- package/icc-api/model/DiaryNoteExportInfo.d.ts +1 -1
- package/icc-api/model/DiaryNoteExportInfo.js.map +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js +1 -1
- package/icc-x-api/crypto/ExtendedApisUtilsImpl.js.map +1 -1
- package/icc-x-api/icc-hcparty-x-api.js +1 -1
- package/icc-x-api/icc-hcparty-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.js +3 -3
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/package.json +1 -1
package/icc-api/model/Content.js
CHANGED
|
@@ -20,7 +20,19 @@ const Service_1 = require("./Service");
|
|
|
20
20
|
const ModelHelper_1 = require("./ModelHelper");
|
|
21
21
|
class Content {
|
|
22
22
|
constructor(json) {
|
|
23
|
-
|
|
23
|
+
let binaryData = {};
|
|
24
|
+
if (!!json.binaryValue) {
|
|
25
|
+
if (typeof json.binaryValue === 'string') {
|
|
26
|
+
binaryData.binaryValue = (0, ModelHelper_1.b64_2ab)(json.binaryValue);
|
|
27
|
+
}
|
|
28
|
+
else if (json.binaryValue instanceof ArrayBuffer || ArrayBuffer.isView(json.binaryValue)) {
|
|
29
|
+
binaryData.binaryValue = json.binaryValue;
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
throw new Error(`Invalid type for binaryValue: ${typeof json.binaryValue}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
Object.assign(this, json, binaryData);
|
|
24
36
|
if (!!(json === null || json === void 0 ? void 0 : json.measureValue)) {
|
|
25
37
|
this.measureValue = new Measure_1.Measure(json.measureValue);
|
|
26
38
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Content.js","sourceRoot":"","sources":["../../../icc-api/model/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G,CAAC,CAAC,OAAmB,EAAE,EAAE,CAAC,IAAI,iBAAO,CAAC,OAAO,CAAC,CAAC,CAAA;SAC3F;IACH,CAAC;CAqBF;AA1CD,0BA0CC","sourcesContent":["/**\n * iCure Data Stack API Documentation\n * The iCure Data Stack Application API is the native interface to iCure. This version is obsolete, please use v2.\n *\n * OpenAPI spec version: v1\n *\n *\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen.git\n * Do not edit the class manually.\n */\nimport { Measure } from './Measure'\nimport { Medication } from './Medication'\nimport { Service } from './Service'\nimport { TimeSeries } from './TimeSeries'\n\n/**\n * Information contained in the service. Content is localized, using ISO language code as key\n */\nimport { b64_2ab } from './ModelHelper'\nexport class Content {\n constructor(json: JSON | any) {\n let binaryData: { binaryValue?: ArrayBuffer } = {}\n if (!!json.binaryValue) {\n if (typeof json.binaryValue === 'string') {\n binaryData.binaryValue = b64_2ab(json.binaryValue)\n } else if (json.binaryValue instanceof ArrayBuffer || ArrayBuffer.isView(json.binaryValue)) {\n binaryData.binaryValue = json.binaryValue\n } else {\n throw new Error(`Invalid type for binaryValue: ${typeof json.binaryValue}`)\n }\n }\n Object.assign(this as Content, json, binaryData)\n\n if (!!json?.measureValue) {\n this.measureValue = new Measure(json.measureValue)\n }\n\n if (!!json?.compoundValue) {\n this.compoundValue = json.compoundValue.map((service: JSON | any) => new Service(service))\n }\n }\n\n stringValue?: string\n numberValue?: number\n booleanValue?: boolean\n instantValue?: number\n /**\n * Value as date. The format could have a all three (day, month and year) or values on any of these three, whatever is known.\n */\n fuzzyDateValue?: number\n binaryValue?: ArrayBuffer\n /**\n * Linked document.\n */\n documentId?: string\n measureValue?: Measure\n medicationValue?: Medication\n timeSeries?: TimeSeries\n compoundValue?: Array<Service>\n ratio?: Array<Measure>\n range?: Array<Measure>\n}\n"]}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import { HealthcareParty } from './HealthcareParty';
|
|
13
13
|
export declare class DiaryNoteExportInfo {
|
|
14
14
|
constructor(json: JSON | any);
|
|
15
|
-
|
|
15
|
+
secretForeignKeys?: Array<string>;
|
|
16
16
|
excludedIds?: Array<string>;
|
|
17
17
|
recipient?: HealthcareParty;
|
|
18
18
|
softwareName?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DiaryNoteExportInfo.js","sourceRoot":"","sources":["../../../icc-api/model/DiaryNoteExportInfo.ts"],"names":[],"mappings":";;;AAaA,MAAa,mBAAmB;IAC9B,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAA2B,EAAE,IAAI,CAAC,CAAA;IAClD,CAAC;CAaF;AAhBD,kDAgBC","sourcesContent":["/**\n * iCure Data Stack API Documentation\n * The iCure Data Stack Application API is the native interface to iCure. This version is obsolete, please use v2.\n *\n * OpenAPI spec version: v1\n *\n *\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen.git\n * Do not edit the class manually.\n */\nimport { HealthcareParty } from './HealthcareParty'\n\nexport class DiaryNoteExportInfo {\n constructor(json: JSON | any) {\n Object.assign(this as DiaryNoteExportInfo, json)\n }\n\n
|
|
1
|
+
{"version":3,"file":"DiaryNoteExportInfo.js","sourceRoot":"","sources":["../../../icc-api/model/DiaryNoteExportInfo.ts"],"names":[],"mappings":";;;AAaA,MAAa,mBAAmB;IAC9B,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAA2B,EAAE,IAAI,CAAC,CAAA;IAClD,CAAC;CAaF;AAhBD,kDAgBC","sourcesContent":["/**\n * iCure Data Stack API Documentation\n * The iCure Data Stack Application API is the native interface to iCure. This version is obsolete, please use v2.\n *\n * OpenAPI spec version: v1\n *\n *\n * NOTE: This class is auto generated by the swagger code generator program.\n * https://github.com/swagger-api/swagger-codegen.git\n * Do not edit the class manually.\n */\nimport { HealthcareParty } from './HealthcareParty'\n\nexport class DiaryNoteExportInfo {\n constructor(json: JSON | any) {\n Object.assign(this as DiaryNoteExportInfo, json)\n }\n\n secretForeignKeys?: Array<string>\n excludedIds?: Array<string>\n recipient?: HealthcareParty\n softwareName?: string\n softwareVersion?: string\n tags?: Array<string>\n contexts?: Array<string>\n psy?: boolean\n documentId?: string\n attachmentId?: string\n note?: string\n}\n"]}
|
|
@@ -86,7 +86,7 @@ class ExtendedApisUtilsImpl {
|
|
|
86
86
|
var _a;
|
|
87
87
|
return __awaiter(this, void 0, void 0, function* () {
|
|
88
88
|
const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = yield this.prepareBulkShareRequests(entitiesType, entitiesUpdates);
|
|
89
|
-
const results = yield doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId });
|
|
89
|
+
const results = Object.keys(allRequestsByEntityId).length > 0 ? yield doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId }) : [];
|
|
90
90
|
const updatedEntities = [];
|
|
91
91
|
const updateErrors = [];
|
|
92
92
|
for (const result of results) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAWiB;AAEjB,2EAA6F;AAC7F,2EAAuE;AAIvE,wFAAoF;AAEpF,sDAA0F;AAC1F,qEAAiE;AAKjE,IAAO,WAAW,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACrD,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAC3E,IAAO,2BAA2B,GAAG,uCAAkB,CAAC,2BAA2B,CAAA;AACnF,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAEzD;;;GAGG;AACH,MAAa,qBAAqB;IAChC,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,yBAAoD,EACpD,wBAAkD,EAClD,OAAoB,EACpB,aAAsB;QALtB,eAAU,GAAV,UAAU,CAAkB;QAC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C,IAAI,CAAC,gBAAgB,CAAC,CAAA;QAC/G,IAAI,MAAM,CAAC,iBAAiB,IAAI,MAAM,CAAC,iBAAiB,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;QAC3G,IAAI,MAAM,CAAC,gBAAgB,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;QACrH,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,IAAI,oBAAoB,EAAE;gBACxB,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;oBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;aACF;;gBAAM,OAAO,KAAK,CAAA;SACpB;QACD,OAAO,IAAI,CAAA;IACb,CAAC;CACF;AA/6BD,sDA+6BC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport {\n b2a,\n decryptObject,\n EncryptedEntityWithType,\n EncryptedFieldsManifest,\n encryptObject,\n EntityWithDelegationTypeName,\n hex2ua,\n truncateTrailingNulls,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { SecurityMetadataDecryptor, SecurityMetadataType } from './SecurityMetadataDecryptor'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { SecureDelegationsManager } from './SecureDelegationsManager'\nimport { ShareResult, ShareResultFailure, ShareResultSuccess } from '../utils/ShareResult'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { IccUserXApi } from '../icc-user-x-api'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\nimport * as _ from 'lodash'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\n\n/**\n * @internal this class is for internal use only and may be changed without notice.\n * Methods to support extended apis.\n */\nexport class ExtendedApisUtilsImpl implements ExtendedApisUtils {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly securityMetadataDecryptor: SecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {}\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.EncryptionKey)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.EncryptionKey)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.SecretId)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) => this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.SecretId))\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.OwningEntityId)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.OwningEntityId)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.securityMetadataDecryptor.getEntityAccessLevel(entity.entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())) ===\n AccessLevel.WRITE\n )\n }\n\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n 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.securityMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const accessibleMembers = new Set(\n this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n )\n const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {\n if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {\n return [k]\n } else return []\n })\n allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations }\n orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests\n } else {\n unmodifiedEntitiesIds.push(entityId)\n }\n }\n return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId }\n }\n\n async simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n delegates: {\n [p: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>> {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n const dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n for (const [delegateId, delegateRequests] of Object.entries(delegates)) {\n if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no encryption keys or the current data owner can't access any encryption keys, but sharing is required.`\n )\n }\n if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`\n )\n }\n dataForDelegates[delegateId] = {\n shareSecretIds: delegateRequests.shareSecretIds ?? (await this.secretIdsOf(entity)),\n shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,\n shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,\n requestedPermissions: delegateRequests.requestedPermissions ?? RequestedPermissionEnum.MAX_WRITE,\n }\n }\n const shareResult = await this.bulkShareOrUpdateEncryptedEntityMetadata(\n entity.type,\n [\n {\n entity: entity.entity,\n dataForDelegates,\n },\n ],\n (x) => doRequestBulkShareOrUpdate(x)\n )\n if (shareResult.unmodifiedEntitiesIds.includes(entity.entity.id!)) {\n return new ShareResultSuccess(entity.entity)\n }\n if (!shareResult.updateErrors.length && shareResult.updatedEntities.length === 1) {\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n const requestedDelegates = new Set(Object.keys(delegates))\n const errorsOfRequestedDelegates = shareResult.updateErrors.filter((x) => requestedDelegates.has(x.delegateId))\n if (errorsOfRequestedDelegates.length === 0 && shareResult.updatedEntities.length === 1) {\n console.warn(`Errors with migration of encrypted metadata ${JSON.stringify(shareResult.updateErrors)}.`)\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n return new ShareResultFailure(\n shareResult.updateErrors,\n `There was an error sharing entity with id ${entity.entity.id}. Check the logs for more details.`\n )\n }\n\n private async makeMigrationRequestsIfNeeded(\n entity: EncryptedEntityWithType,\n userRequestsForEntity: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n ): Promise<{ [delegateId: string]: EntityShareOrMetadataUpdateRequest }> {\n const hierarchy = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const legacySecretIds = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(entity.entity, hierarchy, SecurityMetadataType.SecretId)\n const legacyEncryptionKeys = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(\n entity.entity,\n hierarchy,\n SecurityMetadataType.EncryptionKey\n )\n const legacyOwningEntityIds = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(\n entity.entity,\n hierarchy,\n SecurityMetadataType.OwningEntityId\n )\n const res = {} as { [delegateId: string]: EntityShareOrMetadataUpdateRequest }\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n for (const hierarchyMember of hierarchy) {\n const hierarchyMemberMigration = await this.makeMigrationRequestForMemberOfHierarchy(\n entity,\n selfId,\n hierarchyMember,\n userRequestsForEntity[hierarchyMember],\n legacySecretIds,\n legacyEncryptionKeys,\n legacyOwningEntityIds\n )\n if (hierarchyMemberMigration) {\n res[hierarchyMember] = hierarchyMemberMigration\n }\n }\n return res\n }\n\n private async makeMigrationRequestForMemberOfHierarchy(\n entity: EncryptedEntityWithType,\n selfId: string,\n currMemberId: string,\n userRequestForDelegate:\n | {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n | undefined,\n legacySecretIds: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyEncryptionKeys: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyOwningEntityIds: { decrypted: string; dataOwnersWithAccess: string[] }[]\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n // This implementation is very specific from migration from delegations to secure delegations. If in future we will have to migrate from secure delegations to something else, this method may need significant changes in its logic.\n const subHierarchy = this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(currMemberId) : [currMemberId]\n const subHierarchySet = new Set(subHierarchy)\n const legacyAccess =\n selfId === entity.entity.id && currMemberId === selfId\n ? AccessLevel.WRITE\n : await this.securityMetadataDecryptor.getEntityLegacyDelegationAccessLevel(entity.entity, subHierarchy)\n if (!legacyAccess) return undefined\n const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d))).map((x) => x.decrypted)\n const selfLegacyEncryptionKeys = legacyEncryptionKeys\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n const selfLegacyOwningEntityIds = legacyOwningEntityIds\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n let missingSecretIds: string[] = []\n let missingEncryptionKeys: string[] = []\n let missingOwningEntityIds: string[] = []\n if (selfLegacySecretIds.length > 0) {\n const currentSecretIds = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.SecretId)).map(\n (x) => x.decrypted\n )\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.EncryptionKey)).map(\n (x) => x.decrypted\n )\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.OwningEntityId)).map(\n (x) => x.decrypted\n )\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id &&\n currMemberId === selfId &&\n !(await this.securityMetadataDecryptor.getEntitySecureDelegationAccessLevel(entity.entity, subHierarchy))\n if (missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0 || mustCreateRootDelegation) {\n let requestedPermissions: RequestedPermissionInternal\n if (currMemberId === selfId) {\n requestedPermissions = RequestedPermissionInternal.ROOT\n } else {\n requestedPermissions = RequestedPermissionInternal.FULL_WRITE // Legacy permission if present is always write\n }\n return await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entity,\n currMemberId,\n Array.from(new Set([...missingSecretIds, ...(userRequestForDelegate?.shareSecretIds ?? [])])),\n Array.from(new Set([...missingEncryptionKeys, ...(userRequestForDelegate?.shareEncryptionKeys ?? [])])),\n Array.from(new Set([...missingOwningEntityIds, ...(userRequestForDelegate?.shareOwningEntityIds ?? [])])),\n requestedPermissions\n )\n } else return undefined\n }\n\n async tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const triedKeys: Set<string> = new Set()\n const result = await this.doIncrementallyDecryptingKeys(entity.entity, entity.type, async (e, t, keys) => {\n for (const k of keys) {\n if (!triedKeys.has(k.raw)) {\n triedKeys.add(k.raw)\n try {\n const decrypted = await this.primitives.AES.decrypt(k.key, content)\n if (!validator || (await validator(decrypted))) return { success: decrypted }\n } catch (e) {\n console.warn(`Error while attempting to decrypt attachment of ${entity.entity.id} with raw key ${k.raw}: ${e}`)\n }\n }\n }\n return null\n })\n if (result != null) {\n return { data: result.success, wasDecrypted: true }\n } else {\n return { data: content, wasDecrypted: false }\n }\n }\n\n async encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }> {\n const ensureInitialisedKeysResult = await this.ensureEncryptionKeysInitialised(entity, type)\n let updatedEntity: T | undefined\n if (!!ensureInitialisedKeysResult) {\n updatedEntity = await saveEntity(ensureInitialisedKeysResult)\n }\n const encrypted = await this.doIncrementallyDecryptingKeys(entity, type, async (e, t, keys) => {\n for (const k of keys) {\n try {\n return {\n success: {\n encryptedData: await this.primitives.AES.encrypt(k.key, content),\n updatedEntity: updatedEntity,\n },\n }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${k.raw}: ${e}`)\n }\n }\n return null\n })\n if (encrypted != null) return encrypted.success\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async tryDecryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }[]> {\n const nothingToDecryptResults = new Map<string, T>()\n for (const entity of entities) {\n const nothingToDecrypt = await decryptObject(entity, async (encrypted) => {\n return null\n })\n if (nothingToDecrypt != null) {\n nothingToDecryptResults.set(entity.id!, constructor(nothingToDecrypt))\n }\n }\n const actuallyDecryptedResults = await this.doManyIncrementallyDecryptingKeys(\n entities.filter((e) => !nothingToDecryptResults.has(e.id!)),\n entityType,\n async (entity, t, keys) => {\n // The decrypt object will try all keys on each of the sub-objects; this is intentional because even though it\n // shouldn't happen, but it is still possible that some entity could be accidentally merged badly and the merged\n // entity has multiple encryptedSelf (on different sub-entities) that use different keys.\n const decrypted = await decryptObject(entity, (encrypted) => this.tryDecryptJson(keys, encrypted, false))\n if (decrypted != null) {\n return { success: constructor(decrypted) }\n } else {\n return null\n }\n }\n )\n const res = []\n for (const entity of entities) {\n const decrypted = actuallyDecryptedResults.get(entity.id!) ?? nothingToDecryptResults.get(entity.id!)\n if (!decrypted) {\n res.push({ entity: entity, decrypted: false })\n } else {\n res.push({ entity: decrypted, decrypted: true })\n }\n }\n return res\n }\n\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | null> {\n for (const key of potentialKeys) {\n try {\n const decrypted = await this.primitives.AES.decrypt(key.key, encrypted, key.raw)\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return null\n }\n\n async tryEncryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T[]> {\n const entitiesWithInitialisedEncryptionKeys: T[] = []\n for (const entity of entities) {\n entitiesWithInitialisedEncryptionKeys.push((await this.ensureEncryptionKeysInitialised(entity, entityType)) ?? entity)\n }\n const results = await this.doManyIncrementallyDecryptingKeys(entitiesWithInitialisedEncryptionKeys, entityType, async (e, t, keys) => {\n for (const k of keys) {\n try {\n const encrypted = await encryptObject(\n e,\n (obj) => {\n // TODO encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n\n return this.primitives.AES.encrypt(k.key, utf8_2ua(json), k.raw)\n },\n fieldsToEncrypt,\n entityType\n )\n return { success: constructor(encrypted) }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${k.raw}: ${e}`)\n }\n }\n return null\n })\n if (results.size != entitiesWithInitialisedEncryptionKeys.length) {\n if (requireEncryption) {\n throw new Error(\n `Could not encrypt entities ${entitiesWithInitialisedEncryptionKeys.flatMap((e): string[] => (results.has(e.id!) ? [] : [e.id!]))}`\n )\n } else {\n for (const e of entitiesWithInitialisedEncryptionKeys) {\n if (!results.has(e.id!)) {\n await encryptObject(\n e,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n e\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n results.set(e.id!, e)\n }\n }\n }\n }\n return entitiesWithInitialisedEncryptionKeys.map((e) => results.get(e.id!)!)\n }\n\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.securityMetadataDecryptor.hasAnyEncryptionKeys(entity)) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * Add encryption key and share with all auto-delegates already in legacy delegations.\n * TODO disable this logic and simply throw error for post-2018 customers.\n */\n const existingDelegations = new Set(Object.keys(entity.delegations ?? {}))\n const usersWithAccessToNewKey = Object.fromEntries(\n Object.values((await this.userApi.getCurrentUser()).autoDelegations ?? {})\n .flatMap((x) => x)\n .filter((x) => existingDelegations.has(x))\n .map((x) => [x, AccessLevelEnum.WRITE])\n )\n return await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: entity.secretForeignKeys ?? [],\n },\n entityType,\n [],\n [],\n [await this.primitives.AES.generateCryptoKey(true)],\n usersWithAccessToNewKey\n )\n }\n\n private async decryptHierarchy(\n decryptedDataProvider: (dataOwners: string[]) => Promise<{ ownerId: string; extracted: string[] }[]>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n return await decryptedDataProvider(canDecryptOwnerIds)\n }\n\n private async decryptAndMergeHierarchy(\n dataOwnerId: string | undefined,\n decryptedDataProvider: (dataOwners: string[]) => Promise<{ ownerId: string; extracted: string[] }[]>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const decryptedData = await decryptedDataProvider(hierarchy)\n const merged = decryptedData.flatMap((x) => x.extracted)\n return this.deduplicate(merged)\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n async doIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entity: E,\n entityType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<{ success: T } | null> {\n const res = await this.doManyIncrementallyDecryptingKeys([entity], entityType, (e, t, ks) => action(e, t, ks))\n if (res.has(entity.id!)) {\n return { success: res.get(entity.id!)! }\n } else {\n return null\n }\n }\n\n async doManyIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entities: E[],\n entitiesType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<Map<string, T>> {\n if (entities.length == 0) return new Map()\n if (new Set(entities.map((e) => e.id)).size != entities.length) {\n throw new Error(`Duplicate entries in entities ${entities.map((x) => x.id)}`)\n }\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const allExtractedKeysForEntities = Object.fromEntries(entities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const newlyExtractedKeysForEntities = Object.fromEntries(entities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const results = new Map<string, T>()\n const remainingEntitiesById = Object.fromEntries(entities.map((x) => [x.id!, x] as [string, E]))\n const importedKeysByRaw = new Map<string, CryptoKey>()\n const primitives = this.primitives\n\n async function updateExtractedKeysAndDoActionIfNecessary(\n newKeys: { [entityId: string]: string[] },\n forceUpdateOnEntitiesWithNewExtractedKeys: boolean\n ): Promise<void> {\n for (const [entityId, keys] of Object.entries(newKeys)) {\n const newlyExtractedSet = newlyExtractedKeysForEntities[entityId]\n const alreadyExtractedSet = allExtractedKeysForEntities[entityId]\n for (const k of keys) {\n if (!alreadyExtractedSet.has(k)) {\n newlyExtractedSet.add(k)\n if (!importedKeysByRaw.has(k)) {\n importedKeysByRaw.set(k, await primitives.AES.importKey('raw', hex2ua(k)))\n }\n }\n }\n }\n if (\n forceUpdateOnEntitiesWithNewExtractedKeys ||\n Object.keys(remainingEntitiesById).every((eId) => newlyExtractedKeysForEntities[eId].size > 0)\n ) {\n for (const entity of Object.values(remainingEntitiesById)) {\n const currId = entity.id!\n const currNewlyExtracted = newlyExtractedKeysForEntities[currId]\n if (currNewlyExtracted.size > 0) {\n const currAllExtracted = allExtractedKeysForEntities[currId]\n currNewlyExtracted.forEach((k) => currAllExtracted.add(k))\n currNewlyExtracted.clear()\n const actionResult = await action(\n entity,\n entitiesType,\n [...currAllExtracted].map((raw): { raw: string; key: CryptoKey } => ({\n raw: raw,\n key: importedKeysByRaw.get(raw)!,\n }))\n )\n if (actionResult != null) {\n delete remainingEntitiesById[currId]\n results.set(currId, actionResult.success)\n }\n }\n }\n }\n }\n\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptLegacyDelegations(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingCache(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingKnownExchangeData(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingExchangeDataMap(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary({}, true)\n return results\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n argsArray.forEach((arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n this.doCheckEmptyEncryptionMetadata(entity, true)\n }\n\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean {\n return this.doCheckEmptyEncryptionMetadata(entity, false)\n }\n\n private doCheckEmptyEncryptionMetadata(entity: EncryptedEntity, throwErrorIfNonEmpty: boolean): boolean {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (entity.securityMetadata && Object.keys(entity.securityMetadata).length) existingMetadata.push('securityMetadata')\n if (existingMetadata.length > 0) {\n if (throwErrorIfNonEmpty) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n } else return false\n }\n return true\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ExtendedApisUtilsImpl.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ExtendedApisUtilsImpl.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,oCAWiB;AAEjB,2EAA6F;AAC7F,2EAAuE;AAIvE,wFAAoF;AAEpF,sDAA0F;AAC1F,qEAAiE;AAKjE,IAAO,WAAW,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACrD,IAAO,uBAAuB,G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AAM,CAAC,WAAW,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;QACtG,IAAI,MAAM,CAAC,kBAAkB,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAA;QAC3H,IAAI,MAAM,CAAC,cAAc,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;QAC/G,IAAI,MAAM,CAAC,iBAAiB,IAAI,MAAM,CAAC,iBAAiB,CAAC,MAAM;YAAE,gBAAgB,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAA;QAC3G,IAAI,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;AAh7BD,sDAg7BC","sourcesContent":["import { EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport {\n b2a,\n decryptObject,\n EncryptedEntityWithType,\n EncryptedFieldsManifest,\n encryptObject,\n EntityWithDelegationTypeName,\n hex2ua,\n truncateTrailingNulls,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { SecurityMetadataDecryptor, SecurityMetadataType } from './SecurityMetadataDecryptor'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { EntityShareOrMetadataUpdateRequest } from '../../icc-api/model/requests/EntityShareOrMetadataUpdateRequest'\nimport { EntityBulkShareResult } from '../../icc-api/model/requests/EntityBulkShareResult'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { SecureDelegationsManager } from './SecureDelegationsManager'\nimport { ShareResult, ShareResultFailure, ShareResultSuccess } from '../utils/ShareResult'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { IccUserXApi } from '../icc-user-x-api'\nimport { MinimalEntityBulkShareResult } from '../../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { BulkShareOrUpdateMetadataParams, EntityRequestInformation } from '../../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\nimport * as _ from 'lodash'\nimport AccessLevel = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport RequestedPermissionInternal = EntityShareRequest.RequestedPermissionInternal\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\n\n/**\n * @internal this class is for internal use only and may be changed without notice.\n * Methods to support extended apis.\n */\nexport class ExtendedApisUtilsImpl implements ExtendedApisUtils {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly securityMetadataDecryptor: SecurityMetadataDecryptor,\n private readonly secureDelegationsManager: SecureDelegationsManager,\n private readonly userApi: IccUserXApi,\n private readonly useParentKeys: boolean\n ) {}\n\n async encryptionKeysOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.EncryptionKey)\n )\n }\n\n async encryptionKeysForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.EncryptionKey)\n )\n }\n\n async secretIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.SecretId)\n )\n }\n\n async secretIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) => this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.SecretId))\n }\n\n async owningEntityIdsOf(entity: EncryptedEntityWithType, dataOwnerId?: string): Promise<string[]> {\n return await this.decryptAndMergeHierarchy(dataOwnerId, (hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.OwningEntityId)\n )\n }\n\n async owningEntityIdsForHcpHierarchyOf(entity: EncryptedEntityWithType): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.decryptHierarchy((hierarchy) =>\n this.securityMetadataDecryptor.decryptAll(entity.entity, hierarchy, SecurityMetadataType.OwningEntityId)\n )\n }\n\n async hasWriteAccess(entity: EncryptedEntityWithType): Promise<boolean> {\n return (\n (await this.securityMetadataDecryptor.getEntityAccessLevel(entity.entity, await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds())) ===\n AccessLevel.WRITE\n )\n }\n\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n entityType: EntityWithDelegationTypeName,\n owningEntity: string | undefined,\n 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 =\n Object.keys(allRequestsByEntityId).length > 0 ? await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId }) : []\n const updatedEntities: T[] = []\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n if (result.updatedEntity) {\n updatedEntities.push(result.updatedEntity)\n }\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n // TODO implement auto-retry for failed requests if the shouldRetry flag in result.rejectedRequests is set to true\n return {\n updatedEntities,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n async bulkShareOrUpdateEncryptedEntityMetadataNoEntities(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n }\n }[],\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n successfulUpdates: { entityId: string; delegateId: string }[]\n updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[]\n }> {\n const { allRequestsByEntityId, orderedRequestsInfoByEntityId, unmodifiedEntitiesIds } = await this.prepareBulkShareRequests(\n entitiesType,\n entitiesUpdates\n )\n const results = await doRequestBulkShareOrUpdate({ requestsByEntityId: allRequestsByEntityId })\n const updateErrors: {\n entityId: string\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n code?: number\n reason?: string\n }[] = []\n for (const result of results) {\n for (const [errorRequestId, error] of Object.entries(result.rejectedRequests ?? {})) {\n const requestIndex = Number(errorRequestId)\n const { delegateId, request, updatedForMigration } = orderedRequestsInfoByEntityId[result.entityId][requestIndex]\n updateErrors.push({\n entityId: result.entityId,\n delegateId,\n request,\n updatedForMigration,\n code: error.code,\n reason: error.reason,\n })\n }\n }\n const successfulRequests = Object.entries(allRequestsByEntityId)\n .flatMap(([entityId, requests]) => Object.keys(requests).map((delegateId) => ({ entityId, delegateId })))\n .filter(({ entityId, delegateId }) => !updateErrors.some((error) => error.entityId === entityId && error.delegateId === delegateId))\n return {\n successfulUpdates: successfulRequests,\n updateErrors,\n unmodifiedEntitiesIds,\n }\n }\n\n private async prepareBulkShareRequests(\n entitiesType: EntityWithDelegationTypeName,\n entitiesUpdates: {\n entity: EncryptedEntityStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[]\n ): Promise<{\n unmodifiedEntitiesIds: string[]\n allRequestsByEntityId: { [entityId: string]: EntityRequestInformation }\n orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n }\n }> {\n if (new Set(entitiesUpdates.map((e) => e.entity.id)).size !== entitiesUpdates.length) {\n throw new Error('Duplicate requests: the same entity id is present more than once in the input')\n }\n const allRequestsByEntityId = {} as { [entityId: string]: EntityRequestInformation }\n const orderedRequestsInfoByEntityId: {\n [entityId: string]: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[]\n } = {}\n const unmodifiedEntitiesIds: string[] = []\n for (const { entity, dataForDelegates } of entitiesUpdates) {\n const entityId = entity.id\n if (!entityId) throw new Error('Share of an entity requires for the entity to already exist and have an id')\n const entityWithType = { entity, type: entitiesType }\n const currentRequests = {} as { [requestId: string]: EntityShareOrMetadataUpdateRequest }\n const currentOrderedRequests: {\n delegateId: string\n request?: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n updatedForMigration: boolean\n }[] = []\n const migrationRequests = await this.makeMigrationRequestsIfNeeded(entityWithType, dataForDelegates)\n for (const [delegate, request] of Object.entries(migrationRequests)) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: dataForDelegates[delegate],\n updatedForMigration: true,\n })\n }\n for (const [delegate, userRequest] of Object.entries(dataForDelegates)) {\n if (!migrationRequests[delegate]) {\n const request = await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entityWithType,\n delegate,\n userRequest.shareSecretIds ?? [],\n userRequest.shareEncryptionKeys ?? [],\n userRequest.shareOwningEntityIds ?? [],\n userRequest.requestedPermissions\n )\n if (request) {\n currentRequests[String(currentOrderedRequests.length)] = request\n currentOrderedRequests.push({\n delegateId: delegate,\n request: userRequest,\n updatedForMigration: false,\n })\n }\n }\n }\n if (Object.keys(currentRequests).length > 0) {\n const existingDelegationMembersDetails = await this.securityMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const accessibleMembers = new Set(\n this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds() : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n )\n const potentialParentDelegations = Object.entries(existingDelegationMembersDetails).flatMap(([k, members]) => {\n if ((!!members.delegate && accessibleMembers.has(members.delegate)) || (!!members.delegator && accessibleMembers.has(members.delegator))) {\n return [k]\n } else return []\n })\n allRequestsByEntityId[entityId] = { requests: currentRequests, potentialParentDelegations }\n orderedRequestsInfoByEntityId[entityId] = currentOrderedRequests\n } else {\n unmodifiedEntitiesIds.push(entityId)\n }\n }\n return { unmodifiedEntitiesIds, allRequestsByEntityId, orderedRequestsInfoByEntityId }\n }\n\n async simpleShareOrUpdateEncryptedEntityMetadata<T extends EncryptedEntityStub>(\n entity: { entity: T; type: EntityWithDelegationTypeName },\n delegates: {\n [p: string]: {\n shareSecretIds: string[] | undefined\n shareEncryptionKeys: ShareMetadataBehaviour | undefined\n shareOwningEntityIds: ShareMetadataBehaviour | undefined\n requestedPermissions: EntityShareRequest.RequestedPermissionEnum | undefined\n }\n },\n doRequestBulkShareOrUpdate: (request: BulkShareOrUpdateMetadataParams) => Promise<EntityBulkShareResult<T>[]>\n ): Promise<ShareResult<T>> {\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n const dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n for (const [delegateId, delegateRequests] of Object.entries(delegates)) {\n if (!availableEncryptionKeys.length && delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no encryption keys or the current data owner can't access any encryption keys, but sharing is required.`\n )\n }\n if (!availableOwningEntityIds.length && delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(\n `Entity ${JSON.stringify(\n entity\n )} has no owning entity ids or the current data owner can't access any owning entity ids, but sharing is required.`\n )\n }\n dataForDelegates[delegateId] = {\n shareSecretIds: delegateRequests.shareSecretIds ?? (await this.secretIdsOf(entity)),\n shareEncryptionKeys: delegateRequests.shareEncryptionKeys === ShareMetadataBehaviour.NEVER ? [] : availableEncryptionKeys,\n shareOwningEntityIds: delegateRequests.shareOwningEntityIds === ShareMetadataBehaviour.NEVER ? [] : availableOwningEntityIds,\n requestedPermissions: delegateRequests.requestedPermissions ?? RequestedPermissionEnum.MAX_WRITE,\n }\n }\n const shareResult = await this.bulkShareOrUpdateEncryptedEntityMetadata(\n entity.type,\n [\n {\n entity: entity.entity,\n dataForDelegates,\n },\n ],\n (x) => doRequestBulkShareOrUpdate(x)\n )\n if (shareResult.unmodifiedEntitiesIds.includes(entity.entity.id!)) {\n return new ShareResultSuccess(entity.entity)\n }\n if (!shareResult.updateErrors.length && shareResult.updatedEntities.length === 1) {\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n const requestedDelegates = new Set(Object.keys(delegates))\n const errorsOfRequestedDelegates = shareResult.updateErrors.filter((x) => requestedDelegates.has(x.delegateId))\n if (errorsOfRequestedDelegates.length === 0 && shareResult.updatedEntities.length === 1) {\n console.warn(`Errors with migration of encrypted metadata ${JSON.stringify(shareResult.updateErrors)}.`)\n return new ShareResultSuccess(shareResult.updatedEntities[0])\n }\n return new ShareResultFailure(\n shareResult.updateErrors,\n `There was an error sharing entity with id ${entity.entity.id}. Check the logs for more details.`\n )\n }\n\n private async makeMigrationRequestsIfNeeded(\n entity: EncryptedEntityWithType,\n userRequestsForEntity: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n ): Promise<{ [delegateId: string]: EntityShareOrMetadataUpdateRequest }> {\n const hierarchy = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n const legacySecretIds = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(entity.entity, hierarchy, SecurityMetadataType.SecretId)\n const legacyEncryptionKeys = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(\n entity.entity,\n hierarchy,\n SecurityMetadataType.EncryptionKey\n )\n const legacyOwningEntityIds = await this.securityMetadataDecryptor.decryptAllLegacyDelegations(\n entity.entity,\n hierarchy,\n SecurityMetadataType.OwningEntityId\n )\n const res = {} as { [delegateId: string]: EntityShareOrMetadataUpdateRequest }\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n for (const hierarchyMember of hierarchy) {\n const hierarchyMemberMigration = await this.makeMigrationRequestForMemberOfHierarchy(\n entity,\n selfId,\n hierarchyMember,\n userRequestsForEntity[hierarchyMember],\n legacySecretIds,\n legacyEncryptionKeys,\n legacyOwningEntityIds\n )\n if (hierarchyMemberMigration) {\n res[hierarchyMember] = hierarchyMemberMigration\n }\n }\n return res\n }\n\n private async makeMigrationRequestForMemberOfHierarchy(\n entity: EncryptedEntityWithType,\n selfId: string,\n currMemberId: string,\n userRequestForDelegate:\n | {\n shareSecretIds?: string[]\n shareEncryptionKeys?: string[]\n shareOwningEntityIds?: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n | undefined,\n legacySecretIds: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyEncryptionKeys: { decrypted: string; dataOwnersWithAccess: string[] }[],\n legacyOwningEntityIds: { decrypted: string; dataOwnersWithAccess: string[] }[]\n ): Promise<EntityShareOrMetadataUpdateRequest | undefined> {\n // This implementation is very specific from migration from delegations to secure delegations. If in future we will have to migrate from secure delegations to something else, this method may need significant changes in its logic.\n const subHierarchy = this.useParentKeys ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(currMemberId) : [currMemberId]\n const subHierarchySet = new Set(subHierarchy)\n const legacyAccess =\n selfId === entity.entity.id && currMemberId === selfId\n ? AccessLevel.WRITE\n : await this.securityMetadataDecryptor.getEntityLegacyDelegationAccessLevel(entity.entity, subHierarchy)\n if (!legacyAccess) return undefined\n const selfLegacySecretIds = legacySecretIds.filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d))).map((x) => x.decrypted)\n const selfLegacyEncryptionKeys = legacyEncryptionKeys\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n const selfLegacyOwningEntityIds = legacyOwningEntityIds\n .filter((x) => x.dataOwnersWithAccess.some((d) => subHierarchySet.has(d)))\n .map((x) => x.decrypted)\n let missingSecretIds: string[] = []\n let missingEncryptionKeys: string[] = []\n let missingOwningEntityIds: string[] = []\n if (selfLegacySecretIds.length > 0) {\n const currentSecretIds = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.SecretId)).map(\n (x) => x.decrypted\n )\n )\n missingSecretIds = selfLegacySecretIds.filter((x) => !currentSecretIds.has(x))\n }\n if (selfLegacyEncryptionKeys.length > 0) {\n const currentEncryptionKeys = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.EncryptionKey)).map(\n (x) => x.decrypted\n )\n )\n missingEncryptionKeys = selfLegacyEncryptionKeys.filter((x) => !currentEncryptionKeys.has(x))\n }\n if (selfLegacyOwningEntityIds.length > 0) {\n const currentOwningEntityIds = new Set(\n (await this.securityMetadataDecryptor.decryptAllSecureDelegations(entity.entity, [currMemberId], SecurityMetadataType.OwningEntityId)).map(\n (x) => x.decrypted\n )\n )\n missingOwningEntityIds = selfLegacyOwningEntityIds.filter((x) => !currentOwningEntityIds.has(x))\n }\n const mustCreateRootDelegation =\n selfId === entity.entity.id &&\n currMemberId === selfId &&\n !(await this.securityMetadataDecryptor.getEntitySecureDelegationAccessLevel(entity.entity, subHierarchy))\n if (missingSecretIds.length > 0 || missingEncryptionKeys.length > 0 || missingOwningEntityIds.length > 0 || mustCreateRootDelegation) {\n let requestedPermissions: RequestedPermissionInternal\n if (currMemberId === selfId) {\n requestedPermissions = RequestedPermissionInternal.ROOT\n } else {\n requestedPermissions = RequestedPermissionInternal.FULL_WRITE // Legacy permission if present is always write\n }\n return await this.secureDelegationsManager.makeShareOrUpdateRequestParams(\n entity,\n currMemberId,\n Array.from(new Set([...missingSecretIds, ...(userRequestForDelegate?.shareSecretIds ?? [])])),\n Array.from(new Set([...missingEncryptionKeys, ...(userRequestForDelegate?.shareEncryptionKeys ?? [])])),\n Array.from(new Set([...missingOwningEntityIds, ...(userRequestForDelegate?.shareOwningEntityIds ?? [])])),\n requestedPermissions\n )\n } else return undefined\n }\n\n async tryDecryptDataOf(\n entity: EncryptedEntityWithType,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> | undefined\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const triedKeys: Set<string> = new Set()\n const result = await this.doIncrementallyDecryptingKeys(entity.entity, entity.type, async (e, t, keys) => {\n for (const k of keys) {\n if (!triedKeys.has(k.raw)) {\n triedKeys.add(k.raw)\n try {\n const decrypted = await this.primitives.AES.decrypt(k.key, content)\n if (!validator || (await validator(decrypted))) return { success: decrypted }\n } catch (e) {\n console.warn(`Error while attempting to decrypt attachment of ${entity.entity.id} with raw key ${k.raw}: ${e}`)\n }\n }\n }\n return null\n })\n if (result != null) {\n return { data: result.success, wasDecrypted: true }\n } else {\n return { data: content, wasDecrypted: false }\n }\n }\n\n async encryptDataOf<T extends EncryptedEntityStub>(\n entity: T,\n type: EntityWithDelegationTypeName,\n content: ArrayBuffer | Uint8Array,\n saveEntity: (entity: T) => Promise<T>\n ): Promise<{ encryptedData: ArrayBuffer; updatedEntity: T | undefined }> {\n const ensureInitialisedKeysResult = await this.ensureEncryptionKeysInitialised(entity, type)\n let updatedEntity: T | undefined\n if (!!ensureInitialisedKeysResult) {\n updatedEntity = await saveEntity(ensureInitialisedKeysResult)\n }\n const encrypted = await this.doIncrementallyDecryptingKeys(entity, type, async (e, t, keys) => {\n for (const k of keys) {\n try {\n return {\n success: {\n encryptedData: await this.primitives.AES.encrypt(k.key, content),\n updatedEntity: updatedEntity,\n },\n }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${k.raw}: ${e}`)\n }\n }\n return null\n })\n if (encrypted != null) return encrypted.success\n throw new Error(`Could not extract any valid encryption keys for entity ${JSON.stringify(entity)}.`)\n }\n\n async tryDecryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }[]> {\n const nothingToDecryptResults = new Map<string, T>()\n for (const entity of entities) {\n const nothingToDecrypt = await decryptObject(entity, async (encrypted) => {\n return null\n })\n if (nothingToDecrypt != null) {\n nothingToDecryptResults.set(entity.id!, constructor(nothingToDecrypt))\n }\n }\n const actuallyDecryptedResults = await this.doManyIncrementallyDecryptingKeys(\n entities.filter((e) => !nothingToDecryptResults.has(e.id!)),\n entityType,\n async (entity, t, keys) => {\n // The decrypt object will try all keys on each of the sub-objects; this is intentional because even though it\n // shouldn't happen, but it is still possible that some entity could be accidentally merged badly and the merged\n // entity has multiple encryptedSelf (on different sub-entities) that use different keys.\n const decrypted = await decryptObject(entity, (encrypted) => this.tryDecryptJson(keys, encrypted, false))\n if (decrypted != null) {\n return { success: constructor(decrypted) }\n } else {\n return null\n }\n }\n )\n const res = []\n for (const entity of entities) {\n const decrypted = actuallyDecryptedResults.get(entity.id!) ?? nothingToDecryptResults.get(entity.id!)\n if (!decrypted) {\n res.push({ entity: entity, decrypted: false })\n } else {\n res.push({ entity: decrypted, decrypted: true })\n }\n }\n return res\n }\n\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | null> {\n for (const key of potentialKeys) {\n try {\n const decrypted = await this.primitives.AES.decrypt(key.key, encrypted, key.raw)\n return JSON.parse(ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted))\n } catch (e) {}\n }\n return null\n }\n\n async tryEncryptEntities<T extends EncryptedEntity>(\n entities: T[],\n entityType: EntityWithDelegationTypeName,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T[]> {\n const entitiesWithInitialisedEncryptionKeys: T[] = []\n for (const entity of entities) {\n entitiesWithInitialisedEncryptionKeys.push((await this.ensureEncryptionKeysInitialised(entity, entityType)) ?? entity)\n }\n const results = await this.doManyIncrementallyDecryptingKeys(entitiesWithInitialisedEncryptionKeys, entityType, async (e, t, keys) => {\n for (const k of keys) {\n try {\n const encrypted = await encryptObject(\n e,\n (obj) => {\n // TODO encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n\n return this.primitives.AES.encrypt(k.key, utf8_2ua(json), k.raw)\n },\n fieldsToEncrypt,\n entityType\n )\n return { success: constructor(encrypted) }\n } catch (e) {\n console.warn(`Error while encrypting with raw key ${k.raw}: ${e}`)\n }\n }\n return null\n })\n if (results.size != entitiesWithInitialisedEncryptionKeys.length) {\n if (requireEncryption) {\n throw new Error(\n `Could not encrypt entities ${entitiesWithInitialisedEncryptionKeys.flatMap((e): string[] => (results.has(e.id!) ? [] : [e.id!]))}`\n )\n } else {\n for (const e of entitiesWithInitialisedEncryptionKeys) {\n if (!results.has(e.id!)) {\n await encryptObject(\n e,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n e\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n results.set(e.id!, e)\n }\n }\n }\n }\n return entitiesWithInitialisedEncryptionKeys.map((e) => results.get(e.id!)!)\n }\n\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T, entityType: EntityWithDelegationTypeName): Promise<T | undefined> {\n if (this.securityMetadataDecryptor.hasAnyEncryptionKeys(entity)) return undefined\n if (!entity.rev) {\n throw new Error(\n 'New encrypted entity is lacking encryption metadata. ' +\n 'Please instantiate new entities using the `newInstance` method from the respective extended api.'\n )\n }\n /*\n * Add encryption key and share with all auto-delegates already in legacy delegations.\n * TODO disable this logic and simply throw error for post-2018 customers.\n */\n const existingDelegations = new Set(Object.keys(entity.delegations ?? {}))\n const usersWithAccessToNewKey = Object.fromEntries(\n Object.values((await this.userApi.getCurrentUser()).autoDelegations ?? {})\n .flatMap((x) => x)\n .filter((x) => existingDelegations.has(x))\n .map((x) => [x, AccessLevelEnum.WRITE])\n )\n return await this.secureDelegationsManager.entityWithInitialisedEncryptedMetadata(\n {\n ...entity,\n secretForeignKeys: entity.secretForeignKeys ?? [],\n },\n entityType,\n [],\n [],\n [await this.primitives.AES.generateCryptoKey(true)],\n usersWithAccessToNewKey\n )\n }\n\n private async decryptHierarchy(\n decryptedDataProvider: (dataOwners: string[]) => Promise<{ ownerId: string; extracted: string[] }[]>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n return await decryptedDataProvider(canDecryptOwnerIds)\n }\n\n private async decryptAndMergeHierarchy(\n dataOwnerId: string | undefined,\n decryptedDataProvider: (dataOwners: string[]) => Promise<{ ownerId: string; extracted: string[] }[]>\n ): Promise<string[]> {\n const hierarchy = this.useParentKeys\n ? dataOwnerId\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIdsFrom(dataOwnerId)\n : await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())]\n const decryptedData = await decryptedDataProvider(hierarchy)\n const merged = decryptedData.flatMap((x) => x.extracted)\n return this.deduplicate(merged)\n }\n\n private async tryImportKey(key: string): Promise<CryptoKey | undefined> {\n if (!/^[0-9A-Fa-f\\-]+$/g.test(key)) return undefined\n try {\n return await this.primitives.AES.importKey('raw', hex2ua(key.replace(/-/g, '')))\n } catch (e) {\n console.warn(`Could not import key ${key} as an encryption key.`, e)\n return undefined\n }\n }\n\n async doIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entity: E,\n entityType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<{ success: T } | null> {\n const res = await this.doManyIncrementallyDecryptingKeys([entity], entityType, (e, t, ks) => action(e, t, ks))\n if (res.has(entity.id!)) {\n return { success: res.get(entity.id!)! }\n } else {\n return null\n }\n }\n\n async doManyIncrementallyDecryptingKeys<E extends EncryptedEntity | EncryptedEntityStub, T>(\n entities: E[],\n entitiesType: EntityWithDelegationTypeName,\n action: (entity: E, entityType: EntityWithDelegationTypeName, keys: { key: CryptoKey; raw: string }[]) => Promise<{ success: T } | null>\n ): Promise<Map<string, T>> {\n if (entities.length == 0) return new Map()\n if (new Set(entities.map((e) => e.id)).size != entities.length) {\n throw new Error(`Duplicate entries in entities ${entities.map((x) => x.id)}`)\n }\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const allExtractedKeysForEntities = Object.fromEntries(entities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const newlyExtractedKeysForEntities = Object.fromEntries(entities.map((x) => [x.id!, new Set<string>()] as [string, Set<string>]))\n const results = new Map<string, T>()\n const remainingEntitiesById = Object.fromEntries(entities.map((x) => [x.id!, x] as [string, E]))\n const importedKeysByRaw = new Map<string, CryptoKey>()\n const primitives = this.primitives\n\n async function updateExtractedKeysAndDoActionIfNecessary(\n newKeys: { [entityId: string]: string[] },\n forceUpdateOnEntitiesWithNewExtractedKeys: boolean\n ): Promise<void> {\n for (const [entityId, keys] of Object.entries(newKeys)) {\n const newlyExtractedSet = newlyExtractedKeysForEntities[entityId]\n const alreadyExtractedSet = allExtractedKeysForEntities[entityId]\n for (const k of keys) {\n if (!alreadyExtractedSet.has(k)) {\n newlyExtractedSet.add(k)\n if (!importedKeysByRaw.has(k)) {\n importedKeysByRaw.set(k, await primitives.AES.importKey('raw', hex2ua(k)))\n }\n }\n }\n }\n if (\n forceUpdateOnEntitiesWithNewExtractedKeys ||\n Object.keys(remainingEntitiesById).every((eId) => newlyExtractedKeysForEntities[eId].size > 0)\n ) {\n for (const entity of Object.values(remainingEntitiesById)) {\n const currId = entity.id!\n const currNewlyExtracted = newlyExtractedKeysForEntities[currId]\n if (currNewlyExtracted.size > 0) {\n const currAllExtracted = allExtractedKeysForEntities[currId]\n currNewlyExtracted.forEach((k) => currAllExtracted.add(k))\n currNewlyExtracted.clear()\n const actionResult = await action(\n entity,\n entitiesType,\n [...currAllExtracted].map((raw): { raw: string; key: CryptoKey } => ({\n raw: raw,\n key: importedKeysByRaw.get(raw)!,\n }))\n )\n if (actionResult != null) {\n delete remainingEntitiesById[currId]\n results.set(currId, actionResult.success)\n }\n }\n }\n }\n }\n\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptLegacyDelegations(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingCache(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingKnownExchangeData(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary(\n await this.securityMetadataDecryptor.decryptSecureDelegationsUsingExchangeDataMap(\n Object.values(remainingEntitiesById),\n hierarchy,\n SecurityMetadataType.EncryptionKey\n ),\n false\n )\n if (Object.keys(remainingEntitiesById).length == 0) return results\n await updateExtractedKeysAndDoActionIfNecessary({}, true)\n return results\n }\n\n private deduplicate<T>(values: T[]): T[] {\n return [...new Set(values)]\n }\n\n private throwDetailedExceptionForInvalidParameter(argName: string, argValue: any, methodName: string, methodArgs: IArguments) {\n if (argValue) return\n\n let details = '\\nMethod name: icc-crypto-x-api.' + methodName + '()\\nArguments:'\n\n if (methodArgs) {\n try {\n const argsArray = [...methodArgs]\n argsArray.forEach((arg, index) => (details += '\\n[' + index + ']: ' + JSON.stringify(arg)))\n } catch (ex) {\n details += '; a problem occured while logging arguments details: ' + ex\n }\n }\n\n throw new Error('### THIS SHOULD NOT HAPPEN: ' + argName + ' has an invalid value: ' + argValue + details)\n }\n\n private checkEmptyEncryptionMetadata(entity: EncryptedEntity) {\n this.doCheckEmptyEncryptionMetadata(entity, true)\n }\n\n hasEmptyEncryptionMetadata(entity: EncryptedEntity): boolean {\n return this.doCheckEmptyEncryptionMetadata(entity, false)\n }\n\n private doCheckEmptyEncryptionMetadata(entity: EncryptedEntity, throwErrorIfNonEmpty: boolean): boolean {\n const existingMetadata = []\n if (entity.delegations && Object.keys(entity.delegations).length) existingMetadata.push('delegations')\n if (entity.cryptedForeignKeys && Object.keys(entity.cryptedForeignKeys).length) existingMetadata.push('cryptedForeignKeys')\n if (entity.encryptionKeys && Object.keys(entity.encryptionKeys).length) existingMetadata.push('encryptionKeys')\n if (entity.secretForeignKeys && entity.secretForeignKeys.length) existingMetadata.push('secretForeignKeys')\n if (entity.securityMetadata && Object.keys(entity.securityMetadata).length) existingMetadata.push('securityMetadata')\n if (existingMetadata.length > 0) {\n if (throwErrorIfNonEmpty) {\n throw new Error(\n `Entity should have no encryption metadata on initialisation, but the following fields already have some values: ${existingMetadata}\\n` +\n JSON.stringify(entity, undefined, 2)\n )\n } else return false\n }\n return true\n }\n}\n"]}
|
|
@@ -148,7 +148,7 @@ class IccHcpartyXApi extends icc_api_1.IccHcpartyApi {
|
|
|
148
148
|
isValidCbe(cbe) {
|
|
149
149
|
cbe = cbe.replace(new RegExp('[^(0-9)]', 'g'), '');
|
|
150
150
|
cbe = cbe.length == 9 ? '0' + cbe : cbe;
|
|
151
|
-
return 97 - (Number(cbe.substring(0, 8)) % 97) === Number(cbe.substring(8,
|
|
151
|
+
return 97 - (Number(cbe.substring(0, 8)) % 97) === Number(cbe.substring(8, 10));
|
|
152
152
|
}
|
|
153
153
|
subscribeToHealthcarePartyEvents(eventTypes, filter, eventFired, options = {}) {
|
|
154
154
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icc-hcparty-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-hcparty-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAEtD,kDAAiD;AACjD,qDAA8E;AAC9E,0EAAgG;AAEhG,mCAAsE;AACtE,4DAAwE;AACxE,oDAAmD;AAEnD,qCAAqC;AACrC,MAAa,cAAe,SAAQ,uBAAa;IAK/C,YACE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC9D,OAAmB,EACpC,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QAPtC,YAAO,GAAP,OAAO,CAAY;QARtC,qBAAgB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AC1D,UAA+B,EAAE;;YAEjC,OAAO,IAAA,+BAAuB,EAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CACtH,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAC/B,CAAA;QACH,CAAC;KAAA;CACF;AA1KD,wCA0KC","sourcesContent":["import { IccAuthApi, IccHcpartyApi } from '../icc-api'\nimport { HealthcareParty } from '../icc-api/model/HealthcareParty'\nimport * as models from '../icc-api/model/models'\nimport { findName, garnishPersonWithName, hasName } from './utils/person-util'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { AbstractFilter } from './filters/filters'\nimport { subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { ListOfIds } from '../icc-api/model/models'\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccHcpartyXApi extends IccHcpartyApi {\n hcPartyKeysCache: { [key: string]: { [key: string]: string } } = {}\n hcPartyCache: { [key: string]: [number, Promise<HealthcareParty>] } = {}\n\n private CACHE_RETENTION_IN_MS = 300_000\n constructor(\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n private readonly authApi: IccAuthApi,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n }\n\n private getHcPartyFromCache(key: string) {\n const hcpInCache = this.hcPartyCache[key]\n const now = Date.now()\n if (hcpInCache && hcpInCache[0] > now) {\n return hcpInCache[1]\n }\n if (!hcpInCache) {\n console.log(`Cache miss for key ${key} because not in cache`)\n } else {\n console.log(`Cache miss for key ${key} because ${hcpInCache[0]} > ${now}`)\n }\n return null\n }\n\n completeNames(hcParty?: models.HealthcareParty): models.HealthcareParty | undefined {\n if (!hcParty) {\n return hcParty\n }\n\n let finalHcParty = hcParty\n\n if ((!!finalHcParty.lastName || !!finalHcParty.name) && !hasName(finalHcParty, models.PersonName.UseEnum.Official)) {\n finalHcParty = garnishPersonWithName(\n finalHcParty,\n models.PersonName.UseEnum.Official,\n finalHcParty.lastName,\n finalHcParty.firstName,\n finalHcParty.name\n )\n }\n\n if ((!finalHcParty.lastName || !finalHcParty.name) && !!hasName(finalHcParty, models.PersonName.UseEnum.Official)) {\n let officialName = findName(finalHcParty, models.PersonName.UseEnum.Official)\n finalHcParty = {\n ...finalHcParty,\n lastName: officialName!.lastName,\n firstName: officialName!.firstNames ? officialName!.firstNames[0] : undefined,\n name: officialName!.text,\n }\n }\n\n return finalHcParty\n }\n\n putHcPartyInCache(key: string, hcpPromise: Promise<HealthcareParty>): Promise<HealthcareParty> {\n this.hcPartyCache[key] = [Date.now() + this.CACHE_RETENTION_IN_MS, hcpPromise]\n return hcpPromise\n }\n\n createHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty> {\n return super.createHealthcareParty(this.completeNames(body))\n }\n\n createHealthcarePartyInGroup(groupId: string, body?: HealthcareParty): Promise<HealthcareParty> {\n return super.createHealthcarePartyInGroup(groupId, this.completeNames(body))\n }\n\n modifyHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty | any> {\n if (body && body.id) {\n console.log(`Evict key ${body.id} because of modification`)\n delete this.hcPartyCache[body.id]\n }\n\n return super.modifyHealthcareParty(this.completeNames(body)).then((hcp) => this.putHcPartyInCache(hcp.id!, Promise.resolve(hcp)))\n }\n\n async getHealthcareParty(healthcarePartyId: string, bypassCache = false): Promise<HealthcareParty | any> {\n const fromCache = bypassCache ? undefined : this.getHcPartyFromCache(healthcarePartyId)\n if (fromCache) {\n try {\n return await fromCache\n } catch {\n if (this.hcPartyCache[healthcarePartyId][1] === fromCache) {\n delete this.hcPartyCache[healthcarePartyId]\n }\n return this.getHealthcareParty(healthcarePartyId, bypassCache)\n }\n } else {\n return await this.putHcPartyInCache(healthcarePartyId, super.getHealthcareParty(healthcarePartyId))\n }\n }\n\n getHealthcarePartyHierarchyIds(healthcarePartyId: string, bypassCache = false): Promise<string[]> {\n return this.getHealthcareParty(healthcarePartyId, bypassCache).then(async (hcp: HealthcareParty) => {\n return hcp ? (hcp.parentId ? (await this.getHealthcarePartyHierarchyIds(hcp.parentId!, bypassCache)).concat([hcp.id!]) : [hcp.id!]) : []\n })\n }\n\n async getHealthcareParties(healthcarePartyIds: ListOfIds): Promise<Array<HealthcareParty> | any> {\n const ids = healthcarePartyIds.ids\n if (!ids || !ids.length) {\n return Promise.resolve([])\n }\n const cached: Array<[string, HealthcareParty | null]> = []\n for (const id of ids) {\n let hcp\n try {\n hcp = await this.getHcPartyFromCache(id)\n } catch {\n hcp = null\n delete this.hcPartyCache[id]\n }\n cached.push([id, hcp])\n }\n const toFetch = cached.filter((x) => !x[1]).map((x) => x[0])\n\n if (!toFetch.length) {\n return Promise.all(cached.map((x) => x[1]!))\n }\n\n const prom: Promise<HealthcareParty[]> = super.getHealthcareParties(new ListOfIds({ ids: toFetch }))\n return Promise.all(\n cached.map(\n (x) =>\n x[1] ??\n this.putHcPartyInCache(\n x[0],\n prom.then((hcps) => {\n const hcp = hcps.find((h) => h.id === x[0])\n if (!!hcp) {\n return hcp\n } else {\n throw new Error(`Hcp with id ${x[0]} not found`)\n }\n })\n )\n )\n )\n }\n\n getCurrentHealthcareParty(): Promise<HealthcareParty> {\n return super.getCurrentHealthcareParty().then((hcp) => this.putHcPartyInCache(hcp.id!, Promise.resolve(hcp)))\n }\n\n isValidCbe(cbe: string) {\n cbe = cbe.replace(new RegExp('[^(0-9)]', 'g'), '')\n cbe = cbe.length == 9 ? '0' + cbe : cbe\n\n return 97 - (Number(cbe.substring(0, 8)) % 97) === Number(cbe.substring(8, 2))\n }\n\n async subscribeToHealthcarePartyEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<HealthcareParty> | undefined,\n eventFired: (dataSample: HealthcareParty) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n return subscribeToEntityEvents(this.host, this.authApi, 'HealthcareParty', eventTypes, filter, eventFired, options).then(\n (rs) => new ConnectionImpl(rs)\n )\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"icc-hcparty-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-hcparty-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAEtD,kDAAiD;AACjD,qDAA8E;AAC9E,0EAAgG;AAEhG,mCAAsE;AACtE,4DAAwE;AACxE,oDAAmD;AAEnD,qCAAqC;AACrC,MAAa,cAAe,SAAQ,uBAAa;IAK/C,YACE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC9D,OAAmB,EACpC,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QAPtC,YAAO,GAAP,OAAO,CAAY;QARtC,qBAAgB,GAAiD,EAAE,CAAA;QACnE,iBAAY,GAA0D,EAAE,CAAA;QAEhE,0BAAqB,GAAG,MAAO,CAAA;IAavC,CAAC;IAEO,mBAAmB,CAAC,GAAW;QACrC,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAA;QACzC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAA;QACtB,IAAI,UAAU,IAAI,UAAU,CAAC,CAAC,CAAC,GAAG,GAAG,EAAE;YACrC,OAAO,UAAU,CAAC,CAAC,CAAC,CAAA;S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'../icc-api/model/HealthcareParty'\nimport * as models from '../icc-api/model/models'\nimport { findName, garnishPersonWithName, hasName } from './utils/person-util'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { AbstractFilter } from './filters/filters'\nimport { subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { ListOfIds } from '../icc-api/model/models'\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccHcpartyXApi extends IccHcpartyApi {\n hcPartyKeysCache: { [key: string]: { [key: string]: string } } = {}\n hcPartyCache: { [key: string]: [number, Promise<HealthcareParty>] } = {}\n\n private CACHE_RETENTION_IN_MS = 300_000\n constructor(\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n private readonly authApi: IccAuthApi,\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n }\n\n private getHcPartyFromCache(key: string) {\n const hcpInCache = this.hcPartyCache[key]\n const now = Date.now()\n if (hcpInCache && hcpInCache[0] > now) {\n return hcpInCache[1]\n }\n if (!hcpInCache) {\n console.log(`Cache miss for key ${key} because not in cache`)\n } else {\n console.log(`Cache miss for key ${key} because ${hcpInCache[0]} > ${now}`)\n }\n return null\n }\n\n completeNames(hcParty?: models.HealthcareParty): models.HealthcareParty | undefined {\n if (!hcParty) {\n return hcParty\n }\n\n let finalHcParty = hcParty\n\n if ((!!finalHcParty.lastName || !!finalHcParty.name) && !hasName(finalHcParty, models.PersonName.UseEnum.Official)) {\n finalHcParty = garnishPersonWithName(\n finalHcParty,\n models.PersonName.UseEnum.Official,\n finalHcParty.lastName,\n finalHcParty.firstName,\n finalHcParty.name\n )\n }\n\n if ((!finalHcParty.lastName || !finalHcParty.name) && !!hasName(finalHcParty, models.PersonName.UseEnum.Official)) {\n let officialName = findName(finalHcParty, models.PersonName.UseEnum.Official)\n finalHcParty = {\n ...finalHcParty,\n lastName: officialName!.lastName,\n firstName: officialName!.firstNames ? officialName!.firstNames[0] : undefined,\n name: officialName!.text,\n }\n }\n\n return finalHcParty\n }\n\n putHcPartyInCache(key: string, hcpPromise: Promise<HealthcareParty>): Promise<HealthcareParty> {\n this.hcPartyCache[key] = [Date.now() + this.CACHE_RETENTION_IN_MS, hcpPromise]\n return hcpPromise\n }\n\n createHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty> {\n return super.createHealthcareParty(this.completeNames(body))\n }\n\n createHealthcarePartyInGroup(groupId: string, body?: HealthcareParty): Promise<HealthcareParty> {\n return super.createHealthcarePartyInGroup(groupId, this.completeNames(body))\n }\n\n modifyHealthcareParty(body?: HealthcareParty): Promise<HealthcareParty | any> {\n if (body && body.id) {\n console.log(`Evict key ${body.id} because of modification`)\n delete this.hcPartyCache[body.id]\n }\n\n return super.modifyHealthcareParty(this.completeNames(body)).then((hcp) => this.putHcPartyInCache(hcp.id!, Promise.resolve(hcp)))\n }\n\n async getHealthcareParty(healthcarePartyId: string, bypassCache = false): Promise<HealthcareParty | any> {\n const fromCache = bypassCache ? undefined : this.getHcPartyFromCache(healthcarePartyId)\n if (fromCache) {\n try {\n return await fromCache\n } catch {\n if (this.hcPartyCache[healthcarePartyId][1] === fromCache) {\n delete this.hcPartyCache[healthcarePartyId]\n }\n return this.getHealthcareParty(healthcarePartyId, bypassCache)\n }\n } else {\n return await this.putHcPartyInCache(healthcarePartyId, super.getHealthcareParty(healthcarePartyId))\n }\n }\n\n getHealthcarePartyHierarchyIds(healthcarePartyId: string, bypassCache = false): Promise<string[]> {\n return this.getHealthcareParty(healthcarePartyId, bypassCache).then(async (hcp: HealthcareParty) => {\n return hcp ? (hcp.parentId ? (await this.getHealthcarePartyHierarchyIds(hcp.parentId!, bypassCache)).concat([hcp.id!]) : [hcp.id!]) : []\n })\n }\n\n async getHealthcareParties(healthcarePartyIds: ListOfIds): Promise<Array<HealthcareParty> | any> {\n const ids = healthcarePartyIds.ids\n if (!ids || !ids.length) {\n return Promise.resolve([])\n }\n const cached: Array<[string, HealthcareParty | null]> = []\n for (const id of ids) {\n let hcp\n try {\n hcp = await this.getHcPartyFromCache(id)\n } catch {\n hcp = null\n delete this.hcPartyCache[id]\n }\n cached.push([id, hcp])\n }\n const toFetch = cached.filter((x) => !x[1]).map((x) => x[0])\n\n if (!toFetch.length) {\n return Promise.all(cached.map((x) => x[1]!))\n }\n\n const prom: Promise<HealthcareParty[]> = super.getHealthcareParties(new ListOfIds({ ids: toFetch }))\n return Promise.all(\n cached.map(\n (x) =>\n x[1] ??\n this.putHcPartyInCache(\n x[0],\n prom.then((hcps) => {\n const hcp = hcps.find((h) => h.id === x[0])\n if (!!hcp) {\n return hcp\n } else {\n throw new Error(`Hcp with id ${x[0]} not found`)\n }\n })\n )\n )\n )\n }\n\n getCurrentHealthcareParty(): Promise<HealthcareParty> {\n return super.getCurrentHealthcareParty().then((hcp) => this.putHcPartyInCache(hcp.id!, Promise.resolve(hcp)))\n }\n\n isValidCbe(cbe: string) {\n cbe = cbe.replace(new RegExp('[^(0-9)]', 'g'), '')\n cbe = cbe.length == 9 ? '0' + cbe : cbe\n\n return 97 - (Number(cbe.substring(0, 8)) % 97) === Number(cbe.substring(8, 10))\n }\n\n async subscribeToHealthcarePartyEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<HealthcareParty> | undefined,\n eventFired: (dataSample: HealthcareParty) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n return subscribeToEntityEvents(this.host, this.authApi, 'HealthcareParty', eventTypes, filter, eventFired, options).then(\n (rs) => new ConnectionImpl(rs)\n )\n }\n}\n"]}
|
|
@@ -635,7 +635,7 @@ class IccPatientXApi extends icc_api_1.IccPatientApi {
|
|
|
635
635
|
}
|
|
636
636
|
checkInami(inami) {
|
|
637
637
|
const num_inami = inami.replace(new RegExp('[^(0-9)]', 'g'), '');
|
|
638
|
-
const checkDigit = num_inami.substring(6,
|
|
638
|
+
const checkDigit = num_inami.substring(6, 8);
|
|
639
639
|
const numSansCheck = num_inami.substring(0, 6);
|
|
640
640
|
let retour = false;
|
|
641
641
|
//modulo du niss
|
|
@@ -655,9 +655,9 @@ class IccPatientXApi extends icc_api_1.IccPatientApi {
|
|
|
655
655
|
const terNumber = /^[0-9][0-9](([4][0-9])|([5][0-2]))(([0-2][0-9])|([3][0-1]))[0-9]{3}(([0-8][0-9])|([9][0-7]))$/.test(ssin);
|
|
656
656
|
if (normalNumber || bisNumber || terNumber) {
|
|
657
657
|
isValidNiss =
|
|
658
|
-
97 - (Number(ssin.substring(0, 9)) % 97) === Number(ssin.substring(9,
|
|
658
|
+
97 - (Number(ssin.substring(0, 9)) % 97) === Number(ssin.substring(9, 11))
|
|
659
659
|
? true
|
|
660
|
-
: 97 - (Number('2' + ssin.substring(0, 9)) % 97) === Number(ssin.substring(9,
|
|
660
|
+
: 97 - (Number('2' + ssin.substring(0, 9)) % 97) === Number(ssin.substring(9, 11));
|
|
661
661
|
}
|
|
662
662
|
return isValidNiss;
|
|
663
663
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icc-patient-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-patient-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAUtD,4BAA2B;AAC3B,kDAAiD;AACjD,oDAAkG;AAElG,8DAAsD;AACtD,qDAA8E;AAC9E,mCAA4H;AAE5H,0EAAgG;AAChG,uFAAmF;AACnF,wEAAoE;AAEpE,qFAAiF;AACjF,4EAAwE;AAExE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACzD,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAK3E,4DAAwE;AAGxE,qCAAqC;AACrC,MAAa,cAAe,SAAQ,uBAAa;IAG/C,IAAI,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AC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,2BAAc,CAAC,EAAE,CAAC,CAAC,CAAA;QACxC,CAAC;KAAA;IAED,uCAAuC,CAAC,MAAe,EAAE,SAAmB;QAC1E,OAAO,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAC,iCAAiC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,2DAA4B,CAAC,OAAO,EAAE,EAAE,SAAS,CAAC,CAAA;IACpJ,CAAC;IAED;;;;;;;;;;;;;;;;OAgBG;IACG,gDAAgD,CAAC,SAAiB;;;;;YACtE,MAAM,OAAO,GAAG,MAAM,OAAM,UAAU,YAAC,SAAS,CAAC,CAAA;YACjD,IAAI,IAAI,CAAC,YAAY,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,IAAI;gBAAE,OAAO,KAAK,CAAA;YACpE,MAAM,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,2BAA2B,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;YAC3E,OAAO,IAAI,CAAA;QACb,CAAC;KAAA;CACF;AA5vCD,wCA4vCC","sourcesContent":["import { IccAuthApi, IccPatientApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccFormXApi } from './icc-form-x-api'\nimport { IccHcpartyXApi } from './icc-hcparty-x-api'\nimport { IccInvoiceXApi } from './icc-invoice-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { IccClassificationXApi } from './icc-classification-x-api'\n\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\nimport { Document, IcureStub, ListOfIds, MaintenanceTask, Patient } from '../icc-api/model/models'\nimport { IccCalendarItemXApi } from './icc-calendar-item-x-api'\nimport { b64_2ab } from '../icc-api/model/ModelHelper'\nimport { findName, garnishPersonWithName, hasName } from './utils/person-util'\nimport { EncryptedFieldsManifest, parseEncryptedFields, retry, subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { EntityWithDelegationTypeName } from './utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport { MinimalEntityBulkShareResult } from '../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { IccUserXApi } from './icc-user-x-api'\nimport { AbstractFilter } from './filters/filters'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { BulkShareOrUpdateMetadataParams } from '../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccPatientXApi extends IccPatientApi implements EncryptedEntityXApi<models.Patient> {\n private readonly encryptedFields: EncryptedFieldsManifest\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Patient))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly contactApi: IccContactXApi,\n private readonly formApi: IccFormXApi,\n private readonly helementApi: IccHelementXApi,\n private readonly invoiceApi: IccInvoiceXApi,\n private readonly documentApi: IccDocumentXApi,\n private readonly hcpartyApi: IccHcpartyXApi,\n private readonly classificationApi: IccClassificationXApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly calendarItemApi: IccCalendarItemXApi,\n private readonly userApi: IccUserXApi,\n private readonly authApi: IccAuthApi,\n private readonly autofillAuthor: boolean,\n encryptedKeys: Array<string> = ['note'],\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n\n this.encryptedFields = parseEncryptedFields(encryptedKeys, 'Patient.')\n }\n\n /**\n * Creates a new instance of patient with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param p initialised data for the patient. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify\n * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.\n * @param options optional parameters:\n * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the\n * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with\n * auto-delegations, in such case the access level specified here will be used.\n * @return a new instance of patient.\n */\n async newInstance(\n user: models.User,\n p: any = {},\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n } = {}\n ) {\n const patient = {\n ...(p ?? {}),\n _type: 'org.taktik.icure.entities.Patient',\n id: p?.id ?? this.crypto.primitives.randomUuid(),\n created: p?.created ?? new Date().getTime(),\n modified: p?.modified ?? new Date().getTime(),\n responsible: p?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: p?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: p?.codes ?? [],\n tags: p?.tags ?? [],\n }\n\n const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) throw new Error('Can only initialise entities as current data owner.')\n const extraDelegations = {\n ...Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n ),\n ...(options?.additionalDelegates ?? {}),\n }\n const initialisationInfo = await this.crypto.xapi.entityWithInitialisedEncryptedMetadata(\n patient,\n EntityWithDelegationTypeName.Patient,\n undefined,\n undefined,\n true,\n extraDelegations\n )\n return new models.Patient(initialisationInfo.updatedEntity)\n }\n\n completeNames(patient: models.Patient): models.Patient {\n let finalPatient: any = patient\n\n if (!!finalPatient.lastName && !hasName(finalPatient, models.PersonName.UseEnum.Official)) {\n finalPatient = garnishPersonWithName(finalPatient, models.PersonName.UseEnum.Official, finalPatient.lastName, finalPatient.firstName)\n }\n\n if (!!finalPatient.maidenName && !hasName(finalPatient, models.PersonName.UseEnum.Maiden)) {\n finalPatient = garnishPersonWithName(finalPatient, models.PersonName.UseEnum.Maiden, finalPatient.maidenName, finalPatient.firstName)\n }\n\n if (!!finalPatient.alias && !hasName(finalPatient, models.PersonName.UseEnum.Nickname)) {\n finalPatient = garnishPersonWithName(finalPatient, models.PersonName.UseEnum.Nickname, finalPatient.alias, finalPatient.firstName)\n }\n\n if (!finalPatient.lastName && !!hasName(finalPatient, models.PersonName.UseEnum.Official)) {\n const officialName = findName(finalPatient, models.PersonName.UseEnum.Official)\n finalPatient = {\n ...finalPatient,\n lastName: officialName!.lastName,\n firstName: officialName!.firstNames?.[0],\n }\n }\n\n if (!finalPatient.maidenName && !!hasName(finalPatient, models.PersonName.UseEnum.Maiden)) {\n finalPatient = {\n ...finalPatient,\n maidenName: findName(finalPatient, models.PersonName.UseEnum.Maiden)!.lastName,\n }\n }\n\n if (!finalPatient.alias && !!hasName(finalPatient, models.PersonName.UseEnum.Nickname)) {\n finalPatient = {\n ...finalPatient,\n alias: findName(finalPatient, models.PersonName.UseEnum.Nickname)!.lastName,\n }\n }\n\n return new Patient(finalPatient)\n }\n\n /**\n * @deprecated replace with {@link initConfidentialSecretId}\n */\n async initConfidentialDelegation(patient: models.Patient, user: models.User): Promise<models.Patient> {\n return this.initConfidentialSecretId(patient, user)\n }\n\n /**\n * Ensures that the current data owner has some confidential secret ids for the provided patient. If not creates them and updates the patient in the\n * database.\n * @param patient the patient for which you want to initialise the confidential secret id.\n * @param user the current user.\n * @return the updated patient or the original patient if no change was necessary.\n */\n async initConfidentialSecretId(patient: models.Patient, user: models.User): Promise<models.Patient> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (dataOwnerId !== (await this.dataOwnerApi.getCurrentDataOwnerId()))\n throw new Error('You can initialise confidential delegations only for the current data owner')\n let updatedPatient = patient\n if (!patient.rev) {\n updatedPatient = await this.createPatientWithUser(user, patient)\n if (!updatedPatient) throw new Error('Could not create patient')\n }\n const initialised = await this.crypto.confidential.initialiseConfidentialSecretId(updatedPatient, EntityWithDelegationTypeName.Patient, (x) =>\n this.bulkSharePatients(x)\n )\n if (initialised) {\n return initialised\n } else {\n return updatedPatient\n }\n }\n\n createPatient(body?: models.Patient): never {\n throw new Error('Cannot call a method that returns patients without providing a user for de/encryption')\n }\n\n createPatientWithUser(user: models.User, body?: models.Patient): Promise<models.Patient | any> {\n return body\n ? this.encrypt(user, [_.cloneDeep(this.completeNames(body))])\n .then((pats) => super.createPatient(pats[0]))\n .then(async (patient: Patient) => {\n /**\n * This code is a workaround for the fact that the backend is adding empty delegations to the patient when it is created.\n */\n\n const patientDelegations = patient.delegations\n\n if (patientDelegations != undefined && Object.keys(patientDelegations).length > 0) {\n const areDelegationsEmpty = Object\n .values(patientDelegations)\n .every((delegation) => delegation.length === 0)\n\n if (areDelegationsEmpty) {\n return await this.modifyPatientRaw(\n new Patient({\n ...patient,\n delegations: {},\n })\n )\n }\n }\n return patient\n })\n .then((p) => this.decrypt(user, [p]))\n .then((pats) => pats[0])\n : Promise.resolve(null)\n }\n\n filterBy(\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n skip?: number,\n sort?: string,\n desc?: boolean,\n body?: models.FilterChainPatient\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n filterByWithUser(\n user: models.User,\n filterChain: models.FilterChainPatient,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n skip?: number,\n sort?: string,\n desc?: boolean\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .filterPatientsBy(startKey, startDocumentId, limit, skip, sort, desc, filterChain)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n findByAccessLogUserAfterDate(\n userId: string,\n accessType?: string,\n startDate?: number,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n findByAccessLogUserAfterDateWithUser(\n user: models.User,\n userId: string,\n accessType?: string,\n startDate?: number,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .findByAccessLogUserAfterDate(userId, accessType, startDate, startKey, startDocumentId, limit)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n findByAccessLogUserAfterDate_1(externalId: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n findByExternalIdWithUser(user: models.User, externalId: string): Promise<models.Patient | any> {\n return super\n .findByExternalId(externalId)\n .then((pats) => this.decrypt(user, [pats]))\n .then((x) => x[0])\n }\n\n findByNameBirthSsinAuto(\n healthcarePartyId?: string,\n filterValue?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n findByNameBirthSsinAutoWithUser(\n user: models.User,\n healthcarePartyId?: string,\n filterValue?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .findByNameBirthSsinAuto(healthcarePartyId, filterValue, startKey, startDocumentId, limit, sortDirection)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n fuzzySearch(firstName?: string, lastName?: string, dateOfBirth?: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n fuzzySearchWithUser(user: models.User, firstName?: string, lastName?: string, dateOfBirth?: number): Promise<Array<models.Patient> | any> {\n return super.fuzzySearch(firstName, lastName, dateOfBirth).then((pats) => this.decrypt(user, pats))\n }\n\n getPatient(patientId: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n getPatientRaw(patientId: string): Promise<models.Patient | any> {\n return super.getPatient(patientId)\n }\n\n getPatientWithUser(user: models.User, patientId: string): Promise<models.Patient | any> {\n return super\n .getPatient(patientId)\n .then((p) => this.tryDecryptOrReturnOriginal([p]))\n .then((pats) => pats[0].entity)\n }\n\n getPotentiallyEncryptedPatientWithUser(user: models.User, patientId: string): Promise<{ patient: models.Patient; decrypted: boolean }> {\n return super\n .getPatient(patientId)\n .then((p) => this.tryDecryptOrReturnOriginal([p]))\n .then((pats) => ({ patient: pats[0].entity, decrypted: pats[0].decrypted }))\n }\n\n getPatients(body?: models.ListOfIds): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n getPatientsWithUser(user: models.User, body?: models.ListOfIds): Promise<Array<models.Patient> | any> {\n return super.getPatients(body).then((pats) => this.decrypt(user, pats))\n }\n\n listDeletedPatients(startDate?: number, endDate?: number, desc?: boolean, startKey?: string, startDocumentId?: string, limit?: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listDeletedPatientsWithUser(\n user: models.User,\n startDate?: number,\n endDate?: number,\n desc?: boolean,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listDeletedPatients(startDate, endDate, desc, startDocumentId, startKey, limit)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n listDeletedPatients_2(firstName?: string, lastName?: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listDeletedPatientsByNameWithUser(user: models.User, firstName?: string, lastName?: string): Promise<Array<models.Patient> | any> {\n return super.listDeletedPatientsByName(firstName, lastName).then((rows) => this.decrypt(user, rows, false))\n }\n\n listOfMergesAfter(date: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listOfMergesAfterWithUser(user: models.User, date: number): Promise<Array<models.Patient> | any> {\n return super.listOfMergesAfter(date).then((pats) => this.decrypt(user, pats, false))\n }\n\n listOfPatientsModifiedAfter(date: number, startKey?: number, startDocumentId?: string, limit?: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listOfPatientsModifiedAfterWithUser(\n user: models.User,\n date: number,\n startKey?: number,\n startDocumentId?: string,\n limit?: number\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listOfPatientsModifiedAfter(date, startKey, startDocumentId, limit)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n listPatients(hcPartyId?: string, sortField?: string, startKey?: string, startDocumentId?: string, limit?: number, sortDirection?: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listPatientsWithUser(\n user: models.User,\n hcPartyId?: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listPatients(hcPartyId, sortField, startKey, startDocumentId, limit, sortDirection)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n listPatientsByHcParty(\n hcPartyId: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listPatientsByHcPartyWithUser(\n user: models.User,\n hcPartyId: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listPatientsByHcParty(hcPartyId, sortField, startKey, startDocumentId, limit, sortDirection)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n listPatientsOfHcParty(\n hcPartyId: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listPatientsOfHcPartyWithUser(\n user: models.User,\n hcPartyId: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listPatientsOfHcParty(hcPartyId, sortField, startKey, startDocumentId, limit, sortDirection)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n mergeInto(toId: string, fromIds: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n mergeIntoWithUser(user: models.User, toId: string, fromIds: string): Promise<models.Patient | any> {\n return super\n .mergeInto(toId, fromIds)\n .then((p) => this.decrypt(user, [p]))\n .then((pats) => pats[0])\n }\n\n modifyPatient(body?: models.Patient): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n modifyPatientRaw(body?: models.Patient): Promise<models.Patient | any> {\n return super.modifyPatient(body)\n }\n\n modifyPatientWithUser(user: models.User, body?: models.Patient): Promise<models.Patient | null> {\n return body ? this.modifyPatientAs(this.dataOwnerApi.getDataOwnerIdOf(user), body) : Promise.resolve(null)\n }\n\n private modifyPatientAs(dataOwner: string, body: models.Patient): Promise<models.Patient> {\n return this.encryptAs(dataOwner, [_.cloneDeep(this.completeNames(body))])\n .then((pats) => super.modifyPatient(pats[0]))\n .then((p) => this.decryptAs(dataOwner, [p]))\n .then((pats) => pats[0])\n }\n\n modifyPatientReferral(patientId: string, referralId: string, start?: number, end?: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n modifyPatientReferralWithUser(\n user: models.User,\n patientId: string,\n referralId: string,\n start?: number,\n end?: number\n ): Promise<models.Patient | any> {\n return super\n .modifyPatientReferral(patientId, referralId, start, end)\n .then((p) => this.decrypt(user, [p]))\n .then((pats) => pats[0])\n }\n\n encrypt(user: models.User, pats: Array<models.Patient>): Promise<Array<models.Patient>> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n return this.encryptAs(dataOwnerId, pats)\n }\n\n private encryptAs(dataOwner: string, pats: Array<models.Patient>): Promise<Array<models.Patient>> {\n return this.crypto.xapi.tryEncryptEntities(\n pats,\n EntityWithDelegationTypeName.Patient,\n this.encryptedFields,\n true,\n false,\n (x) => new models.Patient(x)\n )\n }\n\n // If patient can't be decrypted returns patient with encrypted data.\n decrypt(user: models.User, patients: Array<models.Patient>, fillDelegations = true): Promise<Array<models.Patient>> {\n return this.decryptAs(this.dataOwnerApi.getDataOwnerIdOf(user), patients, fillDelegations)\n }\n\n private decryptAs(dataOwner: string, patients: Array<models.Patient>, fillDelegations = true): Promise<Array<models.Patient>> {\n return this.tryDecryptOrReturnOriginal(patients).then((ps) => ps.map((p) => p.entity))\n }\n\n async tryDecryptOrReturnOriginal(patients: Array<models.Patient>): Promise<{ entity: models.Patient; decrypted: boolean }[]> {\n return (await this.crypto.xapi.tryDecryptEntities(patients, EntityWithDelegationTypeName.Patient, (x) => new models.Patient(x))).map((p) => {\n if (p.entity.picture && !(p.entity.picture instanceof ArrayBuffer)) {\n return {\n entity: new models.Patient({\n ...p.entity,\n picture: b64_2ab(p.entity.picture),\n }),\n decrypted: p.decrypted,\n }\n } else return p\n })\n }\n\n /**\n * @deprecated replace with {@link shareAllDataOfPatient}\n */\n async share(\n user: models.User,\n patId: string,\n ownerId: string,\n delegateIds: Array<string>,\n delegationTags: { [key: string]: Array<string> },\n usingPost: boolean = false\n ): Promise<{\n patient: models.Patient | null\n statuses: { [key: string]: { success: boolean | null; error: Error | null } }\n } | null> {\n return this.shareAllDataOfPatient(user, patId, ownerId, delegateIds, delegationTags, usingPost)\n }\n\n async shareAllDataOfPatient(\n user: models.User,\n patId: string,\n ownerId: string,\n delegateIds: Array<string>,\n delegationTags: { [key: string]: Array<string> },\n usingPost: boolean = false\n ): Promise<{\n patient: models.Patient | null\n statuses: { [key: string]: { success: boolean | null; error: Error | null } }\n } | null> {\n const allTags: string[] = _.uniq(_.flatMap(Object.values(delegationTags)))\n const status = {\n contacts: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n forms: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n healthElements: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n invoices: {\n success: allTags.includes('financialInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n documents: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n classifications: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n calendarItems: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n patient: { success: false, error: null, modified: 0 } as {\n success: boolean\n error: Error | null\n },\n }\n const hcp = await this.hcpartyApi.getHealthcareParty(ownerId)\n const parentId = hcp.parentId\n let patient = await retry(() => this.getPatientWithUser(user, patId))\n const patientWithInitialisedEncryption = await this.crypto.xapi.ensureEncryptionKeysInitialised(patient, EntityWithDelegationTypeName.Patient)\n if (patientWithInitialisedEncryption) {\n patient = await this.modifyPatientWithUser(user, patientWithInitialisedEncryption)\n }\n\n if (!patient) {\n status.patient = {\n success: false,\n error: new Error('Patient does not exist or cannot initialise encryption keys'),\n }\n return { patient: patient, statuses: status }\n }\n\n const delSfks = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, ownerId)\n const ecKeys = await this.crypto.xapi.encryptionKeysOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, ownerId)\n\n if (delSfks.length) {\n const retrievedHealthElements = await retry(() =>\n (usingPost\n ? this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((hes) =>\n parentId\n ? (usingPost\n ? this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(parentId, _.uniq(delSfks))\n : this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreHes) => _.uniqBy(hes.concat(moreHes), 'id'))\n : hes\n )\n )\n const retrievedForms = await retry(() =>\n (usingPost\n ? this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((frms) =>\n parentId\n ? (usingPost\n ? this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(parentId, _.uniq(delSfks))\n : this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreFrms) => _.uniqBy(frms.concat(moreFrms), 'id'))\n : frms\n )\n )\n const retrievedContacts = await retry(() =>\n (usingPost\n ? this.contactApi.findByHCPartyPatientSecretFKeysUsingPost(ownerId, undefined, undefined, _.uniq(delSfks))\n : this.contactApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((ctcs) =>\n parentId\n ? (usingPost\n ? this.contactApi.findByHCPartyPatientSecretFKeysUsingPost(parentId, undefined, undefined, _.uniq(delSfks))\n : this.contactApi.findByHCPartyPatientSecretFKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreCtcs) => _.uniqBy(ctcs.concat(moreCtcs), 'id'))\n : ctcs\n )\n )\n const retrievedInvoices = await retry(() =>\n (usingPost\n ? this.invoiceApi.findInvoicesDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.invoiceApi.findInvoicesDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((ivs) =>\n parentId\n ? this.invoiceApi\n .findInvoicesDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n .then((moreIvs) => _.uniqBy(ivs.concat(moreIvs), 'id'))\n : ivs\n )\n )\n const retrievedClassifications = await retry(() =>\n this.classificationApi\n .findClassificationsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n .then((cls) =>\n parentId\n ? this.classificationApi\n .findClassificationsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n .then((moreCls) => _.uniqBy(cls.concat(moreCls), 'id'))\n : cls\n )\n )\n const retrievedCalendarItems = await retry(() =>\n (usingPost\n ? this.calendarItemApi.findByHCPartyPatientSecretFKeysArray(ownerId, _.uniq(delSfks))\n : this.calendarItemApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((cls) =>\n parentId\n ? (usingPost\n ? this.calendarItemApi.findByHCPartyPatientSecretFKeysArray(parentId, _.uniq(delSfks))\n : this.calendarItemApi.findByHCPartyPatientSecretFKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreCls) => _.uniqBy(cls.concat(moreCls), 'id'))\n : cls\n )\n )\n const isMedicalInfoTags = (tags: string[]) => tags.includes('medicalInformation') || tags.includes('all')\n const isFinancialInfoTags = (tags: string[]) => tags.includes('financialInformation') || tags.includes('all')\n const doShareEntitiesAndUpdateStatus = async (\n entities: models.IcureStub[],\n entitiesType: EntityWithDelegationTypeName,\n status: {\n success: boolean | null\n error: null | Error\n modified: number\n },\n tagsCondition: (tags: string[]) => boolean,\n doShareMinimal: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<void> => {\n const delegatesToApply = delegateIds.filter((delegateId) => tagsCondition(delegationTags[delegateId]))\n if (entities.length && delegatesToApply.length) {\n const requests: {\n entity: IcureStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[] = []\n for (const entity of entities) {\n const currentEntityRequests: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n const secretIds = await this.crypto.xapi.secretIdsOf({ entity, type: entitiesType }, undefined)\n const encryptionKeys = await this.crypto.xapi.encryptionKeysOf({ entity, type: entitiesType }, undefined)\n const request = {\n shareSecretIds: secretIds,\n shareEncryptionKeys: encryptionKeys,\n shareOwningEntityIds: [patient.id!],\n requestedPermissions: RequestedPermissionEnum.MAX_WRITE,\n }\n for (const delegateId of delegatesToApply) {\n currentEntityRequests[delegateId] = request\n }\n requests.push({ dataForDelegates: currentEntityRequests, entity })\n }\n await this.crypto.xapi\n .bulkShareOrUpdateEncryptedEntityMetadataNoEntities(entitiesType, requests, (x) => doShareMinimal(x))\n .then((shareResult) => {\n status.modified = new Set(shareResult.successfulUpdates.map((x) => x.entityId)).size\n status.success = shareResult.updateErrors.length === 0\n if (!status.success) {\n const errorMsg = `Error while sharing (some) entities of type ${entitiesType} for patient ${patient.id} : ${JSON.stringify(\n shareResult.updateErrors\n )}`\n console.error(errorMsg)\n status.error = new Error(errorMsg)\n }\n })\n .catch((e) => {\n status.success = false\n status.error = e\n })\n } else {\n status.success = true\n }\n }\n await doShareEntitiesAndUpdateStatus(\n retrievedHealthElements,\n EntityWithDelegationTypeName.HealthElement,\n status.healthElements,\n isMedicalInfoTags,\n (x) => this.helementApi.bulkShareHealthElementsMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(retrievedContacts, EntityWithDelegationTypeName.Contact, status.contacts, isMedicalInfoTags, (x) =>\n this.contactApi.bulkShareContactsMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(retrievedInvoices, EntityWithDelegationTypeName.Invoice, status.invoices, isFinancialInfoTags, (x) =>\n this.invoiceApi.bulkShareInvoicesMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(\n retrievedClassifications,\n EntityWithDelegationTypeName.Classification,\n status.classifications,\n isMedicalInfoTags,\n (x) => this.classificationApi.bulkShareClassificationsMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(\n retrievedCalendarItems,\n EntityWithDelegationTypeName.CalendarItem,\n status.calendarItems,\n isMedicalInfoTags,\n (x) => this.calendarItemApi.bulkShareCalendarItemsMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(retrievedForms, EntityWithDelegationTypeName.Form, status.forms, isMedicalInfoTags, (x) =>\n this.formApi.bulkShareFormsMinimal(x)\n )\n }\n const sharePatientDataRequest = {\n shareSecretIds: delSfks,\n shareEncryptionKeys: ecKeys,\n shareOwningEntityIds: [],\n requestedPermissions: RequestedPermissionEnum.MAX_WRITE,\n }\n const sharePatientRequest = {\n entity: patient,\n dataForDelegates: Object.fromEntries(delegateIds.map((delegateId) => [delegateId, sharePatientDataRequest])),\n }\n return await this.crypto.xapi\n .bulkShareOrUpdateEncryptedEntityMetadata(EntityWithDelegationTypeName.Patient, [sharePatientRequest], (x) => this.bulkSharePatients(x))\n .then((shareResult) => {\n if (shareResult.updatedEntities.length && !shareResult.updateErrors.length) {\n status.patient.success = true\n return { patient: shareResult.updatedEntities[0], statuses: status }\n } else {\n const errorMsg = `Error while sharing patient with id ${patient.id} : ${JSON.stringify(shareResult.updateErrors)}`\n console.error(errorMsg)\n status.patient.error = new Error(errorMsg)\n status.patient.success = false\n return { patient: shareResult.updatedEntities[0] ?? patient, statuses: status }\n }\n })\n .catch((e) => {\n status.patient.error = e\n status.patient.success = false\n return { patient, statuses: status }\n })\n }\n\n export(user: models.User, patId: string, ownerId: string, usingPost: boolean = false): Promise<{ id: string }> {\n return this.hcpartyApi.getHealthcareParty(ownerId).then((hcp) => {\n const parentId = hcp.parentId\n\n return retry(() => this.getPatientWithUser(user, patId))\n .then(async (patient: models.Patient) => {\n const initialised = await this.crypto.xapi.ensureEncryptionKeysInitialised(patient, EntityWithDelegationTypeName.Patient)\n if (!initialised) {\n return patient\n } else {\n return await this.modifyPatientWithUser(user, initialised)\n }\n })\n .then(async (patient: models.Patient | null) => {\n if (!patient) {\n return Promise.resolve({ id: patId })\n }\n const delSfks = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, ownerId)\n return delSfks.length\n ? Promise.all([\n retry(() =>\n (usingPost\n ? this.helementApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(','))\n : this.helementApi.findByHCPartyPatientSecretFKeysArray(ownerId, delSfks)\n ).then((hes) =>\n parentId\n ? (usingPost\n ? this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(parentId, _.uniq(delSfks))\n : this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreHes) => _.uniqBy(hes.concat(moreHes), 'id'))\n : hes\n )\n ) as Promise<Array<models.IcureStub>>,\n retry(() =>\n (usingPost\n ? this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((frms) =>\n parentId\n ? (usingPost\n ? this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(parentId, _.uniq(delSfks))\n : this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreFrms) => _.uniqBy(frms.concat(moreFrms), 'id'))\n : frms\n )\n ) as Promise<Array<models.Form>>,\n retry(() =>\n (usingPost\n ? this.contactApi.findByHCPartyPatientSecretFKeysUsingPost(ownerId, undefined, undefined, _.uniq(delSfks))\n : this.contactApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((ctcs) =>\n parentId\n ? (usingPost\n ? this.contactApi.findByHCPartyPatientSecretFKeysUsingPost(parentId, undefined, undefined, _.uniq(delSfks))\n : this.contactApi.findByHCPartyPatientSecretFKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreCtcs) => _.uniqBy(ctcs.concat(moreCtcs), 'id'))\n : ctcs\n )\n ) as Promise<Array<models.Contact>>,\n retry(() =>\n (usingPost\n ? this.invoiceApi.findInvoicesDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.invoiceApi.findInvoicesDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((ivs) =>\n parentId\n ? this.invoiceApi\n .findInvoicesDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n .then((moreIvs) => _.uniqBy(ivs.concat(moreIvs), 'id'))\n : ivs\n )\n ) as Promise<Array<models.IcureStub>>,\n retry(() =>\n this.classificationApi\n .findClassificationsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n .then((cls) =>\n parentId\n ? this.classificationApi\n .findClassificationsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n .then((moreCls) => _.uniqBy(cls.concat(moreCls), 'id'))\n : cls\n )\n ) as Promise<Array<models.Classification>>,\n retry(async () => {\n const delegationSFKs = _.uniq(delSfks).join(',')\n try {\n let calendarItems = await (usingPost\n ? this.calendarItemApi.findByHCPartyPatientSecretFKeysArray(ownerId, _.uniq(delSfks))\n : this.calendarItemApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(',')))\n\n if (parentId) {\n const moreCalendarItems = await (usingPost\n ? this.calendarItemApi.findByHCPartyPatientSecretFKeysArray(parentId, _.uniq(delSfks))\n : this.calendarItemApi.findByHCPartyPatientSecretFKeys(parentId, _.uniq(delSfks).join(',')))\n calendarItems = _.uniqBy(calendarItems.concat(moreCalendarItems), 'id')\n }\n\n return calendarItems\n } catch (ex) {\n console.log(`exception occured exporting calendarItem for ownerId: ${ownerId} - ${ex}`)\n //throw ex\n }\n }) as Promise<Array<models.CalendarItem>>,\n ]).then(([hes, frms, ctcs, ivs, cls, cis]) => {\n const docIds: { [key: string]: number } = {}\n ctcs.forEach(\n (c: models.Contact) =>\n c.services &&\n c.services.forEach((s) => s.content && Object.values(s.content).forEach((c) => c && c.documentId && (docIds[c.documentId] = 1)))\n )\n\n return retry(() => this.documentApi.getDocuments(new ListOfIds({ ids: Object.keys(docIds) }))).then((docs: Array<Document>) => {\n return {\n id: patId,\n patient: patient,\n contacts: ctcs,\n forms: frms,\n healthElements: hes,\n invoices: ivs,\n classifications: cls,\n calItems: cis,\n documents: docs,\n }\n })\n })\n : Promise.resolve({\n id: patId,\n patient: patient,\n contacts: [],\n forms: [],\n healthElements: [],\n invoices: [],\n classifications: [],\n calItems: [],\n documents: [],\n })\n })\n })\n }\n\n checkInami(inami: string): boolean {\n const num_inami = inami.replace(new RegExp('[^(0-9)]', 'g'), '')\n\n const checkDigit = num_inami.substring(6, 2)\n const numSansCheck = num_inami.substring(0, 6)\n let retour = false\n\n //modulo du niss\n const modINAMI = parseInt(numSansCheck) % 97\n\n //obtention du num de check 97 - le resultat du mod\n const checkDigit_2 = 97 - modINAMI\n\n if (parseInt(checkDigit) == checkDigit_2) {\n retour = true\n }\n return retour\n }\n\n isValidSsin(ssin: string) {\n ssin = ssin.replace(new RegExp('[^(0-9)]', 'g'), '')\n let isValidNiss = false\n\n const normalNumber =\n /^[0-9][0-9](([0][0-9])|([1][0-2]))(([0-2][0-9])|([3][0-1]))(([0-9]{2}[1-9])|([0-9][1-9][0-9])|([1-9][0-9]{2}))(([0-8][0-9])|([9][0-7]))$/.test(\n ssin\n )\n const bisNumber = /^[0-9][0-9](([2][0-9])|([3][0-2]))(([0-2][0-9])|([3][0-1]))[0-9]{3}(([0-8][0-9])|([9][0-7]))$/.test(ssin)\n const terNumber = /^[0-9][0-9](([4][0-9])|([5][0-2]))(([0-2][0-9])|([3][0-1]))[0-9]{3}(([0-8][0-9])|([9][0-7]))$/.test(ssin)\n\n if (normalNumber || bisNumber || terNumber) {\n isValidNiss =\n 97 - (Number(ssin.substring(0, 9)) % 97) === Number(ssin.substring(9, 2))\n ? true\n : 97 - (Number('2' + ssin.substring(0, 9)) % 97) === Number(ssin.substring(9, 2))\n }\n\n return isValidNiss\n }\n\n async getPatientIdOfChildDocumentForHcpAndHcpParents(\n childDocument: models.Invoice | models.CalendarItem | models.Contact | models.AccessLog,\n hcpId: string,\n childDocumentType: EntityWithDelegationTypeName\n ): Promise<string> {\n const parentIdsArray = await this.crypto.xapi.owningEntityIdsOf({ entity: childDocument, type: childDocumentType }, hcpId)\n\n const multipleParentIds = _.uniq(parentIdsArray).length > 1\n\n if (multipleParentIds) {\n throw 'Child document with id ' + childDocument.id + ' contains multiple parent ids in its CFKs for hcpId: ' + hcpId\n }\n\n const parentId = _.first(parentIdsArray)\n\n if (!parentId) {\n throw 'Parent id is empty in CFK of child document with id ' + childDocument.id + ' for hcpId: ' + hcpId\n }\n\n let patient: models.Patient = await super.getPatient(parentId!)\n\n let mergeLevel = 0\n const maxMergeLevel = 10\n while (patient.mergeToPatientId) {\n mergeLevel++\n if (mergeLevel === maxMergeLevel) {\n throw 'Too many merged levels for parent (Patient) of child document ' + childDocument.id + ' ; hcpId: ' + hcpId\n }\n\n patient = await super.getPatient(patient.mergeToPatientId!)\n }\n\n return patient.id!\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given patient\n */\n async hasWriteAccess(patient: models.Patient): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: patient, type: EntityWithDelegationTypeName.Patient })\n }\n\n /**\n * Share an existing patient with other data owners, allowing them to access the non-encrypted data of the patient and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param delegateId the id of the data owner which will be granted access to the patient.\n * @param patient the patient to share.\n * @param shareSecretIds the secret ids of the Patient that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Patient is the owning entity id.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * patient does not have encrypted content.\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n patient: models.Patient,\n shareSecretIds: string[],\n options: {\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Patient> {\n return this.shareWithMany(patient, { [delegateId]: { ...options, shareSecretIds: shareSecretIds } })\n }\n\n /**\n * Share an existing patient with other data owners, allowing them to access the non-encrypted data of the patient and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param patient the patient to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds the secret ids of the Patient that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Patient is the owning entity id.\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * patient does not have encrypted content.\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n patient: models.Patient,\n delegates: {\n [delegateIds: string]: {\n shareSecretIds: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Patient> {\n return (await this.tryShareWithMany(patient, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing patient with other data owners, allowing them to access the non-encrypted data of the patient and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param patient the patient to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds the secret ids of the Patient that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Patient is the owning entity id.\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * patient does not have encrypted content.\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n patient: models.Patient,\n delegates: {\n [delegateIds: string]: {\n shareSecretIds: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Patient>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(patient, EntityWithDelegationTypeName.Patient)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyPatientAs(self, entityWithEncryptionKey) : patient\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Patient,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkSharePatients(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decryptAs(self, [e]).then((es) => es[0])))\n }\n\n /**\n * @param patient a patient\n * @return all the decryptable secret ids of the patient, retrieved from the encrypted metadata. The result may be used to find entities where the\n * patient is the 'owning entity', or in the {@link shareWith} method in order to share it with other data owners.\n */\n decryptSecretIdsOf(patient: models.Patient): Promise<string[]> {\n return this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, undefined)\n }\n\n /**\n * @param patient a patient\n * @return the confidential secret ids of the patient, retrieved from the encrypted metadata. The result may be used to find entities where the\n * patient is the 'owning entity', or in the {@link shareWith} method in order to share it with other data owners.\n */\n decryptConfidentialSecretIdsOf(patient: models.Patient): Promise<string[]> {\n return this.crypto.confidential.getConfidentialSecretIds({ entity: patient, type: EntityWithDelegationTypeName.Patient }, undefined)\n }\n\n /**\n * @param patient a patient\n * @return the non-confidential secret ids of the patient, retrieved from the encrypted metadata. The result may be used to find entities where the\n * patient is the 'owning entity', or in the {@link shareWith} method in order to share it with other data owners.\n */\n decryptNonConfidentialSecretIdsOf(patient: models.Patient): Promise<string[]> {\n return this.crypto.confidential.getSecretIdsSharedWithParents({ entity: patient, type: EntityWithDelegationTypeName.Patient })\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Patient\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Patient })\n }\n\n getEncryptionKeysOf(entity: models.Patient): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Patient }, undefined)\n }\n\n /**\n * Merge two patients into one. This method performs the following operations:\n * - The `from` patient will be soft-deleted, and it will point to the `into` patient. Only the `deletionDate` and `mergeToPatientId` fields of the\n * patient will be changed (automatically by this method). Note that the value of {@link from} is only used to verify that the client is aware of\n * the last version of the `from` patient: any changes to its content and/or metadata compared to what is actually stored in the database will be\n * ignored.\n * - The metadata of the `into` patient will be automatically updated to contain also the metadata of the `from` patient and to keep track of the\n * merge:\n * - the `mergedIds` will be updated to contain the `from` patient id\n * - all secret ids of the `from` patient will be added to the `into` patient\n * - all data owners (including anonymous data owners) with access to the `from` patient will have the same access to the merged `into` patient\n * (unless they already had greater access to the `into` patient, in which case they keep the greater access)\n * - The content of the `into` patient will be updated to match the content (name, address, note, ...) of the provided {@link mergedInto} parameter.\n * Note that since the metadata is automatically updated by this method you must not change the metadata of the `mergedInto` patient\n * (`delegations`, mergedInto`, ...): if there is any change between the metadata of the provided `mergedInto` patient and the stored patient this\n * method will fail with an error.\n *\n * In case the revisions of {@link from} and/or {@link mergedInto} does not match the latest revisions for these patients in the database this\n * method will fail without soft-deleting the `from` patient and without updating the `into` patient with the merged content and metadata. You will\n * have to retrieve the updated versions of both patients before retrying the merge.\n *\n * Finally, note that this method only merges existing data, and does not perform any automatic sharing of the data. The secret ids and encryption\n * keys will not be shared with users that had access only to one of the entity, you will have to use the {@link shareWith} method after the merge\n * if you want to do so.\n * For example consider hcps A, B with access to P' and hcps A, C with access to P'', and we merge P'' into P'. After the merge:\n * - A has access to all secret ids of the merged patient and to the encryption key of the merged patient\n * - B has access to the encryption key of the merged patient (since it is the same as in P'), but only to the secret id which was originally from\n * the unmerged P'\n * - C has no access to the encryption key of the merged patient, and has access only to the secret id which was originally from the unmerged P''\n *\n * @param from the original, unmodified `from` patient. Its content will be unchanged and its metadata will be automatically updated by this method\n * to reflect the merge.\n * @param mergedInto the `into` patient with updated content result of the merge with the `from` patient, as specified by your application logic.\n * The metadata of the `mergedInto` patient must not differ from the metadata of the stored version of the patient, since it will be automatically\n * updated by the method.\n * @return the updated `into` patient.\n */\n async mergePatients(from: Patient, mergedInto: Patient): Promise<Patient> {\n const encryptedMerged = (await this.encryptAs(await this.dataOwnerApi.getCurrentDataOwnerId(), [mergedInto]))[0]\n const merged = await super.baseMergePatients(from.id!, from.rev!, encryptedMerged)\n return (await this.tryDecryptOrReturnOriginal([merged]))[0].entity\n }\n\n async subscribeToPatientEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Patient> | undefined,\n eventFired: (patient: Patient) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n const currentUser = await this.userApi.getCurrentUser()\n return subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.Patient,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted) => (await this.decrypt(currentUser, [encrypted]))[0]\n ).then((rs) => new ConnectionImpl(rs))\n }\n\n createDelegationDeAnonymizationMetadata(entity: Patient, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Patient }, delegates)\n }\n\n /**\n * Initializes the exchange data towards a newly invited patient. This allows the doctor to share data with the\n * patient even if the patient has not yet initialized a keypair for himself.\n *\n * This method should be used only if the patient has not yet initialized a keypair for himself. If the patient has\n * already initialized a keypair this method does nothing and returns false. In this case the exchange data will be\n * automatically created the first time you share data with the patient, and your implementation of the crypto\n * strategies will be used to validate the public keys of the patient.\n *\n * Once exchange data is initialized you can use the {@link IccRecoveryXApi.createExchangeDataRecoveryInfo} to\n * generate a key that the patient will be able to use on his first login to immediately gain access to the exchange\n * data (through the {@link IccRecoveryXApi.recoverExchangeData} method).\n *\n * @param patientId the id of the newly invited patient.\n * @return true if exchange data was initialized, false if the patient already has a key pair and the exchange data\n * will be initialized in the standard way (automatically on the first time data is shared with the user).\n */\n async forceInitialiseExchangeDataToNewlyInvitedPatient(patientId: string): Promise<boolean> {\n const patient = await super.getPatient(patientId)\n if (this.dataOwnerApi.getHexPublicKeysOf(patient).size) return false\n await this.crypto.exchangeData.getOrCreateEncryptionDataTo(patientId, true)\n return true\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"icc-patient-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-patient-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAAsD;AAUtD,4BAA2B;AAC3B,kDAAiD;AACjD,oDAAkG;AAElG,8DAAsD;AACtD,qDAA8E;AAC9E,mCAA4H;AAE5H,0EAAgG;AAChG,uFAAmF;AACnF,wEAAoE;AAEpE,qFAAiF;AACjF,4EAAwE;AAExE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AACzD,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAK3E,4DAAwE;AAGxE,qCAAqC;AACrC,MAAa,cAAe,SAAQ,uBAAa;IAG/C,IAAI,OAAO;QACT,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,EAAE,2DAA4B,CAAC,OAAO,CAAC,CAAC,CAAA;IAC7I,CAAC;IAED,YACE,IAAY,EACZ,OAAkC,EACjB,MAAqB,EACrB,UAA0B,EAC1B,OAAoB,EACpB,WAA4B,EAC5B,UAA0B,EAC1B,WAA4B,EAC5B,UAA0B,EAC1B,iBAAwC,EACxC,YAA8B,EAC9B,eAAoC,EACpC,OAAoB,EACpB,OAAmB,EACnB,cAAuB,EACxC,gBAA+B,CAAC,MAAM,CAAC,EACvC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,E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CD,wCA4vCC","sourcesContent":["import { IccAuthApi, IccPatientApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccFormXApi } from './icc-form-x-api'\nimport { IccHcpartyXApi } from './icc-hcparty-x-api'\nimport { IccInvoiceXApi } from './icc-invoice-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { IccClassificationXApi } from './icc-classification-x-api'\n\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\nimport { Document, IcureStub, ListOfIds, MaintenanceTask, Patient } from '../icc-api/model/models'\nimport { IccCalendarItemXApi } from './icc-calendar-item-x-api'\nimport { b64_2ab } from '../icc-api/model/ModelHelper'\nimport { findName, garnishPersonWithName, hasName } from './utils/person-util'\nimport { EncryptedFieldsManifest, parseEncryptedFields, retry, subscribeToEntityEvents, SubscriptionOptions } from './utils'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { EntityWithDelegationTypeName } from './utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../icc-api/model/SecureDelegation'\nimport { MinimalEntityBulkShareResult } from '../icc-api/model/requests/MinimalEntityBulkShareResult'\nimport { EntityShareRequest } from '../icc-api/model/requests/EntityShareRequest'\nimport { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour'\nimport { ShareResult } from './utils/ShareResult'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { XHR } from '../icc-api/api/XHR'\nimport { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi'\nimport { IccUserXApi } from './icc-user-x-api'\nimport { AbstractFilter } from './filters/filters'\nimport { Connection, ConnectionImpl } from '../icc-api/model/Connection'\nimport { BulkShareOrUpdateMetadataParams } from '../icc-api/model/requests/BulkShareOrUpdateMetadataParams'\n\n// noinspection JSUnusedGlobalSymbols\nexport class IccPatientXApi extends IccPatientApi implements EncryptedEntityXApi<models.Patient> {\n private readonly encryptedFields: EncryptedFieldsManifest\n\n get headers(): Promise<Array<XHR.Header>> {\n return super.headers.then((h) => this.crypto.accessControlKeysHeaders.addAccessControlKeysHeaders(h, EntityWithDelegationTypeName.Patient))\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private readonly crypto: IccCryptoXApi,\n private readonly contactApi: IccContactXApi,\n private readonly formApi: IccFormXApi,\n private readonly helementApi: IccHelementXApi,\n private readonly invoiceApi: IccInvoiceXApi,\n private readonly documentApi: IccDocumentXApi,\n private readonly hcpartyApi: IccHcpartyXApi,\n private readonly classificationApi: IccClassificationXApi,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly calendarItemApi: IccCalendarItemXApi,\n private readonly userApi: IccUserXApi,\n private readonly authApi: IccAuthApi,\n private readonly autofillAuthor: boolean,\n encryptedKeys: Array<string> = ['note'],\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n\n this.encryptedFields = parseEncryptedFields(encryptedKeys, 'Patient.')\n }\n\n /**\n * Creates a new instance of patient with initialised encryption metadata (not in the database).\n * @param user the current user.\n * @param p initialised data for the patient. Metadata such as id, creation data, etc. will be automatically initialised, but you can specify\n * other kinds of data or overwrite generated metadata with this. You can't specify encryption metadata.\n * @param options optional parameters:\n * - additionalDelegates: delegates which will have access to the entity in addition to the current data owner and delegates from the\n * auto-delegations. Must be an object which associates each data owner id with the access level to give to that data owner. May overlap with\n * auto-delegations, in such case the access level specified here will be used.\n * @return a new instance of patient.\n */\n async newInstance(\n user: models.User,\n p: any = {},\n options: {\n additionalDelegates?: { [dataOwnerId: string]: AccessLevelEnum }\n } = {}\n ) {\n const patient = {\n ...(p ?? {}),\n _type: 'org.taktik.icure.entities.Patient',\n id: p?.id ?? this.crypto.primitives.randomUuid(),\n created: p?.created ?? new Date().getTime(),\n modified: p?.modified ?? new Date().getTime(),\n responsible: p?.responsible ?? (this.autofillAuthor ? this.dataOwnerApi.getDataOwnerIdOf(user) : undefined),\n author: p?.author ?? (this.autofillAuthor ? user.id : undefined),\n codes: p?.codes ?? [],\n tags: p?.tags ?? [],\n }\n\n const ownerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (ownerId !== (await this.dataOwnerApi.getCurrentDataOwnerId())) throw new Error('Can only initialise entities as current data owner.')\n const extraDelegations = {\n ...Object.fromEntries(\n [...(user.autoDelegations?.all ?? []), ...(user.autoDelegations?.medicalInformation ?? [])].map((d) => [d, AccessLevelEnum.WRITE])\n ),\n ...(options?.additionalDelegates ?? {}),\n }\n const initialisationInfo = await this.crypto.xapi.entityWithInitialisedEncryptedMetadata(\n patient,\n EntityWithDelegationTypeName.Patient,\n undefined,\n undefined,\n true,\n extraDelegations\n )\n return new models.Patient(initialisationInfo.updatedEntity)\n }\n\n completeNames(patient: models.Patient): models.Patient {\n let finalPatient: any = patient\n\n if (!!finalPatient.lastName && !hasName(finalPatient, models.PersonName.UseEnum.Official)) {\n finalPatient = garnishPersonWithName(finalPatient, models.PersonName.UseEnum.Official, finalPatient.lastName, finalPatient.firstName)\n }\n\n if (!!finalPatient.maidenName && !hasName(finalPatient, models.PersonName.UseEnum.Maiden)) {\n finalPatient = garnishPersonWithName(finalPatient, models.PersonName.UseEnum.Maiden, finalPatient.maidenName, finalPatient.firstName)\n }\n\n if (!!finalPatient.alias && !hasName(finalPatient, models.PersonName.UseEnum.Nickname)) {\n finalPatient = garnishPersonWithName(finalPatient, models.PersonName.UseEnum.Nickname, finalPatient.alias, finalPatient.firstName)\n }\n\n if (!finalPatient.lastName && !!hasName(finalPatient, models.PersonName.UseEnum.Official)) {\n const officialName = findName(finalPatient, models.PersonName.UseEnum.Official)\n finalPatient = {\n ...finalPatient,\n lastName: officialName!.lastName,\n firstName: officialName!.firstNames?.[0],\n }\n }\n\n if (!finalPatient.maidenName && !!hasName(finalPatient, models.PersonName.UseEnum.Maiden)) {\n finalPatient = {\n ...finalPatient,\n maidenName: findName(finalPatient, models.PersonName.UseEnum.Maiden)!.lastName,\n }\n }\n\n if (!finalPatient.alias && !!hasName(finalPatient, models.PersonName.UseEnum.Nickname)) {\n finalPatient = {\n ...finalPatient,\n alias: findName(finalPatient, models.PersonName.UseEnum.Nickname)!.lastName,\n }\n }\n\n return new Patient(finalPatient)\n }\n\n /**\n * @deprecated replace with {@link initConfidentialSecretId}\n */\n async initConfidentialDelegation(patient: models.Patient, user: models.User): Promise<models.Patient> {\n return this.initConfidentialSecretId(patient, user)\n }\n\n /**\n * Ensures that the current data owner has some confidential secret ids for the provided patient. If not creates them and updates the patient in the\n * database.\n * @param patient the patient for which you want to initialise the confidential secret id.\n * @param user the current user.\n * @return the updated patient or the original patient if no change was necessary.\n */\n async initConfidentialSecretId(patient: models.Patient, user: models.User): Promise<models.Patient> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n if (dataOwnerId !== (await this.dataOwnerApi.getCurrentDataOwnerId()))\n throw new Error('You can initialise confidential delegations only for the current data owner')\n let updatedPatient = patient\n if (!patient.rev) {\n updatedPatient = await this.createPatientWithUser(user, patient)\n if (!updatedPatient) throw new Error('Could not create patient')\n }\n const initialised = await this.crypto.confidential.initialiseConfidentialSecretId(updatedPatient, EntityWithDelegationTypeName.Patient, (x) =>\n this.bulkSharePatients(x)\n )\n if (initialised) {\n return initialised\n } else {\n return updatedPatient\n }\n }\n\n createPatient(body?: models.Patient): never {\n throw new Error('Cannot call a method that returns patients without providing a user for de/encryption')\n }\n\n createPatientWithUser(user: models.User, body?: models.Patient): Promise<models.Patient | any> {\n return body\n ? this.encrypt(user, [_.cloneDeep(this.completeNames(body))])\n .then((pats) => super.createPatient(pats[0]))\n .then(async (patient: Patient) => {\n /**\n * This code is a workaround for the fact that the backend is adding empty delegations to the patient when it is created.\n */\n\n const patientDelegations = patient.delegations\n\n if (patientDelegations != undefined && Object.keys(patientDelegations).length > 0) {\n const areDelegationsEmpty = Object\n .values(patientDelegations)\n .every((delegation) => delegation.length === 0)\n\n if (areDelegationsEmpty) {\n return await this.modifyPatientRaw(\n new Patient({\n ...patient,\n delegations: {},\n })\n )\n }\n }\n return patient\n })\n .then((p) => this.decrypt(user, [p]))\n .then((pats) => pats[0])\n : Promise.resolve(null)\n }\n\n filterBy(\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n skip?: number,\n sort?: string,\n desc?: boolean,\n body?: models.FilterChainPatient\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n filterByWithUser(\n user: models.User,\n filterChain: models.FilterChainPatient,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n skip?: number,\n sort?: string,\n desc?: boolean\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .filterPatientsBy(startKey, startDocumentId, limit, skip, sort, desc, filterChain)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n findByAccessLogUserAfterDate(\n userId: string,\n accessType?: string,\n startDate?: number,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n findByAccessLogUserAfterDateWithUser(\n user: models.User,\n userId: string,\n accessType?: string,\n startDate?: number,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .findByAccessLogUserAfterDate(userId, accessType, startDate, startKey, startDocumentId, limit)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n findByAccessLogUserAfterDate_1(externalId: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n findByExternalIdWithUser(user: models.User, externalId: string): Promise<models.Patient | any> {\n return super\n .findByExternalId(externalId)\n .then((pats) => this.decrypt(user, [pats]))\n .then((x) => x[0])\n }\n\n findByNameBirthSsinAuto(\n healthcarePartyId?: string,\n filterValue?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n findByNameBirthSsinAutoWithUser(\n user: models.User,\n healthcarePartyId?: string,\n filterValue?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .findByNameBirthSsinAuto(healthcarePartyId, filterValue, startKey, startDocumentId, limit, sortDirection)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n fuzzySearch(firstName?: string, lastName?: string, dateOfBirth?: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n fuzzySearchWithUser(user: models.User, firstName?: string, lastName?: string, dateOfBirth?: number): Promise<Array<models.Patient> | any> {\n return super.fuzzySearch(firstName, lastName, dateOfBirth).then((pats) => this.decrypt(user, pats))\n }\n\n getPatient(patientId: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n getPatientRaw(patientId: string): Promise<models.Patient | any> {\n return super.getPatient(patientId)\n }\n\n getPatientWithUser(user: models.User, patientId: string): Promise<models.Patient | any> {\n return super\n .getPatient(patientId)\n .then((p) => this.tryDecryptOrReturnOriginal([p]))\n .then((pats) => pats[0].entity)\n }\n\n getPotentiallyEncryptedPatientWithUser(user: models.User, patientId: string): Promise<{ patient: models.Patient; decrypted: boolean }> {\n return super\n .getPatient(patientId)\n .then((p) => this.tryDecryptOrReturnOriginal([p]))\n .then((pats) => ({ patient: pats[0].entity, decrypted: pats[0].decrypted }))\n }\n\n getPatients(body?: models.ListOfIds): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n getPatientsWithUser(user: models.User, body?: models.ListOfIds): Promise<Array<models.Patient> | any> {\n return super.getPatients(body).then((pats) => this.decrypt(user, pats))\n }\n\n listDeletedPatients(startDate?: number, endDate?: number, desc?: boolean, startKey?: string, startDocumentId?: string, limit?: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listDeletedPatientsWithUser(\n user: models.User,\n startDate?: number,\n endDate?: number,\n desc?: boolean,\n startKey?: string,\n startDocumentId?: string,\n limit?: number\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listDeletedPatients(startDate, endDate, desc, startDocumentId, startKey, limit)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n listDeletedPatients_2(firstName?: string, lastName?: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listDeletedPatientsByNameWithUser(user: models.User, firstName?: string, lastName?: string): Promise<Array<models.Patient> | any> {\n return super.listDeletedPatientsByName(firstName, lastName).then((rows) => this.decrypt(user, rows, false))\n }\n\n listOfMergesAfter(date: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listOfMergesAfterWithUser(user: models.User, date: number): Promise<Array<models.Patient> | any> {\n return super.listOfMergesAfter(date).then((pats) => this.decrypt(user, pats, false))\n }\n\n listOfPatientsModifiedAfter(date: number, startKey?: number, startDocumentId?: string, limit?: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listOfPatientsModifiedAfterWithUser(\n user: models.User,\n date: number,\n startKey?: number,\n startDocumentId?: string,\n limit?: number\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listOfPatientsModifiedAfter(date, startKey, startDocumentId, limit)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n listPatients(hcPartyId?: string, sortField?: string, startKey?: string, startDocumentId?: string, limit?: number, sortDirection?: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listPatientsWithUser(\n user: models.User,\n hcPartyId?: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listPatients(hcPartyId, sortField, startKey, startDocumentId, limit, sortDirection)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n listPatientsByHcParty(\n hcPartyId: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listPatientsByHcPartyWithUser(\n user: models.User,\n hcPartyId: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listPatientsByHcParty(hcPartyId, sortField, startKey, startDocumentId, limit, sortDirection)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n listPatientsOfHcParty(\n hcPartyId: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n listPatientsOfHcPartyWithUser(\n user: models.User,\n hcPartyId: string,\n sortField?: string,\n startKey?: string,\n startDocumentId?: string,\n limit?: number,\n sortDirection?: string\n ): Promise<models.PaginatedListPatient | any> {\n return super\n .listPatientsOfHcParty(hcPartyId, sortField, startKey, startDocumentId, limit, sortDirection)\n .then((pl) => this.decrypt(user, pl.rows!, false).then((dr) => Object.assign(pl, { rows: dr })))\n }\n\n mergeInto(toId: string, fromIds: string): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n mergeIntoWithUser(user: models.User, toId: string, fromIds: string): Promise<models.Patient | any> {\n return super\n .mergeInto(toId, fromIds)\n .then((p) => this.decrypt(user, [p]))\n .then((pats) => pats[0])\n }\n\n modifyPatient(body?: models.Patient): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n modifyPatientRaw(body?: models.Patient): Promise<models.Patient | any> {\n return super.modifyPatient(body)\n }\n\n modifyPatientWithUser(user: models.User, body?: models.Patient): Promise<models.Patient | null> {\n return body ? this.modifyPatientAs(this.dataOwnerApi.getDataOwnerIdOf(user), body) : Promise.resolve(null)\n }\n\n private modifyPatientAs(dataOwner: string, body: models.Patient): Promise<models.Patient> {\n return this.encryptAs(dataOwner, [_.cloneDeep(this.completeNames(body))])\n .then((pats) => super.modifyPatient(pats[0]))\n .then((p) => this.decryptAs(dataOwner, [p]))\n .then((pats) => pats[0])\n }\n\n modifyPatientReferral(patientId: string, referralId: string, start?: number, end?: number): never {\n throw new Error('Cannot call a method that returns contacts without providing a user for de/encryption')\n }\n\n modifyPatientReferralWithUser(\n user: models.User,\n patientId: string,\n referralId: string,\n start?: number,\n end?: number\n ): Promise<models.Patient | any> {\n return super\n .modifyPatientReferral(patientId, referralId, start, end)\n .then((p) => this.decrypt(user, [p]))\n .then((pats) => pats[0])\n }\n\n encrypt(user: models.User, pats: Array<models.Patient>): Promise<Array<models.Patient>> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerIdOf(user)\n return this.encryptAs(dataOwnerId, pats)\n }\n\n private encryptAs(dataOwner: string, pats: Array<models.Patient>): Promise<Array<models.Patient>> {\n return this.crypto.xapi.tryEncryptEntities(\n pats,\n EntityWithDelegationTypeName.Patient,\n this.encryptedFields,\n true,\n false,\n (x) => new models.Patient(x)\n )\n }\n\n // If patient can't be decrypted returns patient with encrypted data.\n decrypt(user: models.User, patients: Array<models.Patient>, fillDelegations = true): Promise<Array<models.Patient>> {\n return this.decryptAs(this.dataOwnerApi.getDataOwnerIdOf(user), patients, fillDelegations)\n }\n\n private decryptAs(dataOwner: string, patients: Array<models.Patient>, fillDelegations = true): Promise<Array<models.Patient>> {\n return this.tryDecryptOrReturnOriginal(patients).then((ps) => ps.map((p) => p.entity))\n }\n\n async tryDecryptOrReturnOriginal(patients: Array<models.Patient>): Promise<{ entity: models.Patient; decrypted: boolean }[]> {\n return (await this.crypto.xapi.tryDecryptEntities(patients, EntityWithDelegationTypeName.Patient, (x) => new models.Patient(x))).map((p) => {\n if (p.entity.picture && !(p.entity.picture instanceof ArrayBuffer)) {\n return {\n entity: new models.Patient({\n ...p.entity,\n picture: b64_2ab(p.entity.picture),\n }),\n decrypted: p.decrypted,\n }\n } else return p\n })\n }\n\n /**\n * @deprecated replace with {@link shareAllDataOfPatient}\n */\n async share(\n user: models.User,\n patId: string,\n ownerId: string,\n delegateIds: Array<string>,\n delegationTags: { [key: string]: Array<string> },\n usingPost: boolean = false\n ): Promise<{\n patient: models.Patient | null\n statuses: { [key: string]: { success: boolean | null; error: Error | null } }\n } | null> {\n return this.shareAllDataOfPatient(user, patId, ownerId, delegateIds, delegationTags, usingPost)\n }\n\n async shareAllDataOfPatient(\n user: models.User,\n patId: string,\n ownerId: string,\n delegateIds: Array<string>,\n delegationTags: { [key: string]: Array<string> },\n usingPost: boolean = false\n ): Promise<{\n patient: models.Patient | null\n statuses: { [key: string]: { success: boolean | null; error: Error | null } }\n } | null> {\n const allTags: string[] = _.uniq(_.flatMap(Object.values(delegationTags)))\n const status = {\n contacts: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n forms: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n healthElements: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n invoices: {\n success: allTags.includes('financialInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n documents: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n classifications: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n calendarItems: {\n success: allTags.includes('medicalInformation') || allTags.includes('all') ? false : null,\n error: null,\n modified: 0,\n },\n patient: { success: false, error: null, modified: 0 } as {\n success: boolean\n error: Error | null\n },\n }\n const hcp = await this.hcpartyApi.getHealthcareParty(ownerId)\n const parentId = hcp.parentId\n let patient = await retry(() => this.getPatientWithUser(user, patId))\n const patientWithInitialisedEncryption = await this.crypto.xapi.ensureEncryptionKeysInitialised(patient, EntityWithDelegationTypeName.Patient)\n if (patientWithInitialisedEncryption) {\n patient = await this.modifyPatientWithUser(user, patientWithInitialisedEncryption)\n }\n\n if (!patient) {\n status.patient = {\n success: false,\n error: new Error('Patient does not exist or cannot initialise encryption keys'),\n }\n return { patient: patient, statuses: status }\n }\n\n const delSfks = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, ownerId)\n const ecKeys = await this.crypto.xapi.encryptionKeysOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, ownerId)\n\n if (delSfks.length) {\n const retrievedHealthElements = await retry(() =>\n (usingPost\n ? this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((hes) =>\n parentId\n ? (usingPost\n ? this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(parentId, _.uniq(delSfks))\n : this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreHes) => _.uniqBy(hes.concat(moreHes), 'id'))\n : hes\n )\n )\n const retrievedForms = await retry(() =>\n (usingPost\n ? this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((frms) =>\n parentId\n ? (usingPost\n ? this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(parentId, _.uniq(delSfks))\n : this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreFrms) => _.uniqBy(frms.concat(moreFrms), 'id'))\n : frms\n )\n )\n const retrievedContacts = await retry(() =>\n (usingPost\n ? this.contactApi.findByHCPartyPatientSecretFKeysUsingPost(ownerId, undefined, undefined, _.uniq(delSfks))\n : this.contactApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((ctcs) =>\n parentId\n ? (usingPost\n ? this.contactApi.findByHCPartyPatientSecretFKeysUsingPost(parentId, undefined, undefined, _.uniq(delSfks))\n : this.contactApi.findByHCPartyPatientSecretFKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreCtcs) => _.uniqBy(ctcs.concat(moreCtcs), 'id'))\n : ctcs\n )\n )\n const retrievedInvoices = await retry(() =>\n (usingPost\n ? this.invoiceApi.findInvoicesDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.invoiceApi.findInvoicesDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((ivs) =>\n parentId\n ? this.invoiceApi\n .findInvoicesDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n .then((moreIvs) => _.uniqBy(ivs.concat(moreIvs), 'id'))\n : ivs\n )\n )\n const retrievedClassifications = await retry(() =>\n this.classificationApi\n .findClassificationsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n .then((cls) =>\n parentId\n ? this.classificationApi\n .findClassificationsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n .then((moreCls) => _.uniqBy(cls.concat(moreCls), 'id'))\n : cls\n )\n )\n const retrievedCalendarItems = await retry(() =>\n (usingPost\n ? this.calendarItemApi.findByHCPartyPatientSecretFKeysArray(ownerId, _.uniq(delSfks))\n : this.calendarItemApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((cls) =>\n parentId\n ? (usingPost\n ? this.calendarItemApi.findByHCPartyPatientSecretFKeysArray(parentId, _.uniq(delSfks))\n : this.calendarItemApi.findByHCPartyPatientSecretFKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreCls) => _.uniqBy(cls.concat(moreCls), 'id'))\n : cls\n )\n )\n const isMedicalInfoTags = (tags: string[]) => tags.includes('medicalInformation') || tags.includes('all')\n const isFinancialInfoTags = (tags: string[]) => tags.includes('financialInformation') || tags.includes('all')\n const doShareEntitiesAndUpdateStatus = async (\n entities: models.IcureStub[],\n entitiesType: EntityWithDelegationTypeName,\n status: {\n success: boolean | null\n error: null | Error\n modified: number\n },\n tagsCondition: (tags: string[]) => boolean,\n doShareMinimal: (request: BulkShareOrUpdateMetadataParams) => Promise<MinimalEntityBulkShareResult[]>\n ): Promise<void> => {\n const delegatesToApply = delegateIds.filter((delegateId) => tagsCondition(delegationTags[delegateId]))\n if (entities.length && delegatesToApply.length) {\n const requests: {\n entity: IcureStub\n dataForDelegates: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n }\n }[] = []\n for (const entity of entities) {\n const currentEntityRequests: {\n [delegateId: string]: {\n shareSecretIds: string[]\n shareEncryptionKeys: string[]\n shareOwningEntityIds: string[]\n requestedPermissions: RequestedPermissionEnum\n }\n } = {}\n const secretIds = await this.crypto.xapi.secretIdsOf({ entity, type: entitiesType }, undefined)\n const encryptionKeys = await this.crypto.xapi.encryptionKeysOf({ entity, type: entitiesType }, undefined)\n const request = {\n shareSecretIds: secretIds,\n shareEncryptionKeys: encryptionKeys,\n shareOwningEntityIds: [patient.id!],\n requestedPermissions: RequestedPermissionEnum.MAX_WRITE,\n }\n for (const delegateId of delegatesToApply) {\n currentEntityRequests[delegateId] = request\n }\n requests.push({ dataForDelegates: currentEntityRequests, entity })\n }\n await this.crypto.xapi\n .bulkShareOrUpdateEncryptedEntityMetadataNoEntities(entitiesType, requests, (x) => doShareMinimal(x))\n .then((shareResult) => {\n status.modified = new Set(shareResult.successfulUpdates.map((x) => x.entityId)).size\n status.success = shareResult.updateErrors.length === 0\n if (!status.success) {\n const errorMsg = `Error while sharing (some) entities of type ${entitiesType} for patient ${patient.id} : ${JSON.stringify(\n shareResult.updateErrors\n )}`\n console.error(errorMsg)\n status.error = new Error(errorMsg)\n }\n })\n .catch((e) => {\n status.success = false\n status.error = e\n })\n } else {\n status.success = true\n }\n }\n await doShareEntitiesAndUpdateStatus(\n retrievedHealthElements,\n EntityWithDelegationTypeName.HealthElement,\n status.healthElements,\n isMedicalInfoTags,\n (x) => this.helementApi.bulkShareHealthElementsMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(retrievedContacts, EntityWithDelegationTypeName.Contact, status.contacts, isMedicalInfoTags, (x) =>\n this.contactApi.bulkShareContactsMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(retrievedInvoices, EntityWithDelegationTypeName.Invoice, status.invoices, isFinancialInfoTags, (x) =>\n this.invoiceApi.bulkShareInvoicesMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(\n retrievedClassifications,\n EntityWithDelegationTypeName.Classification,\n status.classifications,\n isMedicalInfoTags,\n (x) => this.classificationApi.bulkShareClassificationsMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(\n retrievedCalendarItems,\n EntityWithDelegationTypeName.CalendarItem,\n status.calendarItems,\n isMedicalInfoTags,\n (x) => this.calendarItemApi.bulkShareCalendarItemsMinimal(x)\n )\n await doShareEntitiesAndUpdateStatus(retrievedForms, EntityWithDelegationTypeName.Form, status.forms, isMedicalInfoTags, (x) =>\n this.formApi.bulkShareFormsMinimal(x)\n )\n }\n const sharePatientDataRequest = {\n shareSecretIds: delSfks,\n shareEncryptionKeys: ecKeys,\n shareOwningEntityIds: [],\n requestedPermissions: RequestedPermissionEnum.MAX_WRITE,\n }\n const sharePatientRequest = {\n entity: patient,\n dataForDelegates: Object.fromEntries(delegateIds.map((delegateId) => [delegateId, sharePatientDataRequest])),\n }\n return await this.crypto.xapi\n .bulkShareOrUpdateEncryptedEntityMetadata(EntityWithDelegationTypeName.Patient, [sharePatientRequest], (x) => this.bulkSharePatients(x))\n .then((shareResult) => {\n if (shareResult.updatedEntities.length && !shareResult.updateErrors.length) {\n status.patient.success = true\n return { patient: shareResult.updatedEntities[0], statuses: status }\n } else {\n const errorMsg = `Error while sharing patient with id ${patient.id} : ${JSON.stringify(shareResult.updateErrors)}`\n console.error(errorMsg)\n status.patient.error = new Error(errorMsg)\n status.patient.success = false\n return { patient: shareResult.updatedEntities[0] ?? patient, statuses: status }\n }\n })\n .catch((e) => {\n status.patient.error = e\n status.patient.success = false\n return { patient, statuses: status }\n })\n }\n\n export(user: models.User, patId: string, ownerId: string, usingPost: boolean = false): Promise<{ id: string }> {\n return this.hcpartyApi.getHealthcareParty(ownerId).then((hcp) => {\n const parentId = hcp.parentId\n\n return retry(() => this.getPatientWithUser(user, patId))\n .then(async (patient: models.Patient) => {\n const initialised = await this.crypto.xapi.ensureEncryptionKeysInitialised(patient, EntityWithDelegationTypeName.Patient)\n if (!initialised) {\n return patient\n } else {\n return await this.modifyPatientWithUser(user, initialised)\n }\n })\n .then(async (patient: models.Patient | null) => {\n if (!patient) {\n return Promise.resolve({ id: patId })\n }\n const delSfks = await this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, ownerId)\n return delSfks.length\n ? Promise.all([\n retry(() =>\n (usingPost\n ? this.helementApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(','))\n : this.helementApi.findByHCPartyPatientSecretFKeysArray(ownerId, delSfks)\n ).then((hes) =>\n parentId\n ? (usingPost\n ? this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(parentId, _.uniq(delSfks))\n : this.helementApi.findHealthElementsDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreHes) => _.uniqBy(hes.concat(moreHes), 'id'))\n : hes\n )\n ) as Promise<Array<models.IcureStub>>,\n retry(() =>\n (usingPost\n ? this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((frms) =>\n parentId\n ? (usingPost\n ? this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeysUsingPost(parentId, _.uniq(delSfks))\n : this.formApi.findFormsDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreFrms) => _.uniqBy(frms.concat(moreFrms), 'id'))\n : frms\n )\n ) as Promise<Array<models.Form>>,\n retry(() =>\n (usingPost\n ? this.contactApi.findByHCPartyPatientSecretFKeysUsingPost(ownerId, undefined, undefined, _.uniq(delSfks))\n : this.contactApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((ctcs) =>\n parentId\n ? (usingPost\n ? this.contactApi.findByHCPartyPatientSecretFKeysUsingPost(parentId, undefined, undefined, _.uniq(delSfks))\n : this.contactApi.findByHCPartyPatientSecretFKeys(parentId, _.uniq(delSfks).join(','))\n ).then((moreCtcs) => _.uniqBy(ctcs.concat(moreCtcs), 'id'))\n : ctcs\n )\n ) as Promise<Array<models.Contact>>,\n retry(() =>\n (usingPost\n ? this.invoiceApi.findInvoicesDelegationsStubsByHCPartyPatientForeignKeysUsingPost(ownerId, _.uniq(delSfks))\n : this.invoiceApi.findInvoicesDelegationsStubsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n ).then((ivs) =>\n parentId\n ? this.invoiceApi\n .findInvoicesDelegationsStubsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n .then((moreIvs) => _.uniqBy(ivs.concat(moreIvs), 'id'))\n : ivs\n )\n ) as Promise<Array<models.IcureStub>>,\n retry(() =>\n this.classificationApi\n .findClassificationsByHCPartyPatientForeignKeys(ownerId, _.uniq(delSfks).join(','))\n .then((cls) =>\n parentId\n ? this.classificationApi\n .findClassificationsByHCPartyPatientForeignKeys(parentId, _.uniq(delSfks).join(','))\n .then((moreCls) => _.uniqBy(cls.concat(moreCls), 'id'))\n : cls\n )\n ) as Promise<Array<models.Classification>>,\n retry(async () => {\n const delegationSFKs = _.uniq(delSfks).join(',')\n try {\n let calendarItems = await (usingPost\n ? this.calendarItemApi.findByHCPartyPatientSecretFKeysArray(ownerId, _.uniq(delSfks))\n : this.calendarItemApi.findByHCPartyPatientSecretFKeys(ownerId, _.uniq(delSfks).join(',')))\n\n if (parentId) {\n const moreCalendarItems = await (usingPost\n ? this.calendarItemApi.findByHCPartyPatientSecretFKeysArray(parentId, _.uniq(delSfks))\n : this.calendarItemApi.findByHCPartyPatientSecretFKeys(parentId, _.uniq(delSfks).join(',')))\n calendarItems = _.uniqBy(calendarItems.concat(moreCalendarItems), 'id')\n }\n\n return calendarItems\n } catch (ex) {\n console.log(`exception occured exporting calendarItem for ownerId: ${ownerId} - ${ex}`)\n //throw ex\n }\n }) as Promise<Array<models.CalendarItem>>,\n ]).then(([hes, frms, ctcs, ivs, cls, cis]) => {\n const docIds: { [key: string]: number } = {}\n ctcs.forEach(\n (c: models.Contact) =>\n c.services &&\n c.services.forEach((s) => s.content && Object.values(s.content).forEach((c) => c && c.documentId && (docIds[c.documentId] = 1)))\n )\n\n return retry(() => this.documentApi.getDocuments(new ListOfIds({ ids: Object.keys(docIds) }))).then((docs: Array<Document>) => {\n return {\n id: patId,\n patient: patient,\n contacts: ctcs,\n forms: frms,\n healthElements: hes,\n invoices: ivs,\n classifications: cls,\n calItems: cis,\n documents: docs,\n }\n })\n })\n : Promise.resolve({\n id: patId,\n patient: patient,\n contacts: [],\n forms: [],\n healthElements: [],\n invoices: [],\n classifications: [],\n calItems: [],\n documents: [],\n })\n })\n })\n }\n\n checkInami(inami: string): boolean {\n const num_inami = inami.replace(new RegExp('[^(0-9)]', 'g'), '')\n\n const checkDigit = num_inami.substring(6, 8)\n const numSansCheck = num_inami.substring(0, 6)\n let retour = false\n\n //modulo du niss\n const modINAMI = parseInt(numSansCheck) % 97\n\n //obtention du num de check 97 - le resultat du mod\n const checkDigit_2 = 97 - modINAMI\n\n if (parseInt(checkDigit) == checkDigit_2) {\n retour = true\n }\n return retour\n }\n\n isValidSsin(ssin: string) {\n ssin = ssin.replace(new RegExp('[^(0-9)]', 'g'), '')\n let isValidNiss = false\n\n const normalNumber =\n /^[0-9][0-9](([0][0-9])|([1][0-2]))(([0-2][0-9])|([3][0-1]))(([0-9]{2}[1-9])|([0-9][1-9][0-9])|([1-9][0-9]{2}))(([0-8][0-9])|([9][0-7]))$/.test(\n ssin\n )\n const bisNumber = /^[0-9][0-9](([2][0-9])|([3][0-2]))(([0-2][0-9])|([3][0-1]))[0-9]{3}(([0-8][0-9])|([9][0-7]))$/.test(ssin)\n const terNumber = /^[0-9][0-9](([4][0-9])|([5][0-2]))(([0-2][0-9])|([3][0-1]))[0-9]{3}(([0-8][0-9])|([9][0-7]))$/.test(ssin)\n\n if (normalNumber || bisNumber || terNumber) {\n isValidNiss =\n 97 - (Number(ssin.substring(0, 9)) % 97) === Number(ssin.substring(9, 11))\n ? true\n : 97 - (Number('2' + ssin.substring(0, 9)) % 97) === Number(ssin.substring(9, 11))\n }\n\n return isValidNiss\n }\n\n async getPatientIdOfChildDocumentForHcpAndHcpParents(\n childDocument: models.Invoice | models.CalendarItem | models.Contact | models.AccessLog,\n hcpId: string,\n childDocumentType: EntityWithDelegationTypeName\n ): Promise<string> {\n const parentIdsArray = await this.crypto.xapi.owningEntityIdsOf({ entity: childDocument, type: childDocumentType }, hcpId)\n\n const multipleParentIds = _.uniq(parentIdsArray).length > 1\n\n if (multipleParentIds) {\n throw 'Child document with id ' + childDocument.id + ' contains multiple parent ids in its CFKs for hcpId: ' + hcpId\n }\n\n const parentId = _.first(parentIdsArray)\n\n if (!parentId) {\n throw 'Parent id is empty in CFK of child document with id ' + childDocument.id + ' for hcpId: ' + hcpId\n }\n\n let patient: models.Patient = await super.getPatient(parentId!)\n\n let mergeLevel = 0\n const maxMergeLevel = 10\n while (patient.mergeToPatientId) {\n mergeLevel++\n if (mergeLevel === maxMergeLevel) {\n throw 'Too many merged levels for parent (Patient) of child document ' + childDocument.id + ' ; hcpId: ' + hcpId\n }\n\n patient = await super.getPatient(patient.mergeToPatientId!)\n }\n\n return patient.id!\n }\n\n /**\n * @return if the logged data owner has write access to the content of the given patient\n */\n async hasWriteAccess(patient: models.Patient): Promise<boolean> {\n return this.crypto.xapi.hasWriteAccess({ entity: patient, type: EntityWithDelegationTypeName.Patient })\n }\n\n /**\n * Share an existing patient with other data owners, allowing them to access the non-encrypted data of the patient and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param delegateId the id of the data owner which will be granted access to the patient.\n * @param patient the patient to share.\n * @param shareSecretIds the secret ids of the Patient that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Patient is the owning entity id.\n * @param options optional parameters to customize the sharing behaviour:\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * patient does not have encrypted content.\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWith(\n delegateId: string,\n patient: models.Patient,\n shareSecretIds: string[],\n options: {\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n } = {}\n ): Promise<models.Patient> {\n return this.shareWithMany(patient, { [delegateId]: { ...options, shareSecretIds: shareSecretIds } })\n }\n\n /**\n * Share an existing patient with other data owners, allowing them to access the non-encrypted data of the patient and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param patient the patient to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds the secret ids of the Patient that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Patient is the owning entity id.\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * patient does not have encrypted content.\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return the updated entity\n */\n async shareWithMany(\n patient: models.Patient,\n delegates: {\n [delegateIds: string]: {\n shareSecretIds: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<models.Patient> {\n return (await this.tryShareWithMany(patient, delegates)).updatedEntityOrThrow\n }\n\n /**\n * Share an existing patient with other data owners, allowing them to access the non-encrypted data of the patient and optionally also\n * the encrypted content, with read-only or read-write permissions.\n * @param patient the patient to share.\n * @param delegates associates the id of data owners which will be granted access to the entity, to the following sharing options:\n * - shareSecretIds the secret ids of the Patient that the delegate will be given access to. Allows the delegate to search for data where the\n * shared Patient is the owning entity id.\n * - shareEncryptionKey: specifies if the encryption key of the access log should be shared with the delegate, giving access to all encrypted\n * content of the entity, excluding other encrypted metadata (defaults to {@link ShareMetadataBehaviour.IF_AVAILABLE}). Note that by default a\n * patient does not have encrypted content.\n * {@link ShareMetadataBehaviour.IF_AVAILABLE}).\n * - requestedPermissions: the requested permissions for the delegate, defaults to {@link RequestedPermissionEnum.MAX_WRITE}.\n * @return a promise which will contain the result of the operation: the updated entity if the operation was successful or details of the error if\n * the operation failed.\n */\n async tryShareWithMany(\n patient: models.Patient,\n delegates: {\n [delegateIds: string]: {\n shareSecretIds: string[]\n requestedPermissions?: RequestedPermissionEnum\n shareEncryptionKey?: ShareMetadataBehaviour // Defaults to ShareMetadataBehaviour.IF_AVAILABLE\n }\n }\n ): Promise<ShareResult<models.Patient>> {\n const self = await this.dataOwnerApi.getCurrentDataOwnerId()\n // All entities should have an encryption key.\n const entityWithEncryptionKey = await this.crypto.xapi.ensureEncryptionKeysInitialised(patient, EntityWithDelegationTypeName.Patient)\n const updatedEntity = entityWithEncryptionKey ? await this.modifyPatientAs(self, entityWithEncryptionKey) : patient\n return this.crypto.xapi\n .simpleShareOrUpdateEncryptedEntityMetadata(\n {\n entity: updatedEntity,\n type: EntityWithDelegationTypeName.Patient,\n },\n Object.fromEntries(\n Object.entries(delegates).map(([delegateId, options]) => [\n delegateId,\n {\n requestedPermissions: options.requestedPermissions,\n shareEncryptionKeys: options.shareEncryptionKey,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: options.shareSecretIds,\n },\n ])\n ),\n (x) => this.bulkSharePatients(x)\n )\n .then((r) => r.mapSuccessAsync((e) => this.decryptAs(self, [e]).then((es) => es[0])))\n }\n\n /**\n * @param patient a patient\n * @return all the decryptable secret ids of the patient, retrieved from the encrypted metadata. The result may be used to find entities where the\n * patient is the 'owning entity', or in the {@link shareWith} method in order to share it with other data owners.\n */\n decryptSecretIdsOf(patient: models.Patient): Promise<string[]> {\n return this.crypto.xapi.secretIdsOf({ entity: patient, type: EntityWithDelegationTypeName.Patient }, undefined)\n }\n\n /**\n * @param patient a patient\n * @return the confidential secret ids of the patient, retrieved from the encrypted metadata. The result may be used to find entities where the\n * patient is the 'owning entity', or in the {@link shareWith} method in order to share it with other data owners.\n */\n decryptConfidentialSecretIdsOf(patient: models.Patient): Promise<string[]> {\n return this.crypto.confidential.getConfidentialSecretIds({ entity: patient, type: EntityWithDelegationTypeName.Patient }, undefined)\n }\n\n /**\n * @param patient a patient\n * @return the non-confidential secret ids of the patient, retrieved from the encrypted metadata. The result may be used to find entities where the\n * patient is the 'owning entity', or in the {@link shareWith} method in order to share it with other data owners.\n */\n decryptNonConfidentialSecretIdsOf(patient: models.Patient): Promise<string[]> {\n return this.crypto.confidential.getSecretIdsSharedWithParents({ entity: patient, type: EntityWithDelegationTypeName.Patient })\n }\n\n getDataOwnersWithAccessTo(\n entity: models.Patient\n ): Promise<{ permissionsByDataOwnerId: { [p: string]: AccessLevelEnum }; hasUnknownAnonymousDataOwners: boolean }> {\n return this.crypto.delegationsDeAnonymization.getDataOwnersWithAccessTo({ entity, type: EntityWithDelegationTypeName.Patient })\n }\n\n getEncryptionKeysOf(entity: models.Patient): Promise<string[]> {\n return this.crypto.xapi.encryptionKeysOf({ entity, type: EntityWithDelegationTypeName.Patient }, undefined)\n }\n\n /**\n * Merge two patients into one. This method performs the following operations:\n * - The `from` patient will be soft-deleted, and it will point to the `into` patient. Only the `deletionDate` and `mergeToPatientId` fields of the\n * patient will be changed (automatically by this method). Note that the value of {@link from} is only used to verify that the client is aware of\n * the last version of the `from` patient: any changes to its content and/or metadata compared to what is actually stored in the database will be\n * ignored.\n * - The metadata of the `into` patient will be automatically updated to contain also the metadata of the `from` patient and to keep track of the\n * merge:\n * - the `mergedIds` will be updated to contain the `from` patient id\n * - all secret ids of the `from` patient will be added to the `into` patient\n * - all data owners (including anonymous data owners) with access to the `from` patient will have the same access to the merged `into` patient\n * (unless they already had greater access to the `into` patient, in which case they keep the greater access)\n * - The content of the `into` patient will be updated to match the content (name, address, note, ...) of the provided {@link mergedInto} parameter.\n * Note that since the metadata is automatically updated by this method you must not change the metadata of the `mergedInto` patient\n * (`delegations`, mergedInto`, ...): if there is any change between the metadata of the provided `mergedInto` patient and the stored patient this\n * method will fail with an error.\n *\n * In case the revisions of {@link from} and/or {@link mergedInto} does not match the latest revisions for these patients in the database this\n * method will fail without soft-deleting the `from` patient and without updating the `into` patient with the merged content and metadata. You will\n * have to retrieve the updated versions of both patients before retrying the merge.\n *\n * Finally, note that this method only merges existing data, and does not perform any automatic sharing of the data. The secret ids and encryption\n * keys will not be shared with users that had access only to one of the entity, you will have to use the {@link shareWith} method after the merge\n * if you want to do so.\n * For example consider hcps A, B with access to P' and hcps A, C with access to P'', and we merge P'' into P'. After the merge:\n * - A has access to all secret ids of the merged patient and to the encryption key of the merged patient\n * - B has access to the encryption key of the merged patient (since it is the same as in P'), but only to the secret id which was originally from\n * the unmerged P'\n * - C has no access to the encryption key of the merged patient, and has access only to the secret id which was originally from the unmerged P''\n *\n * @param from the original, unmodified `from` patient. Its content will be unchanged and its metadata will be automatically updated by this method\n * to reflect the merge.\n * @param mergedInto the `into` patient with updated content result of the merge with the `from` patient, as specified by your application logic.\n * The metadata of the `mergedInto` patient must not differ from the metadata of the stored version of the patient, since it will be automatically\n * updated by the method.\n * @return the updated `into` patient.\n */\n async mergePatients(from: Patient, mergedInto: Patient): Promise<Patient> {\n const encryptedMerged = (await this.encryptAs(await this.dataOwnerApi.getCurrentDataOwnerId(), [mergedInto]))[0]\n const merged = await super.baseMergePatients(from.id!, from.rev!, encryptedMerged)\n return (await this.tryDecryptOrReturnOriginal([merged]))[0].entity\n }\n\n async subscribeToPatientEvents(\n eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[],\n filter: AbstractFilter<Patient> | undefined,\n eventFired: (patient: Patient) => Promise<void>,\n options: SubscriptionOptions = {}\n ): Promise<Connection> {\n const currentUser = await this.userApi.getCurrentUser()\n return subscribeToEntityEvents(\n this.host,\n this.authApi,\n EntityWithDelegationTypeName.Patient,\n eventTypes,\n filter,\n eventFired,\n options,\n async (encrypted) => (await this.decrypt(currentUser, [encrypted]))[0]\n ).then((rs) => new ConnectionImpl(rs))\n }\n\n createDelegationDeAnonymizationMetadata(entity: Patient, delegates: string[]): Promise<void> {\n return this.crypto.delegationsDeAnonymization.createOrUpdateDeAnonymizationInfo({ entity, type: EntityWithDelegationTypeName.Patient }, delegates)\n }\n\n /**\n * Initializes the exchange data towards a newly invited patient. This allows the doctor to share data with the\n * patient even if the patient has not yet initialized a keypair for himself.\n *\n * This method should be used only if the patient has not yet initialized a keypair for himself. If the patient has\n * already initialized a keypair this method does nothing and returns false. In this case the exchange data will be\n * automatically created the first time you share data with the patient, and your implementation of the crypto\n * strategies will be used to validate the public keys of the patient.\n *\n * Once exchange data is initialized you can use the {@link IccRecoveryXApi.createExchangeDataRecoveryInfo} to\n * generate a key that the patient will be able to use on his first login to immediately gain access to the exchange\n * data (through the {@link IccRecoveryXApi.recoverExchangeData} method).\n *\n * @param patientId the id of the newly invited patient.\n * @return true if exchange data was initialized, false if the patient already has a key pair and the exchange data\n * will be initialized in the standard way (automatically on the first time data is shared with the user).\n */\n async forceInitialiseExchangeDataToNewlyInvitedPatient(patientId: string): Promise<boolean> {\n const patient = await super.getPatient(patientId)\n if (this.dataOwnerApi.getHexPublicKeysOf(patient).size) return false\n await this.crypto.exchangeData.getOrCreateEncryptionDataTo(patientId, true)\n return true\n }\n}\n"]}
|