@icure/api 8.0.23 → 8.0.25
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/auth/JwtAuthService.js +11 -0
- package/icc-x-api/auth/JwtAuthService.js.map +1 -1
- package/icc-x-api/auth/JwtBridgedAuthService.js +17 -0
- package/icc-x-api/auth/JwtBridgedAuthService.js.map +1 -1
- package/icc-x-api/auth/JwtError.d.ts +7 -0
- package/icc-x-api/auth/JwtError.js +14 -0
- package/icc-x-api/auth/JwtError.js.map +1 -0
- package/icc-x-api/crypto/AES.d.ts +54 -2
- package/icc-x-api/crypto/AES.js +5 -5
- package/icc-x-api/crypto/AES.js.map +1 -1
- package/icc-x-api/crypto/CryptoPrimitives.d.ts +21 -12
- package/icc-x-api/crypto/CryptoPrimitives.js +8 -19
- package/icc-x-api/crypto/CryptoPrimitives.js.map +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js +1 -1
- package/icc-x-api/crypto/DelegationsDeAnonymization.js.map +1 -1
- package/icc-x-api/crypto/HMACUtils.d.ts +8 -1
- package/icc-x-api/crypto/HMACUtils.js +3 -3
- package/icc-x-api/crypto/HMACUtils.js.map +1 -1
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.d.ts +113 -0
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js +477 -0
- package/icc-x-api/crypto/NativeCryptoPrimitivesBridge.js.map +1 -0
- package/icc-x-api/crypto/RSA.d.ts +107 -4
- package/icc-x-api/crypto/RSA.js +4 -4
- package/icc-x-api/crypto/RSA.js.map +1 -1
- package/icc-x-api/crypto/TransferKeysManager.js +6 -1
- package/icc-x-api/crypto/TransferKeysManager.js.map +1 -1
- package/icc-x-api/crypto/shamir.d.ts +7 -3
- package/icc-x-api/crypto/shamir.js +14 -5
- package/icc-x-api/crypto/shamir.js.map +1 -1
- package/icc-x-api/index.d.ts +1 -0
- package/icc-x-api/index.js +5 -3
- package/icc-x-api/index.js.map +1 -1
- package/package.json +1 -1
- package/test/icc-api/api/IccMedicalLocationApi.js +6 -6
- package/test/icc-api/api/IccMedicalLocationApi.js.map +1 -1
- package/test/icc-x-api/auth/jwt-provider-test.d.ts +1 -0
- package/test/icc-x-api/auth/jwt-provider-test.js +138 -0
- package/test/icc-x-api/auth/jwt-provider-test.js.map +1 -0
- package/test/icc-x-api/crud/comprehensive-crud-test.js +1 -1
- package/test/icc-x-api/crud/comprehensive-crud-test.js.map +1 -1
- package/test/icc-x-api/crud/entities-crud-test-interface.js +1 -0
- package/test/icc-x-api/crud/entities-crud-test-interface.js.map +1 -1
- package/test/icc-x-api/crypto/anonymous-delegations-test.js +1 -2
- package/test/icc-x-api/crypto/anonymous-delegations-test.js.map +1 -1
- package/test/icc-x-api/crypto/crypto-utils.js +1 -2
- package/test/icc-x-api/crypto/crypto-utils.js.map +1 -1
- package/test/icc-x-api/crypto/exchange-data-manager-test.js +1 -1
- package/test/icc-x-api/crypto/exchange-data-manager-test.js.map +1 -1
- package/test/icc-x-api/crypto/full-crypto-test.js +1 -2
- package/test/icc-x-api/crypto/full-crypto-test.js.map +1 -1
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js +1 -1
- package/test/icc-x-api/crypto/secure-delegations-manager-test.js.map +1 -1
- package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.js +2 -2
- package/test/icc-x-api/crypto/secure-delegations-metadata-decryptor-test.js.map +1 -1
- package/test/icc-x-api/crypto/shamir.js +6 -7
- package/test/icc-x-api/crypto/shamir.js.map +1 -1
- package/test/icc-x-api/crypto/signature-keys-manager-test.js +1 -1
- package/test/icc-x-api/crypto/signature-keys-manager-test.js.map +1 -1
- package/test/icc-x-api/icc-maintenance-task-x-api-test.js +3 -2
- package/test/icc-x-api/icc-maintenance-task-x-api-test.js.map +1 -1
- package/test/icc-x-api/icc-user-x-api-test.js +1 -1
- package/test/icc-x-api/icc-user-x-api-test.js.map +1 -1
- package/test/icc-x-api/patient-user.js +1 -2
- package/test/icc-x-api/patient-user.js.map +1 -1
- package/test/icc-x-api/test-legacy-data-support.js +2 -3
- package/test/icc-x-api/test-legacy-data-support.js.map +1 -1
- package/test/utils/FakeDataOwnerApi.js +1 -1
- package/test/utils/FakeDataOwnerApi.js.map +1 -1
- package/test/utils/FakeGenericApi.js +1 -1
- package/test/utils/FakeGenericApi.js.map +1 -1
- package/test/utils/TestApi.js +1 -1
- package/test/utils/TestApi.js.map +1 -1
- package/test/utils/TestCryptoStrategies.js +1 -1
- package/test/utils/TestCryptoStrategies.js.map +1 -1
- package/test/utils/test_utils.js +6 -6
- package/test/utils/test_utils.js.map +1 -1
- package/test/icc-api/api/IccArticleApi.d.ts +0 -1
- package/test/icc-api/api/IccArticleApi.js +0 -64
- package/test/icc-api/api/IccArticleApi.js.map +0 -1
|
@@ -12,6 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
12
12
|
exports.JwtAuthService = void 0;
|
|
13
13
|
const XHR_1 = require("../../icc-api/api/XHR");
|
|
14
14
|
const JwtUtils_1 = require("./JwtUtils");
|
|
15
|
+
const JwtError_1 = require("./JwtError");
|
|
15
16
|
/**
|
|
16
17
|
* Differs from JwtBridgedAuthService in that it cannot create new refresh tokens
|
|
17
18
|
*/
|
|
@@ -33,6 +34,14 @@ class JwtAuthService {
|
|
|
33
34
|
getAuthHeaders() {
|
|
34
35
|
return __awaiter(this, void 0, void 0, function* () {
|
|
35
36
|
return this._currentPromise
|
|
37
|
+
.then((x) => ({ authJwt: x === null || x === void 0 ? void 0 : x.authJwt, refreshJwt: x === null || x === void 0 ? void 0 : x.refreshJwt }), (e) => {
|
|
38
|
+
if (e instanceof JwtError_1.JwtError && !!e.jwt && !!e.refreshJwt) {
|
|
39
|
+
return { authJwt: e.jwt, refreshJwt: e.refreshJwt };
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
throw new Error('There was an error while refreshing the token, please re-instantiate the API.');
|
|
43
|
+
}
|
|
44
|
+
})
|
|
36
45
|
.then((x) => {
|
|
37
46
|
const authJwt = x === null || x === void 0 ? void 0 : x.authJwt;
|
|
38
47
|
const refreshJwt = x === null || x === void 0 ? void 0 : x.refreshJwt;
|
|
@@ -46,6 +55,8 @@ class JwtAuthService {
|
|
|
46
55
|
throw new Error('Your iCure back-end version does not support JWT authentication');
|
|
47
56
|
}
|
|
48
57
|
return updatedTokens;
|
|
58
|
+
}, (e) => {
|
|
59
|
+
throw new JwtError_1.JwtError(authJwt, refreshJwt, 'There was an error while refreshing the token, please re-instantiate the API or try again.', e);
|
|
49
60
|
});
|
|
50
61
|
}
|
|
51
62
|
else if (!!this._error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JwtAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;
|
|
1
|
+
{"version":3,"file":"JwtAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAG3C,yCAAkD;AAClD,yCAAqC;AAErC;;GAEG;AACH,MAAa,cAAc;IAIzB,YAA6B,OAAmB,EAAE,UAAoD;QAAzE,YAAO,GAAP,OAAO,CAAY;QAHxC,WAAM,GAAiB,IAAI,CAAA;QAC3B,oBAAe,GAAiE,OAAO,CAAC,OAAO,CAAC,SAAgB,CAAC,CAAA;QAGvH,IAAI,CAAC,CAAC,UAAU,EAAE;YAChB,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,CAAA;SACnD;IACH,CAAC;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,aAAD,CAAC,uBAAD,CAAC,CAAE,UAAiB,CAAC,CAAA;IAC/D,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,C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,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAlFD,wCAkFC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi } from '../../icc-api'\nimport Header = XHR.Header\nimport { isJwtInvalidOrExpired } from './JwtUtils'\nimport { JwtError } from './JwtError'\n\n/**\n * Differs from JwtBridgedAuthService in that it cannot create new refresh tokens\n */\nexport class JwtAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt: string; refreshJwt: string } | undefined> = Promise.resolve(undefined as any)\n\n constructor(private readonly authApi: IccAuthApi, initialJwt?: { authJwt: string; refreshJwt: string }) {\n if (!!initialJwt) {\n this._currentPromise = Promise.resolve(initialJwt)\n }\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x?.refreshJwt as any)\n }\n\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this._currentPromise.then((x) => (x ? { token: x.authJwt, refreshToken: x.refreshJwt } : undefined))\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then(\n (x) => ({ authJwt: x?.authJwt, refreshJwt: x?.refreshJwt }),\n (e: Error) => {\n if (e instanceof JwtError && !!e.jwt && !!e.refreshJwt) {\n return { authJwt: e.jwt, refreshJwt: e.refreshJwt }\n } else {\n throw new Error('There was an error while refreshing the token, please re-instantiate the API.')\n }\n }\n )\n .then((x) => {\n const authJwt = x?.authJwt\n const refreshJwt = x?.refreshJwt\n\n if ((!authJwt || isJwtInvalidOrExpired(authJwt)) && refreshJwt) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then(\n (updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n },\n (e: Error) => {\n throw new JwtError(authJwt, refreshJwt, 'There was an error while refreshing the token, please re-instantiate the API or try again.', e)\n }\n )\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then((x) => {\n return x?.authJwt ? [new XHR.Header('Authorization', `Bearer ${x.authJwt}`)] : Promise.reject('Cannot provide auth: No JWT')\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string): Promise<{ authJwt: string; refreshJwt: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (isJwtInvalidOrExpired(refreshJwt)) {\n throw Error('Missing or expired refresh token: please log in again')\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token!,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
|
|
@@ -14,6 +14,7 @@ const XHR_1 = require("../../icc-api/api/XHR");
|
|
|
14
14
|
const LoginCredentials_1 = require("../../icc-api/model/LoginCredentials");
|
|
15
15
|
const utils_1 = require("../utils");
|
|
16
16
|
var XHRError = XHR_1.XHR.XHRError;
|
|
17
|
+
const JwtError_1 = require("./JwtError");
|
|
17
18
|
/**
|
|
18
19
|
* Differs from JwtAuthService in that it can create new refresh tokens if the old one is expired
|
|
19
20
|
*/
|
|
@@ -36,6 +37,20 @@ class JwtBridgedAuthService {
|
|
|
36
37
|
getJWT() {
|
|
37
38
|
return __awaiter(this, void 0, void 0, function* () {
|
|
38
39
|
return this._currentPromise
|
|
40
|
+
.then(({ authJwt, refreshJwt }) => ({ authJwt, refreshJwt }), (e) => {
|
|
41
|
+
if (e instanceof JwtError_1.JwtError) {
|
|
42
|
+
const wrappedError = e.reason;
|
|
43
|
+
if (!!wrappedError.statusCode && wrappedError.statusCode >= 400 && wrappedError.statusCode < 500) {
|
|
44
|
+
return { authJwt: undefined, refreshJwt: undefined };
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
return { authJwt: e.jwt, refreshJwt: e.refreshJwt };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
return { authJwt: undefined, refreshJwt: undefined };
|
|
52
|
+
}
|
|
53
|
+
})
|
|
39
54
|
.then(({ authJwt, refreshJwt }) => {
|
|
40
55
|
if (!authJwt || this._isJwtInvalidOrExpired(authJwt)) {
|
|
41
56
|
// If it does not have the JWT, tries to get it
|
|
@@ -47,6 +62,8 @@ class JwtBridgedAuthService {
|
|
|
47
62
|
throw new Error('Your iCure back-end version does not support JWT authentication');
|
|
48
63
|
}
|
|
49
64
|
return updatedTokens;
|
|
65
|
+
}, (e) => {
|
|
66
|
+
throw new JwtError_1.JwtError(authJwt, refreshJwt, 'There was an error while refreshing the token, please re-instantiate the API or try again.', e);
|
|
50
67
|
});
|
|
51
68
|
}
|
|
52
69
|
else if (!!this._error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JwtBridgedAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtBridgedAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAE3C,2EAAuE;AAEvE,oCAA8B;AAE9B,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAE9B;;GAEG;AACH,MAAa,qBAAqB;IAIhC,YACU,OAAmB,EACnB,QAA4B,EAC5B,QAA4B,EAC5B,mBAAqD,EAAE,EAC/D,UAA+D;QAJvD,YAAO,GAAP,OAAO,CAAY;QACnB,aAAQ,GAAR,QAAQ,CAAoB;QAC5B,aAAQ,GAAR,QAAQ,CAAoB;QAC5B,qBAAgB,GAAhB,gBAAgB,CAAuC;QAPzD,WAAM,GAAiB,IAAI,CAAA;QAC3B,oBAAe,GAAuD,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QAS/F,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,aAAV,UAAU,cAAV,UAAU,GAA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AAa,CAAC,aAAqB;QACzC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,WAAG,EAAC,aAAa,CAAC,CAAC,CAAA;IACvC,CAAC;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAlID,sDAkIC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { LoginCredentials } from '../../icc-api/model/LoginCredentials'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\nimport XHRError = XHR.XHRError\n\n/**\n * Differs from JwtAuthService in that it can create new refresh tokens if the old one is expired\n */\nexport class JwtBridgedAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt?: string; refreshJwt?: string }> = Promise.resolve({})\n\n constructor(\n private authApi: IccAuthApi,\n private username: string | undefined,\n private password: string | undefined,\n private thirdPartyTokens: { [thirdParty: string]: string } = {},\n initialJwt: { authJwt: string; refreshJwt: string } | undefined\n ) {\n this._currentPromise = Promise.resolve(initialJwt ?? {})\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x.refreshJwt as any)\n }\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this.getAuthHeaders().then(() => this._currentPromise.then(({ authJwt, refreshJwt }) => ({ token: authJwt!, refreshToken: refreshJwt! })))\n }\n\n async getJWT(): Promise<string | undefined> {\n return this._currentPromise\n .then(({ authJwt, refreshJwt }) => {\n if (!authJwt || this._isJwtInvalidOrExpired(authJwt)) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n })\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then(({ authJwt }) => {\n return authJwt\n })\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this.getJWT().then((authJwt) => {\n return [new XHR.Header('Authorization', `Bearer ${authJwt}`)]\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string | undefined): Promise<{ authJwt?: string; refreshJwt?: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (!refreshJwt || this._isJwtInvalidOrExpired(refreshJwt)) {\n return this._loginAndGetTokens()\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n private async _loginAndGetTokens(): Promise<{ authJwt?: string; refreshJwt?: string }> {\n let authResponse: AuthenticationResponse | undefined\n let firstError: XHRError | undefined\n if (this.username && this.password) {\n try {\n authResponse = await this.authApi.login(\n new LoginCredentials({\n username: this.username,\n password: this.password,\n })\n )\n } catch (e) {\n firstError = e as XHRError\n }\n }\n if (!authResponse) {\n authResponse = await (Object.entries(this.thirdPartyTokens) as [OAuthThirdParty, string][]).reduce(async (acc, [thirdParty, token]) => {\n const prev = await acc\n return (\n prev ??\n (token\n ? this.authApi.loginWithThirdPartyToken(thirdParty, token).catch((e) => {\n if (!firstError) {\n firstError = e as XHRError\n }\n return Promise.resolve() as Promise<undefined>\n })\n : undefined)\n )\n }, Promise.resolve() as Promise<AuthenticationResponse | undefined>)\n }\n\n if (!authResponse) {\n if (firstError) throw firstError\n throw new XHRError('', 'Unknown error', 401, 'Unauthorized', new Headers())\n }\n\n return {\n authJwt: authResponse.token,\n refreshJwt: authResponse.refreshToken,\n }\n }\n\n private _isJwtInvalidOrExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return true\n }\n const payload = this._base64Decode(parts[1])\n // Using the 'exp' string is safe to use as it is part of the JWT RFC and cannot be modified by us.\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime() - 10000\n }\n\n private _base64Decode(encodedString: string): any {\n return JSON.parse(a2b(encodedString))\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JwtBridgedAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtBridgedAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAE3C,2EAAuE;AAEvE,oCAA8B;AAE9B,IAAO,QAAQ,GAAG,SAAG,CAAC,QAAQ,CAAA;AAC9B,yCAAqC;AAErC;;GAEG;AACH,MAAa,qBAAqB;IAIhC,YACU,OAAmB,EACnB,QAA4B,EAC5B,QAA4B,EAC5B,mBAAqD,EAAE,EAC/D,UAA+D;QAJvD,YAAO,GAAP,OAAO,CAAY;QACnB,aAAQ,GAAR,QAAQ,CAAoB;QAC5B,aAAQ,GAAR,QAAQ,CAAoB;QAC5B,qBAAgB,GAAhB,gBAAgB,CAAuC;QAPzD,WAAM,GAAiB,IAAI,CAAA;QAC3B,oBAAe,GAAuD,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QAS/F,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,aAAV,UAAU,cAAV,UAAU,GAAI,EAAE,CAAC,CAAA;IAC1D,CAAC;IAED,IAAI,YAAY;QACd,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAiB,CAAC,CAAA;IAC9D,CAAC;IACD,cAAc;QACZ,OAAO,IAAI,CAAC,cAAc,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO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C,YAAY;aACtC,CAAA;QACH,CAAC;KAAA;IAEO,sBAAsB,CAAC,GAAW;QACxC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QAC5B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,OAAO,IAAI,CAAA;SACZ;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;QAC5C,mGAAmG;QACnG,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,CAAA;IACpF,CAAC;IAEO,aAAa,CAAC,aAAqB;QACzC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAA,WAAG,EAAC,aAAa,CAAC,CAAC,CAAA;IACvC,CAAC;IAED,gBAAgB,CAAC,KAAY;QAC3B,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,cAAc;QACZ,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAA;IACtB,CAAC;CACF;AAtJD,sDAsJC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi, OAuthThirdParty } from '../../icc-api'\nimport { LoginCredentials } from '../../icc-api/model/LoginCredentials'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\nimport { AuthenticationResponse } from '../../icc-api/model/AuthenticationResponse'\nimport XHRError = XHR.XHRError\nimport { JwtError } from './JwtError'\n\n/**\n * Differs from JwtAuthService in that it can create new refresh tokens if the old one is expired\n */\nexport class JwtBridgedAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt?: string; refreshJwt?: string }> = Promise.resolve({})\n\n constructor(\n private authApi: IccAuthApi,\n private username: string | undefined,\n private password: string | undefined,\n private thirdPartyTokens: { [thirdParty: string]: string } = {},\n initialJwt: { authJwt: string; refreshJwt: string } | undefined\n ) {\n this._currentPromise = Promise.resolve(initialJwt ?? {})\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x.refreshJwt as any)\n }\n getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this.getAuthHeaders().then(() => this._currentPromise.then(({ authJwt, refreshJwt }) => ({ token: authJwt!, refreshToken: refreshJwt! })))\n }\n\n async getJWT(): Promise<string | undefined> {\n return this._currentPromise\n .then(\n ({ authJwt, refreshJwt }) => ({ authJwt, refreshJwt }),\n (e: Error) => {\n if (e instanceof JwtError) {\n const wrappedError = e.reason as any\n if (!!wrappedError.statusCode && wrappedError.statusCode >= 400 && wrappedError.statusCode < 500) {\n return { authJwt: undefined, refreshJwt: undefined }\n } else {\n return { authJwt: e.jwt, refreshJwt: e.refreshJwt }\n }\n } else {\n return { authJwt: undefined, refreshJwt: undefined }\n }\n }\n )\n .then(({ authJwt, refreshJwt }) => {\n if (!authJwt || this._isJwtInvalidOrExpired(authJwt)) {\n // If it does not have the JWT, tries to get it\n // If the JWT is expired, tries to refresh it\n\n this._currentPromise = this._refreshAuthJwt(refreshJwt).then(\n (updatedTokens) => {\n // If here the token is null,\n // it goes in a suspension status\n if (!updatedTokens.authJwt) {\n throw new Error('Your iCure back-end version does not support JWT authentication')\n }\n\n return updatedTokens\n },\n (e: Error) => {\n throw new JwtError(authJwt, refreshJwt, 'There was an error while refreshing the token, please re-instantiate the API or try again.', e)\n }\n )\n } else if (!!this._error) {\n throw this._error\n }\n return this._currentPromise\n })\n .then(({ authJwt }) => {\n return authJwt\n })\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this.getJWT().then((authJwt) => {\n return [new XHR.Header('Authorization', `Bearer ${authJwt}`)]\n })\n }\n\n private async _refreshAuthJwt(refreshJwt: string | undefined): Promise<{ authJwt?: string; refreshJwt?: string }> {\n // If I do not have a refresh JWT or the refresh JWT is expired,\n // I have to log in again\n if (!refreshJwt || this._isJwtInvalidOrExpired(refreshJwt)) {\n return this._loginAndGetTokens()\n } else {\n return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({\n authJwt: refreshResponse.token,\n refreshJwt: refreshJwt,\n }))\n }\n }\n\n private async _loginAndGetTokens(): Promise<{ authJwt?: string; refreshJwt?: string }> {\n let authResponse: AuthenticationResponse | undefined\n let firstError: XHRError | undefined\n if (this.username && this.password) {\n try {\n authResponse = await this.authApi.login(\n new LoginCredentials({\n username: this.username,\n password: this.password,\n })\n )\n } catch (e) {\n firstError = e as XHRError\n }\n }\n if (!authResponse) {\n authResponse = await (Object.entries(this.thirdPartyTokens) as [OAuthThirdParty, string][]).reduce(async (acc, [thirdParty, token]) => {\n const prev = await acc\n return (\n prev ??\n (token\n ? this.authApi.loginWithThirdPartyToken(thirdParty, token).catch((e) => {\n if (!firstError) {\n firstError = e as XHRError\n }\n return Promise.resolve() as Promise<undefined>\n })\n : undefined)\n )\n }, Promise.resolve() as Promise<AuthenticationResponse | undefined>)\n }\n\n if (!authResponse) {\n if (firstError) throw firstError\n throw new XHRError('', 'Unknown error', 401, 'Unauthorized', new Headers())\n }\n\n return {\n authJwt: authResponse.token,\n refreshJwt: authResponse.refreshToken,\n }\n }\n\n private _isJwtInvalidOrExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return true\n }\n const payload = this._base64Decode(parts[1])\n // Using the 'exp' string is safe to use as it is part of the JWT RFC and cannot be modified by us.\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime() - 10000\n }\n\n private _base64Decode(encodedString: string): any {\n return JSON.parse(a2b(encodedString))\n }\n\n invalidateHeader(error: Error): void {\n this._error = error\n }\n\n isInErrorState(): boolean {\n return !!this._error\n }\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare class JwtError extends Error {
|
|
2
|
+
readonly jwt: string | undefined;
|
|
3
|
+
readonly refreshJwt: string | undefined;
|
|
4
|
+
readonly message: string;
|
|
5
|
+
readonly reason: Error;
|
|
6
|
+
constructor(jwt: string | undefined, refreshJwt: string | undefined, message: string, reason: Error);
|
|
7
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.JwtError = void 0;
|
|
4
|
+
class JwtError extends Error {
|
|
5
|
+
constructor(jwt, refreshJwt, message, reason) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.jwt = jwt;
|
|
8
|
+
this.refreshJwt = refreshJwt;
|
|
9
|
+
this.message = message;
|
|
10
|
+
this.reason = reason;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
exports.JwtError = JwtError;
|
|
14
|
+
//# sourceMappingURL=JwtError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JwtError.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtError.ts"],"names":[],"mappings":";;;AAAA,MAAa,QAAS,SAAQ,KAAK;IACjC,YAAqB,GAAuB,EAAW,UAA8B,EAAW,OAAe,EAAW,MAAa;QACrI,KAAK,CAAC,OAAO,CAAC,CAAA;QADK,QAAG,GAAH,GAAG,CAAoB;QAAW,eAAU,GAAV,UAAU,CAAoB;QAAW,YAAO,GAAP,OAAO,CAAQ;QAAW,WAAM,GAAN,MAAM,CAAO;IAEvI,CAAC;CACF;AAJD,4BAIC","sourcesContent":["export class JwtError extends Error {\n constructor(readonly jwt: string | undefined, readonly refreshJwt: string | undefined, readonly message: string, readonly reason: Error) {\n super(message)\n }\n}\n"]}
|
|
@@ -1,4 +1,56 @@
|
|
|
1
|
-
export
|
|
1
|
+
export interface AESUtils {
|
|
2
|
+
encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
3
|
+
encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>;
|
|
4
|
+
decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
5
|
+
/**
|
|
6
|
+
*
|
|
7
|
+
* @param cryptoKey (CryptoKey)
|
|
8
|
+
* @param encryptedData (ArrayBuffer)
|
|
9
|
+
* @param rawKey
|
|
10
|
+
* @returns {Promise} will be ArrayBuffer
|
|
11
|
+
*/
|
|
12
|
+
decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>;
|
|
13
|
+
/**
|
|
14
|
+
* @deprecated this method is not correct: in some cases decryption may not fail even if the wrong key is used: if the
|
|
15
|
+
* first provided keys are wrong and the last one is correct the decryption will succeed for sure, but there is a small
|
|
16
|
+
* chance that you will get garbage
|
|
17
|
+
*/
|
|
18
|
+
decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer>;
|
|
19
|
+
/**
|
|
20
|
+
*
|
|
21
|
+
* @param toHex boolean, if true, it returns hex String
|
|
22
|
+
* @returns {Promise} either Hex string or CryptoKey
|
|
23
|
+
*/
|
|
24
|
+
generateCryptoKey(toHex: false): Promise<CryptoKey>;
|
|
25
|
+
generateCryptoKey(toHex: true): Promise<string>;
|
|
26
|
+
generateCryptoKey(toHex: boolean): Promise<string | CryptoKey>;
|
|
27
|
+
generateIV(ivByteLength: number): Uint8Array;
|
|
28
|
+
/**
|
|
29
|
+
* This function return a promise which will be the key Format will be either 'raw' or 'jwk'.
|
|
30
|
+
* JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)
|
|
31
|
+
*
|
|
32
|
+
* @param cryptoKey CryptoKey
|
|
33
|
+
* @param format will be 'raw' or 'jwk'
|
|
34
|
+
* @returns {Promise} will the AES Key
|
|
35
|
+
*/
|
|
36
|
+
exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>;
|
|
37
|
+
exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>;
|
|
38
|
+
exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey>;
|
|
39
|
+
/**
|
|
40
|
+
* the ability to import a key that have already been created elsewhere, for use within the web
|
|
41
|
+
* application that is invoking the import function, for use within the importing web application's
|
|
42
|
+
* origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be
|
|
43
|
+
* represented as octets.
|
|
44
|
+
*
|
|
45
|
+
* https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js
|
|
46
|
+
*
|
|
47
|
+
* @param format 'raw' or 'jwk'
|
|
48
|
+
* @param aesKey
|
|
49
|
+
* @returns {*}
|
|
50
|
+
*/
|
|
51
|
+
importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey>;
|
|
52
|
+
}
|
|
53
|
+
export declare class AESUtilsImpl implements AESUtils {
|
|
2
54
|
/********* AES Config **********/
|
|
3
55
|
ivLength: number;
|
|
4
56
|
aesAlgorithmEncryptName: string;
|
|
@@ -51,4 +103,4 @@ export declare class AESUtils {
|
|
|
51
103
|
*/
|
|
52
104
|
importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey>;
|
|
53
105
|
}
|
|
54
|
-
export declare const AES:
|
|
106
|
+
export declare const AES: AESUtilsImpl;
|
package/icc-x-api/crypto/AES.js
CHANGED
|
@@ -9,9 +9,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.AES = exports.
|
|
12
|
+
exports.AES = exports.AESUtilsImpl = void 0;
|
|
13
13
|
const utils_1 = require("../utils");
|
|
14
|
-
class
|
|
14
|
+
class AESUtilsImpl {
|
|
15
15
|
set debug(value) {
|
|
16
16
|
this._debug = value;
|
|
17
17
|
}
|
|
@@ -64,7 +64,7 @@ class AESUtils {
|
|
|
64
64
|
* @param rawKey
|
|
65
65
|
* @returns {Promise} will be ArrayBuffer
|
|
66
66
|
*/
|
|
67
|
-
decrypt(cryptoKey, encryptedData, rawKey
|
|
67
|
+
decrypt(cryptoKey, encryptedData, rawKey) {
|
|
68
68
|
return new Promise((resolve, reject) => {
|
|
69
69
|
if (!cryptoKey) {
|
|
70
70
|
return reject('No crypto key provided for decryption');
|
|
@@ -161,6 +161,6 @@ class AESUtils {
|
|
|
161
161
|
});
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
-
exports.
|
|
165
|
-
exports.AES = new
|
|
164
|
+
exports.AESUtilsImpl = AESUtilsImpl;
|
|
165
|
+
exports.AES = new AESUtilsImpl();
|
|
166
166
|
//# sourceMappingURL=AES.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAAuD;AAEvD,MAAa,QAAQ;IAYnB,IAAI,KAAK,CAAC,KAAc;QACtB,IAAI,CAAC,MAAM,GAAG,KAAK,CAAA;IACrB,CAAC;IAED,YAAY,SAAiB,OAAO,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAE,EAAa;QAfvI,iCAAiC;QACjC,aAAQ,GAAG,EAAE,CAAA;QACb,4BAAuB,GAAG,SAAS,CAAA;QAEnC,oBAAe,GAAoB;YACjC,IAAI,EAAE,SAAS;YACf,MAAM,EAAE,GAAG;SACZ,CAAA;QAEO,WAAM,GAAY,KAAK,CAAA;QAO7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAEK,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C,MAAM,CAAC,CAAC,EAAE;oBACpF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;iBACvD;gBACD,MAAM,GAAG,CAAA;YACX,CAAC,CAAC;iBACD,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAhMD,4BAgMC;AAEY,QAAA,GAAG,GAAG,IAAI,QAAQ,EAAE,CAAA","sourcesContent":["import { appendBuffer, hex2ua, ua2hex } from '../utils'\n\nexport class AESUtils {\n /********* AES Config **********/\n ivLength = 16\n aesAlgorithmEncryptName = 'AES-CBC'\n\n aesKeyGenParams: AesKeyGenParams = {\n name: 'AES-CBC',\n length: 256,\n }\n private crypto: Crypto\n private _debug: boolean = false\n\n set debug(value: boolean) {\n this._debug = value\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n async encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.encrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (plainData instanceof Uint8Array) {\n const buffer = plainData.buffer\n plainData = (buffer.byteLength > plainData.byteLength ? buffer.slice(0, plainData.byteLength) : buffer) as ArrayBuffer\n }\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: this.generateIV(this.ivLength),\n }\n this._debug && console.log(`encrypt ${ua2hex(plainData)} with ${rawKey}`)\n this.crypto.subtle\n .encrypt(\n {\n ...aesAlgorithmEncrypt,\n } /* some ill behaved implementations change the values in place */,\n cryptoKey,\n plainData\n )\n .then(\n (cipherData) => {\n this._debug && console.log(`cipherData: ${ua2hex(cipherData)}`)\n return resolve(appendBuffer(aesAlgorithmEncrypt.iv.buffer as ArrayBuffer, cipherData))\n },\n (err) => reject('AES encryption failed: ' + err)\n )\n })\n }\n\n async decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.decrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (!cryptoKey) {\n return reject('No crypto key provided for decryption')\n }\n const encryptedDataUint8 = encryptedData instanceof ArrayBuffer ? new Uint8Array(encryptedData) : encryptedData\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: encryptedDataUint8.subarray(0, this.ivLength),\n\n /*\n * IF THIS BIT OF CODE PRODUCES A DOMEXCEPTION CODE 0 ERROR, IT MIGHT BE RELATED TO THIS:\n *\n * NOTOK:\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[hcpartyId] && hcparty.hcPartyKeys[hcpartyId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + hcpartyId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[hcpartyId][1];\n *\n * SHOULD BE:\n * var delegatorId = patient.delegations[hcpartyId][0].owner;\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[delegatorId] && hcparty.hcPartyKeys[delegatorId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + delegatorId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[delegatorId][1];\n */\n }\n this._debug && console.log(`decrypt ${ua2hex(encryptedData)} with ${rawKey}`)\n this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then(\n (decipheredData) => {\n this._debug && console.log(`decipheredData: ${ua2hex(decipheredData)}`)\n resolve(decipheredData)\n },\n (err) => {\n reject(new Error('AES decryption failed: ' + err))\n }\n )\n })\n }\n\n async decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer> {\n try {\n return this.decrypt(cryptoKeys[0], uint8Array)\n } catch (e) {\n if (cryptoKeys.length > 1) {\n return this.decryptSome(cryptoKeys.slice(1), uint8Array)\n } else {\n throw e\n }\n }\n }\n\n // generate an AES key\n // noinspection JSUnusedGlobalSymbols\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n return new Promise((resolve: (value: CryptoKey | string) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const cryptoKeyPromise: Promise<CryptoKey> = this.crypto.subtle.generateKey(this.aesKeyGenParams, extractable, keyUsages) as Promise<CryptoKey>\n return toHex === undefined || !toHex\n ? cryptoKeyPromise.then(resolve, reject)\n : cryptoKeyPromise.then((k) => this.exportKey(k, 'raw'), reject).then((raw) => resolve(ua2hex(raw)), reject)\n })\n }\n\n // noinspection JSMethodCanBeStatic\n generateIV(ivByteLength: number): Uint8Array {\n return new Uint8Array(this.crypto.getRandomValues(new Uint8Array(ivByteLength)))\n }\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n return new Promise((resolve: (value: ArrayBuffer | JsonWebKey) => any, reject: (reason: any) => any) => {\n return this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n return new Promise((resolve: (value: CryptoKey) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n return this.crypto.subtle\n .importKey(format as any, aesKey as any, this.aesKeyGenParams, extractable, keyUsages)\n .catch((err) => {\n if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {\n console.warn(`Import of key ${ua2hex(aesKey)} failed`)\n }\n throw err\n })\n .then(resolve, reject)\n })\n }\n}\n\nexport const AES = new AESUtils()\n"]}
|
|
1
|
+
{"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oCAAuD;AAmEvD,MAAa,YAAY;IAYvB,IAAI,KAAK,CAAC,KAAc;QACtB,IAAI,CAAC,MAAM,GAAG,KAAK,CAA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C;QAC5E,OAAO,IAAI,OAAO,CAAC,CAAC,OAAkC,EAAE,MAA4B,EAAE,EAAE;YACtF,MAAM,WAAW,GAAG,IAAI,CAAA;YACxB,MAAM,SAAS,GAAe,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;YACpD,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM;iBACtB,SAAS,CAAC,MAAa,EAAE,MAAa,EAAE,IAAI,CAAC,eAAe,EAAE,WAAW,EAAE,SAAS,CAAC;iBACrF,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,IAAI,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,YAAY,WAAW,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE;oBACpF,OAAO,CAAC,IAAI,CAAC,iBAAiB,IAAA,cAAM,EAAC,MAAM,CAAC,SAAS,CAAC,CAAA;iBACvD;gBACD,MAAM,GAAG,CAAA;YACX,CAAC,CAAC;iBACD,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QAC1B,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAhMD,oCAgMC;AAEY,QAAA,GAAG,GAAG,IAAI,YAAY,EAAE,CAAA","sourcesContent":["import { appendBuffer, hex2ua, ua2hex } from '../utils'\n\nexport interface AESUtils {\n encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>\n\n decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer>\n\n /**\n * @deprecated this method is not correct: in some cases decryption may not fail even if the wrong key is used: if the\n * first provided keys are wrong and the last one is correct the decryption will succeed for sure, but there is a small\n * chance that you will get garbage\n */\n decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer>\n\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n\n generateCryptoKey(toHex: true): Promise<string>\n\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey>\n\n generateIV(ivByteLength: number): Uint8Array\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey>\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey>\n}\n\nexport class AESUtilsImpl implements AESUtils {\n /********* AES Config **********/\n ivLength = 16\n aesAlgorithmEncryptName = 'AES-CBC'\n\n aesKeyGenParams: AesKeyGenParams = {\n name: 'AES-CBC',\n length: 256,\n }\n private crypto: Crypto\n private _debug: boolean = false\n\n set debug(value: boolean) {\n this._debug = value\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this.crypto = crypto\n }\n\n async encryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.encrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n encrypt(cryptoKey: CryptoKey, plainData: ArrayBuffer | Uint8Array, rawKey = '<NA>'): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (plainData instanceof Uint8Array) {\n const buffer = plainData.buffer\n plainData = (buffer.byteLength > plainData.byteLength ? buffer.slice(0, plainData.byteLength) : buffer) as ArrayBuffer\n }\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: this.generateIV(this.ivLength),\n }\n this._debug && console.log(`encrypt ${ua2hex(plainData)} with ${rawKey}`)\n this.crypto.subtle\n .encrypt(\n {\n ...aesAlgorithmEncrypt,\n } /* some ill behaved implementations change the values in place */,\n cryptoKey,\n plainData\n )\n .then(\n (cipherData) => {\n this._debug && console.log(`cipherData: ${ua2hex(cipherData)}`)\n return resolve(appendBuffer(aesAlgorithmEncrypt.iv.buffer as ArrayBuffer, cipherData))\n },\n (err) => reject('AES encryption failed: ' + err)\n )\n })\n }\n\n async decryptWithRawKey(rawKey: string, plainData: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.decrypt(\n await this.importKey('raw', hex2ua(rawKey.replace(/-/g, ''))),\n plainData,\n rawKey // Used for logging only if debug is enabled, ok to always pass\n )\n }\n\n /**\n *\n * @param cryptoKey (CryptoKey)\n * @param encryptedData (ArrayBuffer)\n * @param rawKey\n * @returns {Promise} will be ArrayBuffer\n */\n decrypt(cryptoKey: CryptoKey, encryptedData: ArrayBuffer | Uint8Array, rawKey?: string): Promise<ArrayBuffer> {\n return new Promise((resolve: (value: ArrayBuffer) => any, reject: (reason: any) => any) => {\n if (!cryptoKey) {\n return reject('No crypto key provided for decryption')\n }\n const encryptedDataUint8 = encryptedData instanceof ArrayBuffer ? new Uint8Array(encryptedData) : encryptedData\n const aesAlgorithmEncrypt = {\n name: this.aesAlgorithmEncryptName,\n iv: encryptedDataUint8.subarray(0, this.ivLength),\n\n /*\n * IF THIS BIT OF CODE PRODUCES A DOMEXCEPTION CODE 0 ERROR, IT MIGHT BE RELATED TO THIS:\n *\n * NOTOK:\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[hcpartyId] && hcparty.hcPartyKeys[hcpartyId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + hcpartyId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[hcpartyId][1];\n *\n * SHOULD BE:\n * var delegatorId = patient.delegations[hcpartyId][0].owner;\n * if (!hcparty.hcPartyKeys && !hcparty.hcPartyKeys[delegatorId] && hcparty.hcPartyKeys[delegatorId].length !== 2) {\n * throw 'No hcPartyKey for this Healthcare party(' + delegatorId + ').';\n * }\n * var delegateHcPartyKey = hcparty.hcPartyKeys[delegatorId][1];\n */\n }\n this._debug && console.log(`decrypt ${ua2hex(encryptedData)} with ${rawKey}`)\n this.crypto.subtle.decrypt(aesAlgorithmEncrypt, cryptoKey, encryptedDataUint8.subarray(this.ivLength, encryptedDataUint8.length)).then(\n (decipheredData) => {\n this._debug && console.log(`decipheredData: ${ua2hex(decipheredData)}`)\n resolve(decipheredData)\n },\n (err) => {\n reject(new Error('AES decryption failed: ' + err))\n }\n )\n })\n }\n\n async decryptSome(cryptoKeys: CryptoKey[], uint8Array: Uint8Array): Promise<ArrayBuffer> {\n try {\n return this.decrypt(cryptoKeys[0], uint8Array)\n } catch (e) {\n if (cryptoKeys.length > 1) {\n return this.decryptSome(cryptoKeys.slice(1), uint8Array)\n } else {\n throw e\n }\n }\n }\n\n // generate an AES key\n // noinspection JSUnusedGlobalSymbols\n /**\n *\n * @param toHex boolean, if true, it returns hex String\n * @returns {Promise} either Hex string or CryptoKey\n */\n generateCryptoKey(toHex: false): Promise<CryptoKey>\n generateCryptoKey(toHex: true): Promise<string>\n generateCryptoKey(toHex: boolean): Promise<string | CryptoKey> {\n return new Promise((resolve: (value: CryptoKey | string) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n const cryptoKeyPromise: Promise<CryptoKey> = this.crypto.subtle.generateKey(this.aesKeyGenParams, extractable, keyUsages) as Promise<CryptoKey>\n return toHex === undefined || !toHex\n ? cryptoKeyPromise.then(resolve, reject)\n : cryptoKeyPromise.then((k) => this.exportKey(k, 'raw'), reject).then((raw) => resolve(ua2hex(raw)), reject)\n })\n }\n\n // noinspection JSMethodCanBeStatic\n generateIV(ivByteLength: number): Uint8Array {\n return new Uint8Array(this.crypto.getRandomValues(new Uint8Array(ivByteLength)))\n }\n\n /**\n * This function return a promise which will be the key Format will be either 'raw' or 'jwk'.\n * JWK: Json Web key (ref. http://tools.ietf.org/html/draft-ietf-jose-json-web-key-11)\n *\n * @param cryptoKey CryptoKey\n * @param format will be 'raw' or 'jwk'\n * @returns {Promise} will the AES Key\n */\n exportKey(cryptoKey: CryptoKey, format: 'raw'): Promise<ArrayBuffer>\n exportKey(cryptoKey: CryptoKey, format: 'jwk'): Promise<JsonWebKey>\n exportKey(cryptoKey: CryptoKey, format: 'jwk' | 'raw'): Promise<ArrayBuffer | JsonWebKey> {\n return new Promise((resolve: (value: ArrayBuffer | JsonWebKey) => any, reject: (reason: any) => any) => {\n return this.crypto.subtle.exportKey(format as any, cryptoKey).then(resolve, reject)\n })\n }\n\n /**\n * the ability to import a key that have already been created elsewhere, for use within the web\n * application that is invoking the import function, for use within the importing web application's\n * origin. This necessiates an interoperable key format, such as JSON Web Key [JWK] which may be\n * represented as octets.\n *\n * https://chromium.googlesource.com/chromium/blink.git/+/6b902997e3ca0384c8fa6fe56f79ecd7589d3ca6/LayoutTests/crypto/resources/common.js\n *\n * @param format 'raw' or 'jwk'\n * @param aesKey\n * @returns {*}\n */\n importKey(format: 'jwk' | 'raw', aesKey: JsonWebKey | ArrayBuffer | Uint8Array): Promise<CryptoKey> {\n return new Promise((resolve: (value: CryptoKey) => any, reject: (reason: any) => any) => {\n const extractable = true\n const keyUsages: KeyUsage[] = ['decrypt', 'encrypt']\n return this.crypto.subtle\n .importKey(format as any, aesKey as any, this.aesKeyGenParams, extractable, keyUsages)\n .catch((err) => {\n if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {\n console.warn(`Import of key ${ua2hex(aesKey)} failed`)\n }\n throw err\n })\n .then(resolve, reject)\n })\n }\n}\n\nexport const AES = new AESUtilsImpl()\n"]}
|
|
@@ -2,10 +2,30 @@ import { RSAUtils } from './RSA';
|
|
|
2
2
|
import { AESUtils } from './AES';
|
|
3
3
|
import { ShamirClass } from './shamir';
|
|
4
4
|
import { HMACUtils } from './HMACUtils';
|
|
5
|
+
export interface CryptoPrimitives {
|
|
6
|
+
readonly shamir: ShamirClass;
|
|
7
|
+
readonly RSA: RSAUtils;
|
|
8
|
+
readonly AES: AESUtils;
|
|
9
|
+
readonly HMAC: HMACUtils;
|
|
10
|
+
/**
|
|
11
|
+
* Generates a UUID using a cryptographically secure random number generator.
|
|
12
|
+
*/
|
|
13
|
+
randomUuid(): string;
|
|
14
|
+
/**
|
|
15
|
+
* @param data some data
|
|
16
|
+
* @return the sha256 hash of {@link data}
|
|
17
|
+
*/
|
|
18
|
+
sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
19
|
+
/**
|
|
20
|
+
* @param n how many bytes to generate
|
|
21
|
+
* @return an array with n random bytes
|
|
22
|
+
*/
|
|
23
|
+
randomBytes(n: number): Uint8Array;
|
|
24
|
+
}
|
|
5
25
|
/**
|
|
6
26
|
* Gives access to cryptographic primitives.
|
|
7
27
|
*/
|
|
8
|
-
export declare class CryptoPrimitives {
|
|
28
|
+
export declare class CryptoPrimitivesImpl implements CryptoPrimitives {
|
|
9
29
|
private readonly _rsa;
|
|
10
30
|
private readonly _aes;
|
|
11
31
|
private readonly _shamir;
|
|
@@ -17,18 +37,7 @@ export declare class CryptoPrimitives {
|
|
|
17
37
|
get AES(): AESUtils;
|
|
18
38
|
get HMAC(): HMACUtils;
|
|
19
39
|
constructor(crypto?: Crypto);
|
|
20
|
-
/**
|
|
21
|
-
* Generates a UUID using a cryptographically secure random number generator.
|
|
22
|
-
*/
|
|
23
40
|
randomUuid(): string;
|
|
24
|
-
/**
|
|
25
|
-
* @param data some data
|
|
26
|
-
* @return the sha256 hash of {@link data}
|
|
27
|
-
*/
|
|
28
41
|
sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>;
|
|
29
|
-
/**
|
|
30
|
-
* @param n how many bytes to generate
|
|
31
|
-
* @return an array with n random bytes
|
|
32
|
-
*/
|
|
33
42
|
randomBytes(n: number): Uint8Array;
|
|
34
43
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.CryptoPrimitivesImpl = void 0;
|
|
4
4
|
const RSA_1 = require("./RSA");
|
|
5
5
|
const AES_1 = require("./AES");
|
|
6
6
|
const shamir_1 = require("./shamir");
|
|
@@ -8,7 +8,7 @@ const HMACUtils_1 = require("./HMACUtils");
|
|
|
8
8
|
/**
|
|
9
9
|
* Gives access to cryptographic primitives.
|
|
10
10
|
*/
|
|
11
|
-
class
|
|
11
|
+
class CryptoPrimitivesImpl {
|
|
12
12
|
get crypto() {
|
|
13
13
|
return this._crypto;
|
|
14
14
|
}
|
|
@@ -26,35 +26,24 @@ class CryptoPrimitives {
|
|
|
26
26
|
}
|
|
27
27
|
constructor(crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : {}) {
|
|
28
28
|
this._crypto = crypto;
|
|
29
|
-
this._rsa = new RSA_1.
|
|
30
|
-
this._aes = new AES_1.
|
|
31
|
-
this._shamir = new shamir_1.
|
|
32
|
-
this._hmac = new HMACUtils_1.
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Generates a UUID using a cryptographically secure random number generator.
|
|
36
|
-
*/
|
|
29
|
+
this._rsa = new RSA_1.RSAUtilsImpl(crypto);
|
|
30
|
+
this._aes = new AES_1.AESUtilsImpl(crypto);
|
|
31
|
+
this._shamir = new shamir_1.WebcryptoShamir(crypto);
|
|
32
|
+
this._hmac = new HMACUtils_1.HMACUtilsImpl(crypto);
|
|
33
|
+
}
|
|
37
34
|
randomUuid() {
|
|
38
35
|
return ((1e7).toString() + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g,
|
|
39
36
|
//Keep next inlined or you will lose the random
|
|
40
37
|
(c) => (Number(c) ^ (this.crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4)))).toString(16));
|
|
41
38
|
}
|
|
42
|
-
/**
|
|
43
|
-
* @param data some data
|
|
44
|
-
* @return the sha256 hash of {@link data}
|
|
45
|
-
*/
|
|
46
39
|
sha256(data) {
|
|
47
40
|
return this.crypto.subtle.digest('SHA-256', data);
|
|
48
41
|
}
|
|
49
|
-
/**
|
|
50
|
-
* @param n how many bytes to generate
|
|
51
|
-
* @return an array with n random bytes
|
|
52
|
-
*/
|
|
53
42
|
randomBytes(n) {
|
|
54
43
|
const res = new Uint8Array(n);
|
|
55
44
|
this.crypto.getRandomValues(res);
|
|
56
45
|
return res;
|
|
57
46
|
}
|
|
58
47
|
}
|
|
59
|
-
exports.
|
|
48
|
+
exports.CryptoPrimitivesImpl = CryptoPrimitivesImpl;
|
|
60
49
|
//# sourceMappingURL=CryptoPrimitives.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CryptoPrimitives.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/CryptoPrimitives.ts"],"names":[],"mappings":";;;AAAA,+
|
|
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E,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAE,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CACjI,CAAA;IACH,CAAC;IAED,MAAM,CAAC,IAA8B;QACnC,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;IACnD,CAAC;IAED,WAAW,CAAC,CAAS;QACnB,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAA;QAC7B,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,CAAA;QAChC,OAAO,GAAG,CAAA;IACZ,CAAC;CACF;AApDD,oDAoDC","sourcesContent":["import { RSAUtils, RSAUtilsImpl } from './RSA'\nimport { AESUtils, AESUtilsImpl } from './AES'\nimport { ShamirClass, WebcryptoShamir } from './shamir'\nimport { HMACUtils, HMACUtilsImpl } from './HMACUtils'\n\nexport interface CryptoPrimitives {\n readonly shamir: ShamirClass\n readonly RSA: RSAUtils\n readonly AES: AESUtils\n readonly HMAC: HMACUtils\n /**\n * Generates a UUID using a cryptographically secure random number generator.\n */\n randomUuid(): string\n /**\n * @param data some data\n * @return the sha256 hash of {@link data}\n */\n sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer>\n /**\n * @param n how many bytes to generate\n * @return an array with n random bytes\n */\n randomBytes(n: number): Uint8Array\n}\n\n/**\n * Gives access to cryptographic primitives.\n */\nexport class CryptoPrimitivesImpl implements CryptoPrimitives {\n private readonly _rsa: RSAUtils\n private readonly _aes: AESUtils\n private readonly _shamir: ShamirClass\n private readonly _crypto: Crypto\n private readonly _hmac: HMACUtils\n\n get crypto(): Crypto {\n return this._crypto\n }\n\n get shamir(): ShamirClass {\n return this._shamir\n }\n\n get RSA(): RSAUtils {\n return this._rsa\n }\n\n get AES(): AESUtils {\n return this._aes\n }\n\n get HMAC(): HMACUtils {\n return this._hmac\n }\n\n constructor(crypto: Crypto = typeof window !== 'undefined' ? window.crypto : typeof self !== 'undefined' ? self.crypto : ({} as Crypto)) {\n this._crypto = crypto\n this._rsa = new RSAUtilsImpl(crypto)\n this._aes = new AESUtilsImpl(crypto)\n this._shamir = new WebcryptoShamir(crypto)\n this._hmac = new HMACUtilsImpl(crypto)\n }\n\n randomUuid() {\n return ((1e7).toString() + -1e3 + -4e3 + -8e3 + -1e11).replace(\n /[018]/g,\n //Keep next inlined or you will lose the random\n (c) => (Number(c) ^ ((this.crypto.getRandomValues(new Uint8Array(1))! as Uint8Array)[0] & (15 >> (Number(c) / 4)))).toString(16)\n )\n }\n\n sha256(data: ArrayBuffer | Uint8Array): Promise<ArrayBuffer> {\n return this.crypto.subtle.digest('SHA-256', data)\n }\n\n randomBytes(n: number): Uint8Array {\n const res = new Uint8Array(n)\n this.crypto.getRandomValues(res)\n return res\n }\n}\n"]}
|
|
@@ -221,7 +221,7 @@ class DelegationsDeAnonymization {
|
|
|
221
221
|
// Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.
|
|
222
222
|
const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId);
|
|
223
223
|
const initalisedMapInfo = yield this.xapis.entityWithInitialisedEncryptedMetadata({
|
|
224
|
-
id: this.cryptoPrimitives.
|
|
224
|
+
id: this.cryptoPrimitives.randomUuid(),
|
|
225
225
|
delegate: delegationMembersDetails.delegate,
|
|
226
226
|
delegator: delegationMembersDetails.delegator,
|
|
227
227
|
delegationKey: delegationKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DelegationsDeAnonymization.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/DelegationsDeAnonym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AAiB,CAAC,aAAa,EAC/B,UAAU,EACV,IAAI,CAAC,+BAA+B,EACpC,KAAK,EACL,IAAI,EACJ,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,+CAAsB,CAAC,CAAC,CAAC,CACrC,CAAA;YACD,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CACnC,eAAe,EACf,IAAI,SAAG,CAAC,MAAM,CACZ,6DAA0B,EAC1B,MAAM,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,EAAE,UAAU,CAAC,CAC5H,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA3QD,gEA2QC","sourcesContent":["import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { DelegationMembersDetails, SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { SecureDelegationKeyMap } from '../../icc-api/model/internal/SecureDelegationKeyMap'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedFieldsManifest, parseEncryptedFields } from '../utils'\nimport { IccSecureDelegationKeyMapApi } from '../../icc-api/api/internal/IccSecureDelegationKeyMapApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { AuthenticationProvider, NoAuthenticationProvider } from '../auth/AuthenticationProvider'\nimport { ACCESS_CONTROL_KEYS_HEADER, AccessControlKeysHeadersProvider } from './AccessControlKeysHeadersProvider'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\n\n// TODO could be optimised using bulk methods\nexport class DelegationsDeAnonymization {\n private readonly delegationKeyMapFieldsToEncrypt: EncryptedFieldsManifest\n private readonly delegationKeyMapApi: IccSecureDelegationKeyMapApi\n\n constructor(\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly secureDelegationsMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly xapis: ExtendedApisUtils,\n private readonly cryptoPrimitives: CryptoPrimitives,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\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 private readonly accessControlKeysHeadersProvider: AccessControlKeysHeadersProvider\n ) {\n this.delegationKeyMapFieldsToEncrypt = parseEncryptedFields(['delegate', 'delegator'], 'SecureDelegationKeyMap')\n this.delegationKeyMapApi = new IccSecureDelegationKeyMapApi(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Creates / updates information to allow the data owners in {@link shareWithDataOwners} to de-anonymize the delegations contained within\n * {@link entity}.\n * Note that the delegation de-anonymization information may be used also with other entities of the same type.\n */\n async createOrUpdateDeAnonymizationInfo(entityWithType: EncryptedEntityWithType, shareWithDataOwners: string[]) {\n const delegationsDetails = Object.entries(await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)).flatMap(\n ([canonicalKey, delegation]) => {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [[canonicalKey, delegation], ...aliases.map((alias) => [alias, delegation])] as [string, DelegationMembersDetails][]\n }\n )\n const delegationsForDeanonInfoSharing = delegationsDetails.filter(([_, delegationInfo]) => {\n // Drop fully explicit ones: they don't need de-anonymization info\n return !delegationInfo.fullyExplicit\n })\n // A subset of delegations for which deanon info is relevant AND for which we can also create new info instead of sharing only existing one.\n const delegationsForNewDeanonInfoCreation = delegationsForDeanonInfoSharing.filter(([_, delegationInfo]) => {\n // Drop those for which we don't have the full information needed for the creation of new data.\n return !!delegationInfo.delegate && !!delegationInfo.delegator && !!delegationInfo.accessControlSecret\n })\n const existingDelegationsMap = await this.getDecryptedSecureDelegationKeyMaps(\n delegationsForDeanonInfoSharing.map((x) => x[0]),\n entityWithType.type\n )\n for (const delMapToShare of existingDelegationsMap) {\n await this.ensureDelegationKeyMapSharedWith(entityWithType.type, delMapToShare, shareWithDataOwners)\n }\n const existingDelegationsMapKeys = new Set(existingDelegationsMap.map((x) => x.delegationKey))\n const delegationsToCreate = delegationsForNewDeanonInfoCreation.filter(([k, _]) => !existingDelegationsMapKeys.has(k))\n for (const [delKey, membersDetails] of delegationsToCreate) {\n await this.createSecureDelegationKeyMap(entityWithType.type, delKey, membersDetails, shareWithDataOwners)\n }\n }\n\n /**\n * Get the data owners which can access the entity. See {@link EncryptedEntityXApi.getDataOwnersWithAccessTo} for more details.\n * @param entityWithType an entity.\n */\n async getDataOwnersWithAccessTo(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return this.mergePermissions([\n await this.getDataOwnersWithAccessToSecureDelegations(entityWithType),\n {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entityWithType.entity.delegations ?? {}).map((k) => [k, AccessLevelEnum.WRITE])),\n hasUnknownAnonymousDataOwners: false,\n },\n ])\n }\n\n private async getDataOwnersWithAccessToSecureDelegations(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const secureDelegationDetails = await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const secureDelegationWithUnknownMembers = Object.entries(secureDelegationDetails).flatMap(([canonicalKey, delegation]) => {\n if (!delegation.delegate || !delegation.delegator) {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [{ keys: [canonicalKey, ...aliases], delegation }]\n } else {\n return []\n }\n })\n const secureDelegationKeyMapsByDelegationKey = Object.fromEntries(\n (\n await this.getDecryptedSecureDelegationKeyMaps(\n secureDelegationWithUnknownMembers.flatMap(({ keys }) => keys),\n entityWithType.type\n )\n ).map((x) => [x.delegationKey, x])\n )\n const permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n function addAccess(dataOwnerId: string, level: AccessLevelEnum) {\n if (permissionsByDataOwnerId[dataOwnerId] !== AccessLevelEnum.WRITE) {\n permissionsByDataOwnerId[dataOwnerId] = level\n }\n }\n for (const delegation of Object.values(secureDelegationDetails)) {\n if (delegation.delegate) addAccess(delegation.delegate, delegation.accessLevel)\n if (delegation.delegator) addAccess(delegation.delegator, delegation.accessLevel)\n }\n for (const { keys, delegation } of secureDelegationWithUnknownMembers) {\n const bestKey = keys.find((k) => {\n const currMap = secureDelegationKeyMapsByDelegationKey[k]\n return currMap && !!currMap.delegator && !!currMap.delegate\n })\n if (bestKey) {\n const keyMap = secureDelegationKeyMapsByDelegationKey[bestKey]\n addAccess(keyMap.delegate!, delegation.accessLevel)\n addAccess(keyMap.delegator!, delegation.accessLevel)\n } else {\n hasUnknownAnonymousDataOwners = true\n }\n }\n return { permissionsByDataOwnerId, hasUnknownAnonymousDataOwners }\n }\n\n private async mergePermissions(\n values: {\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }[]\n ): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const accumulatedPermissions: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n for (const v of values) {\n hasUnknownAnonymousDataOwners = hasUnknownAnonymousDataOwners || v.hasUnknownAnonymousDataOwners\n for (const [dataOwnerId, level] of Object.entries(v.permissionsByDataOwnerId)) {\n if (accumulatedPermissions[dataOwnerId] !== AccessLevelEnum.WRITE) {\n accumulatedPermissions[dataOwnerId] = level\n }\n }\n }\n return {\n permissionsByDataOwnerId: accumulatedPermissions,\n hasUnknownAnonymousDataOwners,\n }\n }\n\n private async getDecryptedSecureDelegationKeyMaps(\n delegationIds: string[],\n entityType: EntityWithDelegationTypeName\n ): Promise<SecureDelegationKeyMap[]> {\n if (delegationIds.length) {\n const encryptedMaps = await this.delegationKeyMapApi.getByDelegationKeys(\n { ids: delegationIds },\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n const res: SecureDelegationKeyMap[] = []\n for (const encryptedMap of encryptedMaps) {\n // Use the original entity type\n const decryptionResult = await this.xapis.decryptEntity(encryptedMap, entityType, (x) => new SecureDelegationKeyMap(x))\n if (decryptionResult.decrypted) {\n res.push(decryptionResult.entity)\n }\n }\n return res\n } else return []\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async ensureDelegationKeyMapSharedWith(entityType: EntityWithDelegationTypeName, keyMap: SecureDelegationKeyMap, delegates: string[]) {\n if (!keyMap.delegator || !keyMap.delegate) throw new Error('Illegal state: key map is missing delegator or delegate info.')\n const dataOwnersWithAccessToMapThroughDelegation = Object.values(\n await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails({\n type: entityType,\n entity: keyMap,\n })\n )\n .flatMap((x) => [x.delegate, x.delegator])\n .filter((x) => !!x) as string[]\n // Delegator and delegate got access to the entity when it was first created: no need to share with them ever.\n const dataOwnersWithAccessToMap = new Set([keyMap.delegate, keyMap.delegator, ...dataOwnersWithAccessToMapThroughDelegation])\n const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x))\n if (dataOwnersNeedingShare.length) {\n ;(\n await this.xapis.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: keyMap, type: entityType },\n false,\n Object.fromEntries(\n dataOwnersNeedingShare.map((x) => [\n x,\n {\n shareSecretIds: [],\n shareEncryptionKeys: ShareMetadataBehaviour.REQUIRED,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n },\n ])\n ),\n async (request) =>\n this.delegationKeyMapApi.bulkShareSecureDelegationKeyMap(\n request,\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n )\n ).updatedEntityOrThrow\n }\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async createSecureDelegationKeyMap(\n entityType: EntityWithDelegationTypeName,\n delegationKey: string,\n delegationMembersDetails: DelegationMembersDetails,\n delegates: string[]\n ) {\n if (!delegationMembersDetails.delegate || !delegationMembersDetails.delegator || !delegationMembersDetails.accessControlSecret)\n throw new Error('Illegal state: delegation members details are missing delegate, delegator or access control secret info.')\n const selfDoId = await this.dataOwnerApi.getCurrentDataOwnerId()\n // Ensure that both the delegator and delegate of the delegation this map refers tho can share it later on, even if they did not create it.\n // Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.\n const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId)\n const initalisedMapInfo = await this.xapis.entityWithInitialisedEncryptedMetadata<SecureDelegationKeyMap>(\n {\n id: this.cryptoPrimitives.crypto.randomUUID(),\n delegate: delegationMembersDetails.delegate,\n delegator: delegationMembersDetails.delegator,\n delegationKey: delegationKey,\n },\n entityType,\n undefined,\n undefined,\n true,\n false,\n Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ]))\n )\n const encryptedKeyMap = await this.xapis.tryEncryptEntity(\n initalisedMapInfo.updatedEntity,\n entityType,\n this.delegationKeyMapFieldsToEncrypt,\n false,\n true,\n (x) => new SecureDelegationKeyMap(x)\n )\n await this.delegationKeyMapApi.create(\n encryptedKeyMap,\n new XHR.Header(\n ACCESS_CONTROL_KEYS_HEADER,\n await this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)\n )\n )\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DelegationsDeAnonymization.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/DelegationsDeAnonymization.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,2EAAuE;AACvE,IAAO,eAAe,GAAG,mCAAgB,CAAC,eAAe,CAAA;AAEzD,gGAA4F;AAE5F,qEAAiE;AACjE,wFAAoF;AACpF,IAAO,uBAAuB,GAAG,uCAAkB,CAAC,uBAAuB,CAAA;AAE3E,oCAAwE;AACxE,0GAAsG;AACtG,+CAA2C;AAC3C,2EAAiG;AACjG,yFAAiH;AAIjH,6CAA6C;AAC7C,MAAa,0BAA0B;IAIrC,YACmB,YAA8B,EAC9B,kCAA8E,EAC9E,KAAwB,EACxB,gBAAkC,EAClC,wBAAkD,EACnE,IAAY,EACZ,OAAkC,EAClC,yBAAiD,IAAI,iDAAwB,EAAE,EAC/E,YAA2E,OAAO,MAAM,KAAK,WAAW;QACtG,CAAC,CAAC,MAAM,CAAC,KAAK;QACd,CAAC,CAAC,OAAO,IAAI,KAAK,WAAW;YAC7B,CAAC,CAAC,IAAI,CAAC,KAAK;YACZ,CAAC,CAAC,KAAK,EACQ,gCAAkE;QAblE,iBAAY,GAAZ,YAAY,CAAkB;QAC9B,uCAAkC,GAAlC,kCAAkC,CAA4C;QAC9E,UAAK,GAAL,KAAK,CAAmB;QACxB,qBAAgB,GAAhB,gBAAgB,CAAkB;QAClC,6BAAwB,GAAxB,wBAAwB,CAA0B;QASlD,qCAAgC,GAAhC,gCAAgC,CAAkC;QAE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AQ;gBAC3C,SAAS,EAAE,wBAAwB,CAAC,SAAS;gBAC7C,aAAa,EAAE,aAAa;aAC7B,EACD,UAAU,EACV,SAAS,EACT,SAAS,EACT,IAAI,EACJ,KAAK,EACL,MAAM,CAAC,WAAW,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAC3E,CAAA;YACD,MAAM,eAAe,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,gBAAgB,CACvD,iBAAiB,CAAC,aAAa,EAC/B,UAAU,EACV,IAAI,CAAC,+BAA+B,EACpC,KAAK,EACL,IAAI,EACJ,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,+CAAsB,CAAC,CAAC,CAAC,CACrC,CAAA;YACD,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CACnC,eAAe,EACf,IAAI,SAAG,CAAC,MAAM,CACZ,6DAA0B,EAC1B,MAAM,IAAI,CAAC,wBAAwB,CAAC,2BAA2B,CAAC,CAAC,wBAAwB,CAAC,mBAAmB,CAAC,EAAE,UAAU,CAAC,CAC5H,CACF,CAAA;QACH,CAAC;KAAA;CACF;AA3QD,gEA2QC","sourcesContent":["import { EncryptedEntityWithType, EntityWithDelegationTypeName } from '../utils/EntityWithDelegationTypeName'\nimport { SecureDelegation } from '../../icc-api/model/SecureDelegation'\nimport AccessLevelEnum = SecureDelegation.AccessLevelEnum\nimport { DelegationMembersDetails, SecureDelegationsSecurityMetadataDecryptor } from './SecureDelegationsSecurityMetadataDecryptor'\nimport { SecureDelegationKeyMap } from '../../icc-api/model/internal/SecureDelegationKeyMap'\nimport { ExtendedApisUtils } from './ExtendedApisUtils'\nimport { ShareMetadataBehaviour } from './ShareMetadataBehaviour'\nimport { EntityShareRequest } from '../../icc-api/model/requests/EntityShareRequest'\nimport RequestedPermissionEnum = EntityShareRequest.RequestedPermissionEnum\nimport { CryptoPrimitives } from './CryptoPrimitives'\nimport { EncryptedFieldsManifest, parseEncryptedFields } from '../utils'\nimport { IccSecureDelegationKeyMapApi } from '../../icc-api/api/internal/IccSecureDelegationKeyMapApi'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { AuthenticationProvider, NoAuthenticationProvider } from '../auth/AuthenticationProvider'\nimport { ACCESS_CONTROL_KEYS_HEADER, AccessControlKeysHeadersProvider } from './AccessControlKeysHeadersProvider'\nimport { AccessControlSecretUtils } from './AccessControlSecretUtils'\nimport { IccDataOwnerXApi } from '../icc-data-owner-x-api'\n\n// TODO could be optimised using bulk methods\nexport class DelegationsDeAnonymization {\n private readonly delegationKeyMapFieldsToEncrypt: EncryptedFieldsManifest\n private readonly delegationKeyMapApi: IccSecureDelegationKeyMapApi\n\n constructor(\n private readonly dataOwnerApi: IccDataOwnerXApi,\n private readonly secureDelegationsMetadataDecryptor: SecureDelegationsSecurityMetadataDecryptor,\n private readonly xapis: ExtendedApisUtils,\n private readonly cryptoPrimitives: CryptoPrimitives,\n private readonly accessControlSecretUtils: AccessControlSecretUtils,\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 private readonly accessControlKeysHeadersProvider: AccessControlKeysHeadersProvider\n ) {\n this.delegationKeyMapFieldsToEncrypt = parseEncryptedFields(['delegate', 'delegator'], 'SecureDelegationKeyMap')\n this.delegationKeyMapApi = new IccSecureDelegationKeyMapApi(host, headers, authenticationProvider, fetchImpl)\n }\n\n /**\n * Creates / updates information to allow the data owners in {@link shareWithDataOwners} to de-anonymize the delegations contained within\n * {@link entity}.\n * Note that the delegation de-anonymization information may be used also with other entities of the same type.\n */\n async createOrUpdateDeAnonymizationInfo(entityWithType: EncryptedEntityWithType, shareWithDataOwners: string[]) {\n const delegationsDetails = Object.entries(await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)).flatMap(\n ([canonicalKey, delegation]) => {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [[canonicalKey, delegation], ...aliases.map((alias) => [alias, delegation])] as [string, DelegationMembersDetails][]\n }\n )\n const delegationsForDeanonInfoSharing = delegationsDetails.filter(([_, delegationInfo]) => {\n // Drop fully explicit ones: they don't need de-anonymization info\n return !delegationInfo.fullyExplicit\n })\n // A subset of delegations for which deanon info is relevant AND for which we can also create new info instead of sharing only existing one.\n const delegationsForNewDeanonInfoCreation = delegationsForDeanonInfoSharing.filter(([_, delegationInfo]) => {\n // Drop those for which we don't have the full information needed for the creation of new data.\n return !!delegationInfo.delegate && !!delegationInfo.delegator && !!delegationInfo.accessControlSecret\n })\n const existingDelegationsMap = await this.getDecryptedSecureDelegationKeyMaps(\n delegationsForDeanonInfoSharing.map((x) => x[0]),\n entityWithType.type\n )\n for (const delMapToShare of existingDelegationsMap) {\n await this.ensureDelegationKeyMapSharedWith(entityWithType.type, delMapToShare, shareWithDataOwners)\n }\n const existingDelegationsMapKeys = new Set(existingDelegationsMap.map((x) => x.delegationKey))\n const delegationsToCreate = delegationsForNewDeanonInfoCreation.filter(([k, _]) => !existingDelegationsMapKeys.has(k))\n for (const [delKey, membersDetails] of delegationsToCreate) {\n await this.createSecureDelegationKeyMap(entityWithType.type, delKey, membersDetails, shareWithDataOwners)\n }\n }\n\n /**\n * Get the data owners which can access the entity. See {@link EncryptedEntityXApi.getDataOwnersWithAccessTo} for more details.\n * @param entityWithType an entity.\n */\n async getDataOwnersWithAccessTo(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n return this.mergePermissions([\n await this.getDataOwnersWithAccessToSecureDelegations(entityWithType),\n {\n permissionsByDataOwnerId: Object.fromEntries(Object.keys(entityWithType.entity.delegations ?? {}).map((k) => [k, AccessLevelEnum.WRITE])),\n hasUnknownAnonymousDataOwners: false,\n },\n ])\n }\n\n private async getDataOwnersWithAccessToSecureDelegations(entityWithType: EncryptedEntityWithType): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const secureDelegationDetails = await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails(entityWithType)\n const secureDelegationWithUnknownMembers = Object.entries(secureDelegationDetails).flatMap(([canonicalKey, delegation]) => {\n if (!delegation.delegate || !delegation.delegator) {\n const aliases = Object.entries(entityWithType.entity.securityMetadata?.keysEquivalences ?? {}).flatMap(([alias, canon]) => {\n if (canon == canonicalKey) {\n return [alias]\n } else {\n return []\n }\n })\n return [{ keys: [canonicalKey, ...aliases], delegation }]\n } else {\n return []\n }\n })\n const secureDelegationKeyMapsByDelegationKey = Object.fromEntries(\n (\n await this.getDecryptedSecureDelegationKeyMaps(\n secureDelegationWithUnknownMembers.flatMap(({ keys }) => keys),\n entityWithType.type\n )\n ).map((x) => [x.delegationKey, x])\n )\n const permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n function addAccess(dataOwnerId: string, level: AccessLevelEnum) {\n if (permissionsByDataOwnerId[dataOwnerId] !== AccessLevelEnum.WRITE) {\n permissionsByDataOwnerId[dataOwnerId] = level\n }\n }\n for (const delegation of Object.values(secureDelegationDetails)) {\n if (delegation.delegate) addAccess(delegation.delegate, delegation.accessLevel)\n if (delegation.delegator) addAccess(delegation.delegator, delegation.accessLevel)\n }\n for (const { keys, delegation } of secureDelegationWithUnknownMembers) {\n const bestKey = keys.find((k) => {\n const currMap = secureDelegationKeyMapsByDelegationKey[k]\n return currMap && !!currMap.delegator && !!currMap.delegate\n })\n if (bestKey) {\n const keyMap = secureDelegationKeyMapsByDelegationKey[bestKey]\n addAccess(keyMap.delegate!, delegation.accessLevel)\n addAccess(keyMap.delegator!, delegation.accessLevel)\n } else {\n hasUnknownAnonymousDataOwners = true\n }\n }\n return { permissionsByDataOwnerId, hasUnknownAnonymousDataOwners }\n }\n\n private async mergePermissions(\n values: {\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }[]\n ): Promise<{\n permissionsByDataOwnerId: { [dataOwnerId: string]: AccessLevelEnum }\n hasUnknownAnonymousDataOwners: boolean\n }> {\n const accumulatedPermissions: { [dataOwnerId: string]: AccessLevelEnum } = {}\n let hasUnknownAnonymousDataOwners = false\n for (const v of values) {\n hasUnknownAnonymousDataOwners = hasUnknownAnonymousDataOwners || v.hasUnknownAnonymousDataOwners\n for (const [dataOwnerId, level] of Object.entries(v.permissionsByDataOwnerId)) {\n if (accumulatedPermissions[dataOwnerId] !== AccessLevelEnum.WRITE) {\n accumulatedPermissions[dataOwnerId] = level\n }\n }\n }\n return {\n permissionsByDataOwnerId: accumulatedPermissions,\n hasUnknownAnonymousDataOwners,\n }\n }\n\n private async getDecryptedSecureDelegationKeyMaps(\n delegationIds: string[],\n entityType: EntityWithDelegationTypeName\n ): Promise<SecureDelegationKeyMap[]> {\n if (delegationIds.length) {\n const encryptedMaps = await this.delegationKeyMapApi.getByDelegationKeys(\n { ids: delegationIds },\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n const res: SecureDelegationKeyMap[] = []\n for (const encryptedMap of encryptedMaps) {\n // Use the original entity type\n const decryptionResult = await this.xapis.decryptEntity(encryptedMap, entityType, (x) => new SecureDelegationKeyMap(x))\n if (decryptionResult.decrypted) {\n res.push(decryptionResult.entity)\n }\n }\n return res\n } else return []\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async ensureDelegationKeyMapSharedWith(entityType: EntityWithDelegationTypeName, keyMap: SecureDelegationKeyMap, delegates: string[]) {\n if (!keyMap.delegator || !keyMap.delegate) throw new Error('Illegal state: key map is missing delegator or delegate info.')\n const dataOwnersWithAccessToMapThroughDelegation = Object.values(\n await this.secureDelegationsMetadataDecryptor.getDelegationMemberDetails({\n type: entityType,\n entity: keyMap,\n })\n )\n .flatMap((x) => [x.delegate, x.delegator])\n .filter((x) => !!x) as string[]\n // Delegator and delegate got access to the entity when it was first created: no need to share with them ever.\n const dataOwnersWithAccessToMap = new Set([keyMap.delegate, keyMap.delegator, ...dataOwnersWithAccessToMapThroughDelegation])\n const dataOwnersNeedingShare = delegates.filter((x) => !dataOwnersWithAccessToMap.has(x))\n if (dataOwnersNeedingShare.length) {\n ;(\n await this.xapis.simpleShareOrUpdateEncryptedEntityMetadata(\n { entity: keyMap, type: entityType },\n false,\n Object.fromEntries(\n dataOwnersNeedingShare.map((x) => [\n x,\n {\n shareSecretIds: [],\n shareEncryptionKeys: ShareMetadataBehaviour.REQUIRED,\n shareOwningEntityIds: ShareMetadataBehaviour.NEVER,\n requestedPermissions: RequestedPermissionEnum.FULL_READ,\n },\n ])\n ),\n async (request) =>\n this.delegationKeyMapApi.bulkShareSecureDelegationKeyMap(\n request,\n await this.accessControlKeysHeadersProvider.getAccessControlKeysHeaders(entityType)\n )\n )\n ).updatedEntityOrThrow\n }\n }\n\n // Important: to avoid potentially leaking links between entities of different types the key map calculates the secure delegation keys using the\n // same entity type as the delegation key for which they are mapping information.\n private async createSecureDelegationKeyMap(\n entityType: EntityWithDelegationTypeName,\n delegationKey: string,\n delegationMembersDetails: DelegationMembersDetails,\n delegates: string[]\n ) {\n if (!delegationMembersDetails.delegate || !delegationMembersDetails.delegator || !delegationMembersDetails.accessControlSecret)\n throw new Error('Illegal state: delegation members details are missing delegate, delegator or access control secret info.')\n const selfDoId = await this.dataOwnerApi.getCurrentDataOwnerId()\n // Ensure that both the delegator and delegate of the delegation this map refers tho can share it later on, even if they did not create it.\n // Usually either the delegator or delegate are the current data owner, but sometimes also the child of the delegator or delegate can do it.\n const initialDelegates = [delegationMembersDetails.delegate, delegationMembersDetails.delegator, ...delegates].filter((x) => x != selfDoId)\n const initalisedMapInfo = await this.xapis.entityWithInitialisedEncryptedMetadata<SecureDelegationKeyMap>(\n {\n id: this.cryptoPrimitives.randomUuid(),\n delegate: delegationMembersDetails.delegate,\n delegator: delegationMembersDetails.delegator,\n delegationKey: delegationKey,\n },\n entityType,\n undefined,\n undefined,\n true,\n false,\n Object.fromEntries(initialDelegates.map((x) => [x, AccessLevelEnum.READ]))\n )\n const encryptedKeyMap = await this.xapis.tryEncryptEntity(\n initalisedMapInfo.updatedEntity,\n entityType,\n this.delegationKeyMapFieldsToEncrypt,\n false,\n true,\n (x) => new SecureDelegationKeyMap(x)\n )\n await this.delegationKeyMapApi.create(\n encryptedKeyMap,\n new XHR.Header(\n ACCESS_CONTROL_KEYS_HEADER,\n await this.accessControlSecretUtils.getEncodedAccessControlKeys([delegationMembersDetails.accessControlSecret], entityType)\n )\n )\n }\n}\n"]}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
export
|
|
1
|
+
export interface HMACUtils {
|
|
2
|
+
generateKey(): Promise<CryptoKey>;
|
|
3
|
+
exportKey(key: CryptoKey): Promise<ArrayBuffer>;
|
|
4
|
+
importKey(key: ArrayBuffer): Promise<CryptoKey>;
|
|
5
|
+
sign(key: CryptoKey, data: ArrayBuffer): Promise<ArrayBuffer>;
|
|
6
|
+
verify(key: CryptoKey, data: ArrayBuffer, signature: ArrayBuffer): Promise<boolean>;
|
|
7
|
+
}
|
|
8
|
+
export declare class HMACUtilsImpl implements HMACUtils {
|
|
2
9
|
private readonly _crypto;
|
|
3
10
|
private readonly recommendedKeyLengthBytes;
|
|
4
11
|
private readonly params;
|