@icure/api 5.2.38 → 5.3.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"icc-invoice-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-invoice-x-api.ts"],"names":[],"mappings":";;;AAAA,wCAA2D;AAG3D,4BAA2B;AAC3B,kDAAiD;AAGjD,0EAAgG;AAEhG,MAAa,cAAe,SAAQ,uBAAa;IAK/C,YACE,IAAY,EACZ,OAAkC,EAClC,MAAqB,EACrB,YAA6B,EAC7B,YAA8B,EAC9B,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QACvD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;IAClC,CAAC;IAED,WAAW,CAAC,IAAiB,EAAE,OAAuB,EAAE,MAAW,EAAE,EAAE,YAAsB,EAAE;QAC7F,MAAM,OAAO,GAAG,IAAI,MAAM,CAAC,OAAO,CAChC,CAAC,CAAC,MAAM,CACN;YACE,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE;YAC5B,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE;YACjC,KAAK,EAAE,mCAAmC;YAC1C,OAAO,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;YAC7B,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;YAC9B,WAAW,EAAE,IAAI,CA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, IccInvoiceApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\nimport { Invoice } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport class IccInvoiceXApi extends IccInvoiceApi {\n crypto: IccCryptoXApi\n entityrefApi: IccEntityrefApi\n dataOwnerApi: IccDataOwnerXApi\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n crypto: IccCryptoXApi,\n entityrefApi: IccEntityrefApi,\n dataOwnerApi: IccDataOwnerXApi,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.crypto = crypto\n this.entityrefApi = entityrefApi\n this.dataOwnerApi = dataOwnerApi\n }\n\n newInstance(user: models.User, patient: models.Patient, inv: any = {}, delegates: string[] = []): Promise<models.Invoice> {\n const invoice = new models.Invoice(\n _.extend(\n {\n id: this.crypto.randomUuid(),\n groupId: this.crypto.randomUuid(),\n _type: 'org.taktik.icure.entities.Invoice',\n created: new Date().getTime(),\n modified: new Date().getTime(),\n responsible: this.dataOwnerApi.getDataOwnerOf(user),\n author: user.id,\n codes: [],\n tags: [],\n invoicingCodes: [],\n },\n inv || {}\n )\n )\n\n return this.initDelegationsAndEncryptionKeys(user, patient, invoice, delegates)\n }\n\n initEncryptionKeys(user: models.User, invoice: models.Invoice) {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n return this.crypto.initEncryptionKeys(invoice, dataOwnerId!).then((eks) => {\n let promise = Promise.resolve(\n _.extend(invoice, {\n encryptionKeys: eks.encryptionKeys,\n })\n )\n ;(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.financialInformation || []) : []).forEach(\n (delegateId) =>\n (promise = promise.then((invoice) =>\n this.crypto.appendEncryptionKeys(invoice, dataOwnerId!, delegateId, eks.secretId).then((extraEks) => {\n return _.extend(extraEks.modifiedObject, {\n encryptionKeys: extraEks.encryptionKeys,\n })\n })\n ))\n )\n return promise\n })\n }\n\n private initDelegationsAndEncryptionKeys(\n user: models.User,\n patient: models.Patient,\n invoice: models.Invoice,\n delegates: string[] = []\n ): Promise<models.Invoice> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n return this.crypto\n .extractDelegationsSFKs(patient, dataOwnerId)\n .then((secretForeignKeys) => {\n const sfk = secretForeignKeys.extractedKeys[0]\n if (!sfk) throw new Error(\"Could not find secret foreign key for patient '\" + patient.id + \"'\")\n return Promise.all([\n this.crypto.initObjectDelegations(invoice, patient, dataOwnerId!, sfk),\n this.crypto.initEncryptionKeys(invoice, dataOwnerId!),\n ])\n })\n .then((initData) => {\n const dels = initData[0]\n const eks = initData[1]\n _.extend(invoice, {\n delegations: dels.delegations,\n cryptedForeignKeys: dels.cryptedForeignKeys,\n secretForeignKeys: dels.secretForeignKeys,\n encryptionKeys: eks.encryptionKeys,\n })\n\n let promise = Promise.resolve(invoice)\n _.uniq(\n delegates.concat(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.financialInformation || []) : [])\n ).forEach(\n (delegateId) =>\n (promise = promise.then((invoice) =>\n this.crypto.addDelegationsAndEncryptionKeys(patient, invoice, dataOwnerId!, delegateId, dels.secretId, eks.secretId).catch((e) => {\n console.log(e)\n return invoice\n })\n ))\n )\n return promise\n })\n }\n\n createInvoice(invoice: Invoice, prefix?: string): Promise<Invoice> {\n if (!prefix) {\n return super.createInvoice(invoice)\n }\n if (!invoice.id) {\n invoice.id = this.crypto.randomUuid()\n }\n return this.getNextInvoiceReference(prefix, this.entityrefApi)\n .then((reference) => this.createInvoiceReference(reference, invoice.id!, prefix, this.entityrefApi))\n .then((entityReference) => {\n if (!entityReference.id) {\n throw new Error('Cannot create invoice')\n }\n\n if (invoice.internshipNihii) {\n const ref = entityReference.id.substr(prefix.length).replace('0', '1')\n invoice.invoiceReference = ref\n } else {\n invoice.invoiceReference = entityReference.id.substr(prefix.length)\n }\n return super.createInvoice(invoice)\n })\n }\n\n getNextInvoiceReference(prefix: string, entityrefApi: IccEntityrefApi): Promise<number> {\n return entityrefApi.getLatest(prefix).then((entRef: models.EntityReference) => {\n if (!entRef || !entRef.id || !entRef.id!.startsWith(prefix)) return 1\n const sequenceNumber = entRef.id!.split(':').pop() || 0\n return Number(sequenceNumber) + 1\n })\n }\n\n createInvoiceReference(nextReference: number, docId: string, prefix: string, entityrefApi: IccEntityrefApi): Promise<models.EntityReference> {\n return entityrefApi\n .createEntityReference(\n new models.EntityReference({\n id: prefix + nextReference.toString().padStart(6, '0'),\n docId,\n })\n )\n .catch((err) => {\n console.log(err)\n return this.createInvoiceReference(nextReference + 1, docId, prefix, entityrefApi)\n })\n }\n\n /**\n * 1. Check whether there is a delegation with 'hcpartyId' or not.\n * 2. 'fetchHcParty[hcpartyId][1]': is encrypted AES exchange key by RSA public key of him.\n * 3. Obtain the AES exchange key, by decrypting the previous step value with hcparty private key\n * 3.1. KeyPair should be fetch from cache (in jwk)\n * 3.2. if it doesn't exist in the cache, it has to be loaded from Browser Local store, and then import it to WebCrypto\n * 4. Obtain the array of delegations which are delegated to his ID (hcpartyId) in this patient\n * 5. Decrypt and collect all keys (secretForeignKeys) within delegations of previous step (with obtained AES key of step 4)\n * 6. Do the REST call to get all invoices with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the invoices of the patient.\n *\n * @param hcpartyId\n * @param patient (Promise)\n * @param usingPost\n */\n findBy(hcpartyId: string, patient: models.Patient, usingPost: boolean = false): Promise<Array<models.Invoice>> {\n return this.crypto\n .extractDelegationsSFKs(patient, hcpartyId)\n .then((secretForeignKeys) =>\n usingPost\n ? this.findInvoicesByHCPartyPatientForeignKeysUsingPost(secretForeignKeys.hcpartyId!, _.uniq(secretForeignKeys.extractedKeys))\n : this.findInvoicesByHCPartyPatientForeignKeys(secretForeignKeys.hcpartyId!, _.uniq(secretForeignKeys.extractedKeys).join(','))\n )\n .then((invoices) => this.decrypt(hcpartyId, invoices))\n .then(function (decryptedInvoices) {\n return decryptedInvoices\n })\n }\n\n encrypt(user: models.User, invoices: Array<models.Invoice>) {\n return Promise.resolve(invoices)\n }\n\n decrypt(hcpartyId: string, invoices: Array<models.Invoice>): Promise<Array<models.Invoice>> {\n return Promise.resolve(invoices)\n }\n}\n"]}
1
+ {"version":3,"file":"icc-invoice-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-invoice-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAA2D;AAG3D,4BAA2B;AAC3B,kDAAiD;AAGjD,0EAAgG;AAEhG,MAAa,cAAe,SAAQ,uBAAa;IAK/C,YACE,IAAY,EACZ,OAAkC,EAClC,MAAqB,EACrB,YAA6B,EAC7B,YAA8B,EAC9B,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QACvD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;QAChC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;IAClC,CAAC;IAED,WAAW,CAAC,IAAiB,EAAE,OAAuB,EAAE,MAAW,EAAE,EAAE,YAAsB,EAAE;QAC7F,MAAM,OAAO,GAAG,IAAI,MAAM,CAAC,OAAO,CAChC,CAAC,CAAC,MAAM,CACN;YACE,EAAE,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C,SAAS,EAAE,QAAQ,CAAC,CAAC;aACrD,IAAI,CAAC,UAAU,iBAAiB;YAC/B,OAAO,iBAAiB,CAAA;QAC1B,CAAC,CAAC,CAAA;IACN,CAAC;IAED,OAAO,CAAC,IAAiB,EAAE,QAA+B;QACxD,OAAO,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;IAClC,CAAC;IAED,OAAO,CAAC,SAAiB,EAAE,QAA+B;QACxD,OAAO,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;IAClC,CAAC;CACF;AArMD,wCAqMC","sourcesContent":["import { IccEntityrefApi, IccInvoiceApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as _ from 'lodash'\nimport * as models from '../icc-api/model/models'\nimport { Invoice } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport class IccInvoiceXApi extends IccInvoiceApi {\n crypto: IccCryptoXApi\n entityrefApi: IccEntityrefApi\n dataOwnerApi: IccDataOwnerXApi\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n crypto: IccCryptoXApi,\n entityrefApi: IccEntityrefApi,\n dataOwnerApi: IccDataOwnerXApi,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.crypto = crypto\n this.entityrefApi = entityrefApi\n this.dataOwnerApi = dataOwnerApi\n }\n\n newInstance(user: models.User, patient: models.Patient, inv: any = {}, delegates: string[] = []): Promise<models.Invoice> {\n const invoice = new models.Invoice(\n _.extend(\n {\n id: this.crypto.randomUuid(),\n groupId: this.crypto.randomUuid(),\n _type: 'org.taktik.icure.entities.Invoice',\n created: new Date().getTime(),\n modified: new Date().getTime(),\n responsible: this.dataOwnerApi.getDataOwnerOf(user),\n author: user.id,\n codes: [],\n tags: [],\n invoicingCodes: [],\n },\n inv || {}\n )\n )\n\n return this.initDelegationsAndEncryptionKeys(user, patient, invoice, delegates)\n }\n\n initEncryptionKeys(user: models.User, invoice: models.Invoice) {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n return this.crypto.initEncryptionKeys(invoice, dataOwnerId!).then((eks) => {\n let promise = Promise.resolve(\n _.extend(invoice, {\n encryptionKeys: eks.encryptionKeys,\n })\n )\n ;(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.financialInformation || []) : []).forEach(\n (delegateId) =>\n (promise = promise.then((invoice) =>\n this.crypto.appendEncryptionKeys(invoice, dataOwnerId!, delegateId, eks.secretId).then((extraEks) => {\n return _.extend(extraEks.modifiedObject, {\n encryptionKeys: extraEks.encryptionKeys,\n })\n })\n ))\n )\n return promise\n })\n }\n\n private initDelegationsAndEncryptionKeys(\n user: models.User,\n patient: models.Patient,\n invoice: models.Invoice,\n delegates: string[] = []\n ): Promise<models.Invoice> {\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n return this.crypto\n .extractDelegationsSFKs(patient, dataOwnerId)\n .then(async (secretForeignKeys) => {\n const sfk = secretForeignKeys.extractedKeys[0]\n if (!sfk) {\n await this.crypto.reportError('Get sfk for Invoice creation', [patient], dataOwnerId!)\n throw new Error(\"Could not find secret foreign key for patient '\" + patient.id + \"'\")\n }\n return Promise.all([\n this.crypto.initObjectDelegations(invoice, patient, dataOwnerId!, sfk),\n this.crypto.initEncryptionKeys(invoice, dataOwnerId!),\n ])\n })\n .then((initData) => {\n const dels = initData[0]\n const eks = initData[1]\n _.extend(invoice, {\n delegations: dels.delegations,\n cryptedForeignKeys: dels.cryptedForeignKeys,\n secretForeignKeys: dels.secretForeignKeys,\n encryptionKeys: eks.encryptionKeys,\n })\n\n let promise = Promise.resolve(invoice)\n _.uniq(\n delegates.concat(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.financialInformation || []) : [])\n ).forEach(\n (delegateId) =>\n (promise = promise.then((invoice) =>\n this.crypto.addDelegationsAndEncryptionKeys(patient, invoice, dataOwnerId!, delegateId, dels.secretId, eks.secretId).catch((e) => {\n console.log(e)\n return invoice\n })\n ))\n )\n return promise\n })\n }\n\n createInvoice(invoice: Invoice, prefix?: string): Promise<Invoice> {\n if (!prefix) {\n return super.createInvoice(invoice)\n }\n if (!invoice.id) {\n invoice.id = this.crypto.randomUuid()\n }\n return this.getNextInvoiceReference(prefix, this.entityrefApi)\n .then((reference) => this.createInvoiceReference(reference, invoice.id!, prefix, this.entityrefApi))\n .then((entityReference) => {\n if (!entityReference.id) {\n throw new Error('Cannot create invoice')\n }\n\n if (invoice.internshipNihii) {\n const ref = entityReference.id.substr(prefix.length).replace('0', '1')\n invoice.invoiceReference = ref\n } else {\n invoice.invoiceReference = entityReference.id.substr(prefix.length)\n }\n return super.createInvoice(invoice)\n })\n }\n\n getNextInvoiceReference(prefix: string, entityrefApi: IccEntityrefApi): Promise<number> {\n return entityrefApi.getLatest(prefix).then((entRef: models.EntityReference) => {\n if (!entRef || !entRef.id || !entRef.id!.startsWith(prefix)) return 1\n const sequenceNumber = entRef.id!.split(':').pop() || 0\n return Number(sequenceNumber) + 1\n })\n }\n\n createInvoiceReference(nextReference: number, docId: string, prefix: string, entityrefApi: IccEntityrefApi): Promise<models.EntityReference> {\n return entityrefApi\n .createEntityReference(\n new models.EntityReference({\n id: prefix + nextReference.toString().padStart(6, '0'),\n docId,\n })\n )\n .catch((err) => {\n console.log(err)\n return this.createInvoiceReference(nextReference + 1, docId, prefix, entityrefApi)\n })\n }\n\n /**\n * 1. Check whether there is a delegation with 'hcpartyId' or not.\n * 2. 'fetchHcParty[hcpartyId][1]': is encrypted AES exchange key by RSA public key of him.\n * 3. Obtain the AES exchange key, by decrypting the previous step value with hcparty private key\n * 3.1. KeyPair should be fetch from cache (in jwk)\n * 3.2. if it doesn't exist in the cache, it has to be loaded from Browser Local store, and then import it to WebCrypto\n * 4. Obtain the array of delegations which are delegated to his ID (hcpartyId) in this patient\n * 5. Decrypt and collect all keys (secretForeignKeys) within delegations of previous step (with obtained AES key of step 4)\n * 6. Do the REST call to get all invoices with (allSecretForeignKeysDelimitedByComa, hcpartyId)\n *\n * After these painful steps, you have the invoices of the patient.\n *\n * @param hcpartyId\n * @param patient (Promise)\n * @param usingPost\n */\n findBy(hcpartyId: string, patient: models.Patient, usingPost: boolean = false): Promise<Array<models.Invoice>> {\n return this.crypto\n .extractDelegationsSFKs(patient, hcpartyId)\n .then((secretForeignKeys) =>\n usingPost\n ? this.findInvoicesByHCPartyPatientForeignKeysUsingPost(secretForeignKeys.hcpartyId!, _.uniq(secretForeignKeys.extractedKeys))\n : this.findInvoicesByHCPartyPatientForeignKeys(secretForeignKeys.hcpartyId!, _.uniq(secretForeignKeys.extractedKeys).join(','))\n )\n .then((invoices) => this.decrypt(hcpartyId, invoices))\n .then(function (decryptedInvoices) {\n return decryptedInvoices\n })\n }\n\n encrypt(user: models.User, invoices: Array<models.Invoice>) {\n return Promise.resolve(invoices)\n }\n\n decrypt(hcpartyId: string, invoices: Array<models.Invoice>): Promise<Array<models.Invoice>> {\n return Promise.resolve(invoices)\n }\n}\n"]}
@@ -1,4 +1,13 @@
1
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
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.IccMessageXApi = void 0;
4
13
  const icc_api_1 = require("../icc-api");
@@ -33,12 +42,14 @@ class IccMessageXApi extends icc_api_1.IccMessageApi {
33
42
  const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user);
34
43
  return this.crypto
35
44
  .extractDelegationsSFKs(patient, dataOwnerId)
36
- .then((secretForeignKeys) => {
45
+ .then((secretForeignKeys) => __awaiter(this, void 0, void 0, function* () {
37
46
  const sfk = secretForeignKeys.extractedKeys[0];
38
- if (!!patient && !sfk)
47
+ if (!!patient && !sfk) {
48
+ yield this.crypto.reportError('Get sfk for Message creation', [patient], dataOwnerId);
39
49
  throw new Error("Could not find secret foreign key for patient '" + patient.id + "'");
50
+ }
40
51
  return this.crypto.initObjectDelegations(message, patient, dataOwnerId, secretForeignKeys.extractedKeys[0]);
41
- })
52
+ }))
42
53
  .then((initData) => {
43
54
  _.extend(message, {
44
55
  delegations: initData.delegations,
@@ -1 +1 @@
1
- {"version":3,"file":"icc-message-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-message-x-api.ts"],"names":[],"mappings":";;;AAAA,wCAA0C;AAG1C,4BAA2B;AAI3B,0EAAgG;AAEhG,MAAa,cAAe,SAAQ,uBAAa;IAG/C,YACE,IAAY,EACZ,OAAkC,EAC1B,MAAqB,EAC7B,YAA8B,EAC9B,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QAT/C,WAAM,GAAN,MAAM,CAAe;QAU7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;IAClC,CAAC;IAED,qCAAq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import * as _ from 'lodash'\n\nimport { Patient, User } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport class IccMessageXApi extends IccMessageApi {\n dataOwnerApi: IccDataOwnerXApi\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private crypto: IccCryptoXApi,\n dataOwnerApi: IccDataOwnerXApi,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.crypto = crypto\n this.dataOwnerApi = dataOwnerApi\n }\n\n // noinspection JSUnusedGlobalSymbols\n newInstance(user: User, m: any) {\n return this.newInstanceWithPatient(user, null, m)\n }\n\n newInstanceWithPatient(user: User, patient: Patient | null, m: any = {}, delegates: string[] = []) {\n const message = _.extend(\n {\n id: this.crypto.randomUuid(),\n _type: 'org.taktik.icure.entities.Message',\n created: new Date().getTime(),\n modified: new Date().getTime(),\n responsible: this.dataOwnerApi.getDataOwnerOf(user),\n author: user.id,\n codes: [],\n tags: [],\n },\n m || {}\n )\n\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n\n return this.crypto\n .extractDelegationsSFKs(patient, dataOwnerId)\n .then((secretForeignKeys) => {\n const sfk = secretForeignKeys.extractedKeys[0]\n if (!!patient && !sfk) throw new Error(\"Could not find secret foreign key for patient '\" + patient.id + \"'\")\n return this.crypto.initObjectDelegations(message, patient, dataOwnerId!, secretForeignKeys.extractedKeys[0])\n })\n .then((initData) => {\n _.extend(message, {\n delegations: initData.delegations,\n cryptedForeignKeys: initData.cryptedForeignKeys,\n secretForeignKeys: initData.secretForeignKeys,\n })\n\n let promise = Promise.resolve(message)\n _.uniq(\n delegates.concat(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.medicalInformation || []) : [])\n ).forEach(\n (delegateId) =>\n (promise = promise.then((helement) =>\n this.crypto\n .extendedDelegationsAndCryptedForeignKeys(helement, patient, dataOwnerId!, delegateId, initData.secretId)\n .then((extraData) =>\n _.extend(helement, {\n delegations: extraData.delegations,\n cryptedForeignKeys: extraData.cryptedForeignKeys,\n })\n )\n .catch((e) => {\n console.log(e)\n return helement\n })\n ))\n )\n return promise\n })\n }\n}\n"]}
1
+ {"version":3,"file":"icc-message-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-message-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wCAA0C;AAG1C,4BAA2B;AAI3B,0EAAgG;AAEhG,MAAa,cAAe,SAAQ,uBAAa;IAG/C,YACE,IAAY,EACZ,OAAkC,EAC1B,MAAqB,EAC7B,YAA8B,EAC9B,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK;QAET,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,CAAC,CAAA;QAT/C,WAAM,GAAN,MAAM,CAAe;QAU7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAA;IAClC,CAAC;IAED,qCAAqC;IACrC,WAAW,CAAC,IAAU,EAAE,CAAM;QAC5B,OAAO,IAAI,CAAC,sBAAsB,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;IACnD,CAAC;IAED,sBAAsB,CAAC,IAAU,EAAE,OAAuB,EAAE,IAAS,EAAE,EAAE,YAAsB,EAAE;QAC/F,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CACtB;YACE,EAAE,EAAE,IAAI,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Q,CAAC,iBAAiB;aAC9C,CAAC,CAAA;YAEF,IAAI,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;YACtC,CAAC,CAAC,IAAI,CACJ,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,kBAAkB,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CACrI,CAAC,OAAO,CACP,CAAC,UAAU,EAAE,EAAE,CACb,CAAC,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CACnC,IAAI,CAAC,MAAM;iBACR,wCAAwC,CAAC,QAAQ,EAAE,OAAO,EAAE,WAAY,EAAE,UAAU,EAAE,QAAQ,CAAC,QAAQ,CAAC;iBACxG,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAClB,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE;gBACjB,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,kBAAkB,EAAE,SAAS,CAAC,kBAAkB;aACjD,CAAC,CACH;iBACA,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;gBACX,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;gBACd,OAAO,QAAQ,CAAA;YACjB,CAAC,CAAC,CACL,CAAC,CACL,CAAA;YACD,OAAO,OAAO,CAAA;QAChB,CAAC,CAAC,CAAA;IACN,CAAC;CACF;AAlFD,wCAkFC","sourcesContent":["import { IccMessageApi } from '../icc-api'\nimport { IccCryptoXApi } from './icc-crypto-x-api'\n\nimport * as _ from 'lodash'\n\nimport { Patient, User } from '../icc-api/model/models'\nimport { IccDataOwnerXApi } from './icc-data-owner-x-api'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport class IccMessageXApi extends IccMessageApi {\n dataOwnerApi: IccDataOwnerXApi\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n private crypto: IccCryptoXApi,\n dataOwnerApi: IccDataOwnerXApi,\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n this.crypto = crypto\n this.dataOwnerApi = dataOwnerApi\n }\n\n // noinspection JSUnusedGlobalSymbols\n newInstance(user: User, m: any) {\n return this.newInstanceWithPatient(user, null, m)\n }\n\n newInstanceWithPatient(user: User, patient: Patient | null, m: any = {}, delegates: string[] = []) {\n const message = _.extend(\n {\n id: this.crypto.randomUuid(),\n _type: 'org.taktik.icure.entities.Message',\n created: new Date().getTime(),\n modified: new Date().getTime(),\n responsible: this.dataOwnerApi.getDataOwnerOf(user),\n author: user.id,\n codes: [],\n tags: [],\n },\n m || {}\n )\n\n const dataOwnerId = this.dataOwnerApi.getDataOwnerOf(user)\n\n return this.crypto\n .extractDelegationsSFKs(patient, dataOwnerId)\n .then(async (secretForeignKeys) => {\n const sfk = secretForeignKeys.extractedKeys[0]\n if (!!patient && !sfk) {\n await this.crypto.reportError('Get sfk for Message creation', [patient], dataOwnerId!)\n throw new Error(\"Could not find secret foreign key for patient '\" + patient.id + \"'\")\n }\n return this.crypto.initObjectDelegations(message, patient, dataOwnerId!, secretForeignKeys.extractedKeys[0])\n })\n .then((initData) => {\n _.extend(message, {\n delegations: initData.delegations,\n cryptedForeignKeys: initData.cryptedForeignKeys,\n secretForeignKeys: initData.secretForeignKeys,\n })\n\n let promise = Promise.resolve(message)\n _.uniq(\n delegates.concat(user.autoDelegations ? (user.autoDelegations.all || []).concat(user.autoDelegations.medicalInformation || []) : [])\n ).forEach(\n (delegateId) =>\n (promise = promise.then((helement) =>\n this.crypto\n .extendedDelegationsAndCryptedForeignKeys(helement, patient, dataOwnerId!, delegateId, initData.secretId)\n .then((extraData) =>\n _.extend(helement, {\n delegations: extraData.delegations,\n cryptedForeignKeys: extraData.cryptedForeignKeys,\n })\n )\n .catch((e) => {\n console.log(e)\n return helement\n })\n ))\n )\n return promise\n })\n }\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import { IccCryptoXApi } from '../icc-crypto-x-api';
2
+ import { EncryptedEntity } from '../../icc-api/model/models';
3
+ export declare class ErrorReporting {
4
+ private readonly crypto;
5
+ constructor(crypto: IccCryptoXApi);
6
+ collectDataForReport(description: string, // Description of what caused the error
7
+ involvedEntities: EncryptedEntity[], // Entities that were being processed when the error occurred
8
+ dataOwnerId: string): Promise<{
9
+ minimalData: object;
10
+ fullData: object;
11
+ }>;
12
+ private collectFullData;
13
+ private collectDataOwnerHierarchy;
14
+ private collectAvailableKeypairsPublic;
15
+ private getDelegators;
16
+ private findEncryptedExchangeKeys;
17
+ private decryptExchangeKeys;
18
+ private decryptDelegations;
19
+ private decryptDelegationLikes;
20
+ }
@@ -0,0 +1,382 @@
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
+ exports.ErrorReporting = void 0;
13
+ const binary_utils_1 = require("./binary-utils");
14
+ var Result;
15
+ (function (Result) {
16
+ class Success {
17
+ constructor(content) {
18
+ this.content = content;
19
+ }
20
+ map(f) {
21
+ return f(this.content).then((x) => new Success(x));
22
+ }
23
+ flatMap(f) {
24
+ return f(this.content);
25
+ }
26
+ mapErrorMsg(f) {
27
+ return this;
28
+ }
29
+ pojo() {
30
+ return this.content;
31
+ }
32
+ getOrElse(defaultValue) {
33
+ return this.content;
34
+ }
35
+ }
36
+ Result.Success = Success;
37
+ class Failure {
38
+ constructor(failedOperation, errorMsg) {
39
+ this.failedOperation = failedOperation;
40
+ this.errorMsg = errorMsg;
41
+ }
42
+ map() {
43
+ return Promise.resolve(this);
44
+ }
45
+ flatMap() {
46
+ return Promise.resolve(this);
47
+ }
48
+ mapErrorMsg(f) {
49
+ return new Failure(this.failedOperation, f(this.errorMsg));
50
+ }
51
+ pojo() {
52
+ return { failedOperation: this.failedOperation, errorMsg: this.errorMsg };
53
+ }
54
+ getOrElse(defaultValue) {
55
+ return defaultValue();
56
+ }
57
+ }
58
+ Result.Failure = Failure;
59
+ function wrap(operation, f) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ try {
62
+ return new Success(yield f());
63
+ }
64
+ catch (e) {
65
+ const errorMsg = e instanceof Error ? e.message : typeof e === 'string' ? e : `Unexpected of type ${typeof e} content ${JSON.stringify(e)}`;
66
+ return new Failure(operation, errorMsg);
67
+ }
68
+ });
69
+ }
70
+ Result.wrap = wrap;
71
+ })(Result || (Result = {}));
72
+ class ErrorReporting {
73
+ constructor(crypto) {
74
+ this.crypto = crypto;
75
+ }
76
+ collectDataForReport(description, // Description of what caused the error
77
+ involvedEntities, // Entities that were being processed when the error occurred
78
+ dataOwnerId // Id of the data owner who was doing the processing when the error occurred
79
+ ) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ const fullData = yield this.collectFullData(description, involvedEntities, dataOwnerId);
82
+ return {
83
+ fullData: yield new FullDataExporter(this.crypto).exportDataToPojo(fullData),
84
+ minimalData: yield new MinimalDataExporter(this.crypto).exportDataToPojo(fullData),
85
+ };
86
+ });
87
+ }
88
+ collectFullData(description, involvedEntities, dataOwnerId) {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ const hierarchy = yield this.collectDataOwnerHierarchy(dataOwnerId);
91
+ const availableKeypairsPublic = yield this.collectAvailableKeypairsPublic();
92
+ const byDataOwner = yield hierarchy.map((hierarchy) => __awaiter(this, void 0, void 0, function* () {
93
+ const res = {};
94
+ for (const currOwner of hierarchy) {
95
+ const delegators = yield this.getDelegators(involvedEntities, currOwner.dataOwner.id);
96
+ const encryptedExchangeKeys = yield this.findEncryptedExchangeKeys(currOwner.dataOwner.id);
97
+ const decryptedExchangeKeys = yield delegators.flatMap((delegators) => __awaiter(this, void 0, void 0, function* () {
98
+ return this.decryptExchangeKeys(currOwner.dataOwner.id, delegators.map((x) => x.dataOwner.id));
99
+ }));
100
+ const decryptedEntitiesMetadata = yield decryptedExchangeKeys.flatMap((xks) => __awaiter(this, void 0, void 0, function* () {
101
+ return yield this.decryptDelegations(xks, involvedEntities, currOwner.dataOwner.id);
102
+ }));
103
+ res[currOwner.dataOwner.id] = {
104
+ delegators,
105
+ encryptedExchangeKeys,
106
+ decryptedExchangeKeys,
107
+ decryptedEntitiesMetadata,
108
+ };
109
+ }
110
+ return res;
111
+ }));
112
+ return {
113
+ description,
114
+ involvedEntities,
115
+ hierarchy,
116
+ availableKeypairsPublic,
117
+ byDataOwner,
118
+ };
119
+ });
120
+ }
121
+ // res[0] -> self, res[1] -> self.parent, ...
122
+ collectDataOwnerHierarchy(startOwnerId) {
123
+ return __awaiter(this, void 0, void 0, function* () {
124
+ return Result.wrap('collectDataOwnerHierarchy', () => __awaiter(this, void 0, void 0, function* () {
125
+ const res = [];
126
+ res.push(yield this.crypto.getDataOwner(startOwnerId, true));
127
+ while (!!res[res.length - 1].dataOwner.parentId) {
128
+ res.push(yield this.crypto.getDataOwner(res[res.length - 1].dataOwner.parentId, true));
129
+ }
130
+ return res;
131
+ }));
132
+ });
133
+ }
134
+ collectAvailableKeypairsPublic() {
135
+ return __awaiter(this, void 0, void 0, function* () {
136
+ return Result.wrap('collectAvailableKeypairsPublic', () => __awaiter(this, void 0, void 0, function* () {
137
+ const res = {};
138
+ for (const [fp, pair] of Object.entries(this.crypto.rsaKeyPairs)) {
139
+ res[fp] = (0, binary_utils_1.ua2hex)(yield this.crypto.RSA.exportKey(pair.publicKey, 'spki'));
140
+ }
141
+ return res;
142
+ }));
143
+ });
144
+ }
145
+ getDelegators(entities, hierarchyMemberId) {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ return Result.wrap('getDelegators', () => __awaiter(this, void 0, void 0, function* () {
148
+ const allDelegationLikes = entities.flatMap((e) => {
149
+ var _a, _b, _c, _d, _e, _f;
150
+ return [
151
+ ...((_b = (_a = e.delegations) === null || _a === void 0 ? void 0 : _a[hierarchyMemberId]) !== null && _b !== void 0 ? _b : []),
152
+ ...((_d = (_c = e.encryptionKeys) === null || _c === void 0 ? void 0 : _c[hierarchyMemberId]) !== null && _d !== void 0 ? _d : []),
153
+ ...((_f = (_e = e.cryptedForeignKeys) === null || _e === void 0 ? void 0 : _e[hierarchyMemberId]) !== null && _f !== void 0 ? _f : []),
154
+ ];
155
+ });
156
+ const ownerIds = new Set(allDelegationLikes.map((d) => d.owner));
157
+ const res = [];
158
+ for (const ownerId of ownerIds) {
159
+ if (!!ownerId)
160
+ res.push(yield this.crypto.getDataOwner(ownerId, true));
161
+ }
162
+ return res;
163
+ }));
164
+ });
165
+ }
166
+ findEncryptedExchangeKeys(hierarchyMemberId) {
167
+ return __awaiter(this, void 0, void 0, function* () {
168
+ return Result.wrap('findEncryptedExchangeKeys', () => this.crypto.getEncryptedAesExchangeKeysForDelegate(hierarchyMemberId));
169
+ });
170
+ }
171
+ decryptExchangeKeys(hierarchyMemberId, delegatorsIds) {
172
+ return __awaiter(this, void 0, void 0, function* () {
173
+ return Result.wrap('decryptExchangeKeys', () => __awaiter(this, void 0, void 0, function* () { return this.crypto.decryptAndImportAesHcPartyKeysForDelegators(delegatorsIds, hierarchyMemberId); }));
174
+ });
175
+ }
176
+ decryptDelegations(keys, entities, hierarchyMemberId) {
177
+ return __awaiter(this, void 0, void 0, function* () {
178
+ return Result.wrap('decryptDelegations', () => __awaiter(this, void 0, void 0, function* () {
179
+ var _a, _b, _c, _d, _e, _f;
180
+ const res = {};
181
+ for (const entity of entities) {
182
+ const delegations = yield this.decryptDelegationLikes(keys, (_b = (_a = entity.delegations) === null || _a === void 0 ? void 0 : _a[hierarchyMemberId]) !== null && _b !== void 0 ? _b : []);
183
+ const encryptionKeys = yield this.decryptDelegationLikes(keys, (_d = (_c = entity.encryptionKeys) === null || _c === void 0 ? void 0 : _c[hierarchyMemberId]) !== null && _d !== void 0 ? _d : []);
184
+ const cryptedForeignKeys = yield this.decryptDelegationLikes(keys, (_f = (_e = entity.cryptedForeignKeys) === null || _e === void 0 ? void 0 : _e[hierarchyMemberId]) !== null && _f !== void 0 ? _f : []);
185
+ res[entity.id] = { delegations, encryptionKeys, cryptedForeignKeys };
186
+ }
187
+ return res;
188
+ }));
189
+ });
190
+ }
191
+ decryptDelegationLikes(keys, delegationLikes) {
192
+ return __awaiter(this, void 0, void 0, function* () {
193
+ const res = {};
194
+ for (const currDelegation of delegationLikes) {
195
+ const currDelegationRes = {};
196
+ for (const currKey of keys) {
197
+ if (currKey.delegatorId == currDelegation.owner) {
198
+ currDelegationRes[currKey.rawKey] = yield Result.wrap('decryptDelegation', () => __awaiter(this, void 0, void 0, function* () {
199
+ const decrypted = yield this.crypto.AES.decrypt(currKey.key, (0, binary_utils_1.hex2ua)(currDelegation.key));
200
+ return (0, binary_utils_1.ua2string)(decrypted);
201
+ }));
202
+ }
203
+ }
204
+ res[currDelegation.key] = currDelegationRes;
205
+ }
206
+ return res;
207
+ });
208
+ }
209
+ }
210
+ exports.ErrorReporting = ErrorReporting;
211
+ class DataExporter {
212
+ constructor(crypto) {
213
+ this.crypto = crypto;
214
+ }
215
+ exportDataToPojo(data) {
216
+ return __awaiter(this, void 0, void 0, function* () {
217
+ /*
218
+ * To make sure we don't leak info we salt sensitive data before hasing it (for example we want to make sure that we are unable to figure out the
219
+ * actual value of a cfk by comparing its hash to the hash of all the ids of patients/messages in the database)
220
+ */
221
+ const salt = this.crypto.randomUuid();
222
+ const errorMsgSubstitutions = yield this.getErrorMsgSubstitutions(data, salt);
223
+ return {
224
+ description: data.description,
225
+ involvedEntities: data.involvedEntities.map((x) => this.encryptedEntityPojo(x)),
226
+ hierarchy: (yield data.hierarchy.map((res) => Promise.resolve(res.map((x) => this.dataOwnerPojo(x)))))
227
+ .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))
228
+ .pojo(),
229
+ availableKeypairsPublic: data.availableKeypairsPublic.mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions)).pojo(),
230
+ byDataOwner: (yield data.byDataOwner.map((byDataOwnerContent) => __awaiter(this, void 0, void 0, function* () {
231
+ const res = {};
232
+ for (const [dataOwnerId, dataOwnerContent] of Object.entries(byDataOwnerContent)) {
233
+ res[dataOwnerId] = {
234
+ delegators: (yield dataOwnerContent.delegators.map((ds) => Promise.resolve(ds.map((d) => this.dataOwnerPojo(d)))))
235
+ .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))
236
+ .pojo(),
237
+ encryptedExchangeKeys: dataOwnerContent.encryptedExchangeKeys
238
+ .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))
239
+ .pojo(),
240
+ decryptedExchangeKeys: (yield dataOwnerContent.decryptedExchangeKeys.map((x) => this.decryptedExchangeKeysPojo(x, salt)))
241
+ .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))
242
+ .pojo(),
243
+ decryptedEntitiesMetadata: (yield dataOwnerContent.decryptedEntitiesMetadata.map((decryptedEntitiesData) => __awaiter(this, void 0, void 0, function* () {
244
+ const currEntityData = {};
245
+ for (const [entityId, entityData] of Object.entries(decryptedEntitiesData)) {
246
+ currEntityData[entityId] = yield this.decryptedEntityInfoPojo(entityData, salt, errorMsgSubstitutions);
247
+ }
248
+ return currEntityData;
249
+ })))
250
+ .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))
251
+ .pojo(),
252
+ };
253
+ }
254
+ return res;
255
+ })))
256
+ .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))
257
+ .pojo(),
258
+ };
259
+ });
260
+ }
261
+ decryptedExchangeKeysPojo(decryptedExchangeKeys, hashingSalt) {
262
+ return __awaiter(this, void 0, void 0, function* () {
263
+ const res = [];
264
+ for (const d of decryptedExchangeKeys) {
265
+ res.push({
266
+ delegatorId: d.delegatorId,
267
+ keyInfo: yield this.processRawSecretToExtendedInfo(d.rawKey, hashingSalt),
268
+ });
269
+ }
270
+ return res;
271
+ });
272
+ }
273
+ decryptedEntityInfoPojo(data, salt, errorMsgSubstitutions) {
274
+ return __awaiter(this, void 0, void 0, function* () {
275
+ return {
276
+ delegations: yield this.decryptedDelegationInfoPojo(data.delegations, salt, errorMsgSubstitutions),
277
+ encryptionKeys: yield this.decryptedDelegationInfoPojo(data.encryptionKeys, salt, errorMsgSubstitutions),
278
+ cryptedForeignKeys: yield this.decryptedDelegationInfoPojo(data.cryptedForeignKeys, salt, errorMsgSubstitutions),
279
+ };
280
+ });
281
+ }
282
+ decryptedDelegationInfoPojo(data, salt, errorMsgSubstitutions) {
283
+ return __awaiter(this, void 0, void 0, function* () {
284
+ const res = {};
285
+ for (const [encryptedDelegationKey, rawKeys] of Object.entries(data)) {
286
+ const currRawKeys = {};
287
+ for (const [rawKey, result] of Object.entries(rawKeys)) {
288
+ currRawKeys[yield this.processRawSecretToString(rawKey, salt)] = (yield result.map((x) => this.processRawSecretToExtendedInfo(x, salt)))
289
+ .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))
290
+ .pojo();
291
+ }
292
+ res[encryptedDelegationKey] = currRawKeys;
293
+ }
294
+ return res;
295
+ });
296
+ }
297
+ applyErrorMsgSubstitutions(msg, substitutions) {
298
+ let res = msg;
299
+ for (const [key, value] of Object.entries(substitutions)) {
300
+ res = res.split(key).join(value); // Replace all
301
+ }
302
+ return res;
303
+ }
304
+ }
305
+ class FullDataExporter extends DataExporter {
306
+ constructor(crypto) {
307
+ super(crypto);
308
+ }
309
+ dataOwnerPojo(dataOwner) {
310
+ return dataOwner;
311
+ }
312
+ encryptedEntityPojo(entity) {
313
+ return entity;
314
+ }
315
+ processRawSecretToExtendedInfo(rawSecret, salt) {
316
+ return Promise.resolve(rawSecret);
317
+ }
318
+ processRawSecretToString(rawSecret, salt) {
319
+ return Promise.resolve(rawSecret);
320
+ }
321
+ getErrorMsgSubstitutions(data, salt) {
322
+ return Promise.resolve({});
323
+ }
324
+ }
325
+ class MinimalDataExporter extends DataExporter {
326
+ constructor(crypto) {
327
+ super(crypto);
328
+ }
329
+ dataOwnerPojo(dataOwner) {
330
+ return {
331
+ id: dataOwner.dataOwner.id,
332
+ rev: dataOwner.dataOwner.rev,
333
+ type: dataOwner.type,
334
+ publicKey: dataOwner.dataOwner.publicKey,
335
+ aesExchangeKeys: dataOwner.dataOwner.aesExchangeKeys,
336
+ hcPartyKeys: dataOwner.dataOwner.hcPartyKeys,
337
+ };
338
+ }
339
+ encryptedEntityPojo(entity) {
340
+ return {
341
+ id: entity.id,
342
+ rev: entity.rev,
343
+ delegations: entity.delegations,
344
+ cryptedForeignKeys: entity.cryptedForeignKeys,
345
+ encryptionKeys: entity.encryptionKeys,
346
+ secretForeignKeys: entity.secretForeignKeys,
347
+ };
348
+ }
349
+ processRawSecretToExtendedInfo(rawSecret, salt) {
350
+ return __awaiter(this, void 0, void 0, function* () {
351
+ return Object.assign(Object.assign({ hashedValue: yield this.hashWithSalt(rawSecret, salt) }, this.analyseRawSecret(rawSecret)), { byColumnSeparatedPiece: rawSecret.includes(':') ? rawSecret.split(':').map((x) => this.analyseRawSecret(x)) : undefined });
352
+ });
353
+ }
354
+ analyseRawSecret(rawSecret) {
355
+ return {
356
+ length: rawSecret.length,
357
+ isUuid: !!rawSecret.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/),
358
+ isSameCaseHex: !!rawSecret.match(/^[0-9a-f]+$/) || !!rawSecret.match(/^[0-9A-F]+$/),
359
+ isMixedCaseHex: !!rawSecret.match(/^[0-9a-fA-F]+$/),
360
+ };
361
+ }
362
+ processRawSecretToString(rawSecret, salt) {
363
+ return this.hashWithSalt(rawSecret, salt);
364
+ }
365
+ hashWithSalt(data, hashingSalt) {
366
+ return __awaiter(this, void 0, void 0, function* () {
367
+ return (0, binary_utils_1.ua2hex)(yield this.crypto.sha256((0, binary_utils_1.string2ua)(data + hashingSalt)));
368
+ });
369
+ }
370
+ getErrorMsgSubstitutions(data, salt) {
371
+ return __awaiter(this, void 0, void 0, function* () {
372
+ const res = {};
373
+ for (const infoOfCurrentDataOnwer of Object.values(data.byDataOwner.getOrElse(() => ({})))) {
374
+ for (const key of infoOfCurrentDataOnwer.decryptedExchangeKeys.getOrElse(() => [])) {
375
+ res[key.rawKey] = 'hashedRawKey-' + (yield this.hashWithSalt(key.delegatorId, salt));
376
+ }
377
+ }
378
+ return res;
379
+ });
380
+ }
381
+ }
382
+ //# sourceMappingURL=error-reporting.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-reporting.js","sourceRoot":"","sources":["../../../icc-x-api/utils/error-reporting.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,iDAAqE;AASrE,IAAU,MAAM,CAyDf;AAzDD,WAAU,MAAM;IACd,MAAa,OAAO;QAClB,YAA6B,OAAU;YAAV,YAAO,GAAP,OAAO,CAAG;QAAG,CAAC;QAE3C,GAAG,CAAI,CAA6B;YAClC,OAAO,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAA;QACpD,CAAC;QAED,OAAO,CAAI,CAAqC;YAC9C,OAAO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AI,sBAAsB,CAAC,qBAAqB,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE;oBAClF,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,eAAe,GAAG,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,WAAW,EAAE,IAAI,CAAC,CAAC,CAAA;iBACrF;aACF;YACD,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF","sourcesContent":["import { CachedDataOwner, DelegatorAndKeys, IccCryptoXApi } from '../icc-crypto-x-api'\nimport { Delegation, EncryptedEntity } from '../../icc-api/model/models'\nimport { hex2ua, string2ua, ua2hex, ua2string } from './binary-utils'\n\ninterface Result<A> {\n map<B>(f: (content: A) => Promise<B>): Promise<Result<B>>\n mapErrorMsg(f: (errorMsg: string) => string): Result<A>\n flatMap<B>(f: (content: A) => Promise<Result<B>>): Promise<Result<B>>\n pojo(): any\n getOrElse(defaultValue: () => A): A\n}\nnamespace Result {\n export class Success<A> implements Result<A> {\n constructor(private readonly content: A) {}\n\n map<B>(f: (content: A) => Promise<B>): Promise<Result<B>> {\n return f(this.content).then((x) => new Success(x))\n }\n\n flatMap<B>(f: (content: A) => Promise<Result<B>>): Promise<Result<B>> {\n return f(this.content)\n }\n\n mapErrorMsg(f: (errorMsg: string) => string): Result<A> {\n return this\n }\n\n pojo(): any {\n return this.content\n }\n\n getOrElse(defaultValue: () => A): A {\n return this.content\n }\n }\n\n export class Failure implements Result<never> {\n constructor(private readonly failedOperation: string, private readonly errorMsg: string) {}\n\n map<B>(): Promise<Result<B>> {\n return Promise.resolve(this)\n }\n\n flatMap<B>(): Promise<Result<B>> {\n return Promise.resolve(this)\n }\n\n mapErrorMsg(f: (errorMsg: string) => string): Result<never> {\n return new Failure(this.failedOperation, f(this.errorMsg))\n }\n\n pojo(): any {\n return { failedOperation: this.failedOperation, errorMsg: this.errorMsg }\n }\n\n getOrElse(defaultValue: () => never): never {\n return defaultValue()\n }\n }\n\n export async function wrap<A>(operation: string, f: () => Promise<A>): Promise<Result<A>> {\n try {\n return new Success(await f())\n } catch (e) {\n const errorMsg = e instanceof Error ? e.message : typeof e === 'string' ? e : `Unexpected of type ${typeof e} content ${JSON.stringify(e)}`\n return new Failure(operation, errorMsg)\n }\n }\n}\n\ntype DecryptedDelegationInfo = { [encryptedDelegationKey: string]: { [rawKey: string]: Result<string> } } // rawKey: exchangeKey used in the decryption\n\ntype DecryptedEntityInfo = {\n delegations: DecryptedDelegationInfo\n encryptionKeys: DecryptedDelegationInfo\n cryptedForeignKeys: DecryptedDelegationInfo\n}\n\ntype EncryptedExchangeKeys = { [delegator: string]: { [mainXkDelegatorPubFp: string]: { [xkEncryptionPubFp: string]: string /*encryptedXkByKey*/ } } }\n\ntype ByDataOwnerData = {\n delegators: Result<CachedDataOwner[]>\n encryptedExchangeKeys: Result<EncryptedExchangeKeys> // As retrieved using the view: may differ from data retrieved by delegators\n decryptedExchangeKeys: Result<DelegatorAndKeys[]>\n decryptedEntitiesMetadata: Result<{ [entityId: string]: DecryptedEntityInfo }>\n}\n\ntype FullData = {\n description: string\n involvedEntities: EncryptedEntity[]\n hierarchy: Result<CachedDataOwner[]>\n availableKeypairsPublic: Result<{ [fp: string]: string }>\n byDataOwner: Result<{\n [dataOwnerId: string]: ByDataOwnerData\n }>\n}\n\nexport class ErrorReporting {\n constructor(private readonly crypto: IccCryptoXApi) {}\n\n async collectDataForReport(\n description: string, // Description of what caused the error\n involvedEntities: EncryptedEntity[], // Entities that were being processed when the error occurred\n dataOwnerId: string // Id of the data owner who was doing the processing when the error occurred\n ): Promise<{\n minimalData: object // Does not contain any sensitive data\n fullData: object // May contain sensitive data, we should not ask for it unless desperate\n }> {\n const fullData = await this.collectFullData(description, involvedEntities, dataOwnerId)\n return {\n fullData: await new FullDataExporter(this.crypto).exportDataToPojo(fullData),\n minimalData: await new MinimalDataExporter(this.crypto).exportDataToPojo(fullData),\n }\n }\n\n private async collectFullData(description: string, involvedEntities: EncryptedEntity[], dataOwnerId: string): Promise<FullData> {\n const hierarchy = await this.collectDataOwnerHierarchy(dataOwnerId)\n const availableKeypairsPublic = await this.collectAvailableKeypairsPublic()\n const byDataOwner = await hierarchy.map(async (hierarchy) => {\n const res = {} as { [dataOwnerId: string]: ByDataOwnerData }\n for (const currOwner of hierarchy) {\n const delegators = await this.getDelegators(involvedEntities, currOwner.dataOwner.id!)\n const encryptedExchangeKeys = await this.findEncryptedExchangeKeys(currOwner.dataOwner.id!)\n const decryptedExchangeKeys = await delegators.flatMap(async (delegators) => {\n return this.decryptExchangeKeys(\n currOwner.dataOwner.id!,\n delegators.map((x) => x.dataOwner.id!)\n )\n })\n const decryptedEntitiesMetadata = await decryptedExchangeKeys.flatMap(async (xks) => {\n return await this.decryptDelegations(xks, involvedEntities, currOwner.dataOwner.id!)\n })\n res[currOwner.dataOwner.id!] = {\n delegators,\n encryptedExchangeKeys,\n decryptedExchangeKeys,\n decryptedEntitiesMetadata,\n }\n }\n return res\n })\n return {\n description,\n involvedEntities,\n hierarchy,\n availableKeypairsPublic,\n byDataOwner,\n }\n }\n\n // res[0] -> self, res[1] -> self.parent, ...\n private async collectDataOwnerHierarchy(startOwnerId: string): Promise<Result<CachedDataOwner[]>> {\n return Result.wrap('collectDataOwnerHierarchy', async () => {\n const res = []\n res.push(await this.crypto.getDataOwner(startOwnerId, true))\n while (!!(res[res.length - 1].dataOwner as any).parentId) {\n res.push(await this.crypto.getDataOwner((res[res.length - 1].dataOwner as any).parentId, true))\n }\n return res\n })\n }\n\n private async collectAvailableKeypairsPublic(): Promise<Result<{ [fp: string]: string }>> {\n return Result.wrap('collectAvailableKeypairsPublic', async () => {\n const res = {} as { [fp: string]: string }\n for (const [fp, pair] of Object.entries(this.crypto.rsaKeyPairs)) {\n res[fp] = ua2hex(await this.crypto.RSA.exportKey(pair.publicKey, 'spki'))\n }\n return res\n })\n }\n\n private async getDelegators(entities: EncryptedEntity[], hierarchyMemberId: string): Promise<Result<CachedDataOwner[]>> {\n return Result.wrap('getDelegators', async () => {\n const allDelegationLikes = entities.flatMap((e) => [\n ...(e.delegations?.[hierarchyMemberId] ?? []),\n ...(e.encryptionKeys?.[hierarchyMemberId] ?? []),\n ...(e.cryptedForeignKeys?.[hierarchyMemberId] ?? []),\n ])\n const ownerIds = new Set(allDelegationLikes.map((d) => d.owner))\n const res = []\n for (const ownerId of ownerIds) {\n if (!!ownerId) res.push(await this.crypto.getDataOwner(ownerId, true))\n }\n return res\n })\n }\n\n private async findEncryptedExchangeKeys(hierarchyMemberId: string): Promise<Result<EncryptedExchangeKeys>> {\n return Result.wrap('findEncryptedExchangeKeys', () => this.crypto.getEncryptedAesExchangeKeysForDelegate(hierarchyMemberId))\n }\n\n private async decryptExchangeKeys(hierarchyMemberId: string, delegatorsIds: string[]): Promise<Result<DelegatorAndKeys[]>> {\n return Result.wrap('decryptExchangeKeys', async () => this.crypto.decryptAndImportAesHcPartyKeysForDelegators(delegatorsIds, hierarchyMemberId))\n }\n\n private async decryptDelegations(keys: DelegatorAndKeys[], entities: EncryptedEntity[], hierarchyMemberId: string) {\n return Result.wrap('decryptDelegations', async () => {\n const res = {} as { [entityId: string]: DecryptedEntityInfo }\n for (const entity of entities) {\n const delegations = await this.decryptDelegationLikes(keys, entity.delegations?.[hierarchyMemberId] ?? [])\n const encryptionKeys = await this.decryptDelegationLikes(keys, entity.encryptionKeys?.[hierarchyMemberId] ?? [])\n const cryptedForeignKeys = await this.decryptDelegationLikes(keys, entity.cryptedForeignKeys?.[hierarchyMemberId] ?? [])\n res[entity.id!] = { delegations, encryptionKeys, cryptedForeignKeys }\n }\n return res\n })\n }\n\n private async decryptDelegationLikes(keys: DelegatorAndKeys[], delegationLikes: Delegation[]): Promise<DecryptedDelegationInfo> {\n const res = {} as DecryptedDelegationInfo\n for (const currDelegation of delegationLikes) {\n const currDelegationRes = {} as { [rawKey: string]: Result<string> }\n for (const currKey of keys) {\n if (currKey.delegatorId == currDelegation.owner) {\n currDelegationRes[currKey.rawKey] = await Result.wrap('decryptDelegation', async () => {\n const decrypted = await this.crypto.AES.decrypt(currKey.key, hex2ua(currDelegation.key!))\n return ua2string(decrypted)\n })\n }\n }\n res[currDelegation.key!] = currDelegationRes\n }\n return res\n }\n}\n\nabstract class DataExporter {\n protected constructor(protected readonly crypto: IccCryptoXApi) {}\n\n async exportDataToPojo(data: FullData): Promise<object> {\n /*\n * To make sure we don't leak info we salt sensitive data before hasing it (for example we want to make sure that we are unable to figure out the\n * actual value of a cfk by comparing its hash to the hash of all the ids of patients/messages in the database)\n */\n const salt = this.crypto.randomUuid()\n const errorMsgSubstitutions = await this.getErrorMsgSubstitutions(data, salt)\n return {\n description: data.description,\n involvedEntities: data.involvedEntities.map((x) => this.encryptedEntityPojo(x)),\n hierarchy: (await data.hierarchy.map((res) => Promise.resolve(res.map((x) => this.dataOwnerPojo(x)))))\n .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))\n .pojo(),\n availableKeypairsPublic: data.availableKeypairsPublic.mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions)).pojo(),\n byDataOwner: (\n await data.byDataOwner.map(async (byDataOwnerContent) => {\n const res = {} as { [dataOwnerId: string]: object }\n for (const [dataOwnerId, dataOwnerContent] of Object.entries(byDataOwnerContent)) {\n res[dataOwnerId] = {\n delegators: (await dataOwnerContent.delegators.map((ds) => Promise.resolve(ds.map((d) => this.dataOwnerPojo(d)))))\n .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))\n .pojo(),\n encryptedExchangeKeys: dataOwnerContent.encryptedExchangeKeys\n .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))\n .pojo(),\n decryptedExchangeKeys: (await dataOwnerContent.decryptedExchangeKeys.map((x) => this.decryptedExchangeKeysPojo(x, salt)))\n .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))\n .pojo(),\n decryptedEntitiesMetadata: (\n await dataOwnerContent.decryptedEntitiesMetadata.map(async (decryptedEntitiesData) => {\n const currEntityData = {} as { [entityId: string]: object }\n for (const [entityId, entityData] of Object.entries(decryptedEntitiesData)) {\n currEntityData[entityId] = await this.decryptedEntityInfoPojo(entityData, salt, errorMsgSubstitutions)\n }\n return currEntityData\n })\n )\n .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))\n .pojo(),\n }\n }\n return res\n })\n )\n .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))\n .pojo(),\n }\n }\n\n protected abstract getErrorMsgSubstitutions(data: FullData, salt: string): Promise<{ [key: string]: string }>\n protected abstract encryptedEntityPojo(entity: EncryptedEntity): object\n protected abstract dataOwnerPojo(dataOwner: CachedDataOwner): object\n protected async decryptedExchangeKeysPojo(decryptedExchangeKeys: DelegatorAndKeys[], hashingSalt: string): Promise<object> {\n const res = []\n for (const d of decryptedExchangeKeys) {\n res.push({\n delegatorId: d.delegatorId,\n keyInfo: await this.processRawSecretToExtendedInfo(d.rawKey, hashingSalt),\n })\n }\n return res\n }\n private async decryptedEntityInfoPojo(data: DecryptedEntityInfo, salt: string, errorMsgSubstitutions: { [key: string]: string }): Promise<object> {\n return {\n delegations: await this.decryptedDelegationInfoPojo(data.delegations, salt, errorMsgSubstitutions),\n encryptionKeys: await this.decryptedDelegationInfoPojo(data.encryptionKeys, salt, errorMsgSubstitutions),\n cryptedForeignKeys: await this.decryptedDelegationInfoPojo(data.cryptedForeignKeys, salt, errorMsgSubstitutions),\n }\n }\n private async decryptedDelegationInfoPojo(\n data: DecryptedDelegationInfo,\n salt: string,\n errorMsgSubstitutions: { [key: string]: string }\n ): Promise<object> {\n const res = {} as { [encryptedDelegationKey: string]: object }\n for (const [encryptedDelegationKey, rawKeys] of Object.entries(data)) {\n const currRawKeys = {} as { [rawKey: string]: object }\n for (const [rawKey, result] of Object.entries(rawKeys)) {\n currRawKeys[await this.processRawSecretToString(rawKey, salt)] = (await result.map((x) => this.processRawSecretToExtendedInfo(x, salt)))\n .mapErrorMsg((x) => this.applyErrorMsgSubstitutions(x, errorMsgSubstitutions))\n .pojo()\n }\n res[encryptedDelegationKey] = currRawKeys\n }\n return res\n }\n protected abstract processRawSecretToString(rawSecret: string, salt: string): Promise<string>\n protected abstract processRawSecretToExtendedInfo(rawSecret: string, salt: string): Promise<any>\n\n private applyErrorMsgSubstitutions(msg: string, substitutions: { [key: string]: string }): string {\n let res = msg\n for (const [key, value] of Object.entries(substitutions)) {\n res = res.split(key).join(value) // Replace all\n }\n return res\n }\n}\n\nclass FullDataExporter extends DataExporter {\n constructor(crypto: IccCryptoXApi) {\n super(crypto)\n }\n\n protected dataOwnerPojo(dataOwner: CachedDataOwner): object {\n return dataOwner\n }\n\n protected encryptedEntityPojo(entity: EncryptedEntity): object {\n return entity\n }\n\n protected processRawSecretToExtendedInfo(rawSecret: string, salt: string): Promise<any> {\n return Promise.resolve(rawSecret)\n }\n\n protected processRawSecretToString(rawSecret: string, salt: string): Promise<string> {\n return Promise.resolve(rawSecret)\n }\n\n protected getErrorMsgSubstitutions(data: FullData, salt: string): Promise<{ [p: string]: string }> {\n return Promise.resolve({})\n }\n}\n\nclass MinimalDataExporter extends DataExporter {\n constructor(crypto: IccCryptoXApi) {\n super(crypto)\n }\n\n protected dataOwnerPojo(dataOwner: CachedDataOwner): object {\n return {\n id: dataOwner.dataOwner.id,\n rev: dataOwner.dataOwner.rev,\n type: dataOwner.type,\n publicKey: dataOwner.dataOwner.publicKey,\n aesExchangeKeys: dataOwner.dataOwner.aesExchangeKeys,\n hcPartyKeys: dataOwner.dataOwner.hcPartyKeys,\n }\n }\n\n protected encryptedEntityPojo(entity: EncryptedEntity): object {\n return {\n id: entity.id,\n rev: entity.rev,\n delegations: entity.delegations,\n cryptedForeignKeys: entity.cryptedForeignKeys,\n encryptionKeys: entity.encryptionKeys,\n secretForeignKeys: entity.secretForeignKeys,\n }\n }\n\n protected async processRawSecretToExtendedInfo(rawSecret: string, salt: string): Promise<any> {\n return {\n hashedValue: await this.hashWithSalt(rawSecret, salt),\n ...this.analyseRawSecret(rawSecret),\n byColumnSeparatedPiece: rawSecret.includes(':') ? rawSecret.split(':').map((x) => this.analyseRawSecret(x)) : undefined,\n }\n }\n\n private analyseRawSecret(rawSecret: string): object {\n return {\n length: rawSecret.length,\n isUuid: !!rawSecret.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/),\n isSameCaseHex: !!rawSecret.match(/^[0-9a-f]+$/) || !!rawSecret.match(/^[0-9A-F]+$/),\n isMixedCaseHex: !!rawSecret.match(/^[0-9a-fA-F]+$/),\n }\n }\n\n protected processRawSecretToString(rawSecret: string, salt: string): Promise<string> {\n return this.hashWithSalt(rawSecret, salt)\n }\n\n private async hashWithSalt(data: string, hashingSalt: string): Promise<string> {\n return ua2hex(await this.crypto.sha256(string2ua(data + hashingSalt)))\n }\n\n protected async getErrorMsgSubstitutions(data: FullData, salt: string): Promise<{ [p: string]: string }> {\n const res: { [p: string]: string } = {}\n for (const infoOfCurrentDataOnwer of Object.values(data.byDataOwner.getOrElse(() => ({})))) {\n for (const key of infoOfCurrentDataOnwer.decryptedExchangeKeys.getOrElse(() => [])) {\n res[key.rawKey] = 'hashedRawKey-' + (await this.hashWithSalt(key.delegatorId, salt))\n }\n }\n return res\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icure/api",
3
- "version": "5.2.38",
3
+ "version": "5.3.1",
4
4
  "description": "Typescript version of iCure standalone API client",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",