@icure/api 7.1.7 → 7.1.9
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/Patient.js +13 -1
- package/icc-api/model/Patient.js.map +1 -1
- package/icc-x-api/crypto/EntitiesEncryption.js +1 -1
- package/icc-x-api/crypto/EntitiesEncryption.js.map +1 -1
- package/icc-x-api/icc-contact-x-api.d.ts +3 -8
- package/icc-x-api/icc-contact-x-api.js.map +1 -1
- package/icc-x-api/icc-device-x-api.d.ts +2 -4
- package/icc-x-api/icc-device-x-api.js.map +1 -1
- package/icc-x-api/icc-hcparty-x-api.d.ts +2 -4
- package/icc-x-api/icc-hcparty-x-api.js.map +1 -1
- package/icc-x-api/icc-helement-x-api.d.ts +2 -4
- package/icc-x-api/icc-helement-x-api.js.map +1 -1
- package/icc-x-api/icc-maintenance-task-x-api.d.ts +2 -4
- package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
- package/icc-x-api/icc-patient-x-api.d.ts +2 -4
- package/icc-x-api/icc-patient-x-api.js.map +1 -1
- package/icc-x-api/icc-user-x-api.d.ts +2 -4
- package/icc-x-api/icc-user-x-api.js +4 -1
- package/icc-x-api/icc-user-x-api.js.map +1 -1
- package/icc-x-api/utils/crypto-utils.js +3 -0
- package/icc-x-api/utils/crypto-utils.js.map +1 -1
- package/icc-x-api/utils/websocket.d.ts +4 -2
- package/icc-x-api/utils/websocket.js +20 -19
- package/icc-x-api/utils/websocket.js.map +1 -1
- package/package.json +1 -2
package/icc-api/model/Patient.js
CHANGED
|
@@ -7,7 +7,19 @@ exports.Patient = void 0;
|
|
|
7
7
|
const ModelHelper_1 = require("./ModelHelper");
|
|
8
8
|
class Patient {
|
|
9
9
|
constructor(json) {
|
|
10
|
-
|
|
10
|
+
let pictureData = {};
|
|
11
|
+
if (!!json.picture) {
|
|
12
|
+
if (typeof json.picture === 'string') {
|
|
13
|
+
pictureData.picture = (0, ModelHelper_1.b64_2ab)(json.picture);
|
|
14
|
+
}
|
|
15
|
+
else if (json.picture instanceof ArrayBuffer || ArrayBuffer.isView(json.picture)) {
|
|
16
|
+
pictureData.picture = json.picture;
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
throw new Error(`Invalid type for picture: ${typeof json.picture}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
Object.assign(this, json, pictureData);
|
|
11
23
|
}
|
|
12
24
|
}
|
|
13
25
|
exports.Patient = Patient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Patient.js","sourceRoot":"","sources":["../../../icc-api/model/Patient.ts"],"names":[],"mappings":";;;AA0BA;;GAEG;AACH,+CAAuC;AACvC,MAAa,OAAO;IAClB,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAAe,EAAE,IAAI,EAAE,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAA,qBAAO,EAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;IAC/F,CAAC;CA4RF;AA/RD,0BA+RC;AACD,WAAiB,OAAO;IAET,kBAAU,GAAG;QACxB,IAAI,EAAE,MAAoB;QAC1B,MAAM,EAAE,QAAsB;QAC9B,aAAa,EAAE,eAA6B;QAC5C,OAAO,EAAE,SAAuB;QAChC,aAAa,EAAE,eAA6B;QAC5C,eAAe,EAAE,iBAA+B;QAChD,OAAO,EAAE,SAAuB;KACjC,CAAA;IAEY,oBAAY,GAAG;QAC1B,IAAI,EAAE,MAAsB;QAC5B,MAAM,EAAE,QAAwB;QAChC,aAAa,EAAE,eAA+B;QAC9C,OAAO,EAAE,SAAyB;QAClC,aAAa,EAAE,eAA+B;QAC9C,eAAe,EAAE,iBAAiC;QAClD,OAAO,EAAE,SAAyB;KACnC,CAAA;IAEY,8BAAsB,GAAG;QACpC,QAAQ,EAAE,UAAoC;QAC9C,KAAK,EAAE,OAAiC;QACxC,WAAW,EAAE,cAAwC;QACrD,OAAO,EAAE,SAAmC;QAC5C,SAAS,EAAE,YAAsC;QACjD,OAAO,EAAE,SAAmC;QAC5C,IAAI,EAAE,MAAgC;KACvC,CAAA;IAgBY,0BAAkB,GAAG;QAChC,MAAM,EAAE,QAA8B;QACtC,QAAQ,EAAE,WAAiC;QAC3C,OAAO,EAAE,SAA+B;QACxC,SAAS,EAAE,WAAiC;QAC5C,QAAQ,EAAE,UAAgC;QAC1C,SAAS,EAAE,WAAiC;QAC5C,OAAO,EAAE,SAA+B;QACxC,OAAO,EAAE,SAA+B;QACxC,WAAW,EAAE,aAAmC;QAChD,OAAO,EAAE,SAA+B;QACxC,QAAQ,EAAE,UAAgC;QAC1C,KAAK,EAAE,OAA6B;QACpC,QAAQ,EAAE,UAAgC;QAC1C,UAAU,EAAE,YAAkC;KAC/C,CAAA;AACH,CAAC,EA9DgB,OAAO,GAAP,eAAO,KAAP,eAAO,QA8DvB","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 { Address } from './Address'\nimport { CodeStub } from './CodeStub'\nimport { Delegation } from './Delegation'\nimport { EmploymentInfo } from './EmploymentInfo'\nimport { FinancialInstitutionInformation } from './FinancialInstitutionInformation'\nimport { Identifier } from './Identifier'\nimport { Insurability } from './Insurability'\nimport { MedicalHouseContract } from './MedicalHouseContract'\nimport { Partnership } from './Partnership'\nimport { PatientHealthCareParty } from './PatientHealthCareParty'\nimport { PersonName } from './PersonName'\nimport { PropertyStub } from './PropertyStub'\nimport { SchoolingInfo } from './SchoolingInfo'\nimport { Annotation } from './Annotation'\n\n/**\n * This entity is a root level object. It represents a patient It is serialized in JSON and saved in the underlying icure-patient CouchDB database.\n */\nimport { b64_2ab } from './ModelHelper'\nexport class Patient {\n constructor(json: JSON | any) {\n Object.assign(this as Patient, json, json?.picture ? { picture: b64_2ab(json.picture) } : {})\n }\n\n /**\n * the Id of the patient. We encourage using either a v4 UUID or a HL7 Id.\n */\n id?: string\n /**\n * the revision of the patient in the database, used for conflict management / optimistic locking.\n */\n rev?: string\n identifier?: Array<Identifier>\n /**\n * The timestamp (unix epoch in ms) of creation of this entity, will be filled automatically if missing. Not enforced by the application server.\n */\n created?: number\n /**\n * The date (unix epoch in ms) of the latest modification of this entity, will be filled automatically if missing. Not enforced by the application server.\n */\n modified?: number\n /**\n * The id of the User that has created this entity, will be filled automatically if missing. Not enforced by the application server.\n */\n author?: string\n /**\n * The id of the HealthcareParty that is responsible for this entity, will be filled automatically if missing. Not enforced by the application server.\n */\n responsible?: string\n /**\n * A tag is an item from a codification system that qualifies an entity as being member of a certain class, whatever the value it might have taken. If the tag qualifies the content of a field, it means that whatever the content of the field, the tag will always apply. For example, the label of a field is qualified using a tag. LOINC is a codification system typically used for tags.\n */\n tags?: Array<CodeStub>\n /**\n * A code is an item from a codification system that qualifies the content of this entity. SNOMED-CT, ICPC-2 or ICD-10 codifications systems can be used for codes\n */\n codes?: Array<CodeStub>\n /**\n * Soft delete (unix epoch in ms) timestamp of the object.\n */\n endOfLife?: number\n /**\n * hard delete (unix epoch in ms) timestamp of the object. Filled automatically when deletePatient is called.\n */\n deletionDate?: number\n /**\n * the firstname (name) of the patient.\n */\n firstName?: string\n /**\n * the lastname (surname) of the patient. This is the official lastname that should be used for official administrative purposes.\n */\n lastName?: string\n /**\n * the list of all names of the patient, also containing the official full name information. Ordered by preference of use. First element is therefore the official name used for the patient in the application\n */\n names?: Array<PersonName>\n /**\n * the name of the company this patient is member of.\n */\n companyName?: string\n /**\n * the list of languages spoken by the patient ordered by fluency (alpha-2 code http://www.loc.gov/standards/iso639-2/ascii_8bits.html).\n */\n languages?: Array<string>\n /**\n * the list of addresses (with address type).\n */\n addresses?: Array<Address>\n /**\n * Mr., Ms., Pr., Dr. ...\n */\n civility?: string\n /**\n * the gender of the patient: male, female, indeterminate, changed, changedToMale, changedToFemale, unknown\n */\n gender?: Patient.GenderEnum\n /**\n * the birth sex of the patient: male, female, indeterminate, unknown\n */\n birthSex?: Patient.BirthSexEnum\n /**\n * The id of the patient this patient has been merged with.\n */\n mergeToPatientId?: string\n /**\n * The ids of the patients that have been merged inside this patient.\n */\n mergedIds?: Array<string>\n /**\n * An alias of the person, nickname, ...\n */\n alias?: string\n /**\n * Is the patient active (boolean).\n */\n active?: boolean\n /**\n * When not active, the reason for deactivation.\n */\n deactivationReason?: Patient.DeactivationReasonEnum\n /**\n * Deactivation date of the patient\n */\n deactivationDate?: number\n /**\n * Social security inscription number.\n */\n ssin?: string\n /**\n * Lastname at birth (can be different of the current name), depending on the country, must be used to design the patient .\n */\n maidenName?: string\n /**\n * Lastname of the spouse for a married woman, depending on the country, can be used to design the patient.\n */\n spouseName?: string\n /**\n * Lastname of the partner, should not be used to design the patient.\n */\n partnerName?: string\n /**\n * any of `single`, `in_couple`, `married`, `separated`, `divorced`, `divorcing`, `widowed`, `widower`, `complicated`, `unknown`, `contract`, `other`.\n */\n personalStatus?: Patient.PersonalStatusEnum\n /**\n * The birthdate encoded as a fuzzy date on 8 positions (YYYYMMDD) MM and/or DD can be set to 00 if unknown (19740000 is a valid date).\n */\n dateOfBirth?: number\n /**\n * The date of death encoded as a fuzzy date on 8 positions (YYYYMMDD) MM and/or DD can be set to 00 if unknown (19740000 is a valid date).\n */\n dateOfDeath?: number\n /**\n * Timestamp of the latest validation of the eID of the person..\n */\n timestampOfLatestEidReading?: number\n /**\n * The place of birth.\n */\n placeOfBirth?: string\n /**\n * The place of death.\n */\n placeOfDeath?: string\n /**\n * Is the patient deceased.\n */\n deceased?: boolean\n /**\n * The level of education (college degree, undergraduate, phd).\n */\n education?: string\n /**\n * The current professional activity.\n */\n profession?: string\n /**\n * A text note (can be confidential, encrypted by default).\n * @deprecated use notes instead with proper tags\n */\n note?: string\n /**\n * An administrative note, not confidential.\n * @deprecated use notes instead with proper tags\n */\n administrativeNote?: string\n /**\n * A list of localized notes.\n */\n notes?: Annotation[]\n /**\n * The nationality of the patient.\n */\n nationality?: string\n /**\n * The race of the patient.\n */\n race?: string\n /**\n * The ethnicity of the patient.\n */\n ethnicity?: string\n /**\n * The id of the user that usually handles this patient.\n */\n preferredUserId?: string\n /**\n * A picture usually saved in JPEG format.\n */\n picture?: ArrayBuffer\n /**\n * An external (from another source) id with no guarantee or requirement for unicity .\n */\n externalId?: string\n /**\n * List of insurance coverages (of class Insurability, see below).\n */\n insurabilities?: Array<Insurability>\n /**\n * List of partners, or persons of contact (of class Partnership, see below).\n */\n partnerships?: Array<Partnership>\n /**\n * Links (usually for therapeutic reasons) between this patient and healthcare parties (of class PatientHealthcareParty).\n */\n patientHealthCareParties?: Array<PatientHealthCareParty>\n /**\n * Financial information (Bank, bank account) used to reimburse the patient.\n */\n financialInstitutionInformation?: Array<FinancialInstitutionInformation>\n /**\n * Contracts between the patient and the healthcare entity.\n */\n medicalHouseContracts?: Array<MedicalHouseContract>\n /**\n * Codified list of professions exercised by this patient.\n */\n patientProfessions?: Array<CodeStub>\n /**\n * Extra parameters\n */\n parameters?: { [key: string]: Array<string> }\n /**\n * Extra properties\n */\n properties?: Array<PropertyStub>\n /**\n * For each couple of HcParties (delegator and delegate), this map contains the exchange AES key. The delegator is always this hcp, the key of the map is the id of the delegate.The AES exchange key is encrypted using RSA twice : once using this hcp public key (index 0 in the Array) and once using the other hcp public key (index 1 in the Array). For a pair of HcParties. Each HcParty always has one AES exchange key for himself.\n */\n hcPartyKeys?: { [key: string]: Array<string> }\n /**\n * Extra AES exchange keys, usually the ones we lost access to at some point. The structure is { publicKey: { delegateId: { myPubKey1: aesExKey_for_this, delegatePubKey1: aesExKey_for_delegate } } }\n */\n aesExchangeKeys?: { [key: string]: { [key: string]: { [key: string]: string } } }\n /**\n * Our private keys encrypted with our public keys. The structure is { publicKey1: { publicKey2: privateKey2_encrypted_with_publicKey1, publicKey3: privateKey3_encrypted_with_publicKey1 } }\n */\n transferKeys?: { [key: string]: { [key: string]: string } }\n /**\n * The privateKeyShamirPartitions are used to share this hcp's private RSA key with a series of other hcParties using Shamir's algorithm. The key of the map is the hcp Id with whom this partition has been shared. The value is \\\"threshold⎮partition in hex\\\" encrypted using the the partition's holder's public RSA key\n */\n privateKeyShamirPartitions?: { [key: string]: string }\n /**\n * The public key of this hcp\n */\n publicKey?: string\n /**\n * The public keys of this actor which should be used for RSA-OAEP with sha256 encryption.\n */\n publicKeysForOaepWithSha256?: string[]\n /**\n * The secretForeignKeys are filled at the to many end of a one to many relationship (for example inside Contact for the Patient -> Contacts relationship). Used when we want to find all contacts for a specific patient. These keys are in clear. You can have several to partition the medical document space.\n */\n secretForeignKeys?: Array<string>\n /**\n * The secretForeignKeys are filled at the to many end of a one to many relationship (for example inside Contact for the Patient -> Contacts relationship). Used when we want to find the patient for a specific contact. These keys are the encrypted id (using the hcParty key for the delegate) that can be found in clear inside the patient. ids encrypted using the hcParty keys.\n */\n cryptedForeignKeys?: { [key: string]: Array<Delegation> }\n /**\n * When a document is created, the responsible generates a cryptographically random master key (never to be used for something else than referencing from other entities). He/she encrypts it using his own AES exchange key and stores it as a delegation. The responsible is thus always in the delegations as well\n */\n delegations?: { [key: string]: Array<Delegation> }\n /**\n * When a document needs to be encrypted, the responsible generates a cryptographically random master key (different from the delegation key, never to appear in clear anywhere in the db. He/she encrypts it using his own AES exchange key and stores it as a delegation\n */\n encryptionKeys?: { [key: string]: Array<Delegation> }\n /**\n * The base64 encoded data of this object, formatted as JSON and encrypted in AES using the random master key from encryptionKeys.\n */\n encryptedSelf?: string\n /**\n * The id of the medical location where this entity was created.\n */\n medicalLocationId?: string\n nonDuplicateIds?: Array<string>\n encryptedAdministrativesDocuments?: Array<string>\n comment?: string\n warning?: string\n fatherBirthCountry?: CodeStub\n birthCountry?: CodeStub\n nativeCountry?: CodeStub\n socialStatus?: CodeStub\n mainSourceOfIncome?: CodeStub\n schoolingInfos?: Array<SchoolingInfo>\n employementInfos?: Array<EmploymentInfo>\n}\nexport namespace Patient {\n export type GenderEnum = 'male' | 'female' | 'indeterminate' | 'changed' | 'changedToMale' | 'changedToFemale' | 'unknown'\n export const GenderEnum = {\n Male: 'male' as GenderEnum,\n Female: 'female' as GenderEnum,\n Indeterminate: 'indeterminate' as GenderEnum,\n Changed: 'changed' as GenderEnum,\n ChangedToMale: 'changedToMale' as GenderEnum,\n ChangedToFemale: 'changedToFemale' as GenderEnum,\n Unknown: 'unknown' as GenderEnum,\n }\n export type BirthSexEnum = 'male' | 'female' | 'indeterminate' | 'changed' | 'changedToMale' | 'changedToFemale' | 'unknown'\n export const BirthSexEnum = {\n Male: 'male' as BirthSexEnum,\n Female: 'female' as BirthSexEnum,\n Indeterminate: 'indeterminate' as BirthSexEnum,\n Changed: 'changed' as BirthSexEnum,\n ChangedToMale: 'changedToMale' as BirthSexEnum,\n ChangedToFemale: 'changedToFemale' as BirthSexEnum,\n Unknown: 'unknown' as BirthSexEnum,\n }\n export type DeactivationReasonEnum = 'deceased' | 'moved' | 'other_doctor' | 'retired' | 'no_contact' | 'unknown' | 'none'\n export const DeactivationReasonEnum = {\n Deceased: 'deceased' as DeactivationReasonEnum,\n Moved: 'moved' as DeactivationReasonEnum,\n OtherDoctor: 'other_doctor' as DeactivationReasonEnum,\n Retired: 'retired' as DeactivationReasonEnum,\n NoContact: 'no_contact' as DeactivationReasonEnum,\n Unknown: 'unknown' as DeactivationReasonEnum,\n None: 'none' as DeactivationReasonEnum,\n }\n export type PersonalStatusEnum =\n | 'single'\n | 'in_couple'\n | 'married'\n | 'separated'\n | 'divorced'\n | 'divorcing'\n | 'widowed'\n | 'widower'\n | 'complicated'\n | 'unknown'\n | 'contract'\n | 'other'\n | 'annulled'\n | 'polygamous'\n export const PersonalStatusEnum = {\n Single: 'single' as PersonalStatusEnum,\n InCouple: 'in_couple' as PersonalStatusEnum,\n Married: 'married' as PersonalStatusEnum,\n Separated: 'separated' as PersonalStatusEnum,\n Divorced: 'divorced' as PersonalStatusEnum,\n Divorcing: 'divorcing' as PersonalStatusEnum,\n Widowed: 'widowed' as PersonalStatusEnum,\n Widower: 'widower' as PersonalStatusEnum,\n Complicated: 'complicated' as PersonalStatusEnum,\n Unknown: 'unknown' as PersonalStatusEnum,\n Contract: 'contract' as PersonalStatusEnum,\n Other: 'other' as PersonalStatusEnum,\n Annulled: 'annulled' as PersonalStatusEnum,\n Polygamous: 'polygamous' as PersonalStatusEnum,\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Patient.js","sourceRoot":"","sources":["../../../icc-api/model/Patient.ts"],"names":[],"mappings":";;;AA0BA;;GAEG;AACH,+CAAuC;AACvC,MAAa,OAAO;IAClB,YAAY,IAAgB;QAC1B,IAAI,WAAW,GAA8B,EAAE,CAAA;QAC/C,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE;YAClB,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,EAAE;gBACpC,WAAW,CAAC,OAAO,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,OAAO,CAAC,CAAA;aAC5C;iBAAM,IAAI,IAAI,CAAC,OAAO,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;gBAClF,WAAW,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;aACnC;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,6BAA6B,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC,CAAA;aACpE;SACF;QACD,MAAM,CAAC,MAAM,CAAC,IAAe,EAAE,IAAI,EAAE,WAAW,CAAC,CAAA;IACnD,CAAC;CA4RF;AAzSD,0BAySC;AACD,WAAiB,OAAO;IAET,kBAAU,GAAG;QACxB,IAAI,EAAE,MAAoB;QAC1B,MAAM,EAAE,QAAsB;QAC9B,aAAa,EAAE,eAA6B;QAC5C,OAAO,EAAE,SAAuB;QAChC,aAAa,EAAE,eAA6B;QAC5C,eAAe,EAAE,iBAA+B;QAChD,OAAO,EAAE,SAAuB;KACjC,CAAA;IAEY,oBAAY,GAAG;QAC1B,IAAI,EAAE,MAAsB;QAC5B,MAAM,EAAE,QAAwB;QAChC,aAAa,EAAE,eAA+B;QAC9C,OAAO,EAAE,SAAyB;QAClC,aAAa,EAAE,eAA+B;QAC9C,eAAe,EAAE,iBAAiC;QAClD,OAAO,EAAE,SAAyB;KACnC,CAAA;IAEY,8BAAsB,GAAG;QACpC,QAAQ,EAAE,UAAoC;QAC9C,KAAK,EAAE,OAAiC;QACxC,WAAW,EAAE,cAAwC;QACrD,OAAO,EAAE,SAAmC;QAC5C,SAAS,EAAE,YAAsC;QACjD,OAAO,EAAE,SAAmC;QAC5C,IAAI,EAAE,MAAgC;KACvC,CAAA;IAgBY,0BAAkB,GAAG;QAChC,MAAM,EAAE,QAA8B;QACtC,QAAQ,EAAE,WAAiC;QAC3C,OAAO,EAAE,SAA+B;QACxC,SAAS,EAAE,WAAiC;QAC5C,QAAQ,EAAE,UAAgC;QAC1C,SAAS,EAAE,WAAiC;QAC5C,OAAO,EAAE,SAA+B;QACxC,OAAO,EAAE,SAA+B;QACxC,WAAW,EAAE,aAAmC;QAChD,OAAO,EAAE,SAA+B;QACxC,QAAQ,EAAE,UAAgC;QAC1C,KAAK,EAAE,OAA6B;QACpC,QAAQ,EAAE,UAAgC;QAC1C,UAAU,EAAE,YAAkC;KAC/C,CAAA;AACH,CAAC,EA9DgB,OAAO,GAAP,eAAO,KAAP,eAAO,QA8DvB","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 { Address } from './Address'\nimport { CodeStub } from './CodeStub'\nimport { Delegation } from './Delegation'\nimport { EmploymentInfo } from './EmploymentInfo'\nimport { FinancialInstitutionInformation } from './FinancialInstitutionInformation'\nimport { Identifier } from './Identifier'\nimport { Insurability } from './Insurability'\nimport { MedicalHouseContract } from './MedicalHouseContract'\nimport { Partnership } from './Partnership'\nimport { PatientHealthCareParty } from './PatientHealthCareParty'\nimport { PersonName } from './PersonName'\nimport { PropertyStub } from './PropertyStub'\nimport { SchoolingInfo } from './SchoolingInfo'\nimport { Annotation } from './Annotation'\n\n/**\n * This entity is a root level object. It represents a patient It is serialized in JSON and saved in the underlying icure-patient CouchDB database.\n */\nimport { b64_2ab } from './ModelHelper'\nexport class Patient {\n constructor(json: JSON | any) {\n let pictureData: { picture?: ArrayBuffer } = {}\n if (!!json.picture) {\n if (typeof json.picture === 'string') {\n pictureData.picture = b64_2ab(json.picture)\n } else if (json.picture instanceof ArrayBuffer || ArrayBuffer.isView(json.picture)) {\n pictureData.picture = json.picture\n } else {\n throw new Error(`Invalid type for picture: ${typeof json.picture}`)\n }\n }\n Object.assign(this as Patient, json, pictureData)\n }\n\n /**\n * the Id of the patient. We encourage using either a v4 UUID or a HL7 Id.\n */\n id?: string\n /**\n * the revision of the patient in the database, used for conflict management / optimistic locking.\n */\n rev?: string\n identifier?: Array<Identifier>\n /**\n * The timestamp (unix epoch in ms) of creation of this entity, will be filled automatically if missing. Not enforced by the application server.\n */\n created?: number\n /**\n * The date (unix epoch in ms) of the latest modification of this entity, will be filled automatically if missing. Not enforced by the application server.\n */\n modified?: number\n /**\n * The id of the User that has created this entity, will be filled automatically if missing. Not enforced by the application server.\n */\n author?: string\n /**\n * The id of the HealthcareParty that is responsible for this entity, will be filled automatically if missing. Not enforced by the application server.\n */\n responsible?: string\n /**\n * A tag is an item from a codification system that qualifies an entity as being member of a certain class, whatever the value it might have taken. If the tag qualifies the content of a field, it means that whatever the content of the field, the tag will always apply. For example, the label of a field is qualified using a tag. LOINC is a codification system typically used for tags.\n */\n tags?: Array<CodeStub>\n /**\n * A code is an item from a codification system that qualifies the content of this entity. SNOMED-CT, ICPC-2 or ICD-10 codifications systems can be used for codes\n */\n codes?: Array<CodeStub>\n /**\n * Soft delete (unix epoch in ms) timestamp of the object.\n */\n endOfLife?: number\n /**\n * hard delete (unix epoch in ms) timestamp of the object. Filled automatically when deletePatient is called.\n */\n deletionDate?: number\n /**\n * the firstname (name) of the patient.\n */\n firstName?: string\n /**\n * the lastname (surname) of the patient. This is the official lastname that should be used for official administrative purposes.\n */\n lastName?: string\n /**\n * the list of all names of the patient, also containing the official full name information. Ordered by preference of use. First element is therefore the official name used for the patient in the application\n */\n names?: Array<PersonName>\n /**\n * the name of the company this patient is member of.\n */\n companyName?: string\n /**\n * the list of languages spoken by the patient ordered by fluency (alpha-2 code http://www.loc.gov/standards/iso639-2/ascii_8bits.html).\n */\n languages?: Array<string>\n /**\n * the list of addresses (with address type).\n */\n addresses?: Array<Address>\n /**\n * Mr., Ms., Pr., Dr. ...\n */\n civility?: string\n /**\n * the gender of the patient: male, female, indeterminate, changed, changedToMale, changedToFemale, unknown\n */\n gender?: Patient.GenderEnum\n /**\n * the birth sex of the patient: male, female, indeterminate, unknown\n */\n birthSex?: Patient.BirthSexEnum\n /**\n * The id of the patient this patient has been merged with.\n */\n mergeToPatientId?: string\n /**\n * The ids of the patients that have been merged inside this patient.\n */\n mergedIds?: Array<string>\n /**\n * An alias of the person, nickname, ...\n */\n alias?: string\n /**\n * Is the patient active (boolean).\n */\n active?: boolean\n /**\n * When not active, the reason for deactivation.\n */\n deactivationReason?: Patient.DeactivationReasonEnum\n /**\n * Deactivation date of the patient\n */\n deactivationDate?: number\n /**\n * Social security inscription number.\n */\n ssin?: string\n /**\n * Lastname at birth (can be different of the current name), depending on the country, must be used to design the patient .\n */\n maidenName?: string\n /**\n * Lastname of the spouse for a married woman, depending on the country, can be used to design the patient.\n */\n spouseName?: string\n /**\n * Lastname of the partner, should not be used to design the patient.\n */\n partnerName?: string\n /**\n * any of `single`, `in_couple`, `married`, `separated`, `divorced`, `divorcing`, `widowed`, `widower`, `complicated`, `unknown`, `contract`, `other`.\n */\n personalStatus?: Patient.PersonalStatusEnum\n /**\n * The birthdate encoded as a fuzzy date on 8 positions (YYYYMMDD) MM and/or DD can be set to 00 if unknown (19740000 is a valid date).\n */\n dateOfBirth?: number\n /**\n * The date of death encoded as a fuzzy date on 8 positions (YYYYMMDD) MM and/or DD can be set to 00 if unknown (19740000 is a valid date).\n */\n dateOfDeath?: number\n /**\n * Timestamp of the latest validation of the eID of the person..\n */\n timestampOfLatestEidReading?: number\n /**\n * The place of birth.\n */\n placeOfBirth?: string\n /**\n * The place of death.\n */\n placeOfDeath?: string\n /**\n * Is the patient deceased.\n */\n deceased?: boolean\n /**\n * The level of education (college degree, undergraduate, phd).\n */\n education?: string\n /**\n * The current professional activity.\n */\n profession?: string\n /**\n * A text note (can be confidential, encrypted by default).\n * @deprecated use notes instead with proper tags\n */\n note?: string\n /**\n * An administrative note, not confidential.\n * @deprecated use notes instead with proper tags\n */\n administrativeNote?: string\n /**\n * A list of localized notes.\n */\n notes?: Annotation[]\n /**\n * The nationality of the patient.\n */\n nationality?: string\n /**\n * The race of the patient.\n */\n race?: string\n /**\n * The ethnicity of the patient.\n */\n ethnicity?: string\n /**\n * The id of the user that usually handles this patient.\n */\n preferredUserId?: string\n /**\n * A picture usually saved in JPEG format.\n */\n picture?: ArrayBuffer\n /**\n * An external (from another source) id with no guarantee or requirement for unicity .\n */\n externalId?: string\n /**\n * List of insurance coverages (of class Insurability, see below).\n */\n insurabilities?: Array<Insurability>\n /**\n * List of partners, or persons of contact (of class Partnership, see below).\n */\n partnerships?: Array<Partnership>\n /**\n * Links (usually for therapeutic reasons) between this patient and healthcare parties (of class PatientHealthcareParty).\n */\n patientHealthCareParties?: Array<PatientHealthCareParty>\n /**\n * Financial information (Bank, bank account) used to reimburse the patient.\n */\n financialInstitutionInformation?: Array<FinancialInstitutionInformation>\n /**\n * Contracts between the patient and the healthcare entity.\n */\n medicalHouseContracts?: Array<MedicalHouseContract>\n /**\n * Codified list of professions exercised by this patient.\n */\n patientProfessions?: Array<CodeStub>\n /**\n * Extra parameters\n */\n parameters?: { [key: string]: Array<string> }\n /**\n * Extra properties\n */\n properties?: Array<PropertyStub>\n /**\n * For each couple of HcParties (delegator and delegate), this map contains the exchange AES key. The delegator is always this hcp, the key of the map is the id of the delegate.The AES exchange key is encrypted using RSA twice : once using this hcp public key (index 0 in the Array) and once using the other hcp public key (index 1 in the Array). For a pair of HcParties. Each HcParty always has one AES exchange key for himself.\n */\n hcPartyKeys?: { [key: string]: Array<string> }\n /**\n * Extra AES exchange keys, usually the ones we lost access to at some point. The structure is { publicKey: { delegateId: { myPubKey1: aesExKey_for_this, delegatePubKey1: aesExKey_for_delegate } } }\n */\n aesExchangeKeys?: { [key: string]: { [key: string]: { [key: string]: string } } }\n /**\n * Our private keys encrypted with our public keys. The structure is { publicKey1: { publicKey2: privateKey2_encrypted_with_publicKey1, publicKey3: privateKey3_encrypted_with_publicKey1 } }\n */\n transferKeys?: { [key: string]: { [key: string]: string } }\n /**\n * The privateKeyShamirPartitions are used to share this hcp's private RSA key with a series of other hcParties using Shamir's algorithm. The key of the map is the hcp Id with whom this partition has been shared. The value is \\\"threshold⎮partition in hex\\\" encrypted using the the partition's holder's public RSA key\n */\n privateKeyShamirPartitions?: { [key: string]: string }\n /**\n * The public key of this hcp\n */\n publicKey?: string\n /**\n * The public keys of this actor which should be used for RSA-OAEP with sha256 encryption.\n */\n publicKeysForOaepWithSha256?: string[]\n /**\n * The secretForeignKeys are filled at the to many end of a one to many relationship (for example inside Contact for the Patient -> Contacts relationship). Used when we want to find all contacts for a specific patient. These keys are in clear. You can have several to partition the medical document space.\n */\n secretForeignKeys?: Array<string>\n /**\n * The secretForeignKeys are filled at the to many end of a one to many relationship (for example inside Contact for the Patient -> Contacts relationship). Used when we want to find the patient for a specific contact. These keys are the encrypted id (using the hcParty key for the delegate) that can be found in clear inside the patient. ids encrypted using the hcParty keys.\n */\n cryptedForeignKeys?: { [key: string]: Array<Delegation> }\n /**\n * When a document is created, the responsible generates a cryptographically random master key (never to be used for something else than referencing from other entities). He/she encrypts it using his own AES exchange key and stores it as a delegation. The responsible is thus always in the delegations as well\n */\n delegations?: { [key: string]: Array<Delegation> }\n /**\n * When a document needs to be encrypted, the responsible generates a cryptographically random master key (different from the delegation key, never to appear in clear anywhere in the db. He/she encrypts it using his own AES exchange key and stores it as a delegation\n */\n encryptionKeys?: { [key: string]: Array<Delegation> }\n /**\n * The base64 encoded data of this object, formatted as JSON and encrypted in AES using the random master key from encryptionKeys.\n */\n encryptedSelf?: string\n /**\n * The id of the medical location where this entity was created.\n */\n medicalLocationId?: string\n nonDuplicateIds?: Array<string>\n encryptedAdministrativesDocuments?: Array<string>\n comment?: string\n warning?: string\n fatherBirthCountry?: CodeStub\n birthCountry?: CodeStub\n nativeCountry?: CodeStub\n socialStatus?: CodeStub\n mainSourceOfIncome?: CodeStub\n schoolingInfos?: Array<SchoolingInfo>\n employementInfos?: Array<EmploymentInfo>\n}\nexport namespace Patient {\n export type GenderEnum = 'male' | 'female' | 'indeterminate' | 'changed' | 'changedToMale' | 'changedToFemale' | 'unknown'\n export const GenderEnum = {\n Male: 'male' as GenderEnum,\n Female: 'female' as GenderEnum,\n Indeterminate: 'indeterminate' as GenderEnum,\n Changed: 'changed' as GenderEnum,\n ChangedToMale: 'changedToMale' as GenderEnum,\n ChangedToFemale: 'changedToFemale' as GenderEnum,\n Unknown: 'unknown' as GenderEnum,\n }\n export type BirthSexEnum = 'male' | 'female' | 'indeterminate' | 'changed' | 'changedToMale' | 'changedToFemale' | 'unknown'\n export const BirthSexEnum = {\n Male: 'male' as BirthSexEnum,\n Female: 'female' as BirthSexEnum,\n Indeterminate: 'indeterminate' as BirthSexEnum,\n Changed: 'changed' as BirthSexEnum,\n ChangedToMale: 'changedToMale' as BirthSexEnum,\n ChangedToFemale: 'changedToFemale' as BirthSexEnum,\n Unknown: 'unknown' as BirthSexEnum,\n }\n export type DeactivationReasonEnum = 'deceased' | 'moved' | 'other_doctor' | 'retired' | 'no_contact' | 'unknown' | 'none'\n export const DeactivationReasonEnum = {\n Deceased: 'deceased' as DeactivationReasonEnum,\n Moved: 'moved' as DeactivationReasonEnum,\n OtherDoctor: 'other_doctor' as DeactivationReasonEnum,\n Retired: 'retired' as DeactivationReasonEnum,\n NoContact: 'no_contact' as DeactivationReasonEnum,\n Unknown: 'unknown' as DeactivationReasonEnum,\n None: 'none' as DeactivationReasonEnum,\n }\n export type PersonalStatusEnum =\n | 'single'\n | 'in_couple'\n | 'married'\n | 'separated'\n | 'divorced'\n | 'divorcing'\n | 'widowed'\n | 'widower'\n | 'complicated'\n | 'unknown'\n | 'contract'\n | 'other'\n | 'annulled'\n | 'polygamous'\n export const PersonalStatusEnum = {\n Single: 'single' as PersonalStatusEnum,\n InCouple: 'in_couple' as PersonalStatusEnum,\n Married: 'married' as PersonalStatusEnum,\n Separated: 'separated' as PersonalStatusEnum,\n Divorced: 'divorced' as PersonalStatusEnum,\n Divorcing: 'divorcing' as PersonalStatusEnum,\n Widowed: 'widowed' as PersonalStatusEnum,\n Widower: 'widower' as PersonalStatusEnum,\n Complicated: 'complicated' as PersonalStatusEnum,\n Unknown: 'unknown' as PersonalStatusEnum,\n Contract: 'contract' as PersonalStatusEnum,\n Other: 'other' as PersonalStatusEnum,\n Annulled: 'annulled' as PersonalStatusEnum,\n Polygamous: 'polygamous' as PersonalStatusEnum,\n }\n}\n"]}
|
|
@@ -370,7 +370,7 @@ class EntitiesEncryption {
|
|
|
370
370
|
// TODO should encoding of binary data should probably be applied to everything?
|
|
371
371
|
const json = encodeBinaryData
|
|
372
372
|
? JSON.stringify(obj, (k, v) => {
|
|
373
|
-
return v instanceof ArrayBuffer || v
|
|
373
|
+
return v instanceof ArrayBuffer || ArrayBuffer.isView(v)
|
|
374
374
|
? (0, utils_1.b2a)(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))
|
|
375
375
|
: v;
|
|
376
376
|
})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,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;aAC5F;YAAC,OAAO,EAAE,EAAE;gBACX,OAAO,IAAI,uDAAuD,GAAG,EAAE,CAAA;aACxE;SACF;QAED,MAAM,IAAI,KAAK,CAAC,8BAA8B,GAAG,OAAO,GAAG,yBAAyB,GAAG,QAAQ,GAAG,OAAO,CAAC,CAAA;IAC5G,CAAC;IAEO,4BAA4B,CAAC,MAAuB;QAC1D,MAAM,gBAAgB,GAAG,EAAE,CAAA;QAC3B,IAAI,MAAM,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,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;gBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;SACF;IACH,CAAC;CACF;AAv6BD,gDAu6BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport {\n b2a,\n encryptObject,\n decryptObject,\n EncryptedFieldsManifest,\n hex2ua,\n parseEncryptedFields,\n string2ua,\n truncateTrailingNulls,\n ua2hex,\n ua2string,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly exchangeKeysManager: ExchangeKeysManager,\n private readonly useParentKeys: boolean\n ) {}\n\n /**\n * Get the data owners which can access the entity\n * @param entity an entity.\n */\n async getDataOwnersWithAccessTo(entity: EncryptedEntity): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: 'WRITE' }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entity.delegations ?? {}).map((x) => [x, 'WRITE'])),\n hasUnknownAnonymousDataOwners: false,\n }\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n autoShareSecretIds: boolean,\n delegatesShareInfo: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKey?: ShareMetadataBehaviour\n shareOwningEntityIds?: ShareMetadataBehaviour\n }\n }\n ): Promise<T | undefined> {\n if (!Object.keys(delegatesShareInfo).length) {\n throw new Error('Must specify at least a delegate')\n }\n let defaultSecretIds: string[] | undefined\n if (autoShareSecretIds) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n defaultSecretIds = availableSecretIds\n } else {\n defaultSecretIds = [this.primitives.randomUuid()]\n }\n }\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let updatedEntity = undefined\n for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {\n let shareSecretIds: string[] = autoShareSecretIds ? defaultSecretIds! : requests.shareSecretIds ?? []\n let actualShareEncryptionKeys: string[] = []\n if (requests.shareEncryptionKey !== ShareMetadataBehaviour.NEVER) {\n if (!availableEncryptionKeys.length && requests.shareEncryptionKey === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (requests.shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n if (!availableOwningEntityIds.length && requests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n updatedEntity =\n (await this.entityWithExtendedEncryptedMetadata(\n updatedEntity ?? entity,\n delegateId,\n shareSecretIds,\n actualShareEncryptionKeys,\n actualShareOwningEntityIds\n )) ?? updatedEntity\n }\n return updatedEntity\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T | undefined> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return undefined\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf((await this.ensureEncryptionKeysInitialised(entity)) ?? entity, dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async tryDecryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n /* ignore */\n }\n }\n return { data: content, wasDecrypted: false }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string | undefined,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n const text = ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted)\n return JSON.parse(text)\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string | undefined,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n entityWithInitialisedEncryptionKeys ?? entity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || v instanceof Uint8Array\n ? b2a(new Uint8Array(v).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n 'entity'\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T | undefined> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) 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 * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n return Promise.all(\n canDecryptOwnerIds.map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\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 extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\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 /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as CryptoActorStubWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.stub?.id\n ? {\n ...entity,\n rev: updatedDelegator!.stub.rev,\n hcPartyKeys: updatedDelegator!.stub.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.stub.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\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 _.each(argsArray, (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 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 (existingMetadata.length > 0) {\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 }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"EntitiesEncryption.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/EntitiesEncryption.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAaiB;AACjB,4BAA2B;AAE3B,gEAAuD;AACvD,qEAAiE;AAGjE;;;GAGG;AACH,MAAa,kBAAkB;IAC7B,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,mBAAwC,EACxC,aAAsB;QAHtB,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,wBAAmB,GAAnB,mBAAmB,CAAqB;QACxC,kBAAa,G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C,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,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE;YAC/B,MAAM,IAAI,KAAK,CACb,mHAAmH,gBAAgB,IAAI;gBACrI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CACvC,CAAA;SACF;IACH,CAAC;CACF;AAv6BD,gDAu6BC","sourcesContent":["import { Delegation, EncryptedEntity, EncryptedEntityStub } from '../../icc-api/model/models'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { ExchangeKeysManager } from './ExchangeKeysManager'\nimport {\n b2a,\n encryptObject,\n decryptObject,\n EncryptedFieldsManifest,\n hex2ua,\n parseEncryptedFields,\n string2ua,\n truncateTrailingNulls,\n ua2hex,\n ua2string,\n ua2utf8,\n utf8_2ua,\n} from '../utils'\nimport * as _ from 'lodash'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { arrayEquals } from '../utils/collection-utils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * @internal this class is for internal use only and may be changed without notice\n * Give access to functions for retrieving encryption metadata of entities.\n */\nexport class EntitiesEncryption {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly exchangeKeysManager: ExchangeKeysManager,\n private readonly useParentKeys: boolean\n ) {}\n\n /**\n * Get the data owners which can access the entity\n * @param entity an entity.\n */\n async getDataOwnersWithAccessTo(entity: EncryptedEntity): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: 'WRITE' }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entity.delegations ?? {}).map((x) => [x, 'WRITE'])),\n hasUnknownAnonymousDataOwners: false,\n }\n }\n\n /**\n * Get the encryption keys of an entity that the provided data owner can access, potentially using the keys for his parent.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that the provided data owner can decrypt, deduplicated.\n */\n async encryptionKeysOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n // Legacy entities may have encryption keys in delegations.\n return this.extractMergedHierarchyFromDelegationAndOwner(\n Object.keys(entity.encryptionKeys ?? {}).length > 0 ? entity.encryptionKeys! : entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the encryption keys of an entity that the current data owner and his parents can access. The resulting array contains the keys for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes keys accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same keys, but the keys extracted for each data owner are deduplicated.\n * There should only be one encryption key for each entity, but the method supports more to allow to deal with conflicts and merged duplicate data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the encryption keys that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async encryptionKeysForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.encryptionKeys ?? {},\n (k) => this.validateEncryptionKey(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the provided data owner can access, potentially using the keys for his parent.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids (SFKs) that the provided data owner can decrypt, deduplicated.\n */\n async secretIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.delegations ?? {},\n dataOwnerId,\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the secret ids (SFKs) of an entity that the current data owner and his parents can access. The resulting array contains the ids for each data\n * owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids accessible through the parent keys). The order of\n * the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same secret ids, but the secret ids extracted for each data owner are deduplicated.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only secret ids associated to tags which satisfy the provided filter.\n * @return the secret ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async secretIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.delegations ?? {},\n (k) => this.validateSecretId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids (CFKs) that the provided data owner can decrypt, deduplicated.\n */\n async owningEntityIdsOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<string[]> {\n return this.extractMergedHierarchyFromDelegationAndOwner(\n entity.cryptedForeignKeys ?? {},\n dataOwnerId,\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * Get the decrypted owning entity ids (formerly CFKs) for the provided entity that can be decrypted using the private keys of the current data\n * owner and his parents. The owning entity id would be, for example, the id of a patient for contact and healthcare elements, or the id of a\n * message for documents.\n * The resulting array contains the ids for each data owner in the hierarchy which can be decrypted using only that data owner keys (excludes ids\n * accessible through the parent keys). The order of the array is the same as in {@link IccDataOwnerXApi.getCurrentDataOwnerHierarchyIds}.\n * Note that different data owners may have access to the same owning entity ids, but the owning entity ids extracted for each data owner are\n * deduplicated in case they could be accessed through different delegations.\n * There should only be one owning entity id for each entity, but the method supports more to allow to deal with conflicts and merged duplicate\n * data.\n * @param entity an encrypted entity.\n * @param tagsFilter allows to obtain only owning entity ids associated to tags which satisfy the provided filter.\n * @return the owning entity ids that each member of the current data owner hierarchy can decrypt using only his keys and not keys of his parents.\n */\n async owningEntityIdsForHcpHierarchyOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n return this.extractedHierarchyFromDelegation(\n entity.cryptedForeignKeys ?? {},\n (k) => this.validateOwningEntityId(k),\n (t) => tagsFilter(t)\n )\n }\n\n /**\n * @internal this method is intended only for internal use and may be changed without notice.\n * Initializes encryption metadata for an entity. This includes the encrypted secret id, owning entity id, and encryption key for the entity, and\n * the clear text secret foreign key of the parent entity.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param owningEntity id of the owning entity, if any (e.g. patient id for Contact/HealtchareElement, message id for Document, ...).\n * @param owningEntitySecretId secret id of the parent entity, to use in the secret foreign keys for the provided entity, if any.\n * @param initialiseEncryptionKeys if false this method will not initialize any encryption keys. Use only for entities which use delegations for\n * access control but don't actually have any encrypted content.\n * @param additionalDelegations automatically shares the\n * @param tags tags to associate with the initial encryption keys and metadata\n * @throws if the entity already has non-empty values for encryption metadata.\n * @return an updated copy of the entity.\n */\n async entityWithInitialisedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n owningEntity: string | undefined,\n owningEntitySecretId: string | undefined,\n initialiseEncryptionKeys: boolean,\n additionalDelegations: string[] = [],\n tags: string[] = []\n ): Promise<{\n updatedEntity: T\n rawEncryptionKey: string | undefined\n secretId: string\n }> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithInitialisedEncryptedMetadata', arguments)\n this.checkEmptyEncryptionMetadata(entity)\n const secretId = this.primitives.randomUuid()\n const rawEncryptionKey = initialiseEncryptionKeys ? ua2hex(this.primitives.randomBytes(16)) : undefined\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const allIds = [selfId, ...new Set(additionalDelegations.filter((x) => x !== selfId))]\n const loadKeysResult = await this.loadEncryptionKeysForDelegates(entity, allIds)\n const updatedEntity = await allIds.reduce<Promise<T>>(\n async (prevUpdate, delegateId) =>\n await this.createOrUpdateEntityDelegations(\n await prevUpdate,\n delegateId,\n [],\n [],\n [],\n [secretId],\n initialiseEncryptionKeys ? [rawEncryptionKey!] : [],\n owningEntity ? [owningEntity] : [],\n tags,\n loadKeysResult.keysForDelegates\n ),\n Promise.resolve(loadKeysResult.updatedEntity)\n )\n if (owningEntitySecretId) {\n updatedEntity.secretForeignKeys = [owningEntitySecretId]\n }\n return { updatedEntity, secretId, rawEncryptionKey }\n }\n\n async entityWithAutoExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n autoShareSecretIds: boolean,\n delegatesShareInfo: {\n [delegateId: string]: {\n shareSecretIds?: string[]\n shareEncryptionKey?: ShareMetadataBehaviour\n shareOwningEntityIds?: ShareMetadataBehaviour\n }\n }\n ): Promise<T | undefined> {\n if (!Object.keys(delegatesShareInfo).length) {\n throw new Error('Must specify at least a delegate')\n }\n let defaultSecretIds: string[] | undefined\n if (autoShareSecretIds) {\n const availableSecretIds = await this.secretIdsOf(entity)\n if (availableSecretIds.length) {\n defaultSecretIds = availableSecretIds\n } else {\n defaultSecretIds = [this.primitives.randomUuid()]\n }\n }\n const availableEncryptionKeys = await this.encryptionKeysOf(entity)\n const availableOwningEntityIds = await this.owningEntityIdsOf(entity)\n let updatedEntity = undefined\n for (const [delegateId, requests] of Object.entries(delegatesShareInfo)) {\n let shareSecretIds: string[] = autoShareSecretIds ? defaultSecretIds! : requests.shareSecretIds ?? []\n let actualShareEncryptionKeys: string[] = []\n if (requests.shareEncryptionKey !== ShareMetadataBehaviour.NEVER) {\n if (!availableEncryptionKeys.length && requests.shareEncryptionKey === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no encryption keys or the current data owner can't access any encryption keys.`)\n }\n actualShareEncryptionKeys = availableEncryptionKeys\n }\n let actualShareOwningEntityIds: string[] = []\n if (requests.shareOwningEntityIds !== ShareMetadataBehaviour.NEVER) {\n if (!availableOwningEntityIds.length && requests.shareOwningEntityIds === ShareMetadataBehaviour.REQUIRED) {\n throw new Error(`Entity ${JSON.stringify(entity)} has no owning entity ids or the current data owner can't access any owning entity ids.`)\n }\n actualShareOwningEntityIds = availableOwningEntityIds\n }\n updatedEntity =\n (await this.entityWithExtendedEncryptedMetadata(\n updatedEntity ?? entity,\n delegateId,\n shareSecretIds,\n actualShareEncryptionKeys,\n actualShareOwningEntityIds\n )) ?? updatedEntity\n }\n return updatedEntity\n }\n\n /**\n * Updates encryption metadata for an entity in order to share it with a delegate or in order to add additional encrypted metadata for an existing\n * delegate.\n * The first time this method is used for a specific delegate it will give access to all unencrypted content of the entity to the delegate data\n * owner. Additionally, this method also allows to share new or existing secret ids (shareSecretId), encryption keys (shareEncryptionKeys) and\n * owning entity ids (shareOwningEntityIds) for the entity.\n * You can use methods like {@link secretIdsOf}, {@link secretIdsForHcpHierarchyOf}, {@link encryptionKeysOf}, ... to retrieve the data you want to\n * share. In most cases you may want to share everything related to the entity, but note that if you use confidential delegations for patients you\n * may want to avoid sharing the confidential secret ids of the current user with other hcps.\n * This method returns a modified copy of the entity.\n * @param entity entity which requires encryption metadata initialisation.\n * @param delegateId id of the delegate to share data with.\n * @param shareSecretIds secret ids to share.\n * @param shareEncryptionKeys encryption keys to share.\n * @param shareOwningEntityIds owning enttiy ids to share.\n * @param newTags tags to associate with the new encryption keys and metadata. Existing data won't be changed.\n * @throws if any of the shareX parameters is set to `true` but the corresponding piece of data could not be retrieved.\n * @return an updated copy of the entity.\n */\n async entityWithExtendedEncryptedMetadata<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n shareSecretIds: string[],\n shareEncryptionKeys: string[],\n shareOwningEntityIds: string[],\n newTags: string[] = []\n ): Promise<T | undefined> {\n this.throwDetailedExceptionForInvalidParameter('entity.id', entity.id, 'entityWithSharedEncryptedMetadata', arguments)\n async function checkInputAndGet(input: string[], inputName: string, validate: (x: string) => boolean | Promise<boolean>): Promise<string[]> {\n for (const x of input) {\n const validation = validate(x)\n if (validation !== true && validation !== false && !(await validation)) throw new Error(`Invalid input for ${inputName}.`)\n }\n return input\n }\n const secretIdsToShare = await checkInputAndGet(shareSecretIds, 'secretIds', (x) => this.validateSecretId(x))\n const encryptionKeysToShare = await checkInputAndGet(shareEncryptionKeys, 'encryptionKeys', (x) => this.validateEncryptionKey(x))\n const owningEntityIdsToShare = await checkInputAndGet(shareOwningEntityIds, 'owningEntityIds', (x) => this.validateOwningEntityId(x))\n const deduplicateInfoSecretIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.delegations ?? {},\n secretIdsToShare,\n (x) => this.validateSecretId(x)\n )\n const deduplicateInfoEncryptionKeys = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.encryptionKeys ?? {},\n encryptionKeysToShare,\n (x) => this.validateEncryptionKey(x)\n )\n const deduplicateInfoOwningEntityIds = await this.deduplicateDelegationsAndFilterRequiredEntries(\n delegateId,\n entity.cryptedForeignKeys ?? {},\n owningEntityIdsToShare,\n (x) => this.validateOwningEntityId(x)\n )\n /*TODO\n * Temporary hack since secret id is necessary to create a delegation for access control: if there is no delegation existing from me to the\n * delegate and there is no new secret id to be created create a new random id.\n */\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n if (deduplicateInfoSecretIds.missingEntries.length === 0 && !deduplicateInfoSecretIds.deduplicatedDelegations.some((d) => d.owner === selfId)) {\n deduplicateInfoSecretIds.missingEntries.push(this.primitives.randomUuid())\n }\n if (\n deduplicateInfoSecretIds.missingEntries.length === 0 &&\n deduplicateInfoEncryptionKeys.missingEntries.length === 0 &&\n deduplicateInfoOwningEntityIds.missingEntries.length === 0\n )\n return undefined\n const { updatedEntity, keysForDelegates } = await this.loadEncryptionKeysForDelegates(entity, [delegateId])\n return this.createOrUpdateEntityDelegations(\n updatedEntity,\n delegateId,\n deduplicateInfoSecretIds.deduplicatedDelegations,\n deduplicateInfoEncryptionKeys.deduplicatedDelegations,\n deduplicateInfoOwningEntityIds.deduplicatedDelegations,\n deduplicateInfoSecretIds.missingEntries,\n deduplicateInfoEncryptionKeys.missingEntries,\n deduplicateInfoOwningEntityIds.missingEntries,\n newTags,\n keysForDelegates\n )\n }\n\n /**\n * Encrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys of the entity there is no guarantee on which key will be used.\n * Note: you should not use this method to encrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to encrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to encrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param tagsFilter allows to use for encryption only keys associated to tags which pass the filter.\n * @return the encrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity.\n */\n async encryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<ArrayBuffer> {\n const keys = await this.encryptionKeysOf((await this.ensureEncryptionKeysInitialised(entity)) ?? entity, dataOwnerId, tagsFilter)\n if (keys.length === 0)\n throw new Error(\n `Could not extract any encryption keys of entity ${entity} for data owner ${\n dataOwnerId ?? (await this.dataOwnerApi.getCurrentDataOwnerId())\n }.`\n )\n return this.primitives.AES.encryptWithRawKey(keys[0], content)\n }\n\n /**\n * Decrypts data using a key of the entity that the provided data owner can access (current data owner by default). If the provided data owner can\n * access multiple encryption keys each of them will be tried for decryption until one of them gives a result that is valid according to the\n * provided validator.\n * Note: you should not use this method to decrypt the `encryptedSelf` of iCure entities, since that will be automatically handled by the extended\n * apis. You should use this method only to decrypt additional data, such as document attachments.\n * @param entity an entity.\n * @param content data of the entity which you want to decrypt.\n * @param dataOwnerId optionally a data owner part of the hierarchy for the current data owner, defaults to the current data owner.\n * @param validator a function which verifies the correctness of decrypted content: helps to identify decryption with the wrong key without relying\n * solely on padding.\n * @param tagsFilter allows to use for decryption only keys associated to tags which pass the filter.\n * @return the decrypted data.\n * @throws if the provided data owner can't access any encryption keys for the entity, or if no key could be found which provided valid decrypted\n * content according to the validator.\n */\n async tryDecryptDataOf(\n entity: EncryptedEntity | EncryptedEntityStub,\n content: ArrayBuffer | Uint8Array,\n validator: (decryptedData: ArrayBuffer) => Promise<boolean> = () => Promise.resolve(true),\n dataOwnerId?: string,\n tagsFilter: (tags: string[]) => Promise<boolean> = () => Promise.resolve(true)\n ): Promise<{ data: ArrayBuffer; wasDecrypted: boolean }> {\n const keys = await this.encryptionKeysOf(entity, dataOwnerId, tagsFilter)\n for (const key of keys) {\n try {\n const decrypted = await this.primitives.AES.decryptWithRawKey(key, content)\n if (await validator(decrypted)) return { data: decrypted, wasDecrypted: true }\n } catch (e) {\n /* ignore */\n }\n }\n return { data: content, wasDecrypted: false }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Decrypts the content of an encrypted entity.\n */\n async decryptEntity<T extends EncryptedEntity>(\n entity: T,\n ownerId: string | undefined,\n constructor: (json: any) => T\n ): Promise<{ entity: T; decrypted: boolean }> {\n const encryptionKeys = await this.importAllValidKeys(await this.encryptionKeysOf(entity, ownerId))\n if (!encryptionKeys.length) return { entity, decrypted: false }\n return {\n entity: constructor(\n await decryptObject(entity, async (encrypted) => {\n return (await this.tryDecryptJson(encryptionKeys, encrypted, false)) ?? {}\n })\n ),\n decrypted: true,\n }\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries using the provided keys to decrypt some json.\n */\n async tryDecryptJson(\n potentialKeys: { key: CryptoKey; raw: string }[],\n encrypted: Uint8Array,\n truncateTrailingDecryptedNulls: boolean\n ): Promise<{} | undefined> {\n for (const key of potentialKeys) {\n try {\n const decrypted = (await this.primitives.AES.decrypt(key.key, encrypted, key.raw)) ?? encrypted\n const text = ua2utf8(truncateTrailingDecryptedNulls ? truncateTrailingNulls(new Uint8Array(decrypted)) : decrypted)\n return JSON.parse(text)\n } catch (e) {}\n }\n return undefined\n }\n\n /**\n * @internal this method is intended for internal use only and may be changed without notice.\n * Tries to encrypt the content of an encrypted entity.\n * 1. If valid key for encryption is found the method returns the entity with the encrypted fields specified by cryptedKeys\n * 2. If requireEncryption is true and no key could be found for encryption of the entity the method fails.\n * 3. If requireEncryption is false and no key could be found for encryption the method will only check that the entity does not specify any value\n * for fields which should be encrypted according to cryptedKeys (e.g. note in a patient by default). If the entity specifies a value for any field\n * which should be encrypted the method throws an error, otherwise the method returns the original entity.\n */\n async tryEncryptEntity<T extends EncryptedEntity>(\n entity: T,\n dataOwnerId: string | undefined,\n fieldsToEncrypt: EncryptedFieldsManifest,\n encodeBinaryData: boolean,\n requireEncryption: boolean,\n constructor: (json: any) => T\n ): Promise<T> {\n const entityWithInitialisedEncryptionKeys = await this.ensureEncryptionKeysInitialised(entity)\n const encryptionKey = await this.tryImportFirstValidKey(await this.encryptionKeysOf(entity, dataOwnerId), entity.id!)\n if (!!encryptionKey) {\n return constructor(\n await encryptObject(\n entityWithInitialisedEncryptionKeys ?? entity,\n (obj) => {\n // TODO should encoding of binary data should probably be applied to everything?\n const json = encodeBinaryData\n ? JSON.stringify(obj, (k, v) => {\n return v instanceof ArrayBuffer || ArrayBuffer.isView(v)\n ? b2a(new Uint8Array(v as ArrayBufferLike).reduce((d, b) => d + String.fromCharCode(b), ''))\n : v\n })\n : JSON.stringify(obj)\n return this.primitives.AES.encrypt(encryptionKey.key, utf8_2ua(json), encryptionKey.raw)\n },\n fieldsToEncrypt,\n 'entity'\n )\n )\n } else if (requireEncryption) {\n throw new Error(`No key found for encryption of entity ${entity}`)\n } else {\n await encryptObject(\n entity,\n async (obj: { [key: string]: any }) => {\n const hasNonEmptyValues = Object.values(obj).some(\n (v) => v !== undefined && (typeof v !== 'object' || (Array.isArray(v) && v.length > 0) || Object.keys(v).length > 0)\n )\n if (hasNonEmptyValues) {\n throw new Error(\n `Impossible to modify encrypted content of an entity if no encryption key is known.\\nEntity: ${JSON.stringify(\n entity\n )}\\nTo encrypt: ${JSON.stringify(obj)}`\n )\n }\n return Promise.resolve(new ArrayBuffer(1))\n },\n fieldsToEncrypt,\n 'entity'\n )\n return entity\n }\n }\n\n /**\n * @internal This method is for internal use only and may be changed without notice.\n * Ensures that the encryption keys of an entity are initialised. If not will throw an exception or initialise them depending on the content of\n * the entity. This function supports migration of entities using older encryption schemes (delegation only without encrypted keys) or entities\n * which were previously not encrypted.\n */\n async ensureEncryptionKeysInitialised<T extends EncryptedEntity>(entity: T): Promise<T | undefined> {\n if (Object.keys(entity.encryptionKeys ?? {}).length > 0) 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 * If entity was using delegations as legacy encryption keys we will essentially revoke the access to the encrypted data for all other data\n * owners. This however should not be a problem as this form of legacy entities should not exist anymore, and it should be present only in the\n * databases of hcps without collaborators.\n */\n return await this.entityWithExtendedEncryptedMetadata(\n entity,\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n [],\n [ua2hex(this.primitives.randomBytes(16))],\n []\n )\n }\n\n /**\n * Get the decrypted content of a delegation-like object which the provided data owner would be able to access using ONLY HIS EXCHANGE KEYS (does\n * not consider exchange keys for parents).\n * Note that the retrieved exchange keys are decrypted using the private keys available on the device, and results may vary from other devices.\n * @param dataOwnerId id of a data owner, he should be part of the current data owner hierarchy.\n * @param delegations a delegation-like object containing the encrypted key\n * @param includeFromDelegations if true also considers delegation from the provided data owner (or parents) to look for values. This allows to\n * decrypt delegations associated to exchange keys recovered after a giveAccessBack request.\n * @param validateDecrypted validates the decrypted result, to drop decryption results with wrong key that still gave a valid checksum.\n * @param tagsFilter allows to obtain only encryption keys associated to tags which satisfy the provided filter.\n * @return the key which could be decrypted using only keys available on the current device and delegations from/to the provided data owner. May\n * contain duplicates.\n */\n private async extractFromDelegationsForDataOwner(\n dataOwnerId: string,\n delegations: { [delegateId: string]: Delegation[] },\n includeFromDelegations: boolean,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<string[]> {\n const delegationsWithOwner = includeFromDelegations\n ? Object.entries(delegations).flatMap(([delegateId, delegations]) =>\n dataOwnerId === delegateId\n ? this.populateDelegatedTo(delegateId, delegations)\n : this.populateDelegatedTo(\n delegateId,\n delegations.filter((d) => d.owner === dataOwnerId)\n )\n )\n : delegations[dataOwnerId] ?? []\n const res = []\n for (const delegation of delegationsWithOwner) {\n if (await tagsFilter(delegation.tags ?? [])) {\n const decrypted = await this.tryDecryptDelegation(delegation, (k) => validateDecrypted(k))\n if (decrypted) res.push(decrypted)\n }\n }\n return res\n }\n\n // Ensures that the delegatedTo field of delegations has the appropriate values, else returns a copy of the delegations with the appropriate value.\n private populateDelegatedTo(delegateId: string, delegations: Delegation[]): Delegation[] {\n return delegations.map((d) => (d.delegatedTo === delegateId ? d : { ...d, delegatedTo: delegateId }))\n }\n\n private async extractedHierarchyFromDelegation(\n delegations: { [delegateId: string]: Delegation[] },\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\n ): Promise<{ ownerId: string; extracted: string[] }[]> {\n const canDecryptOwnerIds = this.useParentKeys\n ? await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n : [await this.dataOwnerApi.getCurrentDataOwnerId()]\n return Promise.all(\n canDecryptOwnerIds.map(async (ownerId) => {\n const extracted = this.deduplicate(\n await this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n return { ownerId, extracted }\n })\n )\n }\n\n /**\n * @internal This method should be private but is currently public/internal to allow to continue supporting legacy methods\n */\n async extractMergedHierarchyFromDelegationAndOwner(\n delegations: { [delegateId: string]: Delegation[] },\n dataOwnerId: string | undefined,\n validateDecrypted: (result: string) => boolean | Promise<boolean>,\n tagsFilter: (tags: string[]) => Promise<boolean>\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 extractedByOwner = await Promise.all(\n // Reverse is just to keep method behaviour as close as possible to the legacy behaviour, in case someone depended on the ordering.\n [...hierarchy].reverse().map((ownerId) =>\n this.extractFromDelegationsForDataOwner(\n ownerId,\n delegations,\n true,\n (k) => validateDecrypted(k),\n (t) => tagsFilter(t)\n )\n )\n )\n return this.deduplicate(extractedByOwner.flatMap((x) => x))\n }\n\n private async tryDecryptDelegation(\n delegation: Delegation,\n validateDecrypted: (result: string) => boolean | Promise<boolean>\n ): Promise<string | undefined> {\n const exchangeKeys = await this.exchangeKeysManager.getDecryptionExchangeKeysFor(delegation.owner!, delegation.delegatedTo!)\n for (const key of exchangeKeys) {\n try {\n // Format of encrypted key for any delegation should be entityId:key, but with the merging of entities the entityId might not match the\n // current id. As a checksum we are only verifying that the decrypted bytes can be represented as a string with exactly one ':'.\n // Additionally, we also have a validator that is specific for each type of delegation content (encryption key, secret id, ...)\n const decrypted = ua2string(await this.primitives.AES.decrypt(key, hex2ua(delegation.key!)))\n const decryptedSplit = decrypted.split(':')\n if (decryptedSplit.length === 2) {\n const validation = validateDecrypted(decryptedSplit[1])\n if (validation === true || (validation !== false && (await validation))) return decryptedSplit[1]\n } else {\n console.warn(\"Error in the decrypted delegation: content should contain exactly 1 ':', the delegation is ignored.\")\n }\n } catch (e) {\n // Do nothing: the delegation uses another exchange key owner->delegator\n }\n }\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 /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string }> {\n const res = await this.tryImportFirstValidKey(keys, entityId)\n if (!res) throw new Error(`Could not find any valid key for entity ${entityId}.`)\n return res\n }\n\n private async tryImportFirstValidKey(keys: string[], entityId: string): Promise<{ key: CryptoKey; raw: string } | undefined> {\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) return { key: imported, raw: key }\n }\n }\n\n /**\n * @internal this method is for internal use only and may be changed without notice.\n */\n async importAllValidKeys(keys: string[]): Promise<{ key: CryptoKey; raw: string }[]> {\n const res = []\n for (const key of keys) {\n const imported = await this.tryImportKey(key)\n if (imported) res.push({ key: imported, raw: key })\n }\n return res\n }\n\n private async validateEncryptionKey(key: string): Promise<boolean> {\n return !!(await this.tryImportKey(key))\n }\n\n private validateSecretId(key: string): boolean {\n return !!key\n }\n\n private validateOwningEntityId(key: string): boolean {\n return !!key\n }\n\n private async createEncryptionKeyDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n encryptionKey: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!(await this.validateEncryptionKey(encryptionKey))) throw new Error(`Invalid encryption key ${encryptionKey}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, encryptionKey, newTags)\n }\n\n private async createSecretIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n secretId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateSecretId(secretId)) throw new Error(`Invalid secret id ${secretId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, secretId, newTags)\n }\n\n private async createOwningEntityIdDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n owningEntityId: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (!this.validateOwningEntityId(owningEntityId)) throw new Error(`Invalid owning id ${owningEntityId}`)\n return this.createDelegation(entityId, delegateId, exchangeKey, owningEntityId, newTags)\n }\n\n private async createDelegation(\n entityId: string,\n delegateId: string,\n exchangeKey: CryptoKey,\n content: string,\n newTags: string[]\n ): Promise<Delegation> {\n if (entityId.includes(':')) throw new Error(\"Ids for encrypted entities are not allowed to contain ':'\")\n if (content.includes(':')) throw new Error(\"Content of delegations can not contain ':'\")\n return {\n delegatedTo: delegateId,\n owner: await this.dataOwnerApi.getCurrentDataOwnerId(),\n key: ua2hex(await this.primitives.AES.encrypt(exchangeKey, string2ua(entityId + ':' + content))),\n tags: newTags,\n }\n }\n\n private async loadEncryptionKeysForDelegates<T extends EncryptedEntity>(\n entity: T,\n delegates: string[]\n ): Promise<{ updatedEntity: T; keysForDelegates: { [delegateId: string]: CryptoKey[] } }> {\n const { updatedDelegator, keysForDelegates } = await delegates.reduce(\n async (acc, delegateId) => {\n const awaitedAcc = await acc\n const currUpdateResult = await this.exchangeKeysManager.getOrCreateEncryptionExchangeKeysTo(delegateId)\n return {\n updatedDelegator: currUpdateResult.updatedDelegator ?? awaitedAcc.updatedDelegator,\n keysForDelegates: {\n ...awaitedAcc.keysForDelegates,\n [delegateId]: currUpdateResult.keys,\n },\n }\n },\n Promise.resolve({\n updatedDelegator: undefined as CryptoActorStubWithType | undefined,\n keysForDelegates: {} as { [delegateId: string]: CryptoKey[] },\n })\n )\n const updatedEntity =\n entity.id === updatedDelegator?.stub?.id\n ? {\n ...entity,\n rev: updatedDelegator!.stub.rev,\n hcPartyKeys: updatedDelegator!.stub.hcPartyKeys,\n aesExchangeKeys: updatedDelegator!.stub.aesExchangeKeys,\n }\n : entity\n return { updatedEntity, keysForDelegates }\n }\n\n private async createOrUpdateEntityDelegations<T extends EncryptedEntity>(\n entity: T,\n delegateId: string,\n existingSecretIds: Delegation[],\n existingEncryptionKeys: Delegation[],\n existingOwningEntityIds: Delegation[],\n newSecretIds: string[],\n newEncryptionKeys: string[],\n newOwningEntityIds: string[],\n newTags: string[],\n keysForDelegates: { [delegateId: string]: CryptoKey[] }\n ): Promise<T> {\n const entityCopy = _.cloneDeep(entity)\n if (newSecretIds.length === 0 && newEncryptionKeys.length === 0 && newOwningEntityIds.length === 0) return entityCopy\n const chosenKey = keysForDelegates[delegateId][0]\n const updatedSecretIds = [\n ...existingSecretIds,\n ...(await Promise.all(newSecretIds.map((x) => this.createSecretIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedEncryptionKeys = [\n ...existingEncryptionKeys,\n ...(await Promise.all(newEncryptionKeys.map((x) => this.createEncryptionKeyDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n const updatedOwningEntityIds = [\n ...existingOwningEntityIds,\n ...(await Promise.all(newOwningEntityIds.map((x) => this.createOwningEntityIdDelegation(entity.id!, delegateId, chosenKey, x, newTags)))),\n ]\n if (updatedSecretIds.length > 0) {\n entityCopy.delegations = {\n ...(entity.delegations ?? {}),\n [delegateId]: updatedSecretIds,\n }\n }\n if (updatedEncryptionKeys.length > 0) {\n entityCopy.encryptionKeys = {\n ...(entity.encryptionKeys ?? {}),\n [delegateId]: updatedEncryptionKeys,\n }\n }\n if (updatedOwningEntityIds.length > 0) {\n entityCopy.cryptedForeignKeys = {\n ...(entity.cryptedForeignKeys ?? {}),\n [delegateId]: updatedOwningEntityIds,\n }\n }\n return entityCopy\n }\n\n /**\n * De-duplicates all currently accessible delegations, by removing any delegations created by the current data owner which have duplicated content,\n * and checks if any of the required entries are currently available to the delegate through the existing delegations.\n * @param delegateId id of the delegate.\n * @param allDelegations delegations of the entity.\n * @param requiredEntries potentially new entries that the delegate needs to be able to access from the delegations.\n * @param validateDecrypted validator for decrypted delegation content\n * @return the deduplicated delegations\n */\n private async deduplicateDelegationsAndFilterRequiredEntries(\n delegateId: string,\n allDelegations: { [delegateId: string]: Delegation[] },\n requiredEntries: string[],\n validateDecrypted: (x: string) => boolean | Promise<boolean>\n ): Promise<{\n deduplicatedDelegations: Delegation[]\n missingEntries: string[]\n }> {\n const selfId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const delegationsToDelegate = allDelegations[delegateId] ?? []\n const decryptedDelegations = await Promise.all(\n delegationsToDelegate.map(async (d) => ({\n delegation: d,\n content: d.owner === selfId ? await this.tryDecryptDelegation(d, (x) => validateDecrypted(x)) : undefined,\n }))\n )\n const deduplicatedDelegations: Delegation[] = []\n const deduplicatedContent = new Map<string, string[][]>()\n decryptedDelegations.forEach(({ delegation, content }) => {\n if (content === undefined) {\n // Keep all delegations we could not decrypt or from other data owners\n deduplicatedDelegations.push(delegation)\n } else {\n const deduplicatedTags = deduplicatedContent.get(content)\n if (!deduplicatedTags) {\n deduplicatedContent.set(content, [delegation.tags ?? []])\n deduplicatedDelegations.push(delegation)\n } else if (!deduplicatedTags.some((t) => arrayEquals(t, delegation.tags ?? []))) {\n deduplicatedTags.push(delegation.tags ?? [])\n deduplicatedDelegations.push(delegation)\n }\n }\n })\n const delegationsFromDelegateToSelf = (allDelegations[selfId] ?? []).filter((d) => d.owner === delegateId)\n const decryptedDelegationsFromDelegate = new Set(\n await Promise.all(delegationsFromDelegateToSelf.map((d) => this.tryDecryptDelegation(d, (x) => validateDecrypted(x)))).then((dels) =>\n dels.flatMap((x) => (x ? [x] : []))\n )\n )\n return {\n deduplicatedDelegations,\n missingEntries: requiredEntries.filter((entry) => !(deduplicatedContent.has(entry) || decryptedDelegationsFromDelegate.has(entry))),\n }\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 _.each(argsArray, (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 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 (existingMetadata.length > 0) {\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 }\n }\n}\n"]}
|
|
@@ -4,6 +4,7 @@ import * as models from '../icc-api/model/models';
|
|
|
4
4
|
import { Contact, ListOfIds, Service } from '../icc-api/model/models';
|
|
5
5
|
import { PaginatedListContact } from '../icc-api/model/PaginatedListContact';
|
|
6
6
|
import { IccDataOwnerXApi } from './icc-data-owner-x-api';
|
|
7
|
+
import { SubscriptionOptions } from './utils';
|
|
7
8
|
import { AuthenticationProvider } from './auth/AuthenticationProvider';
|
|
8
9
|
import { ShareMetadataBehaviour } from './crypto/ShareMetadataBehaviour';
|
|
9
10
|
import { EncryptedEntityXApi } from './basexapi/EncryptedEntityXApi';
|
|
@@ -211,12 +212,6 @@ export declare class IccContactXApi extends IccContactApi implements EncryptedEn
|
|
|
211
212
|
hasUnknownAnonymousDataOwners: boolean;
|
|
212
213
|
}>;
|
|
213
214
|
getEncryptionKeysOf(entity: Contact): Promise<string[]>;
|
|
214
|
-
subscribeToServiceEvents(eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[], filter: AbstractFilter<Service> | undefined, eventFired: (dataSample: Service) => Promise<void>, options?:
|
|
215
|
-
|
|
216
|
-
connectionRetryIntervalMs?: number;
|
|
217
|
-
}): Promise<Connection>;
|
|
218
|
-
subscribeToContactEvents(eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[], filter: AbstractFilter<Contact> | undefined, eventFired: (dataSample: Contact) => Promise<void>, options?: {
|
|
219
|
-
connectionMaxRetry?: number;
|
|
220
|
-
connectionRetryIntervalMs?: number;
|
|
221
|
-
}): Promise<Connection>;
|
|
215
|
+
subscribeToServiceEvents(eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[], filter: AbstractFilter<Service> | undefined, eventFired: (dataSample: Service) => Promise<void>, options?: SubscriptionOptions): Promise<Connection>;
|
|
216
|
+
subscribeToContactEvents(eventTypes: ('CREATE' | 'UPDATE' | 'DELETE')[], filter: AbstractFilter<Contact> | undefined, eventFired: (dataSample: Contact) => Promise<void>, options?: SubscriptionOptions): Promise<Connection>;
|
|
222
217
|
}
|