@icure/api 8.6.4 → 8.6.5
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/CryptoActorStub.d.ts +2 -0
- package/icc-api/model/CryptoActorStub.js.map +1 -1
- package/icc-api/model/Device.d.ts +1 -0
- package/icc-api/model/Device.js.map +1 -1
- package/icc-api/model/HealthcareParty.d.ts +1 -0
- package/icc-api/model/HealthcareParty.js.map +1 -1
- package/icc-api/model/Patient.d.ts +1 -0
- package/icc-api/model/Patient.js.map +1 -1
- package/icc-x-api/crypto/CryptoStrategies.d.ts +2 -1
- package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js +2 -2
- package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
- package/package.json +1 -1
- package/test/support/CSM-729.d.ts +1 -0
- package/test/support/CSM-729.js +225 -0
- package/test/support/CSM-729.js.map +1 -0
|
@@ -4,6 +4,7 @@ import { Patient } from './Patient';
|
|
|
4
4
|
import { HealthcareParty } from './HealthcareParty';
|
|
5
5
|
import { Device } from './Device';
|
|
6
6
|
import { CodeStub } from './CodeStub';
|
|
7
|
+
import { PropertyStub } from './PropertyStub';
|
|
7
8
|
export declare class CryptoActorStub {
|
|
8
9
|
constructor(json: JSON | any);
|
|
9
10
|
static fromDataOwner(dataOwnerWithType: Patient | HealthcareParty | Device): CryptoActorStub;
|
|
@@ -52,6 +53,7 @@ export declare class CryptoActorStub {
|
|
|
52
53
|
*/
|
|
53
54
|
tags?: Array<CodeStub>;
|
|
54
55
|
parentId?: string;
|
|
56
|
+
cryptoActorProperties?: Array<PropertyStub>;
|
|
55
57
|
}
|
|
56
58
|
export declare class CryptoActorStubWithType {
|
|
57
59
|
constructor(json: JSON | any);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CryptoActorStub.js","sourceRoot":"","sources":["../../../icc-api/model/CryptoActorStub.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"CryptoActorStub.js","sourceRoot":"","sources":["../../../icc-api/model/CryptoActorStub.ts"],"names":[],"mappings":";;;AAQA,MAAa,eAAe;IAC1B,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAAuB,EAAE,IAAI,CAAC,CAAA;IAC9C,CAAC;IAED,MAAM,CAAC,aAAa,CAAC,iBAAqD;QACxE,OAAO,IAAI,eAAe,CAAC;YACzB,EAAE,EAAE,iBAAiB,CAAC,EAAE;YACxB,GAAG,EAAE,iBAAiB,CAAC,GAAG;YAC1B,WAAW,EAAE,iBAAiB,CAAC,WAAW;YAC1C,eAAe,EAAE,iBAAiB,CAAC,eAAe;YAClD,YAAY,EAAE,iBAAiB,CAAC,YAAY;YAC5C,0BAA0B,EAAE,iBAAiB,CAAC,0BAA0B;YACxE,2BAA2B,EAAE,iBAAiB,CAAC,2BAA2B;YAC1E,SAAS,EAAE,iBAAiB,CAAC,SAAS;YACtC,IAAI,EAAE,iBAAiB,CAAC,IAAI;YAC5B,QAAQ,EAAE,iBAAiB,CAAC,QAAQ;SACrC,CAAC,CAAA;IACJ,CAAC;CAkCF;AApDD,0CAoDC;AACD,MAAa,uBAAuB;IAClC,YAAY,IAAgB;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAC1C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAyB,CAAA;IAC5C,CAAC;IAED,MAAM,CAAC,aAAa,CAAC,iBAAoC;QACvD,OAAO,IAAI,uBAAuB,CAAC;YACjC,IAAI,EAAE,eAAe,CAAC,aAAa,CAAC,iBAAiB,CAAC,SAAS,CAAC;YAChE,IAAI,EAAE,iBAAiB,CAAC,IAAI;SAC7B,CAAC,CAAA;IACJ,CAAC;CAIF;AAfD,0DAeC","sourcesContent":["import { DataOwnerTypeEnum } from './DataOwnerTypeEnum'\nimport { DataOwnerWithType } from './DataOwnerWithType'\nimport { Patient } from './Patient'\nimport { HealthcareParty } from './HealthcareParty'\nimport { Device } from './Device'\nimport { CodeStub } from './CodeStub'\nimport { PropertyStub } from './PropertyStub'\n\nexport class CryptoActorStub {\n constructor(json: JSON | any) {\n Object.assign(this as CryptoActorStub, json)\n }\n\n static fromDataOwner(dataOwnerWithType: Patient | HealthcareParty | Device) {\n return new CryptoActorStub({\n id: dataOwnerWithType.id,\n rev: dataOwnerWithType.rev,\n hcPartyKeys: dataOwnerWithType.hcPartyKeys,\n aesExchangeKeys: dataOwnerWithType.aesExchangeKeys,\n transferKeys: dataOwnerWithType.transferKeys,\n privateKeyShamirPartitions: dataOwnerWithType.privateKeyShamirPartitions,\n publicKeysForOaepWithSha256: dataOwnerWithType.publicKeysForOaepWithSha256,\n publicKey: dataOwnerWithType.publicKey,\n tags: dataOwnerWithType.tags,\n parentId: dataOwnerWithType.parentId,\n })\n }\n\n readonly id!: string\n readonly rev?: string\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 keys of this actor which should be used for RSA-OAEP with sha256 encryption.\n */\n publicKeysForOaepWithSha256?: string[]\n /**\n * The public key of this hcp\n */\n publicKey?: 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 parentId?: string\n cryptoActorProperties?: Array<PropertyStub>\n}\nexport class CryptoActorStubWithType {\n constructor(json: JSON | any) {\n this.stub = new CryptoActorStub(json.stub)\n this.type = json.type as DataOwnerTypeEnum\n }\n\n static fromDataOwner(dataOwnerWithType: DataOwnerWithType) {\n return new CryptoActorStubWithType({\n stub: CryptoActorStub.fromDataOwner(dataOwnerWithType.dataOwner),\n type: dataOwnerWithType.type,\n })\n }\n\n stub: CryptoActorStub\n type: DataOwnerTypeEnum\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Device.js","sourceRoot":"","sources":["../../../icc-api/model/Device.ts"],"names":[],"mappings":";;;AAeA;;GAEG;AACH,+
|
|
1
|
+
{"version":3,"file":"Device.js","sourceRoot":"","sources":["../../../icc-api/model/Device.ts"],"names":[],"mappings":";;;AAeA;;GAEG;AACH,+CAAyD;AACzD,MAAa,MAAM;IACjB,YAAY,IAAgB;QAC1B,MAAM,CAAC,MAAM,CAAC,IAAc,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAA,uCAAyB,EAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;IAC/G,CAAC;CA2EF;AA9ED,wBA8EC","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 { CodeStub } from './CodeStub'\nimport { Identifier } from './Identifier'\nimport { PropertyStub } from './PropertyStub'\n\n/**\n * This entity is a root level object. It represents a device. It is serialized in JSON and saved in the underlying icure-base CouchDB database.\n */\nimport { decodeStringOrArrayBuffer } from './ModelHelper'\nexport class Device {\n constructor(json: JSON | any) {\n Object.assign(this as Device, json, json.picture ? { picture: decodeStringOrArrayBuffer(json.picture) } : {})\n }\n\n id?: string\n rev?: string\n /**\n * hard delete (unix epoch in ms) timestamp of the object. Filled automatically when deletePatient is called.\n */\n deletionDate?: number\n identifiers?: 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 * The id of the medical location where this entity was created.\n */\n medicalLocationId?: string\n externalId?: string\n name?: string\n type?: string\n brand?: string\n model?: string\n serialNumber?: string\n parentId?: string\n picture?: ArrayBuffer\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 device 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 device\n */\n publicKey?: string\n /**\n * The public keys of this actor that are generates using the OAEP Sha-256 standard\n */\n publicKeysForOaepWithSha256?: Array<string>\n cryptoActorProperties?: Array<PropertyStub>\n}\n"]}
|
|
@@ -221,6 +221,7 @@ export declare class HealthcareParty {
|
|
|
221
221
|
* The public keys of this actor that are generates using the OAEP Sha-256 standard
|
|
222
222
|
*/
|
|
223
223
|
publicKeysForOaepWithSha256?: Array<string>;
|
|
224
|
+
cryptoActorProperties?: Array<PropertyStub>;
|
|
224
225
|
}
|
|
225
226
|
export declare namespace HealthcareParty {
|
|
226
227
|
type GenderEnum = 'male' | 'female' | 'indeterminate' | 'changed' | 'changedToMale' | 'changedToFemale' | 'unknown';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HealthcareParty.js","sourceRoot":"","sources":["../../../icc-api/model/HealthcareParty.ts"],"names":[],"mappings":";;;AAoBA;;GAEG;AACH,+CAAuC;AAEvC,MAAa,eAAe;IAC1B,YAAY,IAAgB;QAC1B,IAAI,WAAW,GAA8B,EAAE,CAAA;QAC/C,IAAI,CAAC,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAA,EAAE,CAAC;YACpB,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;gBACrC,WAAW,CAAC,OAAO,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAC7C,CAAC;iBAAM,IAAI,IAAI,CAAC,OAAO,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;gBACnF,WAAW,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;YACpC,CAAC;iBAAM,CAAC;gBACN,MAAM,IAAI,KAAK,CAAC,6BAA6B,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC,CAAA;YACrE,CAAC;QACH,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,IAAe,EAAE,IAAI,EAAE,WAAW,CAAC,CAAA;IACnD,CAAC;CAsLF;AAnMD,0CAmMC;AACD,WAAiB,eAAe;IAEjB,0BAAU,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,4BAAY,GAAG;QAC1B,OAAO,EAAE,SAAyB;QAClC,cAAc,EAAE,gBAAgC;QAChD,YAAY,EAAE,cAA8B;KAC7C,CAAA;AACH,CAAC,EAjBgB,eAAe,+BAAf,eAAe,QAiB/B","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 { FinancialInstitutionInformation } from './FinancialInstitutionInformation'\nimport { FlatRateTarification } from './FlatRateTarification'\nimport { HealthcarePartyHistoryStatus } from './HealthcarePartyHistoryStatus'\nimport { Identifier } from './Identifier'\nimport { PersonName } from './PersonName'\nimport { PropertyStub } from './PropertyStub'\n\n/**\n * This entity is a root level object. It represents a healthcare party. It is serialized in JSON and saved in the underlying icure-healthdata CouchDB database.\n */\nimport { b64_2ab } from './ModelHelper'\nimport { Patient } from './Patient'\nexport class HealthcareParty {\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 healthcare party. We encourage using either a v4 UUID or a HL7 Id.\n */\n id?: string\n /**\n * the revision of the healthcare party in the database, used for conflict management / optimistic locking.\n */\n rev?: string\n /**\n * creation timestamp of the object.\n */\n created?: number\n /**\n * last modification timestamp of the object.\n */\n modified?: 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 healthcareparty's identifiers, used by the client to identify uniquely and unambiguously the HCP. However, iCure may not guarantee this uniqueness by itself : This should be done at the client side.\n */\n identifier?: Array<Identifier>\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 * The full name of the healthcare party, used mainly when the healthcare party is an organization\n */\n name?: string\n /**\n * the lastname (surname) of the healthcare party. This is the official lastname that should be used for official administrative purposes.\n */\n lastName?: string\n /**\n * the firstname (name) of the healthcare party.\n */\n firstName?: string\n /**\n * the list of all names of the healthcare party, also containing the official full name information. Ordered by preference of use. First element is therefore the official name used for the healthcare party in the application\n */\n names?: Array<PersonName>\n /**\n * the gender of the healthcare party: male, female, indeterminate, changed, changedToMale, changedToFemale, unknown\n */\n gender?: HealthcareParty.GenderEnum\n /**\n * Mr., Ms., Pr., Dr. ...\n */\n civility?: string\n /**\n * The name of the company this healthcare party is member of\n */\n companyName?: string\n /**\n * Medical specialty of the healthcare party\n */\n speciality?: string\n /**\n * Bank Account identifier of the healhtcare party, IBAN, deprecated, use financial institutions instead\n */\n bankAccount?: string\n /**\n * Bank Identifier Code, the SWIFT Address assigned to the bank, use financial institutions instead\n */\n bic?: string\n proxyBankAccount?: string\n proxyBic?: string\n /**\n * All details included in the invoice header\n */\n invoiceHeader?: string\n /**\n * Identifier number for institution type if the healthcare party is an enterprise\n */\n cbe?: string\n /**\n * Identifier number for the institution if the healthcare party is an organization\n */\n ehp?: string\n /**\n * The id of the user that usually handles this healthcare party.\n */\n userId?: string\n /**\n * Id of parent of the user representing the healthcare party.\n */\n parentId?: string\n convention?: number\n /**\n * National Institute for Health and Invalidity Insurance number assigned to healthcare parties (institution or person).\n */\n nihii?: string\n nihiiSpecCode?: string\n /**\n * Social security inscription number.\n */\n ssin?: string\n /**\n * The list of addresses (with address type).\n */\n addresses?: Array<Address>\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 * A picture usually saved in JPEG format.\n */\n picture?: ArrayBuffer\n /**\n * The healthcare party's status: 'trainee' or 'withconvention' or 'accredited'\n */\n statuses?: Array<HealthcareParty.StatusesEnum>\n /**\n * The healthcare party's status history\n */\n statusHistory?: Array<HealthcarePartyHistoryStatus>\n /**\n * Medical specialty of the healthcare party codified using FHIR or Kmehr codificaiton scheme\n */\n specialityCodes?: Array<CodeStub>\n /**\n * The type of format for contacting the healthcare party, ex: mobile, phone, email, etc.\n */\n sendFormats?: { [key: string]: string }\n /**\n * Text notes.\n */\n notes?: string\n /**\n * List of financial information (Bank, bank account).\n */\n financialInstitutionInformation?: Array<FinancialInstitutionInformation>\n /**\n * A description of the HCP, meant for the public and in multiple languages.\n */\n descr?: { [key: string]: string }\n /**\n * The invoicing scheme this healthcare party adheres to : 'service fee' or 'flat rate'\n */\n billingType?: string\n type?: string\n contactPerson?: string\n contactPersonHcpId?: string\n supervisorId?: string\n flatRateTarifications?: Array<FlatRateTarification>\n importedData?: { [key: string]: string }\n options?: { [key: string]: string }\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 that are generates using the OAEP Sha-256 standard\n */\n publicKeysForOaepWithSha256?: Array<string>\n}\nexport namespace HealthcareParty {\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 StatusesEnum = 'trainee' | 'withconvention' | 'accreditated'\n export const StatusesEnum = {\n Trainee: 'trainee' as StatusesEnum,\n Withconvention: 'withconvention' as StatusesEnum,\n Accreditated: 'accreditated' as StatusesEnum,\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"HealthcareParty.js","sourceRoot":"","sources":["../../../icc-api/model/HealthcareParty.ts"],"names":[],"mappings":";;;AAoBA;;GAEG;AACH,+CAAuC;AAEvC,MAAa,eAAe;IAC1B,YAAY,IAAgB;QAC1B,IAAI,WAAW,GAA8B,EAAE,CAAA;QAC/C,IAAI,CAAC,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAA,EAAE,CAAC;YACpB,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;gBACrC,WAAW,CAAC,OAAO,GAAG,IAAA,qBAAO,EAAC,IAAI,CAAC,OAAO,CAAC,CAAA;YAC7C,CAAC;iBAAM,IAAI,IAAI,CAAC,OAAO,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;gBACnF,WAAW,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAA;YACpC,CAAC;iBAAM,CAAC;gBACN,MAAM,IAAI,KAAK,CAAC,6BAA6B,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC,CAAA;YACrE,CAAC;QACH,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,IAAe,EAAE,IAAI,EAAE,WAAW,CAAC,CAAA;IACnD,CAAC;CAuLF;AApMD,0CAoMC;AACD,WAAiB,eAAe;IAEjB,0BAAU,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,4BAAY,GAAG;QAC1B,OAAO,EAAE,SAAyB;QAClC,cAAc,EAAE,gBAAgC;QAChD,YAAY,EAAE,cAA8B;KAC7C,CAAA;AACH,CAAC,EAjBgB,eAAe,+BAAf,eAAe,QAiB/B","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 { FinancialInstitutionInformation } from './FinancialInstitutionInformation'\nimport { FlatRateTarification } from './FlatRateTarification'\nimport { HealthcarePartyHistoryStatus } from './HealthcarePartyHistoryStatus'\nimport { Identifier } from './Identifier'\nimport { PersonName } from './PersonName'\nimport { PropertyStub } from './PropertyStub'\n\n/**\n * This entity is a root level object. It represents a healthcare party. It is serialized in JSON and saved in the underlying icure-healthdata CouchDB database.\n */\nimport { b64_2ab } from './ModelHelper'\nimport { Patient } from './Patient'\nexport class HealthcareParty {\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 healthcare party. We encourage using either a v4 UUID or a HL7 Id.\n */\n id?: string\n /**\n * the revision of the healthcare party in the database, used for conflict management / optimistic locking.\n */\n rev?: string\n /**\n * creation timestamp of the object.\n */\n created?: number\n /**\n * last modification timestamp of the object.\n */\n modified?: 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 healthcareparty's identifiers, used by the client to identify uniquely and unambiguously the HCP. However, iCure may not guarantee this uniqueness by itself : This should be done at the client side.\n */\n identifier?: Array<Identifier>\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 * The full name of the healthcare party, used mainly when the healthcare party is an organization\n */\n name?: string\n /**\n * the lastname (surname) of the healthcare party. This is the official lastname that should be used for official administrative purposes.\n */\n lastName?: string\n /**\n * the firstname (name) of the healthcare party.\n */\n firstName?: string\n /**\n * the list of all names of the healthcare party, also containing the official full name information. Ordered by preference of use. First element is therefore the official name used for the healthcare party in the application\n */\n names?: Array<PersonName>\n /**\n * the gender of the healthcare party: male, female, indeterminate, changed, changedToMale, changedToFemale, unknown\n */\n gender?: HealthcareParty.GenderEnum\n /**\n * Mr., Ms., Pr., Dr. ...\n */\n civility?: string\n /**\n * The name of the company this healthcare party is member of\n */\n companyName?: string\n /**\n * Medical specialty of the healthcare party\n */\n speciality?: string\n /**\n * Bank Account identifier of the healhtcare party, IBAN, deprecated, use financial institutions instead\n */\n bankAccount?: string\n /**\n * Bank Identifier Code, the SWIFT Address assigned to the bank, use financial institutions instead\n */\n bic?: string\n proxyBankAccount?: string\n proxyBic?: string\n /**\n * All details included in the invoice header\n */\n invoiceHeader?: string\n /**\n * Identifier number for institution type if the healthcare party is an enterprise\n */\n cbe?: string\n /**\n * Identifier number for the institution if the healthcare party is an organization\n */\n ehp?: string\n /**\n * The id of the user that usually handles this healthcare party.\n */\n userId?: string\n /**\n * Id of parent of the user representing the healthcare party.\n */\n parentId?: string\n convention?: number\n /**\n * National Institute for Health and Invalidity Insurance number assigned to healthcare parties (institution or person).\n */\n nihii?: string\n nihiiSpecCode?: string\n /**\n * Social security inscription number.\n */\n ssin?: string\n /**\n * The list of addresses (with address type).\n */\n addresses?: Array<Address>\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 * A picture usually saved in JPEG format.\n */\n picture?: ArrayBuffer\n /**\n * The healthcare party's status: 'trainee' or 'withconvention' or 'accredited'\n */\n statuses?: Array<HealthcareParty.StatusesEnum>\n /**\n * The healthcare party's status history\n */\n statusHistory?: Array<HealthcarePartyHistoryStatus>\n /**\n * Medical specialty of the healthcare party codified using FHIR or Kmehr codificaiton scheme\n */\n specialityCodes?: Array<CodeStub>\n /**\n * The type of format for contacting the healthcare party, ex: mobile, phone, email, etc.\n */\n sendFormats?: { [key: string]: string }\n /**\n * Text notes.\n */\n notes?: string\n /**\n * List of financial information (Bank, bank account).\n */\n financialInstitutionInformation?: Array<FinancialInstitutionInformation>\n /**\n * A description of the HCP, meant for the public and in multiple languages.\n */\n descr?: { [key: string]: string }\n /**\n * The invoicing scheme this healthcare party adheres to : 'service fee' or 'flat rate'\n */\n billingType?: string\n type?: string\n contactPerson?: string\n contactPersonHcpId?: string\n supervisorId?: string\n flatRateTarifications?: Array<FlatRateTarification>\n importedData?: { [key: string]: string }\n options?: { [key: string]: string }\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 that are generates using the OAEP Sha-256 standard\n */\n publicKeysForOaepWithSha256?: Array<string>\n cryptoActorProperties?: Array<PropertyStub>\n}\nexport namespace HealthcareParty {\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 StatusesEnum = 'trainee' | 'withconvention' | 'accreditated'\n export const StatusesEnum = {\n Trainee: 'trainee' as StatusesEnum,\n Withconvention: 'withconvention' as StatusesEnum,\n Accreditated: 'accreditated' as StatusesEnum,\n }\n}\n"]}
|
|
@@ -332,6 +332,7 @@ export declare class Patient {
|
|
|
332
332
|
employementInfos?: Array<EmploymentInfo>;
|
|
333
333
|
securityMetadata?: SecurityMetadata;
|
|
334
334
|
parentId?: never;
|
|
335
|
+
cryptoActorProperties?: Array<PropertyStub>;
|
|
335
336
|
}
|
|
336
337
|
export declare namespace Patient {
|
|
337
338
|
type GenderEnum = 'male' | 'female' | 'indeterminate' | 'changed' | 'changedToMale' | 'changedToFemale' | 'unknown';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Patient.js","sourceRoot":"","sources":["../../../icc-api/model/Patient.ts"],"names":[],"mappings":";;;AA0BA;;GAEG;AACH,+CAAyD;AAGzD,MAAa,OAAO;IAClB,YAAY,IAAgB;QAC1B,IAAI,WAAW,GAA8B,EAAE,CAAA;QAC/C,IAAI,CAAC,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAA,EAAE,CAAC;YACpB,WAAW,CAAC,OAAO,GAAG,IAAA,uCAAyB,EAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/D,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,IAAe,EAAE,IAAI,EAAE,WAAW,CAAC,CAAA;IACnD,CAAC;CA8RF;AArSD,0BAqSC;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,aAAa,EAAE,gBAA0C;QACzD,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,EA/DgB,OAAO,uBAAP,OAAO,QA+DvB","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 { decodeStringOrArrayBuffer } from './ModelHelper'\nimport { SecurityMetadata } from './SecurityMetadata'\n\nexport class Patient {\n constructor(json: JSON | any) {\n let pictureData: { picture?: ArrayBuffer } = {}\n if (!!json?.picture) {\n pictureData.picture = decodeStringOrArrayBuffer(json.picture)\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 that are generates using the OAEP Sha-256 standard\n */\n publicKeysForOaepWithSha256?: 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 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 securityMetadata?: SecurityMetadata\n parentId?: never\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' | 'left_structure' | '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 LeftStructure: 'left_structure' 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,+CAAyD;AAGzD,MAAa,OAAO;IAClB,YAAY,IAAgB;QAC1B,IAAI,WAAW,GAA8B,EAAE,CAAA;QAC/C,IAAI,CAAC,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAA,EAAE,CAAC;YACpB,WAAW,CAAC,OAAO,GAAG,IAAA,uCAAyB,EAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC/D,CAAC;QACD,MAAM,CAAC,MAAM,CAAC,IAAe,EAAE,IAAI,EAAE,WAAW,CAAC,CAAA;IACnD,CAAC;CA+RF;AAtSD,0BAsSC;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,aAAa,EAAE,gBAA0C;QACzD,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,EA/DgB,OAAO,uBAAP,OAAO,QA+DvB","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 { decodeStringOrArrayBuffer } from './ModelHelper'\nimport { SecurityMetadata } from './SecurityMetadata'\n\nexport class Patient {\n constructor(json: JSON | any) {\n let pictureData: { picture?: ArrayBuffer } = {}\n if (!!json?.picture) {\n pictureData.picture = decodeStringOrArrayBuffer(json.picture)\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 that are generates using the OAEP Sha-256 standard\n */\n publicKeysForOaepWithSha256?: 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 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 securityMetadata?: SecurityMetadata\n parentId?: never\n cryptoActorProperties?: Array<PropertyStub>\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' | 'left_structure' | '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 LeftStructure: 'left_structure' 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"]}
|
|
@@ -29,7 +29,8 @@ export interface CryptoStrategies {
|
|
|
29
29
|
* (partially or completely) with `unknownKeys`.
|
|
30
30
|
*
|
|
31
31
|
* The returned value must be an object associating to each data owner id an object with:
|
|
32
|
-
* - `recoveredKeys`: all recovered keys
|
|
32
|
+
* - `recoveredKeys`: all recovered keys, by fingerprint. Will be automatically considered as authentic/trusted unless explicitly marked as unverified in
|
|
33
|
+
* the `keyAuthenticity` object.
|
|
33
34
|
* - `keyAuthenticity`: an object associating to each public key fingerprint its authenticity. Note that if any of the keys from `unknownKeys` is
|
|
34
35
|
* completely missing from this object the key will be considered as unverified in this api instance (same as if associated to false), but this
|
|
35
36
|
* value won't be cached (will be again part of `unknownKeys` in future instances.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CryptoStrategies.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoStrategies.ts"],"names":[],"mappings":"","sourcesContent":["import { KeyPair } from './RSA'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\n/**\n * Allows to customise the behaviour of the crypto api to set keys management, keys recovery, keys trusting in a way that better suits your needs.\n */\nexport interface CryptoStrategies {\n /**\n *\n * The iCure API has an internal mechanism to store private keys. This API stores the private keys in the storage facade you have provided.\n * In a browser, you typically use the LocalStorageFacade, which stores the keys in the browser's local storage.\n *\n * Method called during initialisation of the crypto API to validate keys recovered through iCure's recovery methods and/or to allow recovery of\n * missing keys using means external to iCure.\n * On startup the iCure sdk will try to load all keys for the current data owner and its parent hierarchy: if the sdk can't find some of the keys\n * for any of the data owners (according to the public keys for the data owner in the iCure server) and/or the sdk could recover some private keys\n * but can't verify the authenticity of the key pairs this method will be called.\n * The recovered and verified keys will automatically be cached using the current api {@link KeyStorageFacade} and {@link StorageFacade}\n *\n * The input is an array containing an object for each data owner part of the current data owner hierarchy. The objects are ordered from the data\n * for the topmost parent of the current data owner hierarchy (first element) to the data for the current data owner (last element). Each object\n * contains:\n * - dataOwner: the data owner entity that this object refers to\n * - unknownKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the authenticity status (verified or unverified) is unknown\n * (no result was cached from a previous api instantiation and the key was not generated on the current device).\n * - unavailableKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the sdk could not recover a private key. May overlap\n * (partially or completely) with `unknownKeys`.\n *\n * The returned value must be an object associating to each data owner id an object with:\n * - `recoveredKeys`: all recovered keys
|
|
1
|
+
{"version":3,"file":"CryptoStrategies.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoStrategies.ts"],"names":[],"mappings":"","sourcesContent":["import { KeyPair } from './RSA'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\n/**\n * Allows to customise the behaviour of the crypto api to set keys management, keys recovery, keys trusting in a way that better suits your needs.\n */\nexport interface CryptoStrategies {\n /**\n *\n * The iCure API has an internal mechanism to store private keys. This API stores the private keys in the storage facade you have provided.\n * In a browser, you typically use the LocalStorageFacade, which stores the keys in the browser's local storage.\n *\n * Method called during initialisation of the crypto API to validate keys recovered through iCure's recovery methods and/or to allow recovery of\n * missing keys using means external to iCure.\n * On startup the iCure sdk will try to load all keys for the current data owner and its parent hierarchy: if the sdk can't find some of the keys\n * for any of the data owners (according to the public keys for the data owner in the iCure server) and/or the sdk could recover some private keys\n * but can't verify the authenticity of the key pairs this method will be called.\n * The recovered and verified keys will automatically be cached using the current api {@link KeyStorageFacade} and {@link StorageFacade}\n *\n * The input is an array containing an object for each data owner part of the current data owner hierarchy. The objects are ordered from the data\n * for the topmost parent of the current data owner hierarchy (first element) to the data for the current data owner (last element). Each object\n * contains:\n * - dataOwner: the data owner entity that this object refers to\n * - unknownKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the authenticity status (verified or unverified) is unknown\n * (no result was cached from a previous api instantiation and the key was not generated on the current device).\n * - unavailableKeys: all public keys (in hex-encoded spki format) of `dataOwner` for which the sdk could not recover a private key. May overlap\n * (partially or completely) with `unknownKeys`.\n *\n * The returned value must be an object associating to each data owner id an object with:\n * - `recoveredKeys`: all recovered keys, by fingerprint. Will be automatically considered as authentic/trusted unless explicitly marked as unverified in\n * the `keyAuthenticity` object.\n * - `keyAuthenticity`: an object associating to each public key fingerprint its authenticity. Note that if any of the keys from `unknownKeys` is\n * completely missing from this object the key will be considered as unverified in this api instance (same as if associated to false), but this\n * value won't be cached (will be again part of `unknownKeys` in future instances.\n * @param keysData all information on unknown and unavailable keys for each data owner part of the current data owner hierarchy.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @param keyPairRecoverer a key pair recoverer.\n * @return all recovered keys and key authenticity information, by data owner.\n */\n recoverAndVerifySelfHierarchyKeys(\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[],\n cryptoPrimitives: CryptoPrimitives,\n keyPairRecoverer: KeyPairRecoverer\n ): Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }>\n\n /**\n * The correct initialisation of the crypto API requires that at least 1 verified (or device) key pair is available for each data owner part of the\n * current data owner hierarchy. If no verified key is available for any of the data owner parents the api initialisation will automatically fail,\n * however if there is no verified key for the current data owner you can instead create a new crypto key.\n * @param self the current data owner.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @return depending on which values you return the api initialisation will proceed differently:\n * - If this method returns true a new key will be automatically generated by the sdk.\n * - If this method returns a key pair the crypto api loads the key pair and considers it as a device key.\n * - If this method returns false the initialisation will fail with a predefined error.\n * - If this method throws an error the initialisation will propagate the error.\n * - If this method return the string \"keyless\" the api will be initialized in keyless mode.\n */\n generateNewKeyForDataOwner(self: DataOwnerWithType, cryptoPrimitives: CryptoPrimitives): Promise<KeyPair<CryptoKey> | boolean | 'keyless'>\n\n /**\n * Verifies if the public keys of a data owner which will be the delegate of a new exchange key do actually belong to the person the data owner\n * represents. This method is not called when the delegate would be the current data owner for the api.\n *\n * The user will have to obtain the verified public keys of the delegate from outside iCure, for example by email with another hcp, by checking the\n * personal website of the other user, or by scanning verification qr codes at the doctor office...\n *\n * As long as one of the public keys is verified the creation of a new exchange key will succeed. If no public key is verified the operation will\n * fail.\n * @param delegate the potential data owner delegate.\n * @param publicKeys public keys requiring verification, in spki hex-encoded format.\n * @param cryptoPrimitives cryptographic primitives you can use to support the process.\n * @return all verified public keys, in spki hex-encoded format.\n */\n verifyDelegatePublicKeys(delegate: CryptoActorStubWithType, publicKeys: string[], cryptoPrimitives: CryptoPrimitives): Promise<string[]>\n\n /**\n * Specifies if a data owner requires anonymous delegations, i.e. his id should not appear unencrypted in new secure delegations. This should always\n * be the case for patient data owners.\n * @param dataOwner a data owner.\n * @return true if the delegations for the provided data owner should be anonymous.\n */\n dataOwnerRequiresAnonymousDelegation(dataOwner: CryptoActorStubWithType): boolean\n}\n"]}
|
|
@@ -238,9 +238,9 @@ class UserEncryptionKeysManager {
|
|
|
238
238
|
const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id].recoveredKeys);
|
|
239
239
|
for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {
|
|
240
240
|
const jwkPair = yield this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk');
|
|
241
|
-
yield this.icureStorage.saveKey(keyData.dowt.dataOwner.id, fp, jwkPair, true);
|
|
241
|
+
yield this.icureStorage.saveKey(keyData.dowt.dataOwner.id, fp, jwkPair, currAuthenticity[fp] != undefined ? currAuthenticity[fp] : true);
|
|
242
242
|
}
|
|
243
|
-
const updatedVerifiedMap = yield this.icureStorage.saveSelfVerifiedKeys(keyData.dowt.dataOwner.id, [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce((acc, currFp) => (Object.assign(Object.assign({}, acc), { [currFp]: currFp
|
|
243
|
+
const updatedVerifiedMap = yield this.icureStorage.saveSelfVerifiedKeys(keyData.dowt.dataOwner.id, [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce((acc, currFp) => (Object.assign(Object.assign({}, acc), { [currFp]: currAuthenticity[currFp] != undefined ? currAuthenticity[currFp] : currFp in currExternallyRecovered ? true : undefined })), {}));
|
|
244
244
|
const keysWithExternallyRecovered = Object.assign(Object.assign({}, keyData.availableKeys), Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])));
|
|
245
245
|
let parentKeysForRecovery = {};
|
|
246
246
|
for (let j = 0; j < i; j++) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserEncryptionKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/UserEncryptionKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+BAA2C;AAC3C,oCAAiC;AAEjC,mCAAuC;AAKvC,yEAA8F;AAgB9F,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAG,CAAC,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE,eAAe,EAAE,EAAE,EAAE,IAAG,EAC3G,EAKC,CACF,CACF,CAAA;AAGH;;GAEG;AACH,MAAa,yBAAyB;IAKpC,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,YAAgC,EAChC,WAAwB,EACxB,UAA4B,EAC5B,oBAA6B,EAC7B,gBAAkC,EAClC,eAAwB;QAPxB,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,iBAAY,GAAZ,YAAY,CAAoB;QAChC,gBAAW,GAAX,WAAW,CAAa;QACxB,eAAU,GAAV,UAAU,CAAkB;QAC5B,yBAAoB,GAApB,oBAAoB,CAAS;QAC7B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,oBAAe,GAAf,eAAe,CAAS;QAVnC,cAAS,GAA2F,S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BAAmB,CAAC,SAAS,CAAC,CAAC,MAAM;gBAC7G,CAAC,sBAAsB,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAC5E,CAAC;gBACD,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,SAAS,EAAE,IAAI,CAAC,sBAAsB,iCAAM,UAAU,GAAK,aAAa,EAAG,CAAC,CAAA;gBACjI,KAAK,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC;oBACvD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAA;gBAC5C,CAAC;YACH,CAAC;YACD,OAAO,UAAU,CAAA;QACnB,CAAC;KAAA;IAEO,qBAAqB,CAAI,GAAyC;QACxE,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAA,qBAAa,EAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;IACvF,CAAC;IAEO,cAAc,CAAC,QAAuC;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAA;IACxE,CAAC;CACF;AA7bD,8DA6bC","sourcesContent":["import { DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { KeyPair, ShaVersion } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { fingerprintV1 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean | 'keyless'>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class UserEncryptionKeysManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean,\n private readonly keypairRecoverer: KeyPairRecoverer,\n private readonly selfIsAnonymous: boolean\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives, this.keypairRecoverer),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey && fingerprintV1(this.selfLegacyPublicKey)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwnerOrStub): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner),\n ]).filter((key) => {\n const fp = fingerprintV1(key)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = (await this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {\n if (dataOwner.publicKey == '') {\n if (Object.entries(dataOwner.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${dataOwner.id} has \"\" as public key but has non-empty hcPartyKeys`)\n delete dataOwner.publicKey\n }\n return {\n dataOwner,\n type,\n } as DataOwnerWithType\n })\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n const toInit = this.initialiseParentKeys ? hierarchy : [self]\n for (let i = 0; i < toInit.length; i++) {\n const dowt = toInit[i]\n let parentKeysForRecovery: { [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } } = {}\n for (let j = 0; j < i; j++) {\n parentKeysForRecovery = {\n ...keysData[j].availableKeys,\n ...parentKeysForRecovery,\n }\n }\n const availableKeys = await this.loadAndRecoverKeysFor(dowt, parentKeysForRecovery)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = new Set([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dowt.dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dowt.dataOwner),\n ])\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(fingerprintV1(key)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(fingerprintV1(x) in verifiedKeysMap) && !(availableKeys?.[fingerprintV1(x)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (let i = 0; i < keysData.length; i++) {\n const keyData = keysData[i]\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currFp in currExternallyRecovered || currAuthenticity[currFp],\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n let parentKeysForRecovery: { [p: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } } = {}\n for (let j = 0; j < i; j++) {\n parentKeysForRecovery = {\n ...keysCache[keysData[j].dowt.dataOwner.id!],\n ...parentKeysForRecovery,\n }\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(\n keyData.dowt,\n this.plainKeysByFingerprint({\n ...keysWithExternallyRecovered,\n ...parentKeysForRecovery,\n })\n )\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else if (typeof whatToDo == 'string' && whatToDo == 'keyless') {\n /*\n * Currently non-anonymous data owners aren't allowed to use keyless mode.\n * Today the delegator is not emitted in views and is not used for access control: an entity without delegation\n * self->self but only a delegation self->other would not be searchable by nor accessible to an explicit data\n * owner.\n * This is not a problem for anonymous data owner, since search and access control use the secure delegation\n * key.\n * Since keyless api was designed for use by patients this is not an issue at the time, but if in future we need\n * to support keyless api for explicit data owner before updating views we can add stubs to legacy delegations.\n */\n if (!this.selfIsAnonymous) throw new Error('Keyless api mode is available only for anonymous data owners.')\n this.keysCache = keysCache\n return undefined\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair(ShaVersion.Sha256))\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const jwKey = await this.primitives.RSA.exportKey(keyPair.publicKey, 'jwk')\n if (jwKey.alg !== 'RSA-OAEP-256') {\n throw new Error('Only keys generated with SHA-256 are currently supported')\n }\n const publicKeyFingerprint = fingerprintV1(publicKeyHex)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const updatedSelf = await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...CryptoActorStub.fromDataOwner(selfDataOwner.dataOwner),\n publicKeysForOaepWithSha256: [...(selfDataOwner.dataOwner.publicKeysForOaepWithSha256 ?? []), publicKeyHex],\n },\n type: selfDataOwner.type,\n })\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: { [key: string]: string[] }\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprintsWithVersion = Object.entries(pubKeysFingerprints).flatMap(([shaVersion, fps]) => {\n return fps.map((fp) => [shaVersion, fp] as [ShaVersion, string])\n })\n return await pubKeysFingerprintsWithVersion.reduce(async (acc, [shaVersion, currentFingerprint]) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (!!storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair(\n 'jwk',\n storedKeypair.pair.privateKey,\n 'jwk',\n storedKeypair.pair.publicKey,\n shaVersion\n )\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(\n dataOwner: DataOwnerWithType,\n ancestorsKeys: { [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }\n ): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprints = {\n 'sha-1': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n 'sha-256': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n }\n const loadedKeys =\n pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (\n loadedKeysFingerprints.length !== pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length &&\n (loadedKeysFingerprints.length > 0 || Object.keys(ancestorsKeys).length > 0)\n ) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint({ ...loadedKeys, ...ancestorsKeys }))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [fingerprintV1(k), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"UserEncryptionKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/UserEncryptionKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+BAA2C;AAC3C,oCAAiC;AAEjC,mCAAuC;AAKvC,yEAA8F;AAgB9F,MAAM,8BAA8B,GAA4B,CAAC,CAAC,EAAE,EAAE,CACpE,OAAO,CAAC,OAAO,CACb,CAAC,CAAC,MAAM,CACN,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,CAAC,iCAAM,GAAG,KAAE,CAAC,SAAS,CAAC,SAAS,CAAC,EAAG,CAAC,EAAE,EAAE,aAAa,EAAE,EAAE,EAAE,eAAe,EAAE,EAAE,EAAE,IAAG,EAC3G,EAKC,CACF,CACF,CAAA;AAGH;;GAEG;AACH,MAAa,yBAAyB;IAKpC,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,YAAgC,EAChC,WAAwB,EACxB,UAA4B,EAC5B,oBAA6B,EAC7B,gBAAkC,EAClC,eAAwB;QAPxB,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,iBAAY,GAAZ,YAAY,CAAoB;QAChC,gBAAW,GAAX,WAAW,CAAa;QACxB,eAAU,GAAV,UAAU,CAAkB;QAC5B,yBAAoB,GAApB,oBAAoB,CAAS;QAC7B,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,oBAAe,GAAf,eAAe,CAAS;QAVnC,cAAS,GAA2F,SAAS,CAAA;IAWlH,CAAC;IAEJ;;;;;;;OAOG;IACG,wCAAwC;;YAU5C,IAAI,CAAC,iBAAiB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ShaVersion } from './RSA'\nimport { ua2hex } from '../utils'\nimport { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { fingerprintV1 } from './utils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyRecovery } from './KeyRecovery'\nimport { CryptoStrategies } from './CryptoStrategies'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { KeyPairRecoverer } from './KeyPairRecoverer'\n\ntype KeyPairData = { pair: KeyPair<CryptoKey>; isVerified: boolean; isDevice: boolean }\ntype KeyRecovererAndVerifier = (\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[]\n) => Promise<{\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n}>\nconst nothingKeyRecovererAndVerifier: KeyRecovererAndVerifier = (x) =>\n Promise.resolve(\n x.reduce(\n (acc, { dataOwner }) => ({ ...acc, [dataOwner.dataOwner.id!]: { recoveredKeys: {}, keyAuthenticity: {} } }),\n {} as {\n [dataOwnerId: string]: {\n recoveredKeys: { [keyPairFingerprint: string]: KeyPair<CryptoKey> }\n keyAuthenticity: { [keyPairFingerprint: string]: boolean }\n }\n }\n )\n )\ntype CurrentOwnerKeyGenerator = (self: DataOwnerWithType) => Promise<KeyPair<CryptoKey> | boolean | 'keyless'>\n\n/**\n * Allows to manage public and private keys for the current user and his parent hierarchy.\n */\nexport class UserEncryptionKeysManager {\n private selfId: string | undefined\n private selfLegacyPublicKey: string | undefined\n private keysCache: { [selfOrParentId: string]: { [pubKeyFingerprint: string]: KeyPairData } } | undefined = undefined\n\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly icureStorage: IcureStorageFacade,\n private readonly keyRecovery: KeyRecovery,\n private readonly strategies: CryptoStrategies,\n private readonly initialiseParentKeys: boolean,\n private readonly keypairRecoverer: KeyPairRecoverer,\n private readonly selfIsAnonymous: boolean\n ) {}\n\n /**\n * @internal\n * Get all key pairs available for the current data owner and his parents.\n * @return an object with:\n * - `self` an object containing the current data owner id and the list of key pairs available for the current data owner with verification details.\n * - `parents` the list of parents to the current data owner with the list of key pairs available for each parent. The list is ordered from the\n * topmost ancestor (at index 0) to the direct parent of the current data owner (at the last index, may be 0).\n */\n async getCurrentUserHierarchyAvailableKeypairs(): Promise<{\n self: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }\n parents: {\n dataOwnerId: string\n keys: { pair: KeyPair<CryptoKey>; verified: boolean }[]\n }[]\n }> {\n this.ensureInitialised()\n const hierarchy = await this.dataOwnerApi.getCurrentDataOwnerHierarchyIds()\n const selfId = hierarchy[hierarchy.length - 1]\n const selfKeys = Object.values(this.keysCache![selfId]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice }))\n const remainingHierarchy = hierarchy.slice(0, hierarchy.length - 1)\n return {\n self: {\n dataOwnerId: selfId,\n keys: selfKeys,\n },\n parents: remainingHierarchy.map((x) => ({\n dataOwnerId: x,\n keys: Object.values(this.keysCache![x]).map(({ pair, isVerified, isDevice }) => ({ pair, verified: isVerified || isDevice })),\n })),\n }\n }\n\n /**\n * Get the public keys of available key pairs for the current user in hex-encoded spki representation (uses cached keys: no request is done to the\n * server).\n * By setting {@link verifiedOnly} to true only the public keys for verified key pairs will be returned: these will include only key pairs created\n * on this device or which have been verified using {@link CryptoStrategies} on this device.\n * @param verifiedOnly if true only the verified public keys will be returned.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserAvailablePublicKeysHex(verifiedOnly: boolean): Promise<string[]> {\n this.ensureInitialised()\n let selectedData = Object.values(this.keysCache![this.selfId!])\n if (verifiedOnly) {\n selectedData = selectedData.filter((data) => data.isVerified || data.isDevice)\n }\n return await Promise.all(selectedData.map(async (keyData) => ua2hex(await this.primitives.RSA.exportKey(keyData.pair.publicKey, 'spki'))))\n }\n\n /**\n * Get the public keys of available key pairs for the current user and his parents in hex-encoded spki representation (uses cached keys: no request\n * is done to the server).\n * Note that this will also include unverified keys.\n * @return the spki representation of public keys of available keypairs for the current user.\n */\n async getCurrentUserHierarchyAvailablePublicKeysHex(): Promise<string[]> {\n return await Promise.all(\n Object.values(this.keysCache!)\n .flatMap((pairsForParent) => Object.values(pairsForParent))\n .map(async (keyPairData) => ua2hex(await this.primitives.RSA.exportKey(keyPairData.pair.publicKey, 'spki')))\n )\n }\n\n /**\n * Get a key pair with the provided fingerprint if present.\n * @param fingerprint a key-pair/public-key fingerprint\n * @return the pair associated to the fingerprint and a boolean indicating if the pair is verified, if present, else undefined\n */\n getKeyPairForFingerprint(fingerprint: string): { pair: KeyPair<CryptoKey>; verified: boolean } | undefined {\n const foundVerified = this.getSelfVerifiedKeys().find((x) => x.fingerprint === fingerprint)\n if (foundVerified) return { pair: foundVerified.pair, verified: true }\n const foundOther = this.getDecryptionKeys()[fingerprint]\n if (foundOther) return { pair: foundOther, verified: false }\n return undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Initializes all keys for the current data owner. This method needs to be called before any other method of this class can be used.\n * @throws if the current user is not a data owner, or if there is no key and no new key could be created according to this manager crypt\n * strategies.\n * @return if a new key was created during initialisation the newly created key, else undefined.\n */\n async initialiseKeys(): Promise<{ newKeyPair: KeyPair<CryptoKey>; newKeyFingerprint: string } | undefined> {\n const newKey = await this.doLoadKeys(\n (x) => this.strategies.recoverAndVerifySelfHierarchyKeys(x, this.primitives, this.keypairRecoverer),\n (x) => this.strategies.generateNewKeyForDataOwner(x, this.primitives)\n )\n return newKey ? { newKeyPair: newKey.pair, newKeyFingerprint: newKey.fingerprint } : undefined\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Forces to reload keys for the current data owner. This could be useful if the data owner has logged in from another device in order to update the\n * transfer keys.\n * This method will complete only after keys have been reloaded successfully.\n */\n async reloadKeys(): Promise<void> {\n await this.doLoadKeys(nothingKeyRecovererAndVerifier, (x) => {\n throw new Error(\"Can't create new keys at reload time: it should have already been created on initialisation\")\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all verified key pairs for the current data owner which can safely be used for encryption. This includes all key pairs created on the current\n * device and all recovered key pairs which have been verified.\n * The keys returned by this method will be in the following order:\n * 1. Legacy key pair if it is verified\n * 2. All device key pais, in alphabetical order according to the fingerprint\n * 3. Other verified key pairs, in alphabetical order according to the fingerprint\n * @return all verified keys, in order.\n */\n getSelfVerifiedKeys(): { fingerprint: string; pair: KeyPair<CryptoKey> }[] {\n this.ensureInitialised()\n const selfKeys = this.keysCache![this.selfId!]\n const allKeysEntries = Object.entries(selfKeys)\n\n const legacyKeyFp = this.selfLegacyPublicKey && fingerprintV1(this.selfLegacyPublicKey)\n const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined\n const legacyEntry = legacyKeyData?.isVerified && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : []\n\n function filteredEntries(filterFunction: (fp: string, data: KeyPairData) => boolean) {\n return allKeysEntries\n .filter(([fp, data]) => filterFunction(fp, data) && fp !== legacyKeyFp)\n .sort(([a], [b]) => {\n // need to make sure that the comparison is independent of the locale, but the actual ordering is not that important\n return a == b ? 0 : a > b ? 1 : -1\n })\n .map(([fingerprint, { pair }]) => ({ fingerprint, pair }))\n }\n return [...legacyEntry, ...filteredEntries((_, data) => data.isDevice), ...filteredEntries((_, data) => !data.isDevice && data.isVerified)]\n }\n\n /**\n * Get all verified keys for a member of the current data owner hierarchy in no particular order.\n * @param dataOwner the current data owner or a member of his hierarchy.\n * @throws if the provided data owner is not part of the current data owner hierarchy\n */\n async getVerifiedPublicKeysFor(dataOwner: DataOwnerOrStub): Promise<string[]> {\n this.ensureInitialised()\n const availableKeys = this.keysCache![dataOwner.id!]\n if (!availableKeys) throw new Error(`Data owner ${dataOwner.id} is not part of the hierarchy of the current data owner ${this.selfId}`)\n const availableVerifiedKeysFp = new Set(Object.entries(availableKeys).flatMap(([fp, info]) => (info.isVerified || info.isDevice ? [fp] : [])))\n const otherVerifiedFp = new Set(\n Object.entries(await this.icureStorage.loadSelfVerifiedKeys(dataOwner.id!)).flatMap(([fp, verified]) => (verified ? [fp] : []))\n )\n return Array.from([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner),\n ]).filter((key) => {\n const fp = fingerprintV1(key)\n return availableVerifiedKeysFp.has(fp) || otherVerifiedFp.has(fp)\n })\n }\n\n /**\n * @internal This method is intended for internal use only and may be changed without notice.\n * Get all key pairs for the current data owner and his parents. These keys should be used only for decryption as they may have not been verified.\n * @return all key pairs available for decryption.\n */\n getDecryptionKeys(): { [fingerprint: string]: KeyPair<CryptoKey> } {\n this.ensureInitialised()\n return Object.values(this.keysCache!).reduce((acc, curr) => {\n return {\n ...acc,\n ...this.plainKeysByFingerprint(curr),\n }\n }, {} as { [fp: string]: KeyPair<CryptoKey> })\n }\n\n private async doLoadKeys(\n keyRecovererAndVerifier: KeyRecovererAndVerifier,\n currentOwnerKeyGenerator: CurrentOwnerKeyGenerator\n ): Promise<{ pair: KeyPair<CryptoKey>; fingerprint: string } | undefined> {\n // Load all keys for self from key store\n const hierarchy = (await this.dataOwnerApi.getCurrentDataOwnerHierarchy()).map(({ dataOwner, type }) => {\n if (dataOwner.publicKey == '') {\n if (Object.entries(dataOwner.hcPartyKeys ?? {}).length > 0)\n throw new Error(`Data owner ${dataOwner.id} has \"\" as public key but has non-empty hcPartyKeys`)\n delete dataOwner.publicKey\n }\n return {\n dataOwner,\n type,\n } as DataOwnerWithType\n })\n const self = hierarchy[hierarchy.length - 1]\n this.selfId = self.dataOwner.id!\n const keysData = []\n const toInit = this.initialiseParentKeys ? hierarchy : [self]\n for (let i = 0; i < toInit.length; i++) {\n const dowt = toInit[i]\n let parentKeysForRecovery: { [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } } = {}\n for (let j = 0; j < i; j++) {\n parentKeysForRecovery = {\n ...keysData[j].availableKeys,\n ...parentKeysForRecovery,\n }\n }\n const availableKeys = await this.loadAndRecoverKeysFor(dowt, parentKeysForRecovery)\n const availableKeysFpSet = new Set(Object.keys(availableKeys))\n const verifiedKeysMap = await this.icureStorage.loadSelfVerifiedKeys(dowt.dataOwner.id!)\n const allPublicKeys = new Set([\n ...this.dataOwnerApi.getHexPublicKeysWithSha1Of(dowt.dataOwner),\n ...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dowt.dataOwner),\n ])\n const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {\n return availableKeysFpSet.has(fingerprintV1(key)) ? [] : [key]\n })\n const unknownKeys = Array.from(allPublicKeys).filter(\n (x) => !(fingerprintV1(x) in verifiedKeysMap) && !(availableKeys?.[fingerprintV1(x)]?.isDevice === true)\n )\n keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys })\n }\n const recoveryInfo = keysData.map(({ dowt, unavailableKeys, unknownKeys }) => ({ dataOwner: dowt, unavailableKeys, unknownKeys }))\n const recoveryAndVerificationResult = recoveryInfo.some((x) => x.unavailableKeys.length > 0 || x.unknownKeys.length > 0)\n ? await keyRecovererAndVerifier(recoveryInfo)\n : await nothingKeyRecovererAndVerifier(recoveryInfo)\n const keysCache: { [dataOwnerId: string]: { [fp: string]: KeyPairData } } = {}\n for (let i = 0; i < keysData.length; i++) {\n const keyData = keysData[i]\n const currAuthenticity = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].keyAuthenticity)\n const currExternallyRecovered = this.ensureFingerprintKeys(recoveryAndVerificationResult[keyData.dowt.dataOwner.id!].recoveredKeys)\n for (const [fp, keyPair] of Object.entries(currExternallyRecovered)) {\n const jwkPair = await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk')\n await this.icureStorage.saveKey(keyData.dowt.dataOwner.id!, fp, jwkPair, currAuthenticity[fp] != undefined ? currAuthenticity[fp] : true)\n }\n const updatedVerifiedMap = await this.icureStorage.saveSelfVerifiedKeys(\n keyData.dowt.dataOwner.id!,\n [...Object.keys(currAuthenticity), ...Object.keys(currExternallyRecovered)].reduce(\n (acc, currFp) => ({\n ...acc,\n [currFp]: currAuthenticity[currFp] != undefined ? currAuthenticity[currFp] : currFp in currExternallyRecovered ? true : undefined,\n }),\n {}\n )\n )\n const keysWithExternallyRecovered = {\n ...keyData.availableKeys,\n ...Object.fromEntries(Object.entries(currExternallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n let parentKeysForRecovery: { [p: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } } = {}\n for (let j = 0; j < i; j++) {\n parentKeysForRecovery = {\n ...keysCache[keysData[j].dowt.dataOwner.id!],\n ...parentKeysForRecovery,\n }\n }\n const additionallyRecovered = await this.recoverAndCacheKeys(\n keyData.dowt,\n this.plainKeysByFingerprint({\n ...keysWithExternallyRecovered,\n ...parentKeysForRecovery,\n })\n )\n const keys = {\n ...keysWithExternallyRecovered,\n ...Object.fromEntries(Object.entries(additionallyRecovered).map(([k, v]) => [k, { pair: v, isDevice: false }])),\n }\n keysCache[keyData.dowt.dataOwner.id!] = this.verifyKeys(keys, updatedVerifiedMap)\n }\n if (Object.entries(keysCache).some(([ownerId, data]) => ownerId !== self.dataOwner.id && !this.hasVerifiedKey(data))) {\n throw new Error('Some parent hcps have no verified keys: impossible to generate locally a new key for a parent.')\n } else if (this.hasVerifiedKey(keysCache[self.dataOwner.id!])) {\n this.keysCache = keysCache\n this.selfLegacyPublicKey = self.dataOwner.publicKey\n return undefined\n } else {\n const whatToDo = await currentOwnerKeyGenerator(self)\n if (whatToDo === false) {\n throw new Error(`No verified key found for ${self.dataOwner.id} and settings do not allow creation of a new key.`)\n } else if (typeof whatToDo == 'string' && whatToDo == 'keyless') {\n /*\n * Currently non-anonymous data owners aren't allowed to use keyless mode.\n * Today the delegator is not emitted in views and is not used for access control: an entity without delegation\n * self->self but only a delegation self->other would not be searchable by nor accessible to an explicit data\n * owner.\n * This is not a problem for anonymous data owner, since search and access control use the secure delegation\n * key.\n * Since keyless api was designed for use by patients this is not an issue at the time, but if in future we need\n * to support keyless api for explicit data owner before updating views we can add stubs to legacy delegations.\n */\n if (!this.selfIsAnonymous) throw new Error('Keyless api mode is available only for anonymous data owners.')\n this.keysCache = keysCache\n return undefined\n } else {\n const updateInfo = await this.createAndSaveNewKeyPair(whatToDo === true ? undefined : whatToDo, self)\n // self may be outdated now\n this.selfLegacyPublicKey = updateInfo.updatedSelf.stub.publicKey\n this.keysCache = {\n ...keysCache,\n [self.dataOwner.id!]: {\n ...keysCache[self.dataOwner.id!],\n [updateInfo.publicKeyFingerprint]: { pair: updateInfo.keyPair, isDevice: true, isVerified: true },\n },\n }\n return { pair: updateInfo.keyPair, fingerprint: updateInfo.publicKeyFingerprint }\n }\n }\n }\n\n private async createAndSaveNewKeyPair(\n importedKeyPair: undefined | KeyPair<CryptoKey>,\n selfDataOwner: DataOwnerWithType\n ): Promise<{ publicKeyFingerprint: string; keyPair: KeyPair<CryptoKey>; updatedSelf: CryptoActorStubWithType }> {\n const keyPair = importedKeyPair ?? (await this.primitives.RSA.generateKeyPair(ShaVersion.Sha256))\n const publicKeyHex = ua2hex(await this.primitives.RSA.exportKey(keyPair.publicKey, 'spki'))\n const jwKey = await this.primitives.RSA.exportKey(keyPair.publicKey, 'jwk')\n if (jwKey.alg !== 'RSA-OAEP-256') {\n throw new Error('Only keys generated with SHA-256 are currently supported')\n }\n const publicKeyFingerprint = fingerprintV1(publicKeyHex)\n await this.icureStorage.saveKey(\n selfDataOwner.dataOwner.id!,\n publicKeyFingerprint,\n await this.primitives.RSA.exportKeys(keyPair, 'jwk', 'jwk'),\n true\n )\n await this.icureStorage.saveSelfVerifiedKeys(selfDataOwner.dataOwner.id!, { [publicKeyFingerprint]: true })\n const updatedSelf = await this.dataOwnerApi.modifyCryptoActorStub({\n stub: {\n ...CryptoActorStub.fromDataOwner(selfDataOwner.dataOwner),\n publicKeysForOaepWithSha256: [...(selfDataOwner.dataOwner.publicKeysForOaepWithSha256 ?? []), publicKeyHex],\n },\n type: selfDataOwner.type,\n })\n return { publicKeyFingerprint, keyPair: keyPair, updatedSelf }\n }\n\n private async loadStoredKeys(\n dataOwner: DataOwnerWithType,\n pubKeysFingerprints: { [key: string]: string[] }\n ): Promise<{ [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprintsWithVersion = Object.entries(pubKeysFingerprints).flatMap(([shaVersion, fps]) => {\n return fps.map((fp) => [shaVersion, fp] as [ShaVersion, string])\n })\n return await pubKeysFingerprintsWithVersion.reduce(async (acc, [shaVersion, currentFingerprint]) => {\n const awaitedAcc = await acc\n let loadedPair: { pair: KeyPair<CryptoKey>; isDevice: boolean } | undefined = undefined\n try {\n const storedKeypair = await this.icureStorage.loadKey(dataOwner.dataOwner.id!, currentFingerprint, dataOwner.dataOwner.publicKey)\n if (!!storedKeypair) {\n const importedKey = await this.primitives.RSA.importKeyPair(\n 'jwk',\n storedKeypair.pair.privateKey,\n 'jwk',\n storedKeypair.pair.publicKey,\n shaVersion\n )\n loadedPair = { pair: importedKey, isDevice: storedKeypair.isDevice }\n }\n } catch (e) {\n console.warn('Error while loading keypair', currentFingerprint, e)\n }\n return loadedPair\n ? {\n ...awaitedAcc,\n [currentFingerprint]: loadedPair,\n }\n : awaitedAcc\n }, Promise.resolve({} as { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }))\n }\n\n private verifyKeys(\n keys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } },\n verifiedKeysMap: { [pubKeyFingerprint: string]: boolean }\n ): { [pubKeyFingerprint: string]: KeyPairData } {\n return Object.fromEntries(\n Object.entries(keys).map(\n ([fp, keyData]) => [fp, { ...keyData, isVerified: keyData.isDevice || verifiedKeysMap?.[fp] === true }] as [string, KeyPairData]\n )\n )\n }\n\n private plainKeysByFingerprint(richKeys: { [pubKeyFingerprint: string]: { pair: KeyPair<CryptoKey> } }): {\n [pubKeyFingerprint: string]: KeyPair<CryptoKey>\n } {\n return Object.fromEntries(Object.entries(richKeys).map(([fp, keyData]) => [fp, keyData.pair]))\n }\n\n private ensureInitialised() {\n if (!this.keysCache) throw new Error('Key manager was not properly initialised')\n }\n\n private async recoverAndCacheKeys(\n dataOwner: DataOwnerWithType,\n availableKeys: { [pubKeyFingerprint: string]: KeyPair<CryptoKey> }\n ): Promise<{ [p: string]: KeyPair<CryptoKey> }> {\n const recoveredKeys = await this.keyRecovery.recoverKeys(dataOwner, availableKeys)\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n await this.icureStorage.saveKey(dataOwner.dataOwner.id!, fp, await this.primitives.RSA.exportKeys(pair, 'jwk', 'jwk'), false)\n }\n return recoveredKeys\n }\n\n private async loadAndRecoverKeysFor(\n dataOwner: DataOwnerWithType,\n ancestorsKeys: { [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }\n ): Promise<{ [keyFp: string]: { pair: KeyPair<CryptoKey>; isDevice: boolean } }> {\n const pubKeysFingerprints = {\n 'sha-1': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha1Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n 'sha-256': [...new Set(this.dataOwnerApi.getHexPublicKeysWithSha256Of(dataOwner.dataOwner))].map((x) => fingerprintV1(x)),\n }\n const loadedKeys =\n pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length > 0 ? await this.loadStoredKeys(dataOwner, pubKeysFingerprints) : {}\n const loadedKeysFingerprints = Object.keys(loadedKeys)\n if (\n loadedKeysFingerprints.length !== pubKeysFingerprints['sha-1'].length + pubKeysFingerprints['sha-256'].length &&\n (loadedKeysFingerprints.length > 0 || Object.keys(ancestorsKeys).length > 0)\n ) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint({ ...loadedKeys, ...ancestorsKeys }))\n for (const [fp, pair] of Object.entries(recoveredKeys)) {\n loadedKeys[fp] = { pair, isDevice: false }\n }\n }\n return loadedKeys\n }\n\n private ensureFingerprintKeys<T>(obj: { [shouldBeFingerprint: string]: T }): { [definitelyFingerprint: string]: T } {\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [fingerprintV1(k), v]))\n }\n\n private hasVerifiedKey(keysData: { [fp: string]: KeyPairData }) {\n return Object.values(keysData).some((x) => x.isVerified || x.isDevice)\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import 'isomorphic-fetch';
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
const test_utils_1 = require("../utils/test_utils");
|
|
13
|
+
const icc_x_api_1 = require("../../icc-x-api");
|
|
14
|
+
const chai_1 = require("chai");
|
|
15
|
+
require("isomorphic-fetch");
|
|
16
|
+
const types_1 = require("@icure/test-setup/types");
|
|
17
|
+
const chaiAsPromised = require("chai-as-promised");
|
|
18
|
+
const utils_1 = require("../../icc-x-api/crypto/utils");
|
|
19
|
+
const DataOwnerTypeEnum_1 = require("../../icc-api/model/DataOwnerTypeEnum");
|
|
20
|
+
const crypto_1 = require("crypto");
|
|
21
|
+
const TestStorage_1 = require("../utils/TestStorage");
|
|
22
|
+
const SecureDelegation_1 = require("../../icc-api/model/SecureDelegation");
|
|
23
|
+
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
|
|
24
|
+
var initMasterApi = test_utils_1.TestUtils.initMasterApi;
|
|
25
|
+
(0, test_utils_1.setLocalStorage)(fetch);
|
|
26
|
+
(0, chai_1.use)(chaiAsPromised);
|
|
27
|
+
let env;
|
|
28
|
+
const untrustedKeyPropId = 'untrustedKey';
|
|
29
|
+
class TrustedKeysStrategy {
|
|
30
|
+
constructor(parentKeys, selfKeys, options = {}) {
|
|
31
|
+
this.parentKeys = parentKeys;
|
|
32
|
+
this.selfKeys = selfKeys;
|
|
33
|
+
this.options = options;
|
|
34
|
+
}
|
|
35
|
+
dataOwnerRequiresAnonymousDelegation(dataOwner) {
|
|
36
|
+
return dataOwner.type != DataOwnerTypeEnum_1.DataOwnerTypeEnum.Hcp;
|
|
37
|
+
}
|
|
38
|
+
recoverAndVerifySelfHierarchyKeys(keysData, cryptoPrimitives, keyPairRecoverer) {
|
|
39
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
40
|
+
if (this.options.failRecoverAndVerifySelfHierarchyKeys) {
|
|
41
|
+
throw new Error("Shouldn't call this method now");
|
|
42
|
+
}
|
|
43
|
+
(0, chai_1.expect)(keysData).to.have.length(2);
|
|
44
|
+
const parentKeysWithFp = yield Promise.all(this.parentKeys.map((k) => __awaiter(this, void 0, void 0, function* () {
|
|
45
|
+
return ({
|
|
46
|
+
trusted: k.trusted,
|
|
47
|
+
fp: (0, utils_1.fingerprintV1)(k.pub),
|
|
48
|
+
keypair: yield cryptoPrimitives.RSA.importKeyPair('pkcs8', (0, icc_x_api_1.ua2ab)((0, icc_x_api_1.hex2ua)(k.priv)), 'spki', (0, icc_x_api_1.ua2ab)((0, icc_x_api_1.hex2ua)(k.pub)), k.shaVersion),
|
|
49
|
+
});
|
|
50
|
+
})));
|
|
51
|
+
const selfKeysWithFp = yield Promise.all(this.selfKeys.map((k) => __awaiter(this, void 0, void 0, function* () {
|
|
52
|
+
return ({
|
|
53
|
+
trusted: k.trusted,
|
|
54
|
+
fp: (0, utils_1.fingerprintV1)(k.pub),
|
|
55
|
+
keypair: yield cryptoPrimitives.RSA.importKeyPair('pkcs8', (0, icc_x_api_1.ua2ab)((0, icc_x_api_1.hex2ua)(k.priv)), 'spki', (0, icc_x_api_1.ua2ab)((0, icc_x_api_1.hex2ua)(k.pub)), k.shaVersion),
|
|
56
|
+
});
|
|
57
|
+
})));
|
|
58
|
+
return {
|
|
59
|
+
[keysData[0].dataOwner.dataOwner.id]: {
|
|
60
|
+
recoveredKeys: Object.fromEntries(parentKeysWithFp.map((k) => [k.fp, k.keypair])),
|
|
61
|
+
keyAuthenticity: Object.fromEntries(parentKeysWithFp.map((k) => [k.fp, k.trusted])),
|
|
62
|
+
},
|
|
63
|
+
[keysData[1].dataOwner.dataOwner.id]: {
|
|
64
|
+
recoveredKeys: Object.fromEntries(selfKeysWithFp.map((k) => [k.fp, k.keypair])),
|
|
65
|
+
keyAuthenticity: Object.fromEntries(selfKeysWithFp.map((k) => [k.fp, k.trusted])),
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
verifyDelegatePublicKeys(delegate, publicKeys, cryptoPrimitives) {
|
|
71
|
+
var _a;
|
|
72
|
+
const untrusted = new Set((_a = delegate.stub.cryptoActorProperties) === null || _a === void 0 ? void 0 : _a.flatMap((p) => {
|
|
73
|
+
var _a;
|
|
74
|
+
if (p.id == untrustedKeyPropId && ((_a = p.typedValue) === null || _a === void 0 ? void 0 : _a.stringValue) != undefined) {
|
|
75
|
+
return [p.typedValue.stringValue];
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
}));
|
|
81
|
+
return Promise.resolve(publicKeys.filter((k) => !untrusted.has((0, utils_1.fingerprintV2)(k))));
|
|
82
|
+
}
|
|
83
|
+
generateNewKeyForDataOwner(self, cryptoPrimitives) {
|
|
84
|
+
if (this.options.overrideGenerateNewKeyForDataOwner) {
|
|
85
|
+
return this.options.overrideGenerateNewKeyForDataOwner();
|
|
86
|
+
}
|
|
87
|
+
return Promise.reject(new Error('Should not be called now'));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
describe('CSM-729', function () {
|
|
91
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
92
|
+
before(function () {
|
|
93
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
94
|
+
this.timeout(600000);
|
|
95
|
+
const initializer = yield (0, test_utils_1.getEnvironmentInitializer)();
|
|
96
|
+
env = yield initializer.execute((0, types_1.getEnvVariables)());
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
it('User with untrusted key', function () {
|
|
100
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
101
|
+
const { grandCredentials: parent, parentCredentials: hcp } = yield (0, test_utils_1.createHcpHierarchyApis)(env);
|
|
102
|
+
// Create some data to use the original keys
|
|
103
|
+
const initialApi = yield icc_x_api_1.IcureApi.initialise(env.iCureUrl, { username: hcp.user, password: hcp.password }, new TrustedKeysStrategy([{ priv: parent.privateKey, pub: parent.publicKey, trusted: true, shaVersion: icc_x_api_1.ShaVersion.Sha1 }], [{ priv: hcp.privateKey, pub: hcp.publicKey, trusted: true, shaVersion: icc_x_api_1.ShaVersion.Sha1 }]), crypto_1.webcrypto, fetch, {
|
|
104
|
+
storage: new TestStorage_1.TestStorage(),
|
|
105
|
+
keyStorage: new TestStorage_1.TestKeyStorage(),
|
|
106
|
+
});
|
|
107
|
+
const user = yield initialApi.userApi.getCurrentUser();
|
|
108
|
+
const pat1 = yield initialApi.patientApi.createPatientWithUser(user, yield initialApi.patientApi.newInstance(user, {
|
|
109
|
+
firstName: 'John',
|
|
110
|
+
lastName: 'Doe',
|
|
111
|
+
note: 'Secret note',
|
|
112
|
+
}, {
|
|
113
|
+
additionalDelegates: { [parent.dataOwnerId]: AccessLevelEnum.WRITE },
|
|
114
|
+
}));
|
|
115
|
+
// Check exchange data was created as expected
|
|
116
|
+
const selfSelfXdata = yield initialApi.cryptoApi.exchangeData.base.getExchangeDataByDelegatorDelegatePair(hcp.dataOwnerId, hcp.dataOwnerId);
|
|
117
|
+
const selfParentXdata = yield initialApi.cryptoApi.exchangeData.base.getExchangeDataByDelegatorDelegatePair(hcp.dataOwnerId, parent.dataOwnerId);
|
|
118
|
+
(0, chai_1.expect)(selfSelfXdata).to.not.be.undefined;
|
|
119
|
+
(0, chai_1.expect)(selfParentXdata).to.not.be.undefined;
|
|
120
|
+
(0, chai_1.expect)(selfSelfXdata).to.have.length(1);
|
|
121
|
+
(0, chai_1.expect)(selfParentXdata).to.have.length(1);
|
|
122
|
+
// Prepare for new api with untrusted key
|
|
123
|
+
//// Mark self hcp keys as untrusted
|
|
124
|
+
let selfHcp = yield initialApi.healthcarePartyApi.getCurrentHealthcareParty();
|
|
125
|
+
selfHcp = yield initialApi.healthcarePartyApi.modifyHealthcareParty(Object.assign(Object.assign({}, selfHcp), { cryptoActorProperties: [
|
|
126
|
+
...(selfHcp.cryptoActorProperties || []),
|
|
127
|
+
{
|
|
128
|
+
id: untrustedKeyPropId,
|
|
129
|
+
typedValue: { stringValue: (0, utils_1.fingerprintV2)(hcp.publicKey) },
|
|
130
|
+
},
|
|
131
|
+
] }));
|
|
132
|
+
//// Mark parent hcp keys as untrusted and add new key (currently can't be done through crypto strategies)
|
|
133
|
+
const newParentKey = yield initialApi.cryptoApi.primitives.RSA.generateKeyPair(icc_x_api_1.ShaVersion.Sha256);
|
|
134
|
+
const newParentKeySpki = (0, icc_x_api_1.ua2hex)(yield initialApi.cryptoApi.primitives.RSA.exportKey(newParentKey.publicKey, 'spki'));
|
|
135
|
+
const newParentKeyPkcs8 = (0, icc_x_api_1.ua2hex)(yield initialApi.cryptoApi.primitives.RSA.exportKey(newParentKey.privateKey, 'pkcs8'));
|
|
136
|
+
const adminApi = yield initMasterApi(env);
|
|
137
|
+
let parentHcp = yield adminApi.healthcarePartyApi.getHealthcareParty(parent.dataOwnerId);
|
|
138
|
+
parentHcp = yield adminApi.healthcarePartyApi.modifyHealthcareParty(Object.assign(Object.assign({}, parentHcp), { cryptoActorProperties: [
|
|
139
|
+
...(parentHcp.cryptoActorProperties || []),
|
|
140
|
+
{
|
|
141
|
+
id: untrustedKeyPropId,
|
|
142
|
+
typedValue: { stringValue: (0, utils_1.fingerprintV2)(parent.publicKey) },
|
|
143
|
+
},
|
|
144
|
+
], publicKeysForOaepWithSha256: [...(parentHcp.publicKeysForOaepWithSha256 || []), newParentKeySpki] }));
|
|
145
|
+
//// No need to invalidate exchange data, as untrusted keys are not used to validate it
|
|
146
|
+
// Setup new api
|
|
147
|
+
let didCreateNewKey = false;
|
|
148
|
+
const newHcpKey = yield initialApi.cryptoApi.primitives.RSA.generateKeyPair(icc_x_api_1.ShaVersion.Sha256);
|
|
149
|
+
const newHcpKeySpki = (0, icc_x_api_1.ua2hex)(yield initialApi.cryptoApi.primitives.RSA.exportKey(newHcpKey.publicKey, 'spki'));
|
|
150
|
+
const newHcpKeyPkcs8 = (0, icc_x_api_1.ua2hex)(yield initialApi.cryptoApi.primitives.RSA.exportKey(newHcpKey.privateKey, 'pkcs8'));
|
|
151
|
+
const apiWithUntrustedKeysStorages = {
|
|
152
|
+
// Using a new storage, simulates wiping the local storage
|
|
153
|
+
storage: new TestStorage_1.TestStorage(),
|
|
154
|
+
keyStorage: new TestStorage_1.TestKeyStorage(),
|
|
155
|
+
};
|
|
156
|
+
const apiWithUntrustedKey = yield icc_x_api_1.IcureApi.initialise(env.iCureUrl, { username: hcp.user, password: hcp.password }, new TrustedKeysStrategy([
|
|
157
|
+
{ priv: parent.privateKey, pub: parent.publicKey, trusted: false, shaVersion: icc_x_api_1.ShaVersion.Sha1 },
|
|
158
|
+
{ priv: newParentKeyPkcs8, pub: newParentKeySpki, trusted: true, shaVersion: icc_x_api_1.ShaVersion.Sha256 },
|
|
159
|
+
], [{ priv: hcp.privateKey, pub: hcp.publicKey, trusted: false, shaVersion: icc_x_api_1.ShaVersion.Sha1 }], {
|
|
160
|
+
overrideGenerateNewKeyForDataOwner: () => {
|
|
161
|
+
didCreateNewKey = true;
|
|
162
|
+
return Promise.resolve(newHcpKey);
|
|
163
|
+
},
|
|
164
|
+
}), crypto_1.webcrypto, fetch, apiWithUntrustedKeysStorages);
|
|
165
|
+
(0, chai_1.expect)(didCreateNewKey).to.eq(true);
|
|
166
|
+
// Check all keys are available but only new keys are trusted
|
|
167
|
+
(0, chai_1.expect)(yield apiWithUntrustedKey.cryptoApi.userKeysManager.getVerifiedPublicKeysFor(yield apiWithUntrustedKey.healthcarePartyApi.getHealthcareParty(hcp.dataOwnerId))).to.have.members([newHcpKeySpki]);
|
|
168
|
+
(0, chai_1.expect)(yield apiWithUntrustedKey.cryptoApi.userKeysManager.getVerifiedPublicKeysFor(yield apiWithUntrustedKey.healthcarePartyApi.getHealthcareParty(parent.dataOwnerId))).to.have.members([newParentKeySpki]);
|
|
169
|
+
(0, chai_1.expect)(yield apiWithUntrustedKey.cryptoApi.userKeysManager.getCurrentUserHierarchyAvailablePublicKeysHex()).to.have.members([
|
|
170
|
+
newHcpKeySpki,
|
|
171
|
+
hcp.publicKey,
|
|
172
|
+
parent.publicKey,
|
|
173
|
+
newParentKeySpki,
|
|
174
|
+
]);
|
|
175
|
+
(0, chai_1.expect)(yield apiWithUntrustedKey.cryptoApi.userKeysManager.getCurrentUserAvailablePublicKeysHex(false)).to.have.members([
|
|
176
|
+
newHcpKeySpki,
|
|
177
|
+
hcp.publicKey,
|
|
178
|
+
]);
|
|
179
|
+
// Check can still read old data
|
|
180
|
+
const pat1Recovered = yield apiWithUntrustedKey.patientApi.getPatientWithUser(user, pat1.id);
|
|
181
|
+
(0, chai_1.expect)(pat1Recovered.note).to.eq('Secret note');
|
|
182
|
+
// Check can create new data
|
|
183
|
+
const pat2 = yield initialApi.patientApi.createPatientWithUser(user, yield initialApi.patientApi.newInstance(user, {
|
|
184
|
+
firstName: 'Joe',
|
|
185
|
+
lastName: 'Doe',
|
|
186
|
+
note: 'Secret note',
|
|
187
|
+
}, {
|
|
188
|
+
additionalDelegates: { [parent.dataOwnerId]: AccessLevelEnum.WRITE },
|
|
189
|
+
}));
|
|
190
|
+
// Check created new exchange data and only used the new trusted keys for it
|
|
191
|
+
const selfSelfXdata2 = yield initialApi.cryptoApi.exchangeData.base.getExchangeDataByDelegatorDelegatePair(hcp.dataOwnerId, hcp.dataOwnerId);
|
|
192
|
+
const selfParentXdata2 = yield initialApi.cryptoApi.exchangeData.base.getExchangeDataByDelegatorDelegatePair(hcp.dataOwnerId, parent.dataOwnerId);
|
|
193
|
+
(0, chai_1.expect)(selfSelfXdata2).to.not.be.undefined;
|
|
194
|
+
(0, chai_1.expect)(selfParentXdata2).to.not.be.undefined;
|
|
195
|
+
(0, chai_1.expect)(selfSelfXdata2).to.have.length(2);
|
|
196
|
+
(0, chai_1.expect)(selfParentXdata2).to.have.length(2);
|
|
197
|
+
const newSelfSelfXdata = selfSelfXdata2.filter((xd) => xd.id !== selfSelfXdata[0].id);
|
|
198
|
+
(0, chai_1.expect)(newSelfSelfXdata).to.have.length(1);
|
|
199
|
+
const newSelfSelfXDataUsedFps = Object.keys(newSelfSelfXdata[0].exchangeKey);
|
|
200
|
+
(0, chai_1.expect)(newSelfSelfXDataUsedFps).to.have.length(1);
|
|
201
|
+
(0, chai_1.expect)(newSelfSelfXDataUsedFps[0]).to.eq((0, utils_1.fingerprintV2)(newHcpKeySpki));
|
|
202
|
+
const newSelfParentXdata = selfParentXdata2.filter((xd) => xd.id !== selfParentXdata[0].id);
|
|
203
|
+
(0, chai_1.expect)(newSelfParentXdata).to.have.length(1);
|
|
204
|
+
const newSelfParentXDataUsedFps = Object.keys(newSelfParentXdata[0].exchangeKey);
|
|
205
|
+
(0, chai_1.expect)(newSelfParentXDataUsedFps).to.have.length(2);
|
|
206
|
+
(0, chai_1.expect)(newSelfParentXDataUsedFps).to.have.members([(0, utils_1.fingerprintV2)(newHcpKeySpki), (0, utils_1.fingerprintV2)(newParentKeySpki)]);
|
|
207
|
+
// Check after reinitialization with keys already in storage the "verified" situation is unchanged.
|
|
208
|
+
const apiWithUntrustedKey2 = yield icc_x_api_1.IcureApi.initialise(env.iCureUrl, { username: hcp.user, password: hcp.password }, new TrustedKeysStrategy([], [], { failRecoverAndVerifySelfHierarchyKeys: true }), crypto_1.webcrypto, fetch, apiWithUntrustedKeysStorages);
|
|
209
|
+
(0, chai_1.expect)(yield apiWithUntrustedKey2.cryptoApi.userKeysManager.getVerifiedPublicKeysFor(yield apiWithUntrustedKey2.healthcarePartyApi.getHealthcareParty(hcp.dataOwnerId))).to.have.members([newHcpKeySpki]);
|
|
210
|
+
(0, chai_1.expect)(yield apiWithUntrustedKey2.cryptoApi.userKeysManager.getVerifiedPublicKeysFor(yield apiWithUntrustedKey2.healthcarePartyApi.getHealthcareParty(parent.dataOwnerId))).to.have.members([newParentKeySpki]);
|
|
211
|
+
(0, chai_1.expect)(yield apiWithUntrustedKey2.cryptoApi.userKeysManager.getCurrentUserHierarchyAvailablePublicKeysHex()).to.have.members([
|
|
212
|
+
newHcpKeySpki,
|
|
213
|
+
hcp.publicKey,
|
|
214
|
+
parent.publicKey,
|
|
215
|
+
newParentKeySpki,
|
|
216
|
+
]);
|
|
217
|
+
(0, chai_1.expect)(yield apiWithUntrustedKey2.cryptoApi.userKeysManager.getCurrentUserAvailablePublicKeysHex(false)).to.have.members([
|
|
218
|
+
newHcpKeySpki,
|
|
219
|
+
hcp.publicKey,
|
|
220
|
+
]);
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
//# sourceMappingURL=CSM-729.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
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AgB;iBACjB,CAAC,CAAA;gBACF,IAAA,aAAM,EAAC,MAAM,oBAAoB,CAAC,SAAS,CAAC,eAAe,CAAC,oCAAoC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC;oBACvH,aAAa;oBACb,GAAG,CAAC,SAAS;iBACd,CAAC,CAAA;YACJ,CAAC;SAAA,CAAC,CAAA;IACJ,CAAC;CAAA,CAAC,CAAA","sourcesContent":["import { createHcpHierarchyApis, getEnvironmentInitializer, setLocalStorage, TestUtils } from '../utils/test_utils'\nimport { CryptoPrimitives, CryptoStrategies, hex2ua, IcureApi, KeyPair, ShaVersion, ua2ab, ua2hex } from '../../icc-x-api'\nimport { expect, use as chaiUse } from 'chai'\nimport 'isomorphic-fetch'\nimport { getEnvVariables, TestVars } from '@icure/test-setup/types'\nimport * as chaiAsPromised from 'chai-as-promised'\nimport { fingerprintV1, fingerprintV2 } from '../../icc-x-api/crypto/utils'\nimport { KeyPairRecoverer } from '../../icc-x-api/crypto/KeyPairRecoverer'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\nimport { webcrypto } from 'crypto'\nimport { TestKeyStorage, TestStorage } from '../utils/TestStorage'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport initMasterApi = TestUtils.initMasterApi\n\nsetLocalStorage(fetch)\n\nchaiUse(chaiAsPromised)\n\nlet env: TestVars\n\nconst untrustedKeyPropId = 'untrustedKey'\n\nclass TrustedKeysStrategy implements CryptoStrategies {\n constructor(\n private readonly parentKeys: { pub: string; priv: string; trusted: boolean; shaVersion: ShaVersion }[],\n private readonly selfKeys: { pub: string; priv: string; trusted: boolean; shaVersion: ShaVersion }[],\n private readonly options: {\n failRecoverAndVerifySelfHierarchyKeys?: boolean\n overrideGenerateNewKeyForDataOwner?: () => Promise<KeyPair<CryptoKey> | boolean | 'keyless'>\n } = {}\n ) {}\n\n dataOwnerRequiresAnonymousDelegation(dataOwner: CryptoActorStubWithType): boolean {\n return dataOwner.type != DataOwnerTypeEnum.Hcp\n }\n\n async recoverAndVerifySelfHierarchyKeys(\n keysData: {\n dataOwner: DataOwnerWithType\n unknownKeys: string[]\n unavailableKeys: string[]\n }[],\n cryptoPrimitives: CryptoPrimitives,\n keyPairRecoverer: KeyPairRecoverer\n ): Promise<{\n [p: string]: { recoveredKeys: { [p: string]: KeyPair<CryptoKey> }; keyAuthenticity: { [p: string]: boolean } }\n }> {\n if (this.options.failRecoverAndVerifySelfHierarchyKeys) {\n throw new Error(\"Shouldn't call this method now\")\n }\n expect(keysData).to.have.length(2)\n const parentKeysWithFp = await Promise.all(\n this.parentKeys.map(async (k) => ({\n trusted: k.trusted,\n fp: fingerprintV1(k.pub),\n keypair: await cryptoPrimitives.RSA.importKeyPair('pkcs8', ua2ab(hex2ua(k.priv)), 'spki', ua2ab(hex2ua(k.pub)), k.shaVersion),\n }))\n )\n const selfKeysWithFp = await Promise.all(\n this.selfKeys.map(async (k) => ({\n trusted: k.trusted,\n fp: fingerprintV1(k.pub),\n keypair: await cryptoPrimitives.RSA.importKeyPair('pkcs8', ua2ab(hex2ua(k.priv)), 'spki', ua2ab(hex2ua(k.pub)), k.shaVersion),\n }))\n )\n return {\n [keysData[0].dataOwner.dataOwner.id!]: {\n recoveredKeys: Object.fromEntries(parentKeysWithFp.map((k) => [k.fp, k.keypair])),\n keyAuthenticity: Object.fromEntries(parentKeysWithFp.map((k) => [k.fp, k.trusted])),\n },\n [keysData[1].dataOwner.dataOwner.id!]: {\n recoveredKeys: Object.fromEntries(selfKeysWithFp.map((k) => [k.fp, k.keypair])),\n keyAuthenticity: Object.fromEntries(selfKeysWithFp.map((k) => [k.fp, k.trusted])),\n },\n }\n }\n\n verifyDelegatePublicKeys(delegate: CryptoActorStubWithType, publicKeys: string[], cryptoPrimitives: CryptoPrimitives): Promise<string[]> {\n const untrusted = new Set(\n delegate.stub.cryptoActorProperties?.flatMap((p) => {\n if (p.id == untrustedKeyPropId && p.typedValue?.stringValue != undefined) {\n return [p.typedValue.stringValue]\n } else {\n return []\n }\n })\n )\n return Promise.resolve(publicKeys.filter((k) => !untrusted.has(fingerprintV2(k))))\n }\n\n generateNewKeyForDataOwner(self: DataOwnerWithType, cryptoPrimitives: CryptoPrimitives): Promise<KeyPair<CryptoKey> | boolean | 'keyless'> {\n if (this.options.overrideGenerateNewKeyForDataOwner) {\n return this.options.overrideGenerateNewKeyForDataOwner()\n }\n return Promise.reject(new Error('Should not be called now'))\n }\n}\n\ndescribe('CSM-729', async function () {\n before(async function () {\n this.timeout(600000)\n const initializer = await getEnvironmentInitializer()\n env = await initializer.execute(getEnvVariables())\n })\n\n it('User with untrusted key', async function () {\n const { grandCredentials: parent, parentCredentials: hcp } = await createHcpHierarchyApis(env)\n // Create some data to use the original keys\n const initialApi = await IcureApi.initialise(\n env.iCureUrl,\n { username: hcp.user, password: hcp.password },\n new TrustedKeysStrategy(\n [{ priv: parent.privateKey, pub: parent.publicKey, trusted: true, shaVersion: ShaVersion.Sha1 }],\n [{ priv: hcp.privateKey, pub: hcp.publicKey, trusted: true, shaVersion: ShaVersion.Sha1 }]\n ),\n webcrypto as any,\n fetch,\n {\n storage: new TestStorage(),\n keyStorage: new TestKeyStorage(),\n }\n )\n const user = await initialApi.userApi.getCurrentUser()\n const pat1 = await initialApi.patientApi.createPatientWithUser(\n user,\n await initialApi.patientApi.newInstance(\n user,\n {\n firstName: 'John',\n lastName: 'Doe',\n note: 'Secret note',\n },\n {\n additionalDelegates: { [parent.dataOwnerId]: AccessLevelEnum.WRITE },\n }\n )\n )\n // Check exchange data was created as expected\n const selfSelfXdata = await initialApi.cryptoApi.exchangeData.base.getExchangeDataByDelegatorDelegatePair(hcp.dataOwnerId, hcp.dataOwnerId)\n const selfParentXdata = await initialApi.cryptoApi.exchangeData.base.getExchangeDataByDelegatorDelegatePair(hcp.dataOwnerId, parent.dataOwnerId)\n expect(selfSelfXdata).to.not.be.undefined\n expect(selfParentXdata).to.not.be.undefined\n expect(selfSelfXdata).to.have.length(1)\n expect(selfParentXdata).to.have.length(1)\n // Prepare for new api with untrusted key\n //// Mark self hcp keys as untrusted\n let selfHcp = await initialApi.healthcarePartyApi.getCurrentHealthcareParty()\n selfHcp = await initialApi.healthcarePartyApi.modifyHealthcareParty({\n ...selfHcp,\n cryptoActorProperties: [\n ...(selfHcp.cryptoActorProperties || []),\n {\n id: untrustedKeyPropId,\n typedValue: { stringValue: fingerprintV2(hcp.publicKey) },\n },\n ],\n })\n //// Mark parent hcp keys as untrusted and add new key (currently can't be done through crypto strategies)\n const newParentKey = await initialApi.cryptoApi.primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const newParentKeySpki = ua2hex(await initialApi.cryptoApi.primitives.RSA.exportKey(newParentKey.publicKey, 'spki'))\n const newParentKeyPkcs8 = ua2hex(await initialApi.cryptoApi.primitives.RSA.exportKey(newParentKey.privateKey, 'pkcs8'))\n const adminApi = await initMasterApi(env)\n let parentHcp = await adminApi.healthcarePartyApi.getHealthcareParty(parent.dataOwnerId)\n parentHcp = await adminApi.healthcarePartyApi.modifyHealthcareParty({\n // Hcp normally doesn't have right to modify parent, depends on permissions\n ...parentHcp,\n cryptoActorProperties: [\n ...(parentHcp.cryptoActorProperties || []),\n {\n id: untrustedKeyPropId,\n typedValue: { stringValue: fingerprintV2(parent.publicKey) },\n },\n ],\n publicKeysForOaepWithSha256: [...(parentHcp.publicKeysForOaepWithSha256 || []), newParentKeySpki],\n })\n //// No need to invalidate exchange data, as untrusted keys are not used to validate it\n // Setup new api\n let didCreateNewKey = false\n const newHcpKey = await initialApi.cryptoApi.primitives.RSA.generateKeyPair(ShaVersion.Sha256)\n const newHcpKeySpki = ua2hex(await initialApi.cryptoApi.primitives.RSA.exportKey(newHcpKey.publicKey, 'spki'))\n const newHcpKeyPkcs8 = ua2hex(await initialApi.cryptoApi.primitives.RSA.exportKey(newHcpKey.privateKey, 'pkcs8'))\n const apiWithUntrustedKeysStorages = {\n // Using a new storage, simulates wiping the local storage\n storage: new TestStorage(),\n keyStorage: new TestKeyStorage(),\n }\n const apiWithUntrustedKey = await IcureApi.initialise(\n env.iCureUrl,\n { username: hcp.user, password: hcp.password },\n new TrustedKeysStrategy(\n [\n { priv: parent.privateKey, pub: parent.publicKey, trusted: false, shaVersion: ShaVersion.Sha1 },\n { priv: newParentKeyPkcs8, pub: newParentKeySpki, trusted: true, shaVersion: ShaVersion.Sha256 },\n ],\n [{ priv: hcp.privateKey, pub: hcp.publicKey, trusted: false, shaVersion: ShaVersion.Sha1 }],\n {\n overrideGenerateNewKeyForDataOwner: () => {\n didCreateNewKey = true\n return Promise.resolve(newHcpKey)\n },\n }\n ),\n webcrypto as any,\n fetch,\n apiWithUntrustedKeysStorages\n )\n expect(didCreateNewKey).to.eq(true)\n // Check all keys are available but only new keys are trusted\n expect(\n await apiWithUntrustedKey.cryptoApi.userKeysManager.getVerifiedPublicKeysFor(\n await apiWithUntrustedKey.healthcarePartyApi.getHealthcareParty(hcp.dataOwnerId)\n )\n ).to.have.members([newHcpKeySpki])\n expect(\n await apiWithUntrustedKey.cryptoApi.userKeysManager.getVerifiedPublicKeysFor(\n await apiWithUntrustedKey.healthcarePartyApi.getHealthcareParty(parent.dataOwnerId)\n )\n ).to.have.members([newParentKeySpki])\n expect(await apiWithUntrustedKey.cryptoApi.userKeysManager.getCurrentUserHierarchyAvailablePublicKeysHex()).to.have.members([\n newHcpKeySpki,\n hcp.publicKey,\n parent.publicKey,\n newParentKeySpki,\n ])\n expect(await apiWithUntrustedKey.cryptoApi.userKeysManager.getCurrentUserAvailablePublicKeysHex(false)).to.have.members([\n newHcpKeySpki,\n hcp.publicKey,\n ])\n // Check can still read old data\n const pat1Recovered = await apiWithUntrustedKey.patientApi.getPatientWithUser(user, pat1.id!)\n expect(pat1Recovered.note).to.eq('Secret note')\n // Check can create new data\n const pat2 = await initialApi.patientApi.createPatientWithUser(\n user,\n await initialApi.patientApi.newInstance(\n user,\n {\n firstName: 'Joe',\n lastName: 'Doe',\n note: 'Secret note',\n },\n {\n additionalDelegates: { [parent.dataOwnerId]: AccessLevelEnum.WRITE },\n }\n )\n )\n // Check created new exchange data and only used the new trusted keys for it\n const selfSelfXdata2 = await initialApi.cryptoApi.exchangeData.base.getExchangeDataByDelegatorDelegatePair(hcp.dataOwnerId, hcp.dataOwnerId)\n const selfParentXdata2 = await initialApi.cryptoApi.exchangeData.base.getExchangeDataByDelegatorDelegatePair(hcp.dataOwnerId, parent.dataOwnerId)\n expect(selfSelfXdata2).to.not.be.undefined\n expect(selfParentXdata2).to.not.be.undefined\n expect(selfSelfXdata2).to.have.length(2)\n expect(selfParentXdata2).to.have.length(2)\n const newSelfSelfXdata = selfSelfXdata2.filter((xd) => xd.id !== selfSelfXdata[0].id)!\n expect(newSelfSelfXdata).to.have.length(1)\n const newSelfSelfXDataUsedFps = Object.keys(newSelfSelfXdata[0].exchangeKey)\n expect(newSelfSelfXDataUsedFps).to.have.length(1)\n expect(newSelfSelfXDataUsedFps[0]).to.eq(fingerprintV2(newHcpKeySpki))\n const newSelfParentXdata = selfParentXdata2.filter((xd) => xd.id !== selfParentXdata[0].id)!\n expect(newSelfParentXdata).to.have.length(1)\n const newSelfParentXDataUsedFps = Object.keys(newSelfParentXdata[0].exchangeKey)\n expect(newSelfParentXDataUsedFps).to.have.length(2)\n expect(newSelfParentXDataUsedFps).to.have.members([fingerprintV2(newHcpKeySpki), fingerprintV2(newParentKeySpki)])\n // Check after reinitialization with keys already in storage the \"verified\" situation is unchanged.\n const apiWithUntrustedKey2 = await IcureApi.initialise(\n env.iCureUrl,\n { username: hcp.user, password: hcp.password },\n new TrustedKeysStrategy([], [], { failRecoverAndVerifySelfHierarchyKeys: true }),\n webcrypto as any,\n fetch,\n apiWithUntrustedKeysStorages\n )\n expect(\n await apiWithUntrustedKey2.cryptoApi.userKeysManager.getVerifiedPublicKeysFor(\n await apiWithUntrustedKey2.healthcarePartyApi.getHealthcareParty(hcp.dataOwnerId)\n )\n ).to.have.members([newHcpKeySpki])\n expect(\n await apiWithUntrustedKey2.cryptoApi.userKeysManager.getVerifiedPublicKeysFor(\n await apiWithUntrustedKey2.healthcarePartyApi.getHealthcareParty(parent.dataOwnerId)\n )\n ).to.have.members([newParentKeySpki])\n expect(await apiWithUntrustedKey2.cryptoApi.userKeysManager.getCurrentUserHierarchyAvailablePublicKeysHex()).to.have.members([\n newHcpKeySpki,\n hcp.publicKey,\n parent.publicKey,\n newParentKeySpki,\n ])\n expect(await apiWithUntrustedKey2.cryptoApi.userKeysManager.getCurrentUserAvailablePublicKeysHex(false)).to.have.members([\n newHcpKeySpki,\n hcp.publicKey,\n ])\n })\n})\n"]}
|