@icure/api 8.2.0 → 8.2.2
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/api/IccBekmehrApi.js +2 -1
- package/icc-api/api/IccBekmehrApi.js.map +1 -1
- package/icc-api/api/IccBesamv2Api.js +2 -1
- package/icc-api/api/IccBesamv2Api.js.map +1 -1
- package/icc-api/model/RouteOfAdministration.d.ts +1 -0
- package/icc-api/model/RouteOfAdministration.js.map +1 -1
- package/icc-api/model/Vmp.d.ts +2 -0
- package/icc-api/model/Vmp.js.map +1 -1
- package/icc-api/model/VmpGroup.d.ts +2 -0
- package/icc-api/model/VmpGroup.js.map +1 -1
- package/icc-x-api/crypto/ExchangeKeysManager.d.ts +1 -1
- package/icc-x-api/crypto/ExchangeKeysManager.js +1 -3
- package/icc-x-api/crypto/ExchangeKeysManager.js.map +1 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.d.ts +2 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js +14 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
- package/icc-x-api/icc-bekmehr-x-api.js +1 -1
- package/icc-x-api/icc-bekmehr-x-api.js.map +1 -1
- package/icc-x-api/index.js +2 -3
- package/icc-x-api/index.js.map +1 -1
- package/icc-x-api/utils/proxy-utils.d.ts +2 -0
- package/icc-x-api/utils/proxy-utils.js +24 -0
- package/icc-x-api/utils/proxy-utils.js.map +1 -0
- package/icc-x-api/utils/websocket.d.ts +0 -1
- package/package.json +1 -1
- package/test/utils/FakeEncryptionKeysManager.js +1 -1
- package/test/utils/FakeEncryptionKeysManager.js.map +1 -1
|
@@ -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;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,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;AAvZD,8DAuZC","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 ) {}\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 for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\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 (const keyData of keysData) {\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 const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\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 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(dataOwner: DataOwnerWithType): 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\n ) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\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,EAAE,CAAA;YACxB,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,+BAA+B,EAAE,CAAA;YAC3E,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,MAAM,GAA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AAC,SAAS,CAAC,CAAC,MAAM;gBAC7G,sBAAsB,CAAC,MAAM,GAAG,CAAC,EACjC;gBACA,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,SAAS,EAAE,IAAI,CAAC,sBAAsB,CAAC,UAAU,CAAC,CAAC,CAAA;gBACxG,KAAK,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;oBACtD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAA;iBAC3C;aACF;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;AAnaD,8DAmaC","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 for (const dowt of this.initialiseParentKeys ? hierarchy : [self]) {\n const availableKeys = await this.loadAndRecoverKeysFor(dowt)\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 (const keyData of keysData) {\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 const additionallyRecovered = await this.recoverAndCacheKeys(keyData.dowt, this.plainKeysByFingerprint(keysWithExternallyRecovered))\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(dataOwner: DataOwnerWithType): 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\n ) {\n const recoveredKeys = await this.recoverAndCacheKeys(dataOwner, this.plainKeysByFingerprint(loadedKeys))\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"]}
|
|
@@ -58,7 +58,7 @@ class IccBekmehrXApi extends icc_api_1.IccBekmehrApi {
|
|
|
58
58
|
const that = this;
|
|
59
59
|
const send = (command, uuid, body) => {
|
|
60
60
|
const data = JSON.stringify({ command, uuid, body });
|
|
61
|
-
socket.send(data.length > 65000 ? (0, binary_utils_1.
|
|
61
|
+
socket.send(data.length > 65000 ? (0, binary_utils_1.utf8_2ua)(data).buffer : data);
|
|
62
62
|
};
|
|
63
63
|
const messageHandler = (msg, event) => {
|
|
64
64
|
if (msg.command === 'decrypt') {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icc-bekmehr-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-bekmehr-x-api.ts"],"names":[],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BAC9B,MAAM,CAAC,IAAI,CACT,IAAI,CAAC,SAAS,CAAC;oBACb,UAAU,EAAE;wBACV,SAAS,EAAE,SAAS;wBACpB,QAAQ,EAAE,QAAQ;wBAClB,aAAa,EAAE,aAAa;wBAC5B,OAAO,EAAE,OAAO;wBAChB,IAAI,EAAE,IAAI;qBACX;iBACF,CAAC,CACH,CAAA;YACH,CAAC,CAAC,CAAA;YACF,sBAAsB;YACtB,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,mBAAmB,CAAC,MAAM,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;QACpH,CAAC,CAAC,CACL,CAAA;IACH,CAAC;CACF;AApRD,wCAoRC","sourcesContent":["import * as models from '../icc-api/model/models'\nimport { IccBekmehrApi } from '../icc-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { string2ua, ua2string } from './utils/binary-utils'\nimport { Contact, Document, HealthElement, Service } from '../icc-api/model/models'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport type Patcher = ContactPatcher | HealthElementPatcher | DocumentPatcher | ServicePatcher\nexport interface ContactPatcher {\n type: 'ContactDto'\n patch: (contacts: Contact[]) => Promise<Contact[]>\n}\nexport interface HealthElementPatcher {\n type: 'HealthElementDto'\n patch: (patients: HealthElement[]) => Promise<HealthElement[]>\n}\nexport interface DocumentPatcher {\n type: 'DocumentDto'\n patch: (documents: Document[]) => Promise<Document[]>\n}\nexport interface ServicePatcher {\n type: 'ServiceDto'\n patch: (documents: Service[]) => Promise<Service[]>\n}\n\nexport class IccBekmehrXApi extends IccBekmehrApi {\n private readonly ctcApi: IccContactXApi\n private readonly helementApi: IccHelementXApi\n private readonly documentApi: IccDocumentXApi\n private readonly wssHost: string\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n ctcApi: IccContactXApi,\n helementApi: IccHelementXApi,\n documentApi: IccDocumentXApi,\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.ctcApi = ctcApi\n this.helementApi = helementApi\n this.documentApi = documentApi\n\n this.wssHost = new URL(this.host, typeof window !== 'undefined' ? window.location.href : undefined).href\n .replace(/^http/, 'ws')\n .replace(/\\/rest\\/v.+/, '/ws')\n }\n\n private async getJwt(): Promise<string> {\n const authService = this.authenticationProvider.getAuthService()\n if (!!authService.jwtGetter) {\n const tokens = await authService.jwtGetter()\n if (!tokens) {\n throw new Error('Missing JWT')\n }\n return tokens.token\n } else {\n throw new Error('The existing provider is not a JWT provider')\n }\n }\n\n socketEventListener(\n socket: WebSocket,\n healthcarePartyId: string,\n resolve: (value: Blob) => void,\n reject: (reason?: any) => void,\n patchers: Patcher[],\n progressCallback?: (progress: number) => void\n ) {\n const that = this\n\n const send = (command: string, uuid: string, body: any) => {\n const data = JSON.stringify({ command, uuid, body })\n socket.send(data.length > 65000 ? string2ua(data).buffer : data)\n }\n\n const messageHandler = (msg: any, event: any) => {\n if (msg.command === 'decrypt') {\n if (msg.type === 'ContactDto') {\n that.ctcApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ContactDto')\n .reduce(async (p, patcher) => (patcher as ContactPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'HealthElementDto') {\n that.helementApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'HealthElementDto')\n .reduce(async (p, patcher) => (patcher as HealthElementPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'DocumentDto') {\n that.documentApi\n .decrypt(\n healthcarePartyId,\n msg.body.map((d: JSON) => new Document(d))\n )\n .then((res) =>\n patchers\n .filter((p) => p.type === 'DocumentDto')\n .reduce(async (p, patcher) => (patcher as DocumentPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) =>\n send(\n 'decryptResponse',\n msg.uuid,\n res?.map((d) => {\n const de = d.decryptedAttachment\n const { encryptedAttachment, ...stripped } = d\n return de ? { ...stripped, decryptedAttachment: btoa(ua2string(de)) } : stripped\n })\n )\n )\n } else if (msg.type === 'ServiceDto') {\n that.ctcApi\n .decryptServices(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ServiceDto')\n .reduce(async (p, patcher) => (patcher as ServicePatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n }\n } else if (msg.command === 'progress') {\n if (progressCallback && msg.body && msg.body[0]) {\n progressCallback(msg.body[0].progress)\n }\n } else {\n console.error('error received from backend:' + event.data)\n reject('websocket error: ' + event.data)\n socket.close(4000, 'backend error')\n }\n }\n\n return (event: MessageEvent) => {\n if (typeof event.data === 'string') {\n const msg = JSON.parse(event.data)\n messageHandler(msg, event)\n } else {\n const blob: Blob = event.data\n const subBlob = blob.slice(0, 1)\n const br = new FileReader()\n br.onload = function (e) {\n const firstChar = e.target && new Uint8Array((e.target as any).result as ArrayBuffer)[0]\n\n if (firstChar === 0x7b) {\n const tr = new FileReader()\n tr.onload = function (e) {\n const msg = e.target && JSON.parse((e.target as any).result as string)\n messageHandler(msg, event)\n }\n tr.readAsBinaryString(blob)\n } else {\n resolve(blob)\n socket.close(1000, 'Ok')\n }\n }\n br.readAsArrayBuffer(subBlob)\n }\n }\n }\n\n generateSmfExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SoftwareMedicalFileExport,\n progressCallback?: (progress: number) => void,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSmf?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers, progressCallback))\n })\n )\n }\n\n generateSumehrExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehr?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateSumehrV2ExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehrV2?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateDiaryNoteExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateDiaryNote?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateMedicationSchemeWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n recipientSafe: string,\n version: number,\n body: models.MedicationSchemeExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateMedicationScheme?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: {\n patientId: patientId,\n language: language,\n recipientSafe: recipientSafe,\n version: version,\n info: body,\n },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"icc-bekmehr-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-bekmehr-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AACA,wCAA0C;AAI1C,uDAA0D;AAC1D,oDAAmF;AACnF,0EAAgG;AAoBhG,MAAa,cAAe,SAAQ,uBAAa;IAM/C,YACE,IAAY,EACZ,OAAkC,EAClC,MAAsB,EACtB,WAA4B,EAC5B,WAA4B,EAC5B,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,CAA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Content":["import * as models from '../icc-api/model/models'\nimport { IccBekmehrApi } from '../icc-api'\nimport { IccContactXApi } from './icc-contact-x-api'\nimport { IccDocumentXApi } from './icc-document-x-api'\nimport { IccHelementXApi } from './icc-helement-x-api'\nimport { ua2string, utf8_2ua } from './utils/binary-utils'\nimport { Contact, Document, HealthElement, Service } from '../icc-api/model/models'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\n\nexport type Patcher = ContactPatcher | HealthElementPatcher | DocumentPatcher | ServicePatcher\nexport interface ContactPatcher {\n type: 'ContactDto'\n patch: (contacts: Contact[]) => Promise<Contact[]>\n}\nexport interface HealthElementPatcher {\n type: 'HealthElementDto'\n patch: (patients: HealthElement[]) => Promise<HealthElement[]>\n}\nexport interface DocumentPatcher {\n type: 'DocumentDto'\n patch: (documents: Document[]) => Promise<Document[]>\n}\nexport interface ServicePatcher {\n type: 'ServiceDto'\n patch: (documents: Service[]) => Promise<Service[]>\n}\n\nexport class IccBekmehrXApi extends IccBekmehrApi {\n private readonly ctcApi: IccContactXApi\n private readonly helementApi: IccHelementXApi\n private readonly documentApi: IccDocumentXApi\n private readonly wssHost: string\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n ctcApi: IccContactXApi,\n helementApi: IccHelementXApi,\n documentApi: IccDocumentXApi,\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.ctcApi = ctcApi\n this.helementApi = helementApi\n this.documentApi = documentApi\n\n this.wssHost = new URL(this.host, typeof window !== 'undefined' ? window.location.href : undefined).href\n .replace(/^http/, 'ws')\n .replace(/\\/rest\\/v.+/, '/ws')\n }\n\n private async getJwt(): Promise<string> {\n const authService = this.authenticationProvider.getAuthService()\n if (!!authService.jwtGetter) {\n const tokens = await authService.jwtGetter()\n if (!tokens) {\n throw new Error('Missing JWT')\n }\n return tokens.token\n } else {\n throw new Error('The existing provider is not a JWT provider')\n }\n }\n\n socketEventListener(\n socket: WebSocket,\n healthcarePartyId: string,\n resolve: (value: Blob) => void,\n reject: (reason?: any) => void,\n patchers: Patcher[],\n progressCallback?: (progress: number) => void\n ) {\n const that = this\n\n const send = (command: string, uuid: string, body: any) => {\n const data = JSON.stringify({ command, uuid, body })\n socket.send(data.length > 65000 ? utf8_2ua(data).buffer : data)\n }\n\n const messageHandler = (msg: any, event: any) => {\n if (msg.command === 'decrypt') {\n if (msg.type === 'ContactDto') {\n that.ctcApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ContactDto')\n .reduce(async (p, patcher) => (patcher as ContactPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'HealthElementDto') {\n that.helementApi\n .decrypt(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'HealthElementDto')\n .reduce(async (p, patcher) => (patcher as HealthElementPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n } else if (msg.type === 'DocumentDto') {\n that.documentApi\n .decrypt(\n healthcarePartyId,\n msg.body.map((d: JSON) => new Document(d))\n )\n .then((res) =>\n patchers\n .filter((p) => p.type === 'DocumentDto')\n .reduce(async (p, patcher) => (patcher as DocumentPatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) =>\n send(\n 'decryptResponse',\n msg.uuid,\n res?.map((d) => {\n const de = d.decryptedAttachment\n const { encryptedAttachment, ...stripped } = d\n return de ? { ...stripped, decryptedAttachment: btoa(ua2string(de)) } : stripped\n })\n )\n )\n } else if (msg.type === 'ServiceDto') {\n that.ctcApi\n .decryptServices(healthcarePartyId, msg.body)\n .then((res) =>\n patchers\n .filter((p) => p.type === 'ServiceDto')\n .reduce(async (p, patcher) => (patcher as ServicePatcher).patch(await p), Promise.resolve(res))\n )\n .then((res) => send('decryptResponse', msg.uuid, res))\n }\n } else if (msg.command === 'progress') {\n if (progressCallback && msg.body && msg.body[0]) {\n progressCallback(msg.body[0].progress)\n }\n } else {\n console.error('error received from backend:' + event.data)\n reject('websocket error: ' + event.data)\n socket.close(4000, 'backend error')\n }\n }\n\n return (event: MessageEvent) => {\n if (typeof event.data === 'string') {\n const msg = JSON.parse(event.data)\n messageHandler(msg, event)\n } else {\n const blob: Blob = event.data\n const subBlob = blob.slice(0, 1)\n const br = new FileReader()\n br.onload = function (e) {\n const firstChar = e.target && new Uint8Array((e.target as any).result as ArrayBuffer)[0]\n\n if (firstChar === 0x7b) {\n const tr = new FileReader()\n tr.onload = function (e) {\n const msg = e.target && JSON.parse((e.target as any).result as string)\n messageHandler(msg, event)\n }\n tr.readAsBinaryString(blob)\n } else {\n resolve(blob)\n socket.close(1000, 'Ok')\n }\n }\n br.readAsArrayBuffer(subBlob)\n }\n }\n }\n\n generateSmfExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SoftwareMedicalFileExport,\n progressCallback?: (progress: number) => void,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSmf?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers, progressCallback))\n })\n )\n }\n\n generateSumehrExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehr?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateSumehrV2ExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateSumehrV2?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateDiaryNoteExportWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n body: models.SumehrExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateDiaryNote?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: { patientId: patientId, language: language, info: body },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n\n generateMedicationSchemeWithEncryptionSupport(\n patientId: string,\n healthcarePartyId: string,\n language: string,\n recipientSafe: string,\n version: number,\n body: models.MedicationSchemeExportInfo,\n patchers: Patcher[] = []\n ): Promise<Blob | undefined> {\n return this.getJwt().then(\n (jwt) =>\n new Promise<Blob | undefined>((resolve, reject) => {\n const socket = new WebSocket(`${this.wssHost}/be_kmehr/generateMedicationScheme?jwt=${jwt}`)\n socket.addEventListener('open', function () {\n socket.send(\n JSON.stringify({\n parameters: {\n patientId: patientId,\n language: language,\n recipientSafe: recipientSafe,\n version: version,\n info: body,\n },\n })\n )\n })\n // Listen for messages\n socket.addEventListener('message', this.socketEventListener(socket, healthcarePartyId, resolve, reject, patchers))\n })\n )\n }\n}\n"]}
|
package/icc-x-api/index.js
CHANGED
|
@@ -281,13 +281,12 @@ function initialiseCryptoWithProvider(host, fetchImpl, groupSpecificAuthenticati
|
|
|
281
281
|
const keyRecovery = new KeyRecovery_1.KeyRecovery(cryptoPrimitives, dataOwnerApi, baseExchangeKeysManager, baseExchangeDataManager);
|
|
282
282
|
const recoveryDataEncryption = new RecoveryDataEncryption_1.RecoveryDataEncryption(cryptoPrimitives, baseRecoveryDataApi);
|
|
283
283
|
const keyPairRecoverer = new KeyPairRecoverer_1.KeyPairRecoverer(recoveryDataEncryption);
|
|
284
|
-
const userEncryptionKeysManager = new UserEncryptionKeysManager_1.UserEncryptionKeysManager(cryptoPrimitives, dataOwnerApi, icureStorage, keyRecovery, cryptoStrategies, !params.disableParentKeysInitialisation, keyPairRecoverer);
|
|
284
|
+
const userEncryptionKeysManager = new UserEncryptionKeysManager_1.UserEncryptionKeysManager(cryptoPrimitives, dataOwnerApi, icureStorage, keyRecovery, cryptoStrategies, !params.disableParentKeysInitialisation, keyPairRecoverer, dataOwnerRequiresAnonymousDelegation);
|
|
285
285
|
const newKey = yield userEncryptionKeysManager.initialiseKeys();
|
|
286
286
|
yield new TransferKeysManager_1.TransferKeysManager(cryptoPrimitives, baseExchangeDataManager, dataOwnerApi, userEncryptionKeysManager, icureStorage).updateTransferKeys(yield dataOwnerApi.getCurrentDataOwnerStub());
|
|
287
287
|
// TODO customise cache size?
|
|
288
288
|
const exchangeKeysManager = new ExchangeKeysManager_1.ExchangeKeysManager(userEncryptionKeysManager, baseExchangeKeysManager, dataOwnerApi);
|
|
289
|
-
|
|
290
|
-
exchangeKeysManager.reloadCache(); // Intentionally not awaited to make login feel faster
|
|
289
|
+
exchangeKeysManager.reloadCache();
|
|
291
290
|
const accessControlSecretUtils = new AccessControlSecretUtils_1.AccessControlSecretUtils(cryptoPrimitives);
|
|
292
291
|
const exchangeDataManager = yield (0, ExchangeDataManager_1.initialiseExchangeDataManagerForCurrentDataOwner)(baseExchangeDataManager, userEncryptionKeysManager, accessControlSecretUtils, cryptoStrategies, dataOwnerApi, cryptoPrimitives, !params.disableParentKeysInitialisation);
|
|
293
292
|
if (params.injectExchangeData != null && params.injectExchangeData.details.length > 0) {
|