@icure/api 8.0.9 → 8.0.10
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-x-api/crypto/BaseExchangeDataManager.js +1 -1
- package/icc-x-api/crypto/BaseExchangeDataManager.js.map +1 -1
- package/icc-x-api/crypto/BaseExchangeKeysManager.js +7 -3
- package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -1
- package/icc-x-api/crypto/KeyRecovery.js +1 -1
- package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
- package/icc-x-api/crypto/ShamirKeysManager.js +8 -9
- package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
- package/icc-x-api/crypto/UserEncryptionKeysManager.js +2 -3
- package/icc-x-api/crypto/UserEncryptionKeysManager.js.map +1 -1
- package/icc-x-api/crypto/UserSignatureKeysManager.js +9 -5
- package/icc-x-api/crypto/UserSignatureKeysManager.js.map +1 -1
- package/icc-x-api/crypto/utils.d.ts +12 -0
- package/icc-x-api/crypto/utils.js +21 -1
- package/icc-x-api/crypto/utils.js.map +1 -1
- package/icc-x-api/icc-data-owner-x-api.js +1 -1
- package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
- package/icc-x-api/icc-icure-maintenance-x-api.js +4 -3
- package/icc-x-api/icc-icure-maintenance-x-api.js.map +1 -1
- package/icc-x-api/storage/IcureStorageFacade.js +4 -1
- package/icc-x-api/storage/IcureStorageFacade.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShamirKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ShamirKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,oCAAyC;AAEzC,yEAA6E;AAE7E;;GAEG;AACH,MAAa,iBAAiB;IAC5B,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,qBAAgD,EAChD,mBAAwC;QAHxC,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,G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-owner-x-api'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyPair } from './RSA'\nimport { hex2ua, ua2hex } from '../utils'\nimport { ExchangeDataManager } from './ExchangeDataManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\n\n/**\n * Allows to create or update shamir split keys.\n */\nexport class ShamirKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly exchangeDataManager: ExchangeDataManager\n ) {}\n\n /**\n * Get information on existing private keys splits for the provided data owner. For each private key of the provided data owner which has been\n * split using the Shamir sharing algorithm gives the list of the notaries (other data owners) which hold a copy of the key part.\n * @param dataOwner a data owner\n * @return the existing splits for the current data owner as a publicKeyFingerprint -> notariesIds object\n */\n getExistingSplitsInfo(dataOwner: DataOwnerOrStub): { [keyPairFingerprint: string]: string[] } {\n const legacyPartitionDelegates = Object.keys(dataOwner.privateKeyShamirPartitions ?? {})\n if (legacyPartitionDelegates.length > 0) {\n const fp = dataOwner.publicKey?.slice(-32)\n if (!fp) {\n console.error('Invalid data owner: the owner has legacy key partitions but no legacy key.')\n } else return { [fp]: legacyPartitionDelegates }\n }\n return {}\n }\n\n /**\n * Creates, updates or deletes shamir splits for keys of the current data owner. Any request to update the splits for a specific key will completely\n * replace any existing data on that split (all previous notaries will be ignored).\n * Note: currently you can only split the legacy key pair.\n * @param keySplitsToUpdate the fingerprints of key pairs which will have updated/new splits and the details on how to create the updated splits.\n * @param keySplitsToDelete the fingerprints or hex-encoded spki public keys which will not be shared anymore.\n * @throws if the parameters refer to non-existing or unavailable keys, have split creation details, or if they request to delete a non-existing\n * split.\n */\n async updateSelfSplits(\n keySplitsToUpdate: { [publicKeyHexOrFp: string]: { notariesIds: string[]; minShares: number } },\n keySplitsToDelete: string[]\n ): Promise<CryptoActorStubWithType> {\n const self = CryptoActorStubWithType.fromDataOwner(await this.dataOwnerApi.getCurrentDataOwner())\n const toUpdateSet = new Set(Object.keys(keySplitsToUpdate).map((x) => x.slice(-32)))\n const toDeleteSet = new Set(keySplitsToDelete.slice(-32))\n const intersection = Array.from(toDeleteSet).filter((x) => toUpdateSet.has(x))\n const existingSplits = new Set(Object.keys(this.getExistingSplitsInfo(self.stub)))\n const allKeys = this.encryptionKeysManager.getDecryptionKeys()\n if (toDeleteSet.size !== keySplitsToDelete.length || toUpdateSet.size !== Object.keys(keySplitsToUpdate).length || intersection.length > 0)\n throw new Error(`Duplicate keys in input:\\nkeySplitsToUpdate: ${keySplitsToUpdate}\\nkeySplitsToDelete: ${keySplitsToDelete}`)\n Object.entries(keySplitsToUpdate).forEach(([key, params]) => this.validateShamirParams(key, params))\n if (!Array.from(existingSplits).every((x) => existingSplits.has(x))) {\n throw new Error(`Requested to delete non-existing split.\\nexistingSplits: ${Array.from(existingSplits)}\\ntoDelete:${Array.from(toDeleteSet)}`)\n }\n if (Array.from(toUpdateSet).some((x) => !allKeys[x])) {\n throw new Error(`Private key is not available for some of the requested key split updates. ${keySplitsToUpdate}`)\n }\n const delegatesKeys: { [delegateId: string]: CryptoKey } = {}\n let updatedSelf = self\n for (const delegateId of new Set(Object.values(keySplitsToUpdate).flatMap((x) => x.notariesIds))) {\n const res = await this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, undefined, undefined, false)\n delegatesKeys[delegateId] = res.exchangeKey\n }\n for (const [key, params] of Object.entries(keySplitsToUpdate)) {\n updatedSelf = await this.updateKeySplit(updatedSelf, key.slice(-32), params.notariesIds, params.minShares, delegatesKeys, allKeys)\n }\n for (const keyFp of toDeleteSet) {\n updatedSelf = this.deleteKeySplit(updatedSelf, keyFp)\n }\n return await this.dataOwnerApi.modifyCryptoActorStub(updatedSelf)\n }\n\n /*TODO\n * Get suggested recovery keys: analyse transfer keys and shamir to get keys which should be shared with shamir for optimal recovery.\n */\n\n private validateShamirParams(key: string, params: { notariesIds: string[]; minShares: number }) {\n if (params.notariesIds.length > 0) {\n if (params.minShares > params.notariesIds.length) {\n throw new Error(`Invalid parameters for key ${key}: min shares can't be greater than the number of delegates. ${params}`)\n }\n } else throw new Error(`Invalid parameters for key ${key}: must have at least one delegate. ${params}`)\n }\n\n private deleteKeySplit(dataOwner: CryptoActorStubWithType, keyFp: string): CryptoActorStubWithType {\n if (keyFp !== dataOwner.stub.publicKey?.slice(-32)) {\n throw new Error('Currently it is possible to use shamir splits only for the legacy public key')\n }\n return {\n type: dataOwner.type,\n stub: {\n ...dataOwner.stub,\n privateKeyShamirPartitions: {},\n },\n }\n }\n\n private async updateKeySplit(\n dataOwner: CryptoActorStubWithType,\n keyFp: string,\n delegateIds: string[],\n minShares: number,\n delegatesKeys: { [p: string]: CryptoKey },\n allKeys: { [p: string]: KeyPair<CryptoKey> }\n ): Promise<CryptoActorStubWithType> {\n if (keyFp !== dataOwner.stub.publicKey?.slice(-32)) {\n throw new Error('Currently it is possible to use shamir splits only for the legacy public key')\n }\n return {\n type: dataOwner.type,\n stub: {\n ...dataOwner.stub,\n privateKeyShamirPartitions: await this.createPartitionsFor(allKeys[keyFp], delegateIds, minShares, delegatesKeys),\n },\n }\n }\n\n private async createPartitionsFor(\n keyPair: KeyPair<CryptoKey>,\n delegateIds: string[],\n minShares: number,\n delegatesKeys: { [p: string]: CryptoKey }\n ): Promise<{ [delegateId: string]: string }> {\n const exportedKey = await this.primitives.RSA.exportKey(keyPair.privateKey, 'pkcs8')\n if (delegateIds.length == 1) {\n return await this.encryptShares([exportedKey], delegateIds, delegatesKeys)\n } else {\n const exportedKeysHex = ua2hex(exportedKey)\n const stringShares = this.primitives.shamir.share(exportedKeysHex, delegateIds.length, minShares)\n const paddedStringShares = stringShares.map((x) => `f${x}`) // Shares are uneven length, apart from that they are perfect hexes\n for (const share of paddedStringShares) {\n if (!/^(?:[0-9a-f][0-9a-f])+$/g.test(share)) throw new Error('Unexpected result of shamir split: padded shares should be a valid hex value')\n if (share !== ua2hex(hex2ua(share))) throw new Error('Unexpected result with encoding-decoding share')\n }\n return await this.encryptShares(\n paddedStringShares.map((x) => hex2ua(x)),\n delegateIds,\n delegatesKeys\n )\n }\n }\n\n private async encryptShares(\n shares: ArrayBuffer[],\n delegateIds: string[],\n delegatesKeys: { [p: string]: CryptoKey }\n ): Promise<{ [delegateId: string]: string }> {\n return delegateIds.reduce(\n async (acc, delegateId, index) => ({\n ...(await acc),\n [delegateId]: ua2hex(await this.primitives.AES.encrypt(delegatesKeys[delegateId], shares[index])),\n }),\n Promise.resolve({} as { [delegateId: string]: string })\n )\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ShamirKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/ShamirKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,oCAAyC;AAEzC,yEAA6E;AAC7E,mCAAuC;AAEvC;;GAEG;AACH,MAAa,iBAAiB;IAC5B,YACmB,UAA4B,EAC5B,YAA8B,EAC9B,qBAAgD,EAChD,mBAAwC;QAHxC,eAAU,GAAV,UAAU,CAAkB;QAC5B,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,0BAAqB,GAArB,qBAAqB,CAA2B;QAChD,wBAAmB,GAAnB,mBAAmB,CAAqB;IACxD,CAAC;IAEJ;;;;;OAKG;IACH,qBAAqB,CAAC,SAA0B;;QAC9C,MAAM,wBAAwB,GAAG,MAAM,CAAC,IAAI,CAAC,MAAA,SAAS,CAAC,0BAA0B,mCAAI,EAAE,CAAC,CAAA;QACxF,IAAI,wBAAwB,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,MAAM,EAAE,GAAG,SAAS,CAAC,SAAS,IAAI,IAAA,qBAAa,EAAC,SAAS,CAAC,SAAS,CAAC,CAAA;YACpE,IAAI,CAAC,EAAE,EAAE;gBACP,OAAO,CAAC,KAAK,CAAC,4EAA4E,CAAC,CAAA;aAC5F;;gBAAM,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,wBAAw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C,IAAA,cAAM,EAAC,KAAK,CAAC,CAAC;wBAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAA;iBACvG;gBACD,OAAO,MAAM,IAAI,CAAC,aAAa,CAC7B,kBAAkB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAA,cAAM,EAAC,CAAC,CAAC,CAAC,EACxC,WAAW,EACX,aAAa,CACd,CAAA;aACF;QACH,CAAC;KAAA;IAEa,aAAa,CACzB,MAAqB,EACrB,WAAqB,EACrB,aAAyC;;YAEzC,OAAO,WAAW,CAAC,MAAM,CACvB,CAAO,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;gBAAC,OAAA,iCAC7B,CAAC,MAAM,GAAG,CAAC,KACd,CAAC,UAAU,CAAC,EAAE,IAAA,cAAM,EAAC,MAAM,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IACjG,CAAA;cAAA,EACF,OAAO,CAAC,OAAO,CAAC,EAAsC,CAAC,CACxD,CAAA;QACH,CAAC;KAAA;CACF;AAvJD,8CAuJC","sourcesContent":["import { DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { UserEncryptionKeysManager } from './UserEncryptionKeysManager'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { KeyPair } from './RSA'\nimport { hex2ua, ua2hex } from '../utils'\nimport { ExchangeDataManager } from './ExchangeDataManager'\nimport { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub'\nimport { fingerprintV1 } from './utils'\n\n/**\n * Allows to create or update shamir split keys.\n */\nexport class ShamirKeysManager {\n constructor(\n private readonly primitives: CryptoPrimitives,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly encryptionKeysManager: UserEncryptionKeysManager,\n private readonly exchangeDataManager: ExchangeDataManager\n ) {}\n\n /**\n * Get information on existing private keys splits for the provided data owner. For each private key of the provided data owner which has been\n * split using the Shamir sharing algorithm gives the list of the notaries (other data owners) which hold a copy of the key part.\n * @param dataOwner a data owner\n * @return the existing splits for the current data owner as a publicKeyFingerprint -> notariesIds object\n */\n getExistingSplitsInfo(dataOwner: DataOwnerOrStub): { [keyPairFingerprint: string]: string[] } {\n const legacyPartitionDelegates = Object.keys(dataOwner.privateKeyShamirPartitions ?? {})\n if (legacyPartitionDelegates.length > 0) {\n const fp = dataOwner.publicKey && fingerprintV1(dataOwner.publicKey)\n if (!fp) {\n console.error('Invalid data owner: the owner has legacy key partitions but no legacy key.')\n } else return { [fp]: legacyPartitionDelegates }\n }\n return {}\n }\n\n /**\n * Creates, updates or deletes shamir splits for keys of the current data owner. Any request to update the splits for a specific key will completely\n * replace any existing data on that split (all previous notaries will be ignored).\n * Note: currently you can only split the legacy key pair.\n * @param keySplitsToUpdate the fingerprints of key pairs which will have updated/new splits and the details on how to create the updated splits.\n * @param keySplitsToDelete the fingerprints or hex-encoded spki public keys which will not be shared anymore.\n * @throws if the parameters refer to non-existing or unavailable keys, have split creation details, or if they request to delete a non-existing\n * split.\n */\n async updateSelfSplits(\n keySplitsToUpdate: { [publicKeyHexOrFp: string]: { notariesIds: string[]; minShares: number } },\n keySplitsToDelete: string[]\n ): Promise<CryptoActorStubWithType> {\n const self = CryptoActorStubWithType.fromDataOwner(await this.dataOwnerApi.getCurrentDataOwner())\n const toUpdateSet = new Set(Object.keys(keySplitsToUpdate).map((x) => fingerprintV1(x)))\n const toDeleteSet = new Set(Object.keys(keySplitsToDelete).map((x) => fingerprintV1(x)))\n const intersection = Array.from(toDeleteSet).filter((x) => toUpdateSet.has(x))\n const existingSplits = new Set(Object.keys(this.getExistingSplitsInfo(self.stub)))\n const allKeys = this.encryptionKeysManager.getDecryptionKeys()\n if (toDeleteSet.size !== keySplitsToDelete.length || toUpdateSet.size !== Object.keys(keySplitsToUpdate).length || intersection.length > 0)\n throw new Error(`Duplicate keys in input:\\nkeySplitsToUpdate: ${keySplitsToUpdate}\\nkeySplitsToDelete: ${keySplitsToDelete}`)\n Object.entries(keySplitsToUpdate).forEach(([key, params]) => this.validateShamirParams(key, params))\n if (!Array.from(existingSplits).every((x) => existingSplits.has(x))) {\n throw new Error(`Requested to delete non-existing split.\\nexistingSplits: ${Array.from(existingSplits)}\\ntoDelete:${Array.from(toDeleteSet)}`)\n }\n if (Array.from(toUpdateSet).some((x) => !allKeys[x])) {\n throw new Error(`Private key is not available for some of the requested key split updates. ${keySplitsToUpdate}`)\n }\n const delegatesKeys: { [delegateId: string]: CryptoKey } = {}\n let updatedSelf = self\n for (const delegateId of new Set(Object.values(keySplitsToUpdate).flatMap((x) => x.notariesIds))) {\n const res = await this.exchangeDataManager.getOrCreateEncryptionDataTo(delegateId, undefined, undefined, false)\n delegatesKeys[delegateId] = res.exchangeKey\n }\n for (const [key, params] of Object.entries(keySplitsToUpdate)) {\n updatedSelf = await this.updateKeySplit(updatedSelf, fingerprintV1(key), params.notariesIds, params.minShares, delegatesKeys, allKeys)\n }\n for (const keyFp of toDeleteSet) {\n updatedSelf = this.deleteKeySplit(updatedSelf, keyFp)\n }\n return await this.dataOwnerApi.modifyCryptoActorStub(updatedSelf)\n }\n\n /*TODO\n * Get suggested recovery keys: analyse transfer keys and shamir to get keys which should be shared with shamir for optimal recovery.\n */\n\n private validateShamirParams(key: string, params: { notariesIds: string[]; minShares: number }) {\n if (params.notariesIds.length > 0) {\n if (params.minShares > params.notariesIds.length) {\n throw new Error(`Invalid parameters for key ${key}: min shares can't be greater than the number of delegates. ${params}`)\n }\n } else throw new Error(`Invalid parameters for key ${key}: must have at least one delegate. ${params}`)\n }\n\n private deleteKeySplit(dataOwner: CryptoActorStubWithType, keyFp: string): CryptoActorStubWithType {\n if (!dataOwner.stub.publicKey || keyFp !== fingerprintV1(dataOwner.stub.publicKey)) {\n throw new Error('Currently it is possible to use shamir splits only for the legacy public key')\n }\n return {\n type: dataOwner.type,\n stub: {\n ...dataOwner.stub,\n privateKeyShamirPartitions: {},\n },\n }\n }\n\n private async updateKeySplit(\n dataOwner: CryptoActorStubWithType,\n keyFp: string,\n delegateIds: string[],\n minShares: number,\n delegatesKeys: { [p: string]: CryptoKey },\n allKeys: { [p: string]: KeyPair<CryptoKey> }\n ): Promise<CryptoActorStubWithType> {\n if (!dataOwner.stub.publicKey || keyFp !== fingerprintV1(dataOwner.stub.publicKey)) {\n throw new Error('Currently it is possible to use shamir splits only for the legacy public key')\n }\n return {\n type: dataOwner.type,\n stub: {\n ...dataOwner.stub,\n privateKeyShamirPartitions: await this.createPartitionsFor(allKeys[keyFp], delegateIds, minShares, delegatesKeys),\n },\n }\n }\n\n private async createPartitionsFor(\n keyPair: KeyPair<CryptoKey>,\n delegateIds: string[],\n minShares: number,\n delegatesKeys: { [p: string]: CryptoKey }\n ): Promise<{ [delegateId: string]: string }> {\n const exportedKey = await this.primitives.RSA.exportKey(keyPair.privateKey, 'pkcs8')\n if (delegateIds.length == 1) {\n return await this.encryptShares([exportedKey], delegateIds, delegatesKeys)\n } else {\n const exportedKeysHex = ua2hex(exportedKey)\n const stringShares = this.primitives.shamir.share(exportedKeysHex, delegateIds.length, minShares)\n const paddedStringShares = stringShares.map((x) => `f${x}`) // Shares are uneven length, apart from that they are perfect hexes\n for (const share of paddedStringShares) {\n if (!/^(?:[0-9a-f][0-9a-f])+$/g.test(share)) throw new Error('Unexpected result of shamir split: padded shares should be a valid hex value')\n if (share !== ua2hex(hex2ua(share))) throw new Error('Unexpected result with encoding-decoding share')\n }\n return await this.encryptShares(\n paddedStringShares.map((x) => hex2ua(x)),\n delegateIds,\n delegatesKeys\n )\n }\n }\n\n private async encryptShares(\n shares: ArrayBuffer[],\n delegateIds: string[],\n delegatesKeys: { [p: string]: CryptoKey }\n ): Promise<{ [delegateId: string]: string }> {\n return delegateIds.reduce(\n async (acc, delegateId, index) => ({\n ...(await acc),\n [delegateId]: ua2hex(await this.primitives.AES.encrypt(delegatesKeys[delegateId], shares[index])),\n }),\n Promise.resolve({} as { [delegateId: string]: string })\n )\n }\n}\n"]}
|
|
@@ -138,11 +138,10 @@ class UserEncryptionKeysManager {
|
|
|
138
138
|
* @return all verified keys, in order.
|
|
139
139
|
*/
|
|
140
140
|
getSelfVerifiedKeys() {
|
|
141
|
-
var _a;
|
|
142
141
|
this.ensureInitialised();
|
|
143
142
|
const selfKeys = this.keysCache[this.selfId];
|
|
144
143
|
const allKeysEntries = Object.entries(selfKeys);
|
|
145
|
-
const legacyKeyFp =
|
|
144
|
+
const legacyKeyFp = this.selfLegacyPublicKey && (0, utils_2.fingerprintV1)(this.selfLegacyPublicKey);
|
|
146
145
|
const legacyKeyData = legacyKeyFp ? selfKeys[legacyKeyFp] : undefined;
|
|
147
146
|
const legacyEntry = (legacyKeyData === null || legacyKeyData === void 0 ? void 0 : legacyKeyData.isVerified) && legacyKeyFp ? [{ fingerprint: legacyKeyFp, pair: legacyKeyData.pair }] : [];
|
|
148
147
|
function filteredEntries(filterFunction) {
|
|
@@ -216,7 +215,7 @@ class UserEncryptionKeysManager {
|
|
|
216
215
|
...this.dataOwnerApi.getHexPublicKeysWithSha256Of(dowt.dataOwner),
|
|
217
216
|
]);
|
|
218
217
|
const unavailableKeys = Array.from(allPublicKeys).flatMap((key) => {
|
|
219
|
-
return availableKeysFpSet.has(
|
|
218
|
+
return availableKeysFpSet.has((0, utils_2.fingerprintV1)(key)) ? [] : [key];
|
|
220
219
|
});
|
|
221
220
|
const unknownKeys = Array.from(allPublicKeys).filter((x) => { var _a; return !((0, utils_2.fingerprintV1)(x) in verifiedKeysMap) && !(((_a = availableKeys === null || availableKeys === void 0 ? void 0 : availableKeys[(0, utils_2.fingerprintV1)(x)]) === null || _a === void 0 ? void 0 : _a.isDevice) === true); });
|
|
222
221
|
keysData.push({ dowt, availableKeys, unavailableKeys, unknownKeys });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserEncryptionKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto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;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;AApZD,8DAoZC","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>\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?.slice(-32)\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(key.slice(-32)) ? [] : [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 {\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/cryp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EO,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;AApZD,8DAoZC","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>\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 {\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"]}
|
|
@@ -42,10 +42,13 @@ class UserSignatureKeysManager {
|
|
|
42
42
|
}
|
|
43
43
|
else {
|
|
44
44
|
const generatedPair = yield this.primitives.RSA.generateSignatureKeyPair();
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
45
|
+
const exportedPub = (0, utils_1.ua2hex)(yield this.primitives.RSA.exportKey(generatedPair.publicKey, 'spki'));
|
|
46
|
+
(0, utils_2.checkStandardPublicKeyTail)(exportedPub);
|
|
47
|
+
const fpV2 = (0, utils_2.fingerprintV2)(exportedPub);
|
|
48
|
+
// For consistency with encryption keys we use fpv1 when saving
|
|
49
|
+
yield this.iCureStorage.saveSignatureKeyPair(dataOwnerId, (0, utils_2.fingerprintV1)(exportedPub), yield this.primitives.RSA.exportKeys(generatedPair, 'jwk', 'jwk'));
|
|
50
|
+
this.verificationKeysCache.set(fpV2, generatedPair.publicKey);
|
|
51
|
+
this.signatureKeysCache = { fingerprint: fpV2, keyPair: generatedPair };
|
|
49
52
|
return this.signatureKeysCache;
|
|
50
53
|
}
|
|
51
54
|
});
|
|
@@ -61,7 +64,8 @@ class UserSignatureKeysManager {
|
|
|
61
64
|
const cached = this.verificationKeysCache.get(fingerprint);
|
|
62
65
|
if (cached)
|
|
63
66
|
return cached;
|
|
64
|
-
|
|
67
|
+
// For consistency with encryption keys we use fpv1 when saving
|
|
68
|
+
const loaded = yield this.iCureStorage.loadSignatureVerificationKey(yield this.dataOwnerApi.getCurrentDataOwnerId(), (0, utils_2.fingerprintV2ToStandardV1)(fingerprint));
|
|
65
69
|
if (loaded) {
|
|
66
70
|
const imported = yield this.primitives.RSA.importVerificationKey('jwk', loaded);
|
|
67
71
|
this.verificationKeysCache.set(fingerprint, imported);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserSignatureKeysManager.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/UserSignatureKeysManager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,oCAAmD;AAEnD,
|
|
1
|
+
{"version":3,"file":"UserSignatureKeysManager.js","sourceRoot":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AAE,QAAQ,CAAC,CAAA;gBACrD,OAAO,QAAQ,CAAA;aAChB;QACH,CAAC;KAAA;CACF;AAxED,4DAwEC","sourcesContent":["import { IcureStorageFacade } from '../storage/IcureStorageFacade'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { hex2ua, jwk2spki, ua2hex } from '../utils'\nimport { KeyPair } from './RSA'\nimport { checkStandardPublicKeyTail, fingerprintV1, fingerprintV2, fingerprintV2ToStandardV1 } from './utils'\n\nexport class UserSignatureKeysManager {\n constructor(\n private readonly iCureStorage: IcureStorageFacade,\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly primitives: CryptoPrimitives\n ) {}\n\n private signatureKeysCache:\n | {\n fingerprint: string\n keyPair: KeyPair<CryptoKey>\n }\n | undefined = undefined\n private verificationKeysCache = new Map<string, CryptoKey>()\n\n /**\n * Get a key which can be used to sign data in order to allow verification of the data authenticity in the future.\n */\n async getOrCreateSignatureKeyPair(): Promise<{\n fingerprint: string\n keyPair: KeyPair<CryptoKey>\n }> {\n if (this.signatureKeysCache) return this.signatureKeysCache\n const dataOwnerId = await this.dataOwnerApi.getCurrentDataOwnerId()\n const existing = await this.iCureStorage.loadSignatureKey(dataOwnerId)\n if (existing) {\n const fingerprint = fingerprintV1(jwk2spki(existing.publicKey))\n this.signatureKeysCache = {\n fingerprint,\n keyPair: {\n privateKey: await this.primitives.RSA.importSignatureKey('jwk', existing.privateKey),\n publicKey: await this.primitives.RSA.importVerificationKey('jwk', existing.publicKey),\n },\n }\n return this.signatureKeysCache\n } else {\n const generatedPair = await this.primitives.RSA.generateSignatureKeyPair()\n const exportedPub = ua2hex(await this.primitives.RSA.exportKey(generatedPair.publicKey, 'spki'))\n checkStandardPublicKeyTail(exportedPub)\n const fpV2 = fingerprintV2(exportedPub)\n // For consistency with encryption keys we use fpv1 when saving\n await this.iCureStorage.saveSignatureKeyPair(\n dataOwnerId,\n fingerprintV1(exportedPub),\n await this.primitives.RSA.exportKeys(generatedPair, 'jwk', 'jwk')\n )\n this.verificationKeysCache.set(fpV2, generatedPair.publicKey)\n this.signatureKeysCache = { fingerprint: fpV2, keyPair: generatedPair }\n return this.signatureKeysCache\n }\n }\n\n /**\n * Get all available keys which can be used to verify the authenticity of a signature which should have been created\n * by the current data owner.\n * @param fingerprint v1 fingerprint of the key to retrieve.\n * @return all available verification keys by fingerprint.\n */\n async getSignatureVerificationKey(fingerprint: string): Promise<CryptoKey | undefined> {\n const cached = this.verificationKeysCache.get(fingerprint)\n if (cached) return cached\n // For consistency with encryption keys we use fpv1 when saving\n const loaded = await this.iCureStorage.loadSignatureVerificationKey(\n await this.dataOwnerApi.getCurrentDataOwnerId(),\n fingerprintV2ToStandardV1(fingerprint)\n )\n if (loaded) {\n const imported = await this.primitives.RSA.importVerificationKey('jwk', loaded)\n this.verificationKeysCache.set(fingerprint, imported)\n return imported\n }\n }\n}\n"]}
|
|
@@ -92,3 +92,15 @@ export declare function fingerprintIsV1(fp: string): boolean;
|
|
|
92
92
|
* @return true if the fingerprint is in V2 format, false otherwise.
|
|
93
93
|
*/
|
|
94
94
|
export declare function fingerprintIsV2(fp: string): boolean;
|
|
95
|
+
/**
|
|
96
|
+
* @internal this function is meant only for internal use and may be changed without notice.
|
|
97
|
+
* @param fp the fingerprint v2.
|
|
98
|
+
* @return the fingerprint v1 using the standard tail.
|
|
99
|
+
*/
|
|
100
|
+
export declare function fingerprintV2ToStandardV1(fp: string): string;
|
|
101
|
+
/**
|
|
102
|
+
* @internal this function is meant only for internal use and may be changed without notice.
|
|
103
|
+
* @param publicKeyOrFpv1 a public key in spki format or a public key fp v1
|
|
104
|
+
* @throws if the input does not terminate with 0203010001
|
|
105
|
+
*/
|
|
106
|
+
export declare function checkStandardPublicKeyTail(publicKeyOrFpv1: string): void;
|
|
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.fingerprintIsV2 = exports.fingerprintIsV1 = exports.fingerprintV1toV2 = exports.fingerprintV2 = exports.fingerprintV1 = exports.getShaVersionForKey = exports.ensureDelegationForSelf = exports.loadPublicKeys = exports.fingerprintToPublicKeysMapOf = exports.transferKeysFpGraphOf = exports.hexPublicKeysWithSha1Of = exports.hexPublicKeysWithSha256Of = void 0;
|
|
12
|
+
exports.checkStandardPublicKeyTail = exports.fingerprintV2ToStandardV1 = exports.fingerprintIsV2 = exports.fingerprintIsV1 = exports.fingerprintV1toV2 = exports.fingerprintV2 = exports.fingerprintV1 = exports.getShaVersionForKey = exports.ensureDelegationForSelf = exports.loadPublicKeys = exports.fingerprintToPublicKeysMapOf = exports.transferKeysFpGraphOf = exports.hexPublicKeysWithSha1Of = exports.hexPublicKeysWithSha256Of = void 0;
|
|
13
13
|
// Uses fp as node names
|
|
14
14
|
const graph_utils_1 = require("../utils/graph-utils");
|
|
15
15
|
const RSA_1 = require("./RSA");
|
|
@@ -191,4 +191,24 @@ function fingerprintIsV2(fp) {
|
|
|
191
191
|
return fp.length === 22;
|
|
192
192
|
}
|
|
193
193
|
exports.fingerprintIsV2 = fingerprintIsV2;
|
|
194
|
+
/**
|
|
195
|
+
* @internal this function is meant only for internal use and may be changed without notice.
|
|
196
|
+
* @param fp the fingerprint v2.
|
|
197
|
+
* @return the fingerprint v1 using the standard tail.
|
|
198
|
+
*/
|
|
199
|
+
function fingerprintV2ToStandardV1(fp) {
|
|
200
|
+
return fp + '0203010001';
|
|
201
|
+
}
|
|
202
|
+
exports.fingerprintV2ToStandardV1 = fingerprintV2ToStandardV1;
|
|
203
|
+
/**
|
|
204
|
+
* @internal this function is meant only for internal use and may be changed without notice.
|
|
205
|
+
* @param publicKeyOrFpv1 a public key in spki format or a public key fp v1
|
|
206
|
+
* @throws if the input does not terminate with 0203010001
|
|
207
|
+
*/
|
|
208
|
+
function checkStandardPublicKeyTail(publicKeyOrFpv1) {
|
|
209
|
+
if (publicKeyOrFpv1.slice(-10) != '0203010001') {
|
|
210
|
+
throw new Error('Illegal state: generated public key should end with 0203010001');
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
exports.checkStandardPublicKeyTail = checkStandardPublicKeyTail;
|
|
194
214
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wBAAwB;AACxB,sDAAsF;AAEtF,+BAA4C;AAC5C,oCAA+D;AAC/D,yDAAqD;AAKrD,qEAAiE;AACjE,wFAAoF;AAEpF,6EAAyE;AACzE,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,SAAoB;;IAC5D,OAAO,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,MAAA,SAAS,CAAC,2BAA2B,mCAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAa,CAAC,CAAA;AAC7G,CAAC;AAFD,8DAEC;AAED;;;GAGG;AACH,SAAgB,uBAAuB,CAAC,SAAoB;;IAC1D,OAAO,IAAI,GAAG,CAAC,CAAC,SAAS,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,MAAA,SAAS,CAAC,eAAe,mCAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAa,CAAC,CAAA;AACjI,CAAC;AAFD,0DAEC;AAED;;;;;;GAMG;AACH,SAAgB,qBAAqB,CAAC,SAAoB;;IACxD,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,uBAAuB,CAAC,SAAS,CAAC,EAAE,GAAG,yB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,CAAA;AACvB,CAAC;AAFD,sCAEC;AAED;;;;;;GAMG;AACH,SAAgB,aAAa,CAAC,GAAW;IACvC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAA;AAC5B,CAAC;AAFD,sCAEC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,EAAU;IAC1C,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAA;AACzB,CAAC;AAFD,8CAEC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC","sourcesContent":["// Uses fp as node names\nimport { acyclic, graphFromEdges, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { DataOwner, DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { RSAUtils, ShaVersion } from './RSA'\nimport { EntityWithDelegationTypeName, hex2ua } from '../utils'\nimport { Patient } from '../../icc-api/model/Patient'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedEntityWithType } from '../utils/EntityWithDelegationTypeName'\nimport { IccPatientApi } from '../../icc-api'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha256.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha256Of(dataOwner: DataOwner) {\n return new Set([...(dataOwner.publicKeysForOaepWithSha256 ?? [])].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha1.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha1Of(dataOwner: DataOwner) {\n return new Set([dataOwner.publicKey, ...Object.keys(dataOwner.aesExchangeKeys ?? {})].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get the transfer key graph for a data owner. Node names are the public key fingerprints of the data owner's keys, and an edge represents a key\n * which can be retrieved from another key using the transfer keys.\n * @param dataOwner a data owner.\n * @return a graph representing the possible key recovery paths using transfer keys for hte provided data owner.\n */\nexport function transferKeysFpGraphOf(dataOwner: DataOwner): StronglyConnectedGraph {\n const publicKeys = Array.from([...hexPublicKeysWithSha1Of(dataOwner), ...hexPublicKeysWithSha256Of(dataOwner)])\n const edges: [string, string][] = []\n Object.entries(dataOwner.transferKeys ?? {}).forEach(([from, tos]) => {\n Object.keys(tos).forEach((to) => {\n edges.push([fingerprintV1(from), fingerprintV1(to)])\n })\n })\n return acyclic(\n graphFromEdges(\n edges,\n publicKeys.map((x) => fingerprintV1(x))\n )\n )\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get a map for converting public keys fingerprint to full public keys for the provided data owner.\n * @param dataOwner a data owner.\n * @param shaVersion gets only the keys that are generated with this SHA version (default: 'sha-1').\n * @return a map to convert fingerprints of the data owner into full public keys.\n */\nexport function fingerprintToPublicKeysMapOf(dataOwner: DataOwner, shaVersion: ShaVersion): { [fp: string]: string } {\n const publicKeys = shaVersion === 'sha-1' ? Array.from(hexPublicKeysWithSha1Of(dataOwner)) : Array.from(hexPublicKeysWithSha256Of(dataOwner))\n const res: { [fp: string]: string } = {}\n publicKeys.forEach((pk) => {\n res[fingerprintV1(pk)] = pk\n })\n return res\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Load many public keys in spki format.\n * @param rsa the rsa service\n * @param publicKeysSpkiHex public keys in spki format, hex encoded.\n * @param shaVersion the version of the Sha algorithm used in the keys generations. ()\n * @return public keys as crypto keys by their fingerprint.\n */\nexport async function loadPublicKeys(\n rsa: RSAUtils,\n publicKeysSpkiHex: string[],\n shaVersion: ShaVersion\n): Promise<{ [publicKeyFingerprint: string]: CryptoKey }> {\n return Object.fromEntries(\n await Promise.all(publicKeysSpkiHex.map(async (x) => [fingerprintV1(x), await rsa.importKey('spki', hex2ua(x), ['encrypt'], shaVersion)]))\n )\n}\n\n/**\n * @internal This method is intended only for internal use and may be changed without notice.\n * Creates a delegation for the current data owner if the data owner is an encrypted entity and there is no delegation to himself.\n * @return the updated self.\n */\nexport async function ensureDelegationForSelf(\n dataOwnerApi: IccDataOwnerXApi,\n xapi: ExtendedApisUtils,\n patientApi: IccPatientApi,\n cryptoPrimitives: CryptoPrimitives\n): Promise<DataOwnerWithType> {\n const self = await dataOwnerApi.getCurrentDataOwner()\n if (self.type === 'patient') {\n const patient = new Patient(self.dataOwner)\n const patientWithType: EncryptedEntityWithType = { entity: patient, type: EntityWithDelegationTypeName.Patient }\n const availableSecretIds = await xapi.secretIdsOf(patientWithType, undefined)\n if (availableSecretIds.length) {\n return self\n } else {\n if (xapi.hasEmptyEncryptionMetadata(patient)) {\n // This should not really happen, usually some user will have already initialised the patient and its encryption metadata.\n const updatedPatient = await xapi.entityWithInitialisedEncryptedMetadata(\n patient,\n EntityWithDelegationTypeName.Patient,\n undefined,\n undefined,\n true,\n true,\n {}\n )\n return { dataOwner: await patientApi.modifyPatient(updatedPatient.updatedEntity), type: DataOwnerTypeEnum.Patient }\n } else {\n const updatedPatient = await xapi.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n false,\n {\n [patient.id!]: {\n shareEncryptionKeys: ShareMetadataBehaviour.IF_AVAILABLE,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [cryptoPrimitives.randomUuid()],\n requestedPermissions: RequestedPermissionEnum.FULL_WRITE,\n },\n },\n (x) => patientApi.bulkSharePatients(x)\n )\n return { dataOwner: updatedPatient.updatedEntityOrThrow, type: DataOwnerTypeEnum.Patient }\n }\n }\n } else {\n return self\n }\n}\n\n/**\n * Search a public key in the data owner and returns the corresponding SHA version used to generate it or undefined if not found.\n * @param dataOwner the data owner.\n * @param publicKey the public key.\n * @return 'sha-1', 'sha-256', undefined\n */\nexport function getShaVersionForKey(dataOwner: DataOwnerOrStub, publicKey: string): ShaVersion | undefined {\n return dataOwner.publicKey === publicKey || Object.keys(dataOwner.aesExchangeKeys ?? {}).includes(publicKey)\n ? ShaVersion.Sha1\n : !!dataOwner.publicKeysForOaepWithSha256?.includes(publicKey)\n ? ShaVersion.Sha256\n : undefined\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters)\n * of the SPKI key.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV1(key: string): string {\n return key.slice(-32)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters) from which the\n * last 5 (10 characters) are removed because they are a constant of the SPKI format.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV2(key: string): string {\n return key.slice(-32, -10)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Converts the fingerprint of a key from a V1 format to a V2 format.\n * @param fp the fingerprint of the key in the V1 format.\n * @return the fingerprint of the key in the v2 format.\n */\nexport function fingerprintV1toV2(fp: string): string {\n return fp.slice(0, -10)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V1 format, false otherwise.\n */\nexport function fingerprintIsV1(fp: string): boolean {\n return fp.length === 32\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V2 format, false otherwise.\n */\nexport function fingerprintIsV2(fp: string): boolean {\n return fp.length === 22\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wBAAwB;AACxB,sDAAsF;AAEtF,+BAA4C;AAC5C,oCAA+D;AAC/D,yDAAqD;AAKrD,qEAAiE;AACjE,wFAAoF;AAEpF,6EAAyE;AACzE,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,SAAoB;;IAC5D,OAAO,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,MAAA,SAAS,CAAC,2BAA2B,mCAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAa,CAAC,CAAA;AAC7G,CAAC;AAFD,8DAEC;AAED;;;GAGG;AACH,SAAgB,uBAAuB,CAAC,SAAoB;;IAC1D,OAAO,IAAI,GAAG,CAAC,CAAC,SAAS,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,MAAA,SAAS,CAAC,eAAe,mCAAI,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAa,CAAC,CAAA;AACjI,CAAC;AAFD,0DAEC;AAED;;;;;;GAMG;AACH,SAAgB,qBAAqB,CAAC,SAAoB;;IACxD,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,uBAAuB,CAAC,SAAS,CAAC,EAAE,GAAG,yBAAyB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;IAC/G,MAAM,KAAK,GAAuB,EAA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,GAAW;IACvC,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAA;AAC5B,CAAC;AAFD,sCAEC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,EAAU;IAC1C,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAA;AACzB,CAAC;AAFD,8CAEC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,eAAe,CAAC,EAAU;IACxC,OAAO,EAAE,CAAC,MAAM,KAAK,EAAE,CAAA;AACzB,CAAC;AAFD,0CAEC;AAED;;;;GAIG;AACH,SAAgB,yBAAyB,CAAC,EAAU;IAClD,OAAO,EAAE,GAAG,YAAY,CAAA;AAC1B,CAAC;AAFD,8DAEC;AAED;;;;GAIG;AACH,SAAgB,0BAA0B,CAAC,eAAuB;IAChE,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,IAAI,YAAY,EAAE;QAC9C,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAA;KAClF;AACH,CAAC;AAJD,gEAIC","sourcesContent":["// Uses fp as node names\nimport { acyclic, graphFromEdges, StronglyConnectedGraph } from '../utils/graph-utils'\nimport { DataOwner, DataOwnerOrStub, IccDataOwnerXApi } from '../icc-data-owner-x-api'\nimport { RSAUtils, ShaVersion } from './RSA'\nimport { EntityWithDelegationTypeName, hex2ua } from '../utils'\nimport { Patient } from '../../icc-api/model/Patient'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedEntityWithType } from '../utils/EntityWithDelegationTypeName'\nimport { IccPatientApi } from '../../icc-api'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport { DataOwnerWithType } from '../../icc-api/model/DataOwnerWithType'\nimport { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha256.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha256Of(dataOwner: DataOwner) {\n return new Set([...(dataOwner.publicKeysForOaepWithSha256 ?? [])].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * Get the public keys of a data owner which should be used for RSA-OAEP with sha1.\n * @param dataOwner\n */\nexport function hexPublicKeysWithSha1Of(dataOwner: DataOwner) {\n return new Set([dataOwner.publicKey, ...Object.keys(dataOwner.aesExchangeKeys ?? {})].filter((pubKey) => !!pubKey) as string[])\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get the transfer key graph for a data owner. Node names are the public key fingerprints of the data owner's keys, and an edge represents a key\n * which can be retrieved from another key using the transfer keys.\n * @param dataOwner a data owner.\n * @return a graph representing the possible key recovery paths using transfer keys for hte provided data owner.\n */\nexport function transferKeysFpGraphOf(dataOwner: DataOwner): StronglyConnectedGraph {\n const publicKeys = Array.from([...hexPublicKeysWithSha1Of(dataOwner), ...hexPublicKeysWithSha256Of(dataOwner)])\n const edges: [string, string][] = []\n Object.entries(dataOwner.transferKeys ?? {}).forEach(([from, tos]) => {\n Object.keys(tos).forEach((to) => {\n edges.push([fingerprintV1(from), fingerprintV1(to)])\n })\n })\n return acyclic(\n graphFromEdges(\n edges,\n publicKeys.map((x) => fingerprintV1(x))\n )\n )\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Get a map for converting public keys fingerprint to full public keys for the provided data owner.\n * @param dataOwner a data owner.\n * @param shaVersion gets only the keys that are generated with this SHA version (default: 'sha-1').\n * @return a map to convert fingerprints of the data owner into full public keys.\n */\nexport function fingerprintToPublicKeysMapOf(dataOwner: DataOwner, shaVersion: ShaVersion): { [fp: string]: string } {\n const publicKeys = shaVersion === 'sha-1' ? Array.from(hexPublicKeysWithSha1Of(dataOwner)) : Array.from(hexPublicKeysWithSha256Of(dataOwner))\n const res: { [fp: string]: string } = {}\n publicKeys.forEach((pk) => {\n res[fingerprintV1(pk)] = pk\n })\n return res\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Load many public keys in spki format.\n * @param rsa the rsa service\n * @param publicKeysSpkiHex public keys in spki format, hex encoded.\n * @param shaVersion the version of the Sha algorithm used in the keys generations. ()\n * @return public keys as crypto keys by their fingerprint.\n */\nexport async function loadPublicKeys(\n rsa: RSAUtils,\n publicKeysSpkiHex: string[],\n shaVersion: ShaVersion\n): Promise<{ [publicKeyFingerprint: string]: CryptoKey }> {\n return Object.fromEntries(\n await Promise.all(publicKeysSpkiHex.map(async (x) => [fingerprintV1(x), await rsa.importKey('spki', hex2ua(x), ['encrypt'], shaVersion)]))\n )\n}\n\n/**\n * @internal This method is intended only for internal use and may be changed without notice.\n * Creates a delegation for the current data owner if the data owner is an encrypted entity and there is no delegation to himself.\n * @return the updated self.\n */\nexport async function ensureDelegationForSelf(\n dataOwnerApi: IccDataOwnerXApi,\n xapi: ExtendedApisUtils,\n patientApi: IccPatientApi,\n cryptoPrimitives: CryptoPrimitives\n): Promise<DataOwnerWithType> {\n const self = await dataOwnerApi.getCurrentDataOwner()\n if (self.type === 'patient') {\n const patient = new Patient(self.dataOwner)\n const patientWithType: EncryptedEntityWithType = { entity: patient, type: EntityWithDelegationTypeName.Patient }\n const availableSecretIds = await xapi.secretIdsOf(patientWithType, undefined)\n if (availableSecretIds.length) {\n return self\n } else {\n if (xapi.hasEmptyEncryptionMetadata(patient)) {\n // This should not really happen, usually some user will have already initialised the patient and its encryption metadata.\n const updatedPatient = await xapi.entityWithInitialisedEncryptedMetadata(\n patient,\n EntityWithDelegationTypeName.Patient,\n undefined,\n undefined,\n true,\n true,\n {}\n )\n return { dataOwner: await patientApi.modifyPatient(updatedPatient.updatedEntity), type: DataOwnerTypeEnum.Patient }\n } else {\n const updatedPatient = await xapi.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: patient, type: EntityWithDelegationTypeName.Patient },\n false,\n {\n [patient.id!]: {\n shareEncryptionKeys: ShareMetadataBehaviour.IF_AVAILABLE,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n shareSecretIds: [cryptoPrimitives.randomUuid()],\n requestedPermissions: RequestedPermissionEnum.FULL_WRITE,\n },\n },\n (x) => patientApi.bulkSharePatients(x)\n )\n return { dataOwner: updatedPatient.updatedEntityOrThrow, type: DataOwnerTypeEnum.Patient }\n }\n }\n } else {\n return self\n }\n}\n\n/**\n * Search a public key in the data owner and returns the corresponding SHA version used to generate it or undefined if not found.\n * @param dataOwner the data owner.\n * @param publicKey the public key.\n * @return 'sha-1', 'sha-256', undefined\n */\nexport function getShaVersionForKey(dataOwner: DataOwnerOrStub, publicKey: string): ShaVersion | undefined {\n return dataOwner.publicKey === publicKey || Object.keys(dataOwner.aesExchangeKeys ?? {}).includes(publicKey)\n ? ShaVersion.Sha1\n : !!dataOwner.publicKeysForOaepWithSha256?.includes(publicKey)\n ? ShaVersion.Sha256\n : undefined\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters)\n * of the SPKI key.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV1(key: string): string {\n return key.slice(-32)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Calculates the fingerprint from the hexadecimal representation of a SPKI key. The fingerprint is calculated as the last 16 bytes (32 characters) from which the\n * last 5 (10 characters) are removed because they are a constant of the SPKI format.\n * @param key the hexadecimal representation of the SPKI key.\n * @return the fingerprint.\n */\nexport function fingerprintV2(key: string): string {\n return key.slice(-32, -10)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * Converts the fingerprint of a key from a V1 format to a V2 format.\n * @param fp the fingerprint of the key in the V1 format.\n * @return the fingerprint of the key in the v2 format.\n */\nexport function fingerprintV1toV2(fp: string): string {\n return fp.slice(0, -10)\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V1 format, false otherwise.\n */\nexport function fingerprintIsV1(fp: string): boolean {\n return fp.length === 32\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint.\n * @return true if the fingerprint is in V2 format, false otherwise.\n */\nexport function fingerprintIsV2(fp: string): boolean {\n return fp.length === 22\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param fp the fingerprint v2.\n * @return the fingerprint v1 using the standard tail.\n */\nexport function fingerprintV2ToStandardV1(fp: string): string {\n return fp + '0203010001'\n}\n\n/**\n * @internal this function is meant only for internal use and may be changed without notice.\n * @param publicKeyOrFpv1 a public key in spki format or a public key fp v1\n * @throws if the input does not terminate with 0203010001\n */\nexport function checkStandardPublicKeyTail(publicKeyOrFpv1: string) {\n if (publicKeyOrFpv1.slice(-10) != '0203010001') {\n throw new Error('Illegal state: generated public key should end with 0203010001')\n }\n}\n"]}
|
|
@@ -185,7 +185,7 @@ class IccDataOwnerXApi extends IccDataownerApi_1.IccDataownerApi {
|
|
|
185
185
|
}
|
|
186
186
|
checkDataOwnerIntegrity(dataOwner) {
|
|
187
187
|
const keys = new Set([...this.getHexPublicKeysWithSha1Of(dataOwner), ...this.getHexPublicKeysWithSha256Of(dataOwner)]);
|
|
188
|
-
if (new Set(Array.from(keys).map((x) =>
|
|
188
|
+
if (new Set(Array.from(keys).map((x) => (0, utils_1.fingerprintV2)(x))).size != keys.size)
|
|
189
189
|
throw new Error(`Different public keys for ${dataOwner.id} have the same fingerprint; this should not happen in normal circumstances. Please report this error to iCure.`);
|
|
190
190
|
}
|
|
191
191
|
forceLoadCurrentDataOwnerHierarchyAndCacheIds() {
|
|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,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,0BAA0B,CAAC,SAAS,CAAC,EAAE,GAAG,IAAI,CAAC,4BAA4B,CAAC,SAAS,CAAC,CAAC,CAAC,CAAA;QACtH,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI;YACtE,MAAM,IAAI,KAAK,CACb,6BAA6B,SAAS,CAAC,EAAE,gHAAgH,CAC1J,CAAA;IACL,CAAC;IAEa,6CAA6C;;YACzD,IAAI,IAAI,GAAG,MAAM,IAAI,CAAC,mBAAmB,EAAE,CAAA;YAC3C,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;YAC5C,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,IAAI,CAAA;YACrC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,CAAA;YAChB,OAAQ,IAAI,CAAC,SAA6B,CAAC,QAAQ,EAAE;gBACnD,IAAI,GAAG,MAAM,IAAI,CAAC,YAAY,CAAE,IAAI,CAAC,SAA6B,CAAC,QAAS,CAAC,CAAA;gBAC7E,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAA;aACrB;YACD,IAAI,CAAC,4BAA4B,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,EAAG,CAAC,CAAA;YACnE,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF;AAvLD,4CAuLC","sourcesContent":["import { User } from '../icc-api/model/User'\nimport { IccDeviceApi, IccPatientApi, IccUserApi } from '../icc-api'\nimport { HealthcareParty } from '../icc-api/model/HealthcareParty'\nimport { Patient } from '../icc-api/model/Patient'\nimport { Device } from '../icc-api/model/Device'\nimport { fingerprintV1, hexPublicKeysWithSha1Of, hexPublicKeysWithSha256Of } from './crypto/utils'\nimport { IccHcpartyXApi } from './icc-hcparty-x-api'\nimport { XHR } from '../icc-api/api/XHR'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../icc-api/model/CryptoActorStub'\nimport { DataOwnerTypeEnum } from '../icc-api/model/DataOwnerTypeEnum'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { IccDataownerApi } from '../icc-api/api/IccDataownerApi'\nimport { DataOwnerWithType } from '../icc-api/model/DataOwnerWithType'\n\nexport type DataOwnerOrStub = DataOwner | CryptoActorStub\nexport type DataOwner = HealthcareParty | Patient | Device\n\nexport class IccDataOwnerXApi extends IccDataownerApi {\n private currentDataOwnerType: DataOwnerTypeEnum | undefined\n private currentDataOwnerHierarchyIds: string[] | undefined\n\n private get selfDataOwnerId(): string | undefined {\n if (!this.currentDataOwnerHierarchyIds) return undefined\n return this.currentDataOwnerHierarchyIds[this.currentDataOwnerHierarchyIds.length - 1]\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Gets the public keys of a data owner to be used for encryption with RSA-OAEP+SHA-1, in hex format.\n * @param dataOwner a data owner.\n * @return the public keys for the data owner in hex format.\n */\n getHexPublicKeysWithSha1Of(dataOwner: DataOwnerOrStub): Set<string> {\n return hexPublicKeysWithSha1Of(dataOwner)\n }\n\n /**\n * Gets the public keys of a data owner to be used for encryption with RSA-OAEP+SHA-256, in hex format.\n * @param dataOwner a data owner.\n * @return the public keys for the data owner in hex format.\n */\n getHexPublicKeysWithSha256Of(dataOwner: DataOwnerOrStub): Set<string> {\n return hexPublicKeysWithSha256Of(dataOwner)\n }\n\n /**\n * Gets all public keys of a data owner to be used for encryption, in hex format. Note that this may include keys that should be used for different\n * encryption algorithms.\n */\n getHexPublicKeysOf(dataOwner: DataOwnerOrStub): Set<string> {\n return new Set([...this.getHexPublicKeysWithSha1Of(dataOwner), ...this.getHexPublicKeysWithSha256Of(dataOwner)])\n }\n\n async getCurrentDataOwnerStub(): Promise<CryptoActorStubWithType> {\n return CryptoActorStubWithType.fromDataOwner(await this.getCurrentDataOwner())\n }\n\n /**\n * If the logged user is a data owner get the current data owner. This information is cached without expiration, and will only be updated in case\n * of forced refresh.\n * @throws if the current user is not a data owner.\n */\n async getCurrentDataOwnerId(): Promise<string> {\n if (!this.currentDataOwnerHierarchyIds) {\n await this.getCurrentDataOwnerHierarchyIds()\n }\n return this.currentDataOwnerHierarchyIds![this.currentDataOwnerHierarchyIds!.length - 1]\n }\n\n /**\n * If the logged user is a data owner get its parent hierarchy. This information is cached without expiration, and will only be updated in case\n * of forced refresh.\n * The resulting array starts with the topmost parent (the only ancestor without a parent) and ends with the data owner itself.\n * @throws if the current user is not a data owner.\n */\n async getCurrentDataOwnerHierarchyIds(): Promise<string[]> {\n if (!this.currentDataOwnerHierarchyIds) {\n await this.forceLoadCurrentDataOwnerHierarchyAndCacheIds()\n }\n return [...this.currentDataOwnerHierarchyIds!]\n }\n\n /**\n * Get the hierarchy for the current data owner starting from the specified parent.\n * @throws an array starting at the topmost parent and ending at the provided parent id. If the provided id is not part of the hierarchy throws an\n * error.\n */\n async getCurrentDataOwnerHierarchyIdsFrom(parentId: string): Promise<string[]> {\n if (!this.currentDataOwnerHierarchyIds) {\n await this.getCurrentDataOwnerHierarchyIds()\n }\n const res = []\n for (const dataOwnerId of this.currentDataOwnerHierarchyIds!) {\n res.push(dataOwnerId)\n if (dataOwnerId === parentId) return res\n }\n throw new Error(`${parentId} is not part of the data owner hierarchy for the current user`)\n }\n\n /**\n * If the logged user is a data owner get the current data owner and all of his parents.\n * @throws if the current user is not a data owner.\n * @return the current data owner hierarchy, starting from the topmost parent to the current data owner.\n */\n async getCurrentDataOwnerHierarchy(): Promise<DataOwnerWithType[]> {\n if (!this.currentDataOwnerHierarchyIds) {\n return await this.forceLoadCurrentDataOwnerHierarchyAndCacheIds()\n } else return Promise.all(this.currentDataOwnerHierarchyIds!.map((id) => this.getDataOwner(id)))\n }\n\n /**\n * If the logged user is a data owner get the type of the current data owner. This information is cached.\n * @throws if the current user is not a data owner\n */\n async getCurrentDataOwnerType(): Promise<DataOwnerTypeEnum> {\n if (!this.currentDataOwnerHierarchyIds) {\n await this.forceLoadCurrentDataOwnerHierarchyAndCacheIds()\n }\n return this.currentDataOwnerType!\n }\n\n /**\n * Get the id of the data owner entity for a user.\n * @param user a user that is also a data owner.\n * @return the id of the data owner corresponding to the provided user.\n * @throws if the user is not a data owner.\n */\n getDataOwnerIdOf(user: User): string {\n const dataOwnerId = user.healthcarePartyId ?? user.patientId ?? user.deviceId\n if (dataOwnerId == undefined) {\n throw Error(`User ${user.id} is not a data owner`)\n }\n return dataOwnerId\n }\n\n /**\n * Get a data owner. Note that this does not decrpyt patient data owners.\n * @param ownerId id of the data owner to retrieve (patient, medical device, hcp, ...)\n * @return the data owner with the provided id\n * @throws if you have no access to the data owner. Use {@link getCryptoActorStub}.\n */\n async getDataOwner(ownerId: string): Promise<DataOwnerWithType> {\n return super.getDataOwner(ownerId).then((dowt) => {\n if (dowt.dataOwner.id === this.selfDataOwnerId) this.checkDataOwnerIntegrity(dowt.dataOwner)\n return dowt\n })\n }\n\n /**\n * Get a crypto actor stub for a data owner.\n * @param ownerId id of the data owner for which you want to retrieve the stub (patient, medical device, hcp, ...)\n * @return the crypto actor stub of the data owner with the provided id\n */\n async getCryptoActorStub(ownerId: string): Promise<CryptoActorStubWithType> {\n return super.getCryptoActorStub(ownerId).then((dowt) => {\n if (dowt.stub.id === this.selfDataOwnerId) this.checkDataOwnerIntegrity(dowt.stub)\n return dowt\n })\n }\n\n /**\n * Clears the cache of current data owner id and parent hierarchy ids. The hierarchy of a data owner should not normally change over time, so this\n * method should be rarely needed.\n */\n clearCurrentDataOwnerIdsCache() {\n this.currentDataOwnerHierarchyIds = undefined\n }\n\n private checkDataOwnerIntegrity(dataOwner: DataOwnerOrStub) {\n const keys = new Set([...this.getHexPublicKeysWithSha1Of(dataOwner), ...this.getHexPublicKeysWithSha256Of(dataOwner)])\n if (new Set(Array.from(keys).map((x) => x.slice(-32))).size != keys.size)\n throw new Error(\n `Different public keys for ${dataOwner.id} have the same fingerprint; this should not happen in normal circumstances. Please report this error to iCure.`\n )\n }\n\n private async forceLoadCurrentDataOwnerHierarchyAndCacheIds(): Promise<DataOwnerWithType[]> {\n let curr = await this.getCurrentDataOwner()\n this.checkDataOwnerIntegrity(curr.dataOwner)\n this.currentDataOwnerType = curr.type\n let res = [curr]\n while ((curr.dataOwner as HealthcareParty).parentId) {\n curr = await this.getDataOwner((curr.dataOwner as HealthcareParty).parentId!)\n res = [curr, ...res]\n }\n this.currentDataOwnerHierarchyIds = res.map((x) => x.dataOwner.id!)\n return res\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"icc-data-owner-x-api.js","sourceRoot":"","sources":["../../icc-x-api/icc-data-owner-x-api.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,0CAAiH;AAGjH,sEAA2F;AAE3F,0EAAgG;AAChG,oEAAgE;AAMhE,MAAa,gBAAiB,SAAQ,iCAAe;IAInD,IAAY,eAAe;QACzB,IAAI,CAAC,IAAI,CAAC,4BAA4B;YAAE,OAAO,SAAS,CAAA;QACxD,OAAO,IAAI,CAAC,4BAA4B,CAAC,IAAI,CAAC,4BAA4B,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;IACxF,CAAC;IAED,YACE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;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AI,CAAC,SAAS,CAAC,CAAA;YAC5C,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,IAAI,CAAA;YACrC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,CAAA;YAChB,OAAQ,IAAI,CAAC,SAA6B,CAAC,QAAQ,EAAE;gBACnD,IAAI,GAAG,MAAM,IAAI,CAAC,YAAY,CAAE,IAAI,CAAC,SAA6B,CAAC,QAAS,CAAC,CAAA;gBAC7E,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAA;aACrB;YACD,IAAI,CAAC,4BAA4B,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,EAAG,CAAC,CAAA;YACnE,OAAO,GAAG,CAAA;QACZ,CAAC;KAAA;CACF;AAvLD,4CAuLC","sourcesContent":["import { User } from '../icc-api/model/User'\nimport { IccDeviceApi, IccPatientApi, IccUserApi } from '../icc-api'\nimport { HealthcareParty } from '../icc-api/model/HealthcareParty'\nimport { Patient } from '../icc-api/model/Patient'\nimport { Device } from '../icc-api/model/Device'\nimport { fingerprintV1, fingerprintV2, hexPublicKeysWithSha1Of, hexPublicKeysWithSha256Of } from './crypto/utils'\nimport { IccHcpartyXApi } from './icc-hcparty-x-api'\nimport { XHR } from '../icc-api/api/XHR'\nimport { CryptoActorStub, CryptoActorStubWithType } from '../icc-api/model/CryptoActorStub'\nimport { DataOwnerTypeEnum } from '../icc-api/model/DataOwnerTypeEnum'\nimport { AuthenticationProvider, NoAuthenticationProvider } from './auth/AuthenticationProvider'\nimport { IccDataownerApi } from '../icc-api/api/IccDataownerApi'\nimport { DataOwnerWithType } from '../icc-api/model/DataOwnerWithType'\n\nexport type DataOwnerOrStub = DataOwner | CryptoActorStub\nexport type DataOwner = HealthcareParty | Patient | Device\n\nexport class IccDataOwnerXApi extends IccDataownerApi {\n private currentDataOwnerType: DataOwnerTypeEnum | undefined\n private currentDataOwnerHierarchyIds: string[] | undefined\n\n private get selfDataOwnerId(): string | undefined {\n if (!this.currentDataOwnerHierarchyIds) return undefined\n return this.currentDataOwnerHierarchyIds[this.currentDataOwnerHierarchyIds.length - 1]\n }\n\n constructor(\n host: string,\n headers: { [key: string]: string },\n authenticationProvider: AuthenticationProvider = new NoAuthenticationProvider(),\n fetchImpl: (input: RequestInfo, init?: RequestInit) => Promise<Response> = typeof window !== 'undefined'\n ? window.fetch\n : typeof self !== 'undefined'\n ? self.fetch\n : fetch\n ) {\n super(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Gets the public keys of a data owner to be used for encryption with RSA-OAEP+SHA-1, in hex format.\n * @param dataOwner a data owner.\n * @return the public keys for the data owner in hex format.\n */\n getHexPublicKeysWithSha1Of(dataOwner: DataOwnerOrStub): Set<string> {\n return hexPublicKeysWithSha1Of(dataOwner)\n }\n\n /**\n * Gets the public keys of a data owner to be used for encryption with RSA-OAEP+SHA-256, in hex format.\n * @param dataOwner a data owner.\n * @return the public keys for the data owner in hex format.\n */\n getHexPublicKeysWithSha256Of(dataOwner: DataOwnerOrStub): Set<string> {\n return hexPublicKeysWithSha256Of(dataOwner)\n }\n\n /**\n * Gets all public keys of a data owner to be used for encryption, in hex format. Note that this may include keys that should be used for different\n * encryption algorithms.\n */\n getHexPublicKeysOf(dataOwner: DataOwnerOrStub): Set<string> {\n return new Set([...this.getHexPublicKeysWithSha1Of(dataOwner), ...this.getHexPublicKeysWithSha256Of(dataOwner)])\n }\n\n async getCurrentDataOwnerStub(): Promise<CryptoActorStubWithType> {\n return CryptoActorStubWithType.fromDataOwner(await this.getCurrentDataOwner())\n }\n\n /**\n * If the logged user is a data owner get the current data owner. This information is cached without expiration, and will only be updated in case\n * of forced refresh.\n * @throws if the current user is not a data owner.\n */\n async getCurrentDataOwnerId(): Promise<string> {\n if (!this.currentDataOwnerHierarchyIds) {\n await this.getCurrentDataOwnerHierarchyIds()\n }\n return this.currentDataOwnerHierarchyIds![this.currentDataOwnerHierarchyIds!.length - 1]\n }\n\n /**\n * If the logged user is a data owner get its parent hierarchy. This information is cached without expiration, and will only be updated in case\n * of forced refresh.\n * The resulting array starts with the topmost parent (the only ancestor without a parent) and ends with the data owner itself.\n * @throws if the current user is not a data owner.\n */\n async getCurrentDataOwnerHierarchyIds(): Promise<string[]> {\n if (!this.currentDataOwnerHierarchyIds) {\n await this.forceLoadCurrentDataOwnerHierarchyAndCacheIds()\n }\n return [...this.currentDataOwnerHierarchyIds!]\n }\n\n /**\n * Get the hierarchy for the current data owner starting from the specified parent.\n * @throws an array starting at the topmost parent and ending at the provided parent id. If the provided id is not part of the hierarchy throws an\n * error.\n */\n async getCurrentDataOwnerHierarchyIdsFrom(parentId: string): Promise<string[]> {\n if (!this.currentDataOwnerHierarchyIds) {\n await this.getCurrentDataOwnerHierarchyIds()\n }\n const res = []\n for (const dataOwnerId of this.currentDataOwnerHierarchyIds!) {\n res.push(dataOwnerId)\n if (dataOwnerId === parentId) return res\n }\n throw new Error(`${parentId} is not part of the data owner hierarchy for the current user`)\n }\n\n /**\n * If the logged user is a data owner get the current data owner and all of his parents.\n * @throws if the current user is not a data owner.\n * @return the current data owner hierarchy, starting from the topmost parent to the current data owner.\n */\n async getCurrentDataOwnerHierarchy(): Promise<DataOwnerWithType[]> {\n if (!this.currentDataOwnerHierarchyIds) {\n return await this.forceLoadCurrentDataOwnerHierarchyAndCacheIds()\n } else return Promise.all(this.currentDataOwnerHierarchyIds!.map((id) => this.getDataOwner(id)))\n }\n\n /**\n * If the logged user is a data owner get the type of the current data owner. This information is cached.\n * @throws if the current user is not a data owner\n */\n async getCurrentDataOwnerType(): Promise<DataOwnerTypeEnum> {\n if (!this.currentDataOwnerHierarchyIds) {\n await this.forceLoadCurrentDataOwnerHierarchyAndCacheIds()\n }\n return this.currentDataOwnerType!\n }\n\n /**\n * Get the id of the data owner entity for a user.\n * @param user a user that is also a data owner.\n * @return the id of the data owner corresponding to the provided user.\n * @throws if the user is not a data owner.\n */\n getDataOwnerIdOf(user: User): string {\n const dataOwnerId = user.healthcarePartyId ?? user.patientId ?? user.deviceId\n if (dataOwnerId == undefined) {\n throw Error(`User ${user.id} is not a data owner`)\n }\n return dataOwnerId\n }\n\n /**\n * Get a data owner. Note that this does not decrpyt patient data owners.\n * @param ownerId id of the data owner to retrieve (patient, medical device, hcp, ...)\n * @return the data owner with the provided id\n * @throws if you have no access to the data owner. Use {@link getCryptoActorStub}.\n */\n async getDataOwner(ownerId: string): Promise<DataOwnerWithType> {\n return super.getDataOwner(ownerId).then((dowt) => {\n if (dowt.dataOwner.id === this.selfDataOwnerId) this.checkDataOwnerIntegrity(dowt.dataOwner)\n return dowt\n })\n }\n\n /**\n * Get a crypto actor stub for a data owner.\n * @param ownerId id of the data owner for which you want to retrieve the stub (patient, medical device, hcp, ...)\n * @return the crypto actor stub of the data owner with the provided id\n */\n async getCryptoActorStub(ownerId: string): Promise<CryptoActorStubWithType> {\n return super.getCryptoActorStub(ownerId).then((dowt) => {\n if (dowt.stub.id === this.selfDataOwnerId) this.checkDataOwnerIntegrity(dowt.stub)\n return dowt\n })\n }\n\n /**\n * Clears the cache of current data owner id and parent hierarchy ids. The hierarchy of a data owner should not normally change over time, so this\n * method should be rarely needed.\n */\n clearCurrentDataOwnerIdsCache() {\n this.currentDataOwnerHierarchyIds = undefined\n }\n\n private checkDataOwnerIntegrity(dataOwner: DataOwnerOrStub) {\n const keys = new Set([...this.getHexPublicKeysWithSha1Of(dataOwner), ...this.getHexPublicKeysWithSha256Of(dataOwner)])\n if (new Set(Array.from(keys).map((x) => fingerprintV2(x))).size != keys.size)\n throw new Error(\n `Different public keys for ${dataOwner.id} have the same fingerprint; this should not happen in normal circumstances. Please report this error to iCure.`\n )\n }\n\n private async forceLoadCurrentDataOwnerHierarchyAndCacheIds(): Promise<DataOwnerWithType[]> {\n let curr = await this.getCurrentDataOwner()\n this.checkDataOwnerIntegrity(curr.dataOwner)\n this.currentDataOwnerType = curr.type\n let res = [curr]\n while ((curr.dataOwner as HealthcareParty).parentId) {\n curr = await this.getDataOwner((curr.dataOwner as HealthcareParty).parentId!)\n res = [curr, ...res]\n }\n this.currentDataOwnerHierarchyIds = res.map((x) => x.dataOwner.id!)\n return res\n }\n}\n"]}
|
|
@@ -19,6 +19,7 @@ const KeyPairUpdateRequest_1 = require("./maintenance/KeyPairUpdateRequest");
|
|
|
19
19
|
const SecureDelegation_1 = require("../icc-api/model/SecureDelegation");
|
|
20
20
|
const DataOwnerTypeEnum_1 = require("../icc-api/model/DataOwnerTypeEnum");
|
|
21
21
|
var AccessLevelEnum = SecureDelegation_1.SecureDelegation.AccessLevelEnum;
|
|
22
|
+
const utils_2 = require("./crypto/utils");
|
|
22
23
|
/**
|
|
23
24
|
* Api for interpreting maintenance tasks and applying required client-side actions.
|
|
24
25
|
*/
|
|
@@ -64,7 +65,7 @@ class IccIcureMaintenanceXApi {
|
|
|
64
65
|
}
|
|
65
66
|
}
|
|
66
67
|
const hexNewPubKey = (0, utils_1.ua2hex)(yield this.crypto.primitives.RSA.exportKey(keypair.publicKey, 'spki'));
|
|
67
|
-
const hexNewPubKeyFp =
|
|
68
|
+
const hexNewPubKeyFp = (0, utils_2.fingerprintV1)(hexNewPubKey);
|
|
68
69
|
const selfId = yield this.dataOwnerApi.getCurrentDataOwnerId();
|
|
69
70
|
const requestDataOwnersForExchangeKeys = (yield this.getExchangeKeysInfosOf(selfId, requestToOwnerTypes))
|
|
70
71
|
.filter((info) => !info.fingerprints.has(hexNewPubKeyFp))
|
|
@@ -95,12 +96,12 @@ class IccIcureMaintenanceXApi {
|
|
|
95
96
|
const infoTo = Object.entries(allExchangeKeys.keysToOwner).flatMap(([delegatorId, delegatorFpToKeys]) => Object.values(delegatorFpToKeys).map((encryptedKeys) => ({
|
|
96
97
|
delegator: delegatorId,
|
|
97
98
|
delegate: dataOwnerId,
|
|
98
|
-
fingerprints: new Set(Object.keys(encryptedKeys).map((x) =>
|
|
99
|
+
fingerprints: new Set(Object.keys(encryptedKeys).map((x) => (0, utils_2.fingerprintV1)(x))),
|
|
99
100
|
})));
|
|
100
101
|
const infoFrom = Object.values(allExchangeKeys.keysFromOwner).flatMap((delegateIdToKeys) => Object.entries(delegateIdToKeys).map(([delegateId, encryptedKeys]) => ({
|
|
101
102
|
delegator: dataOwnerId,
|
|
102
103
|
delegate: delegateId,
|
|
103
|
-
fingerprints: new Set(Object.keys(encryptedKeys).map((x) =>
|
|
104
|
+
fingerprints: new Set(Object.keys(encryptedKeys).map((x) => (0, utils_2.fingerprintV1)(x))),
|
|
104
105
|
})));
|
|
105
106
|
return [...infoFrom, ...infoTo];
|
|
106
107
|
});
|