@icure/api 7.0.0-beta.2 → 7.0.0-beta.4

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.
Files changed (217) hide show
  1. package/icc-api/api/IccAccesslogApi.js +2 -1
  2. package/icc-api/api/IccAccesslogApi.js.map +1 -1
  3. package/icc-api/api/IccAgendaApi.js +2 -1
  4. package/icc-api/api/IccAgendaApi.js.map +1 -1
  5. package/icc-api/api/IccAnonymousAccessApi.js +2 -1
  6. package/icc-api/api/IccAnonymousAccessApi.js.map +1 -1
  7. package/icc-api/api/IccApplicationsettingsApi.js +2 -1
  8. package/icc-api/api/IccApplicationsettingsApi.js.map +1 -1
  9. package/icc-api/api/IccArticleApi.js +2 -1
  10. package/icc-api/api/IccArticleApi.js.map +1 -1
  11. package/icc-api/api/IccAuthApi.d.ts +23 -0
  12. package/icc-api/api/IccAuthApi.js +59 -2
  13. package/icc-api/api/IccAuthApi.js.map +1 -1
  14. package/icc-api/api/IccBeefactApi.js +2 -1
  15. package/icc-api/api/IccBeefactApi.js.map +1 -1
  16. package/icc-api/api/IccBekmehrApi.js +2 -1
  17. package/icc-api/api/IccBekmehrApi.js.map +1 -1
  18. package/icc-api/api/IccBeresultexportApi.js +2 -1
  19. package/icc-api/api/IccBeresultexportApi.js.map +1 -1
  20. package/icc-api/api/IccBeresultimportApi.js +2 -1
  21. package/icc-api/api/IccBeresultimportApi.js.map +1 -1
  22. package/icc-api/api/IccBesamv2Api.d.ts +6 -0
  23. package/icc-api/api/IccBesamv2Api.js +15 -1
  24. package/icc-api/api/IccBesamv2Api.js.map +1 -1
  25. package/icc-api/api/IccCalendarItemApi.js +2 -1
  26. package/icc-api/api/IccCalendarItemApi.js.map +1 -1
  27. package/icc-api/api/IccCalendarItemTypeApi.js +2 -1
  28. package/icc-api/api/IccCalendarItemTypeApi.js.map +1 -1
  29. package/icc-api/api/IccClassificationApi.js +2 -1
  30. package/icc-api/api/IccClassificationApi.js.map +1 -1
  31. package/icc-api/api/IccClassificationTemplateApi.js +2 -1
  32. package/icc-api/api/IccClassificationTemplateApi.js.map +1 -1
  33. package/icc-api/api/IccCodeApi.js +2 -1
  34. package/icc-api/api/IccCodeApi.js.map +1 -1
  35. package/icc-api/api/IccContactApi.d.ts +6 -0
  36. package/icc-api/api/IccContactApi.js +26 -1
  37. package/icc-api/api/IccContactApi.js.map +1 -1
  38. package/icc-api/api/IccDataownerApi.d.ts +13 -2
  39. package/icc-api/api/IccDataownerApi.js +32 -5
  40. package/icc-api/api/IccDataownerApi.js.map +1 -1
  41. package/icc-api/api/IccDeviceApi.js +2 -1
  42. package/icc-api/api/IccDeviceApi.js.map +1 -1
  43. package/icc-api/api/IccDoctemplateApi.js +2 -1
  44. package/icc-api/api/IccDoctemplateApi.js.map +1 -1
  45. package/icc-api/api/IccDocumentApi.js +2 -1
  46. package/icc-api/api/IccDocumentApi.js.map +1 -1
  47. package/icc-api/api/IccDocumentTemplateApi.js +2 -1
  48. package/icc-api/api/IccDocumentTemplateApi.js.map +1 -1
  49. package/icc-api/api/IccEntityrefApi.js +2 -1
  50. package/icc-api/api/IccEntityrefApi.js.map +1 -1
  51. package/icc-api/api/IccEntitytemplateApi.js +2 -1
  52. package/icc-api/api/IccEntitytemplateApi.js.map +1 -1
  53. package/icc-api/api/IccFormApi.js +2 -1
  54. package/icc-api/api/IccFormApi.js.map +1 -1
  55. package/icc-api/api/IccFrontendmigrationApi.js +2 -1
  56. package/icc-api/api/IccFrontendmigrationApi.js.map +1 -1
  57. package/icc-api/api/IccGroupApi.d.ts +6 -0
  58. package/icc-api/api/IccGroupApi.js +15 -1
  59. package/icc-api/api/IccGroupApi.js.map +1 -1
  60. package/icc-api/api/IccHcpartyApi.js +2 -1
  61. package/icc-api/api/IccHcpartyApi.js.map +1 -1
  62. package/icc-api/api/IccHelementApi.js +2 -1
  63. package/icc-api/api/IccHelementApi.js.map +1 -1
  64. package/icc-api/api/IccIcureApi.js +2 -1
  65. package/icc-api/api/IccIcureApi.js.map +1 -1
  66. package/icc-api/api/IccInsuranceApi.js +2 -1
  67. package/icc-api/api/IccInsuranceApi.js.map +1 -1
  68. package/icc-api/api/IccInvoiceApi.js +2 -1
  69. package/icc-api/api/IccInvoiceApi.js.map +1 -1
  70. package/icc-api/api/IccKeywordApi.js +2 -1
  71. package/icc-api/api/IccKeywordApi.js.map +1 -1
  72. package/icc-api/api/IccMaintenanceTaskApi.js +2 -1
  73. package/icc-api/api/IccMaintenanceTaskApi.js.map +1 -1
  74. package/icc-api/api/IccMedexApi.js +2 -1
  75. package/icc-api/api/IccMedexApi.js.map +1 -1
  76. package/icc-api/api/IccMedicallocationApi.js +2 -1
  77. package/icc-api/api/IccMedicallocationApi.js.map +1 -1
  78. package/icc-api/api/IccMessageApi.js +2 -1
  79. package/icc-api/api/IccMessageApi.js.map +1 -1
  80. package/icc-api/api/IccPatientApi.js +2 -1
  81. package/icc-api/api/IccPatientApi.js.map +1 -1
  82. package/icc-api/api/IccPermissionApi.js +2 -1
  83. package/icc-api/api/IccPermissionApi.js.map +1 -1
  84. package/icc-api/api/IccPlaceApi.js +2 -1
  85. package/icc-api/api/IccPlaceApi.js.map +1 -1
  86. package/icc-api/api/IccPubsubApi.js +2 -1
  87. package/icc-api/api/IccPubsubApi.js.map +1 -1
  88. package/icc-api/api/IccReceiptApi.js +2 -1
  89. package/icc-api/api/IccReceiptApi.js.map +1 -1
  90. package/icc-api/api/IccReplicationApi.js +2 -1
  91. package/icc-api/api/IccReplicationApi.js.map +1 -1
  92. package/icc-api/api/IccRestApiPath.d.ts +1 -0
  93. package/icc-api/api/IccRestApiPath.js +10 -0
  94. package/icc-api/api/IccRestApiPath.js.map +1 -0
  95. package/icc-api/api/IccTarificationApi.js +2 -1
  96. package/icc-api/api/IccTarificationApi.js.map +1 -1
  97. package/icc-api/api/IccTimeTableApi.js +2 -1
  98. package/icc-api/api/IccTimeTableApi.js.map +1 -1
  99. package/icc-api/api/IccTmpApi.js +2 -1
  100. package/icc-api/api/IccTmpApi.js.map +1 -1
  101. package/icc-api/api/IccUserApi.js +2 -1
  102. package/icc-api/api/IccUserApi.js.map +1 -1
  103. package/icc-api/index.d.ts +0 -1
  104. package/icc-api/index.js +0 -1
  105. package/icc-api/index.js.map +1 -1
  106. package/icc-api/model/AuthenticationToken.d.ts +1 -0
  107. package/icc-api/model/AuthenticationToken.js.map +1 -1
  108. package/icc-api/model/CryptoActorStub.d.ts +55 -0
  109. package/icc-api/model/CryptoActorStub.js +35 -0
  110. package/icc-api/model/CryptoActorStub.js.map +1 -0
  111. package/icc-api/model/DataOwnerTypeEnum.d.ts +8 -0
  112. package/icc-api/model/DataOwnerTypeEnum.js +13 -0
  113. package/icc-api/model/DataOwnerTypeEnum.js.map +1 -0
  114. package/icc-api/model/DataOwnerWithType.d.ts +16 -3
  115. package/icc-api/model/DataOwnerWithType.js +22 -7
  116. package/icc-api/model/DataOwnerWithType.js.map +1 -1
  117. package/icc-api/model/Device.d.ts +4 -0
  118. package/icc-api/model/Device.js.map +1 -1
  119. package/icc-api/model/FlatRateTarification.d.ts +4 -1
  120. package/icc-api/model/FlatRateTarification.js +3 -0
  121. package/icc-api/model/FlatRateTarification.js.map +1 -1
  122. package/icc-api/model/HealthcareParty.d.ts +4 -0
  123. package/icc-api/model/HealthcareParty.js.map +1 -1
  124. package/icc-api/model/Patient.d.ts +4 -0
  125. package/icc-api/model/Patient.js.map +1 -1
  126. package/icc-api/model/UserGroup.d.ts +1 -0
  127. package/icc-api/model/UserGroup.js.map +1 -1
  128. package/icc-x-api/auth/AuthenticationProvider.d.ts +67 -6
  129. package/icc-x-api/auth/AuthenticationProvider.js +100 -7
  130. package/icc-x-api/auth/AuthenticationProvider.js.map +1 -1
  131. package/icc-x-api/auth/EnsembleAuthService.d.ts +7 -2
  132. package/icc-x-api/auth/EnsembleAuthService.js +9 -0
  133. package/icc-x-api/auth/EnsembleAuthService.js.map +1 -1
  134. package/icc-x-api/auth/JwtAuthService.d.ts +10 -5
  135. package/icc-x-api/auth/JwtAuthService.js +22 -26
  136. package/icc-x-api/auth/JwtAuthService.js.map +1 -1
  137. package/icc-x-api/auth/JwtBridgedAuthService.d.ts +27 -0
  138. package/icc-x-api/auth/JwtBridgedAuthService.js +131 -0
  139. package/icc-x-api/auth/JwtBridgedAuthService.js.map +1 -0
  140. package/icc-x-api/crypto/AES.js +9 -1
  141. package/icc-x-api/crypto/AES.js.map +1 -1
  142. package/icc-x-api/crypto/BaseExchangeKeysManager.d.ts +4 -2
  143. package/icc-x-api/crypto/BaseExchangeKeysManager.js +32 -31
  144. package/icc-x-api/crypto/BaseExchangeKeysManager.js.map +1 -1
  145. package/icc-x-api/crypto/CryptoStrategies.d.ts +5 -4
  146. package/icc-x-api/crypto/CryptoStrategies.js.map +1 -1
  147. package/icc-x-api/crypto/EntitiesEncryption.d.ts +3 -3
  148. package/icc-x-api/crypto/EntitiesEncryption.js +9 -7
  149. package/icc-x-api/crypto/EntitiesEncryption.js.map +1 -1
  150. package/icc-x-api/crypto/ExchangeKeysManager.d.ts +3 -2
  151. package/icc-x-api/crypto/ExchangeKeysManager.js +3 -3
  152. package/icc-x-api/crypto/ExchangeKeysManager.js.map +1 -1
  153. package/icc-x-api/crypto/KeyManager.js +4 -4
  154. package/icc-x-api/crypto/KeyManager.js.map +1 -1
  155. package/icc-x-api/crypto/KeyRecovery.d.ts +2 -1
  156. package/icc-x-api/crypto/KeyRecovery.js.map +1 -1
  157. package/icc-x-api/crypto/LegacyCryptoStrategies.d.ts +5 -4
  158. package/icc-x-api/crypto/LegacyCryptoStrategies.js +1 -1
  159. package/icc-x-api/crypto/LegacyCryptoStrategies.js.map +1 -1
  160. package/icc-x-api/crypto/ShamirKeysManager.d.ts +4 -3
  161. package/icc-x-api/crypto/ShamirKeysManager.js +8 -7
  162. package/icc-x-api/crypto/ShamirKeysManager.js.map +1 -1
  163. package/icc-x-api/crypto/TransferKeysManager.d.ts +3 -2
  164. package/icc-x-api/crypto/TransferKeysManager.js +6 -6
  165. package/icc-x-api/crypto/TransferKeysManager.js.map +1 -1
  166. package/icc-x-api/crypto/utils.d.ts +7 -6
  167. package/icc-x-api/crypto/utils.js +4 -7
  168. package/icc-x-api/crypto/utils.js.map +1 -1
  169. package/icc-x-api/filters/ServiceByHcPartyTagCodeDateFilter.d.ts +1 -0
  170. package/icc-x-api/filters/ServiceByHcPartyTagCodeDateFilter.js.map +1 -1
  171. package/icc-x-api/icc-accesslog-x-api.d.ts +2 -2
  172. package/icc-x-api/icc-accesslog-x-api.js +9 -4
  173. package/icc-x-api/icc-accesslog-x-api.js.map +1 -1
  174. package/icc-x-api/icc-calendar-item-x-api.js +11 -3
  175. package/icc-x-api/icc-calendar-item-x-api.js.map +1 -1
  176. package/icc-x-api/icc-classification-x-api.js +7 -2
  177. package/icc-x-api/icc-classification-x-api.js.map +1 -1
  178. package/icc-x-api/icc-contact-x-api.d.ts +1 -0
  179. package/icc-x-api/icc-contact-x-api.js +16 -4
  180. package/icc-x-api/icc-contact-x-api.js.map +1 -1
  181. package/icc-x-api/icc-crypto-x-api.d.ts +6 -6
  182. package/icc-x-api/icc-crypto-x-api.js +4 -4
  183. package/icc-x-api/icc-crypto-x-api.js.map +1 -1
  184. package/icc-x-api/icc-data-owner-x-api.d.ts +21 -52
  185. package/icc-x-api/icc-data-owner-x-api.js +36 -68
  186. package/icc-x-api/icc-data-owner-x-api.js.map +1 -1
  187. package/icc-x-api/icc-document-x-api.js +7 -2
  188. package/icc-x-api/icc-document-x-api.js.map +1 -1
  189. package/icc-x-api/icc-form-x-api.js +7 -2
  190. package/icc-x-api/icc-form-x-api.js.map +1 -1
  191. package/icc-x-api/icc-helement-x-api.js +7 -2
  192. package/icc-x-api/icc-helement-x-api.js.map +1 -1
  193. package/icc-x-api/icc-icure-maintenance-x-api.js +8 -8
  194. package/icc-x-api/icc-icure-maintenance-x-api.js.map +1 -1
  195. package/icc-x-api/icc-invoice-x-api.js +7 -2
  196. package/icc-x-api/icc-invoice-x-api.js.map +1 -1
  197. package/icc-x-api/icc-maintenance-task-x-api.js +6 -1
  198. package/icc-x-api/icc-maintenance-task-x-api.js.map +1 -1
  199. package/icc-x-api/icc-message-x-api.js +7 -2
  200. package/icc-x-api/icc-message-x-api.js.map +1 -1
  201. package/icc-x-api/icc-patient-x-api.d.ts +4 -1
  202. package/icc-x-api/icc-patient-x-api.js +8 -7
  203. package/icc-x-api/icc-patient-x-api.js.map +1 -1
  204. package/icc-x-api/icc-receipt-x-api.js +6 -1
  205. package/icc-x-api/icc-receipt-x-api.js.map +1 -1
  206. package/icc-x-api/icc-time-table-x-api.js +6 -1
  207. package/icc-x-api/icc-time-table-x-api.js.map +1 -1
  208. package/icc-x-api/index.d.ts +178 -35
  209. package/icc-x-api/index.js +305 -81
  210. package/icc-x-api/index.js.map +1 -1
  211. package/icc-x-api/maintenance/KeyPairUpdateRequest.d.ts +12 -9
  212. package/icc-x-api/maintenance/KeyPairUpdateRequest.js +11 -17
  213. package/icc-x-api/maintenance/KeyPairUpdateRequest.js.map +1 -1
  214. package/package.json +1 -1
  215. package/icc-api/api/IccBemikronoApi.d.ts +0 -81
  216. package/icc-api/api/IccBemikronoApi.js +0 -162
  217. package/icc-api/api/IccBemikronoApi.js.map +0 -1
@@ -11,21 +11,30 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.JwtAuthService = void 0;
13
13
  const XHR_1 = require("../../icc-api/api/XHR");
14
- const LoginCredentials_1 = require("../../icc-api/model/LoginCredentials");
15
14
  const utils_1 = require("../utils");
16
15
  class JwtAuthService {
17
- constructor(authApi, username, password) {
16
+ constructor(authApi, initialJwt) {
18
17
  this.authApi = authApi;
19
- this.username = username;
20
- this.password = password;
21
18
  this._error = null;
22
- this._currentPromise = Promise.resolve({});
19
+ this._currentPromise = Promise.resolve(undefined);
20
+ if (!!initialJwt) {
21
+ this._currentPromise = Promise.resolve(initialJwt);
22
+ }
23
+ }
24
+ getIcureTokens() {
25
+ return this._currentPromise.then((x) => (x ? { token: x.authJwt, refreshToken: x.refreshJwt } : undefined));
26
+ }
27
+ get refreshToken() {
28
+ return this._currentPromise.then((x) => x === null || x === void 0 ? void 0 : x.refreshJwt);
23
29
  }
24
30
  getAuthHeaders() {
25
31
  return __awaiter(this, void 0, void 0, function* () {
26
32
  return this._currentPromise
27
- .then(({ authJwt, refreshJwt }) => {
28
- if (!authJwt || this._isJwtExpired(authJwt)) {
33
+ .then((x) => {
34
+ var _a;
35
+ const authJwt = x === null || x === void 0 ? void 0 : x.authJwt;
36
+ const refreshJwt = x === null || x === void 0 ? void 0 : x.refreshJwt;
37
+ if ((!authJwt || this._isJwtExpired(authJwt)) && refreshJwt) {
29
38
  // If it does not have the JWT, tries to get it
30
39
  // If the JWT is expired, tries to refresh it
31
40
  this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {
@@ -37,13 +46,13 @@ class JwtAuthService {
37
46
  return updatedTokens;
38
47
  });
39
48
  }
40
- else if (!!this._error) {
41
- throw this._error;
49
+ else {
50
+ throw (_a = this._error) !== null && _a !== void 0 ? _a : 'Expired JWT refresh token in pure JwtAuthService incapable of relogging';
42
51
  }
43
52
  return this._currentPromise;
44
53
  })
45
- .then(({ authJwt }) => {
46
- return [new XHR_1.XHR.Header('Authorization', `Bearer ${authJwt}`)];
54
+ .then((x) => {
55
+ return (x === null || x === void 0 ? void 0 : x.authJwt) ? [new XHR_1.XHR.Header('Authorization', `Bearer ${x.authJwt}`)] : Promise.reject('Cannot provide auth: No JWT');
47
56
  });
48
57
  });
49
58
  }
@@ -51,8 +60,8 @@ class JwtAuthService {
51
60
  return __awaiter(this, void 0, void 0, function* () {
52
61
  // If I do not have a refresh JWT or the refresh JWT is expired,
53
62
  // I have to log in again
54
- if (!refreshJwt || this._isJwtExpired(refreshJwt)) {
55
- return this._loginAndGetTokens();
63
+ if (this._isJwtExpired(refreshJwt)) {
64
+ throw Error('Missing or expired refresh token: please log in again');
56
65
  }
57
66
  else {
58
67
  return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({
@@ -62,19 +71,6 @@ class JwtAuthService {
62
71
  }
63
72
  });
64
73
  }
65
- _loginAndGetTokens() {
66
- return __awaiter(this, void 0, void 0, function* () {
67
- return this.authApi
68
- .login(new LoginCredentials_1.LoginCredentials({
69
- username: this.username,
70
- password: this.password,
71
- }))
72
- .then((authResponse) => ({
73
- authJwt: authResponse.token,
74
- refreshJwt: authResponse.refreshToken,
75
- }));
76
- });
77
- }
78
74
  _isJwtExpired(jwt) {
79
75
  const parts = jwt.split('.');
80
76
  if (parts.length !== 3) {
@@ -1 +1 @@
1
- {"version":3,"file":"JwtAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAE3C,2EAAuE;AAEvE,oCAA8B;AAE9B,MAAa,cAAc;IAIzB,YAAoB,OAAmB,EAAU,QAAgB,EAAU,QAAgB;QAAvE,YAAO,GAAP,OAAO,CAAY;QAAU,aAAQ,GAAR,QAAQ,CAAQ;QAAU,aAAQ,GAAR,QAAQ,CAAQ;QAHnF,WAAM,GAAiB,IAAI,CAAA;QAC3B,oBAAe,GAAuD,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;IAEH,CAAC;IAEzF,cAAc;;YAClB,OAAO,IAAI,CAAC,eAAe;iBACxB,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAE;gBAChC,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE;oBAC3C,+CAA+C;oBAC/C,6CAA6C;oBAE7C,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,EAAE;wBAC7E,6BAA6B;wBAC7B,iCAAiC;wBACjC,IAAI,CAAC,aAAa,CAAC,OAAO,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A;IAEO,aAAa,CAAC,GAAW;QAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QAC5B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,OAAO,KAAK,CAAA;SACb;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;QAC5C,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IAC5E,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;AA/ED,wCA+EC","sourcesContent":["import { AuthService } from './AuthService'\nimport { XHR } from '../../icc-api/api/XHR'\nimport { IccAuthApi } from '../../icc-api'\nimport { LoginCredentials } from '../../icc-api/model/LoginCredentials'\nimport Header = XHR.Header\nimport { a2b } from '../utils'\n\nexport class JwtAuthService implements AuthService {\n private _error: Error | null = null\n private _currentPromise: Promise<{ authJwt?: string; refreshJwt?: string }> = Promise.resolve({})\n\n constructor(private authApi: IccAuthApi, private username: string, private password: string) {}\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then(({ authJwt, refreshJwt }) => {\n if (!authJwt || this._isJwtExpired(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 [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._isJwtExpired(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 return this.authApi\n .login(\n new LoginCredentials({\n username: this.username,\n password: this.password,\n })\n )\n .then((authResponse) => ({\n authJwt: authResponse.token,\n refreshJwt: authResponse.refreshToken,\n }))\n }\n\n private _isJwtExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return false\n }\n const payload = this._base64Decode(parts[1])\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime()\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":"JwtAuthService.js","sourceRoot":"","sources":["../../../icc-x-api/auth/JwtAuthService.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,+CAA2C;AAI3C,oCAA8B;AAI9B,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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,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;AAhFD,wCAgFC","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\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 getIcureTokens(): Promise<{ token: string; refreshToken: string } | undefined> {\n return this._currentPromise.then((x) => (x ? { token: x.authJwt, refreshToken: x.refreshJwt } : undefined) as any)\n }\n\n get refreshToken(): Promise<string | undefined> {\n return this._currentPromise.then((x) => x?.refreshJwt as any)\n }\n\n async getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then((x) => {\n const authJwt = x?.authJwt\n const refreshJwt = x?.refreshJwt\n\n if ((!authJwt || this._isJwtExpired(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((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 {\n throw this._error ?? 'Expired JWT refresh token in pure JwtAuthService incapable of relogging'\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 (this._isJwtExpired(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 private _isJwtExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return false\n }\n const payload = this._base64Decode(parts[1])\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime()\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,27 @@
1
+ import { AuthService } from './AuthService';
2
+ import { XHR } from '../../icc-api/api/XHR';
3
+ import { IccAuthApi } from '../../icc-api';
4
+ import Header = XHR.Header;
5
+ export declare class JwtBridgedAuthService implements AuthService {
6
+ private authApi;
7
+ private username;
8
+ private password;
9
+ private thirdPartyTokens;
10
+ private _error;
11
+ private _currentPromise;
12
+ constructor(authApi: IccAuthApi, username: string, password: string, thirdPartyTokens?: {
13
+ [thirdParty: string]: string;
14
+ });
15
+ get refreshToken(): Promise<string | undefined>;
16
+ getIcureTokens(): Promise<{
17
+ token: string;
18
+ refreshToken: string;
19
+ } | undefined>;
20
+ getAuthHeaders(): Promise<Array<Header>>;
21
+ private _refreshAuthJwt;
22
+ private _loginAndGetTokens;
23
+ private _isJwtExpired;
24
+ private _base64Decode;
25
+ invalidateHeader(error: Error): void;
26
+ isInErrorState(): boolean;
27
+ }
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.JwtBridgedAuthService = void 0;
13
+ const XHR_1 = require("../../icc-api/api/XHR");
14
+ const LoginCredentials_1 = require("../../icc-api/model/LoginCredentials");
15
+ const utils_1 = require("../utils");
16
+ var XHRError = XHR_1.XHR.XHRError;
17
+ class JwtBridgedAuthService {
18
+ constructor(authApi, username, password, thirdPartyTokens = {}) {
19
+ this.authApi = authApi;
20
+ this.username = username;
21
+ this.password = password;
22
+ this.thirdPartyTokens = thirdPartyTokens;
23
+ this._error = null;
24
+ this._currentPromise = Promise.resolve({});
25
+ }
26
+ get refreshToken() {
27
+ return this._currentPromise.then((x) => x.refreshJwt);
28
+ }
29
+ getIcureTokens() {
30
+ return this.getAuthHeaders().then(() => this._currentPromise.then(({ authJwt, refreshJwt }) => ({ token: authJwt, refreshToken: refreshJwt })));
31
+ }
32
+ getAuthHeaders() {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ return this._currentPromise
35
+ .then(({ authJwt, refreshJwt }) => {
36
+ if (!authJwt || this._isJwtExpired(authJwt)) {
37
+ // If it does not have the JWT, tries to get it
38
+ // If the JWT is expired, tries to refresh it
39
+ this._currentPromise = this._refreshAuthJwt(refreshJwt).then((updatedTokens) => {
40
+ // If here the token is null,
41
+ // it goes in a suspension status
42
+ if (!updatedTokens.authJwt) {
43
+ throw new Error('Your iCure back-end version does not support JWT authentication');
44
+ }
45
+ return updatedTokens;
46
+ });
47
+ }
48
+ else if (!!this._error) {
49
+ throw this._error;
50
+ }
51
+ return this._currentPromise;
52
+ })
53
+ .then(({ authJwt }) => {
54
+ return [new XHR_1.XHR.Header('Authorization', `Bearer ${authJwt}`)];
55
+ });
56
+ });
57
+ }
58
+ _refreshAuthJwt(refreshJwt) {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ // If I do not have a refresh JWT or the refresh JWT is expired,
61
+ // I have to log in again
62
+ if (!refreshJwt || this._isJwtExpired(refreshJwt)) {
63
+ return this._loginAndGetTokens();
64
+ }
65
+ else {
66
+ return this.authApi.refreshAuthenticationJWT(refreshJwt).then((refreshResponse) => ({
67
+ authJwt: refreshResponse.token,
68
+ refreshJwt: refreshJwt,
69
+ }));
70
+ }
71
+ });
72
+ }
73
+ _loginAndGetTokens() {
74
+ return __awaiter(this, void 0, void 0, function* () {
75
+ let authResponse;
76
+ let firstError;
77
+ if (this.username && this.password) {
78
+ try {
79
+ authResponse = yield this.authApi.login(new LoginCredentials_1.LoginCredentials({
80
+ username: this.username,
81
+ password: this.password,
82
+ }));
83
+ }
84
+ catch (e) {
85
+ firstError = e;
86
+ }
87
+ }
88
+ if (!authResponse) {
89
+ authResponse = yield Object.entries(this.thirdPartyTokens).reduce((acc, [thirdParty, token]) => __awaiter(this, void 0, void 0, function* () {
90
+ const prev = yield acc;
91
+ return (prev !== null && prev !== void 0 ? prev : (token
92
+ ? this.authApi.loginWithThirdPartyToken(thirdParty, token).catch((e) => {
93
+ if (!firstError) {
94
+ firstError = e;
95
+ }
96
+ return Promise.resolve();
97
+ })
98
+ : undefined));
99
+ }), Promise.resolve());
100
+ }
101
+ if (!authResponse) {
102
+ if (firstError)
103
+ throw firstError;
104
+ throw new XHRError('', 'Unknown error', 401, 'Unauthorized', new Headers());
105
+ }
106
+ return {
107
+ authJwt: authResponse.token,
108
+ refreshJwt: authResponse.refreshToken,
109
+ };
110
+ });
111
+ }
112
+ _isJwtExpired(jwt) {
113
+ const parts = jwt.split('.');
114
+ if (parts.length !== 3) {
115
+ return false;
116
+ }
117
+ const payload = this._base64Decode(parts[1]);
118
+ return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime();
119
+ }
120
+ _base64Decode(encodedString) {
121
+ return JSON.parse((0, utils_1.a2b)(encodedString));
122
+ }
123
+ invalidateHeader(error) {
124
+ this._error = error;
125
+ }
126
+ isInErrorState() {
127
+ return !!this._error;
128
+ }
129
+ }
130
+ exports.JwtBridgedAuthService = JwtBridgedAuthService;
131
+ //# sourceMappingURL=JwtBridgedAuthService.js.map
@@ -0,0 +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,MAAa,qBAAqB;IAIhC,YACU,OAAmB,EACnB,QAAgB,EAChB,QAAgB,EAChB,mBAAqD,EAAE;QAHvD,YAAO,GAAP,OAAO,CAAY;QACnB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,aAAQ,GAAR,QAAQ,CAAQ;QAChB,qBAAgB,GAAhB,gBAAgB,CAAuC;QAPzD,WAAM,GAAiB,IAAI,CAAA;QAC3B,oBAAe,GAAuD,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;IAO9F,CAAC;IAEJ,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,EAAE,UAAU,EAAE,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,IAAI,CAAC,YAAY,EAAE;gBACjB,IAAI,UAAU;oBAAE,MAAM,UAAU,CAAA;gBAChC,MAAM,IAAI,QAAQ,CAAC,EAAE,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,EAAE,IAAI,OAAO,EAAE,CAAC,CAAA;aAC5E;YAED,OAAO;gBACL,OAAO,EAAE,YAAY,CAAC,KAAK;gBAC3B,UAAU,EAAE,YAAY,CAAC,YAAY;aACtC,CAAA;QACH,CAAC;KAAA;IAEO,aAAa,CAAC,GAAW;QAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;QAC5B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;YACtB,OAAO,KAAK,CAAA;SACb;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;QAC5C,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IAC5E,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;AAxHD,sDAwHC","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\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,\n private password: string,\n private thirdPartyTokens: { [thirdParty: string]: string } = {}\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 getAuthHeaders(): Promise<Array<Header>> {\n return this._currentPromise\n .then(({ authJwt, refreshJwt }) => {\n if (!authJwt || this._isJwtExpired(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 [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._isJwtExpired(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 _isJwtExpired(jwt: string): boolean {\n const parts = jwt.split('.')\n if (parts.length !== 3) {\n return false\n }\n const payload = this._base64Decode(parts[1])\n return !('exp' in payload) || payload['exp'] * 1000 < new Date().getTime()\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"]}
@@ -149,7 +149,15 @@ class AESUtils {
149
149
  return new Promise((resolve, reject) => {
150
150
  const extractable = true;
151
151
  const keyUsages = ['decrypt', 'encrypt'];
152
- return this.crypto.subtle.importKey(format, aesKey, this.aesKeyGenParams, extractable, keyUsages).then(resolve, reject);
152
+ return this.crypto.subtle
153
+ .importKey(format, aesKey, this.aesKeyGenParams, extractable, keyUsages)
154
+ .catch((err) => {
155
+ if (format == 'raw' && (aesKey instanceof ArrayBuffer || ArrayBuffer.isView(aesKey))) {
156
+ console.warn(`Import of key ${(0, utils_1.ua2hex)(aesKey)} failed`);
157
+ }
158
+ throw err;
159
+ })
160
+ .then(resolve, reject);
153
161
  });
154
162
  }
155
163
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AES.js","sourceRoot":"","sources":["../../../icc-x-api/crypto/AES.ts"],"names":[],"mappings":";;;;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AC,CAAA;QACrF,CAAC,CAAC,CAAA;IACJ,CAAC;IAED;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,MAAqB,EAAE,MAA6C;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,CAAC,SAAS,CAAC,MAAa,EAAE,MAAa,EAAE,IAAI,CAAC,eAAe,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;QACvI,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AAxLD,4BAwLC;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('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.importKey(format as any, aesKey as any, this.aesKeyGenParams, extractable, keyUsages).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":";;;;;;;;;;;;AAA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F,CAAC,CAAC,CAAA;IACJ,CAAC;IAED;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,MAAqB,EAAE,MAA6C;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,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('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,7 +1,9 @@
1
1
  import { KeyPair } from './RSA';
2
- import { DataOwnerTypeEnum, DataOwnerWithType, IccDataOwnerXApi } from '../icc-data-owner-x-api';
2
+ import { IccDataOwnerXApi } from '../icc-data-owner-x-api';
3
3
  import { CryptoPrimitives } from './CryptoPrimitives';
4
4
  import { IccDeviceApi, IccHcpartyApi, IccPatientApi } from '../../icc-api';
5
+ import { CryptoActorStubWithType } from '../../icc-api/model/CryptoActorStub';
6
+ import { DataOwnerTypeEnum } from '../../icc-api/model/DataOwnerTypeEnum';
5
7
  /**
6
8
  * @internal This class is meant only for internal use and may be changed without notice.
7
9
  * Functions to create and get exchange keys.
@@ -27,7 +29,7 @@ export declare class BaseExchangeKeysManager {
27
29
  createOrUpdateEncryptedExchangeKeyTo(delegateId: string, delegatorMainKeyPair: KeyPair<CryptoKey>, additionalPublicKeys: {
28
30
  [keyFingerprint: string]: CryptoKey;
29
31
  }): Promise<{
30
- updatedDelegator: DataOwnerWithType;
32
+ updatedDelegator: CryptoActorStubWithType;
31
33
  key: CryptoKey;
32
34
  }>;
33
35
  /**
@@ -11,7 +11,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.BaseExchangeKeysManager = void 0;
13
13
  const utils_1 = require("../utils");
14
- const icc_data_owner_x_api_1 = require("../icc-data-owner-x-api");
14
+ const CryptoActorStub_1 = require("../../icc-api/model/CryptoActorStub");
15
+ const DataOwnerTypeEnum_1 = require("../../icc-api/model/DataOwnerTypeEnum");
15
16
  /**
16
17
  * @internal This class is meant only for internal use and may be changed without notice.
17
18
  * Functions to create and get exchange keys.
@@ -40,16 +41,16 @@ class BaseExchangeKeysManager {
40
41
  const delegatorId = yield this.dataOwnerApi.getCurrentDataOwnerId();
41
42
  return yield (0, utils_1.notConcurrent)(this.generateKeyConcurrencyMap, delegatorId, () => __awaiter(this, void 0, void 0, function* () {
42
43
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
43
- const delegator = yield this.dataOwnerApi.getCurrentDataOwner();
44
- const delegate = delegatorId === delegateId ? delegator : yield this.dataOwnerApi.getDataOwner(delegateId);
44
+ const delegator = CryptoActorStub_1.CryptoActorStubWithType.fromDataOwner(yield this.dataOwnerApi.getCurrentDataOwner());
45
+ const delegate = delegatorId === delegateId ? delegator : yield this.dataOwnerApi.getCryptoActorStub(delegateId);
45
46
  const mainDelegatorKeyPairPubHex = (0, utils_1.ua2hex)(yield this.primitives.RSA.exportKey(delegatorMainKeyPair.publicKey, 'spki'));
46
47
  let exchangeKey = undefined;
47
- const existingExchangeKey = (_d = (_c = (_b = (_a = delegator.dataOwner.aesExchangeKeys) === null || _a === void 0 ? void 0 : _a[mainDelegatorKeyPairPubHex]) === null || _b === void 0 ? void 0 : _b[delegateId]) === null || _c === void 0 ? void 0 : _c[mainDelegatorKeyPairPubHex.slice(-32)]) !== null && _d !== void 0 ? _d : (mainDelegatorKeyPairPubHex === delegator.dataOwner.publicKey ? (_f = (_e = delegator.dataOwner.hcPartyKeys) === null || _e === void 0 ? void 0 : _e[delegateId]) === null || _f === void 0 ? void 0 : _f[0] : undefined);
48
+ const existingExchangeKey = (_d = (_c = (_b = (_a = delegator.stub.aesExchangeKeys) === null || _a === void 0 ? void 0 : _a[mainDelegatorKeyPairPubHex]) === null || _b === void 0 ? void 0 : _b[delegateId]) === null || _c === void 0 ? void 0 : _c[mainDelegatorKeyPairPubHex.slice(-32)]) !== null && _d !== void 0 ? _d : (mainDelegatorKeyPairPubHex === delegator.stub.publicKey ? (_f = (_e = delegator.stub.hcPartyKeys) === null || _e === void 0 ? void 0 : _e[delegateId]) === null || _f === void 0 ? void 0 : _f[0] : undefined);
48
49
  if (existingExchangeKey) {
49
50
  exchangeKey = yield this.tryDecryptExchangeKeyWith(existingExchangeKey, delegatorMainKeyPair, undefined);
50
51
  if (!exchangeKey)
51
52
  throw new Error(`Failed to decrypt existing exchange key for update of ${mainDelegatorKeyPairPubHex.slice(-32)}@${delegatorId}->${delegateId}`);
52
- const existingAesExchangeKey = (_h = (_g = delegator.dataOwner.aesExchangeKeys) === null || _g === void 0 ? void 0 : _g[mainDelegatorKeyPairPubHex]) === null || _h === void 0 ? void 0 : _h[delegateId];
53
+ const existingAesExchangeKey = (_h = (_g = delegator.stub.aesExchangeKeys) === null || _g === void 0 ? void 0 : _g[mainDelegatorKeyPairPubHex]) === null || _h === void 0 ? void 0 : _h[delegateId];
53
54
  if (existingAesExchangeKey) {
54
55
  const existingPublicKeysSet = new Set(existingExchangeKey);
55
56
  if (Object.keys(additionalPublicKeys).every((fp) => existingPublicKeysSet.has(fp)))
@@ -61,13 +62,13 @@ class BaseExchangeKeysManager {
61
62
  }
62
63
  const allPublicKeys = Object.assign(Object.assign({}, additionalPublicKeys), { [mainDelegatorKeyPairPubHex.slice(-32)]: delegatorMainKeyPair.publicKey });
63
64
  const encryptedKeyInfo = yield this.encryptExchangeKey(exchangeKey, allPublicKeys);
64
- const updatedDataOwner = Object.assign(Object.assign({}, delegator.dataOwner), { aesExchangeKeys: yield this.updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyInfo.encryptedExchangeKey), publicKey: (_j = delegator.dataOwner.publicKey) !== null && _j !== void 0 ? _j : mainDelegatorKeyPairPubHex });
65
- if (delegator.dataOwner.publicKey === mainDelegatorKeyPairPubHex) {
66
- updatedDataOwner.hcPartyKeys = this.updateLegacyExchangeKeys(delegator, delegate, encryptedKeyInfo.encryptedExchangeKey);
65
+ const updatedStub = Object.assign(Object.assign({}, delegator.stub), { aesExchangeKeys: yield this.updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyInfo.encryptedExchangeKey), publicKey: (_j = delegator.stub.publicKey) !== null && _j !== void 0 ? _j : mainDelegatorKeyPairPubHex });
66
+ if (delegator.stub.publicKey === mainDelegatorKeyPairPubHex) {
67
+ updatedStub.hcPartyKeys = this.updateLegacyExchangeKeys(delegator, delegate, encryptedKeyInfo.encryptedExchangeKey);
67
68
  }
68
- const updatedDelegator = yield this.dataOwnerApi.updateDataOwner({
69
+ const updatedDelegator = yield this.dataOwnerApi.modifyCryptoActorStub({
69
70
  type: delegator.type,
70
- dataOwner: updatedDataOwner,
71
+ stub: updatedStub,
71
72
  });
72
73
  return {
73
74
  key: encryptedKeyInfo.exchangeKey,
@@ -101,8 +102,8 @@ class BaseExchangeKeysManager {
101
102
  getEncryptedExchangeKeysFor(delegatorId, delegateId) {
102
103
  var _a, _b, _c;
103
104
  return __awaiter(this, void 0, void 0, function* () {
104
- const delegator = yield this.dataOwnerApi.getDataOwner(delegatorId);
105
- const res = Object.values((_a = delegator.dataOwner.aesExchangeKeys) !== null && _a !== void 0 ? _a : {}).flatMap((delegateToKey) => {
105
+ const delegator = yield this.dataOwnerApi.getCryptoActorStub(delegatorId);
106
+ const res = Object.values((_a = delegator.stub.aesExchangeKeys) !== null && _a !== void 0 ? _a : {}).flatMap((delegateToKey) => {
106
107
  const encryptedKeyForDelegate = delegateToKey[delegateId];
107
108
  if (encryptedKeyForDelegate) {
108
109
  return [encryptedKeyForDelegate];
@@ -111,7 +112,7 @@ class BaseExchangeKeysManager {
111
112
  return [];
112
113
  }
113
114
  });
114
- const legacyDelegation = (_c = (_b = delegator.dataOwner.hcPartyKeys) === null || _b === void 0 ? void 0 : _b[delegateId]) === null || _c === void 0 ? void 0 : _c[1];
115
+ const legacyDelegation = (_c = (_b = delegator.stub.hcPartyKeys) === null || _b === void 0 ? void 0 : _b[delegateId]) === null || _c === void 0 ? void 0 : _c[1];
115
116
  if (legacyDelegation)
116
117
  res.push({ '': legacyDelegation });
117
118
  return res;
@@ -128,25 +129,25 @@ class BaseExchangeKeysManager {
128
129
  if (otherOwnerTypes.length === 0)
129
130
  throw new Error('otherOwnerTypes must not be empty!');
130
131
  const keysToOwner = yield Promise.all([
131
- otherOwnerTypes.find((x) => x === icc_data_owner_x_api_1.DataOwnerTypeEnum.Hcp)
132
+ otherOwnerTypes.find((x) => x === DataOwnerTypeEnum_1.DataOwnerTypeEnum.Hcp)
132
133
  ? this.hcpartyBaseApi.getAesExchangeKeysForDelegate(dataOwnerId).catch(() => { })
133
134
  : Promise.resolve({}),
134
- otherOwnerTypes.find((x) => x === icc_data_owner_x_api_1.DataOwnerTypeEnum.Patient)
135
+ otherOwnerTypes.find((x) => x === DataOwnerTypeEnum_1.DataOwnerTypeEnum.Patient)
135
136
  ? this.patientBaseApi.getPatientAesExchangeKeysForDelegate(dataOwnerId).catch(() => { })
136
137
  : Promise.resolve({}),
137
- otherOwnerTypes.find((x) => x === icc_data_owner_x_api_1.DataOwnerTypeEnum.Device)
138
+ otherOwnerTypes.find((x) => x === DataOwnerTypeEnum_1.DataOwnerTypeEnum.Device)
138
139
  ? this.deviceBaseApi.getDeviceAesExchangeKeysForDelegate(dataOwnerId).catch(() => { })
139
140
  : Promise.resolve({}),
140
141
  ]).then(([a, b, c]) => (Object.assign(Object.assign(Object.assign({}, a), b), c)));
141
- const dataOwner = yield this.dataOwnerApi.getDataOwner(dataOwnerId);
142
- const allOwnerKeys = yield this.combineLegacyHcpKeysWithAesExchangeKeys(dataOwner.dataOwner, undefined);
142
+ const dataOwner = yield this.dataOwnerApi.getCryptoActorStub(dataOwnerId);
143
+ const allOwnerKeys = yield this.combineLegacyHcpKeysWithAesExchangeKeys(dataOwner.stub, undefined);
143
144
  const filteredDelegates = new Set(yield Array.from(new Set(Object.values(allOwnerKeys).flatMap((x) => Object.keys(x)))).reduce((acc, ownerId) => __awaiter(this, void 0, void 0, function* () {
144
145
  const awaitedAcc = yield acc;
145
146
  if (ownerId === dataOwnerId) {
146
147
  return [...awaitedAcc, ownerId];
147
148
  }
148
149
  else {
149
- const dataOwnerType = (yield this.dataOwnerApi.getDataOwner(ownerId)).type;
150
+ const dataOwnerType = (yield this.dataOwnerApi.getCryptoActorStub(ownerId)).type;
150
151
  if (otherOwnerTypes.some((x) => x === dataOwnerType)) {
151
152
  return [...awaitedAcc, ownerId];
152
153
  }
@@ -189,10 +190,10 @@ class BaseExchangeKeysManager {
189
190
  extendForGiveAccessBackTo(delegatorId, delegateId, newPublicKeyFp, newPublicKey, decryptionKeyPairsByFingerprint) {
190
191
  return __awaiter(this, void 0, void 0, function* () {
191
192
  yield (0, utils_1.notConcurrent)(this.generateKeyConcurrencyMap, delegatorId, () => __awaiter(this, void 0, void 0, function* () {
192
- const delegator = yield this.dataOwnerApi.getDataOwner(delegatorId);
193
- const delegate = yield this.dataOwnerApi.getDataOwner(delegateId);
193
+ const delegator = yield this.dataOwnerApi.getCryptoActorStub(delegatorId);
194
+ const delegate = yield this.dataOwnerApi.getCryptoActorStub(delegateId);
194
195
  let didUpdateSomeKey = false;
195
- const combinedKeys = yield this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.dataOwner, delegate.dataOwner);
196
+ const combinedKeys = yield this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub);
196
197
  const updatedExchangeKeys = {};
197
198
  const newEncryptionKeys = { [newPublicKeyFp]: newPublicKey };
198
199
  for (const [currDelegatorKey, currDelegatesToKeys] of Object.entries(combinedKeys)) {
@@ -215,9 +216,9 @@ class BaseExchangeKeysManager {
215
216
  updatedExchangeKeys[currDelegatorKey] = updatedDelegatesToKeys;
216
217
  }
217
218
  if (didUpdateSomeKey) {
218
- yield this.dataOwnerApi.updateDataOwner({
219
+ yield this.dataOwnerApi.modifyCryptoActorStub({
219
220
  type: delegator.type,
220
- dataOwner: Object.assign(Object.assign({}, delegator.dataOwner), { aesExchangeKeys: updatedExchangeKeys }),
221
+ stub: Object.assign(Object.assign({}, delegator.stub), { aesExchangeKeys: updatedExchangeKeys }),
221
222
  });
222
223
  }
223
224
  }));
@@ -297,19 +298,19 @@ class BaseExchangeKeysManager {
297
298
  }
298
299
  updateLegacyExchangeKeys(delegator, delegate, encryptedKeyMap) {
299
300
  var _a;
300
- const legacyEncryptedKeyDelegator = delegator.dataOwner.publicKey ? encryptedKeyMap[delegator.dataOwner.publicKey] : undefined;
301
- const legacyEncryptedKeyDelegate = delegate.dataOwner.publicKey ? encryptedKeyMap[delegate.dataOwner.publicKey] : undefined;
301
+ const legacyEncryptedKeyDelegator = delegator.stub.publicKey ? encryptedKeyMap[delegator.stub.publicKey] : undefined;
302
+ const legacyEncryptedKeyDelegate = delegate.stub.publicKey ? encryptedKeyMap[delegate.stub.publicKey] : undefined;
302
303
  if (legacyEncryptedKeyDelegator && legacyEncryptedKeyDelegate) {
303
- return Object.assign(Object.assign({}, ((_a = delegator.dataOwner.hcPartyKeys) !== null && _a !== void 0 ? _a : {})), { [delegate.dataOwner.id]: [legacyEncryptedKeyDelegator, legacyEncryptedKeyDelegate] });
304
+ return Object.assign(Object.assign({}, ((_a = delegator.stub.hcPartyKeys) !== null && _a !== void 0 ? _a : {})), { [delegate.stub.id]: [legacyEncryptedKeyDelegator, legacyEncryptedKeyDelegate] });
304
305
  }
305
306
  else
306
- return delegator.dataOwner.hcPartyKeys;
307
+ return delegator.stub.hcPartyKeys;
307
308
  }
308
309
  updateExchangeKeys(delegator, delegate, mainDelegatorKeyPairPubHex, encryptedKeyMap) {
309
310
  var _a, _b, _c;
310
311
  return __awaiter(this, void 0, void 0, function* () {
311
- const combinedAesExchangeKeys = yield this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.dataOwner, delegate.dataOwner);
312
- return this.fixAesExchangeKeyEntriesToFingerprints(Object.assign(Object.assign({}, combinedAesExchangeKeys), { [mainDelegatorKeyPairPubHex]: Object.assign(Object.assign({}, ((_a = combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]) !== null && _a !== void 0 ? _a : {})), { [delegate.dataOwner.id]: Object.assign(Object.assign({}, ((_c = (_b = combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]) === null || _b === void 0 ? void 0 : _b[delegate.dataOwner.id]) !== null && _c !== void 0 ? _c : {})), encryptedKeyMap) }) }));
312
+ const combinedAesExchangeKeys = yield this.combineLegacyHcpKeysWithAesExchangeKeys(delegator.stub, delegate.stub);
313
+ return this.fixAesExchangeKeyEntriesToFingerprints(Object.assign(Object.assign({}, combinedAesExchangeKeys), { [mainDelegatorKeyPairPubHex]: Object.assign(Object.assign({}, ((_a = combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]) !== null && _a !== void 0 ? _a : {})), { [delegate.stub.id]: Object.assign(Object.assign({}, ((_c = (_b = combinedAesExchangeKeys[mainDelegatorKeyPairPubHex]) === null || _b === void 0 ? void 0 : _b[delegate.stub.id]) !== null && _c !== void 0 ? _c : {})), encryptedKeyMap) }) }));
313
314
  });
314
315
  }
315
316
  // Copy all legacy hcp exchange keys into the new aes exchange keys
@@ -327,7 +328,7 @@ class BaseExchangeKeysManager {
327
328
  const counterPartsById = [
328
329
  owner,
329
330
  ...(delegate ? [delegate] : []),
330
- ...(yield Promise.all(unknownDataOwnerCounterPartIds.map((cpid) => __awaiter(this, void 0, void 0, function* () { return (yield this.dataOwnerApi.getDataOwner(cpid)).dataOwner; })))),
331
+ ...(yield Promise.all(unknownDataOwnerCounterPartIds.map((cpid) => __awaiter(this, void 0, void 0, function* () { return (yield this.dataOwnerApi.getCryptoActorStub(cpid)).stub; })))),
331
332
  ].reduce((acc, dataOwner) => {
332
333
  acc[dataOwner.id] = dataOwner;
333
334
  return acc;