@twin.org/api-auth-entity-storage-service 0.0.3-next.9 → 0.9.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +2 -2
  2. package/dist/es/entities/authenticationAuditEntry.js +101 -0
  3. package/dist/es/entities/authenticationAuditEntry.js.map +1 -0
  4. package/dist/es/entities/authenticationRateEntry.js +37 -0
  5. package/dist/es/entities/authenticationRateEntry.js.map +1 -0
  6. package/dist/es/entities/authenticationUser.js +17 -1
  7. package/dist/es/entities/authenticationUser.js.map +1 -1
  8. package/dist/es/index.js +11 -1
  9. package/dist/es/index.js.map +1 -1
  10. package/dist/es/models/IAuthHeaderProcessorConstructorOptions.js.map +1 -1
  11. package/dist/es/models/IEntityStorageAuthenticationAdminServiceConstructorOptions.js.map +1 -1
  12. package/dist/es/models/IEntityStorageAuthenticationAuditServiceConfig.js +4 -0
  13. package/dist/es/models/IEntityStorageAuthenticationAuditServiceConfig.js.map +1 -0
  14. package/dist/es/models/IEntityStorageAuthenticationAuditServiceConstructorOptions.js +2 -0
  15. package/dist/es/models/IEntityStorageAuthenticationAuditServiceConstructorOptions.js.map +1 -0
  16. package/dist/es/models/IEntityStorageAuthenticationRateServiceConfig.js +2 -0
  17. package/dist/es/models/IEntityStorageAuthenticationRateServiceConfig.js.map +1 -0
  18. package/dist/es/models/IEntityStorageAuthenticationRateServiceConstructorOptions.js +2 -0
  19. package/dist/es/models/IEntityStorageAuthenticationRateServiceConstructorOptions.js.map +1 -0
  20. package/dist/es/models/IEntityStorageAuthenticationServiceConfig.js +0 -2
  21. package/dist/es/models/IEntityStorageAuthenticationServiceConfig.js.map +1 -1
  22. package/dist/es/models/IEntityStorageAuthenticationServiceConstructorOptions.js.map +1 -1
  23. package/dist/es/processors/authHeaderProcessor.js +68 -11
  24. package/dist/es/processors/authHeaderProcessor.js.map +1 -1
  25. package/dist/es/restEntryPoints.js +17 -0
  26. package/dist/es/restEntryPoints.js.map +1 -1
  27. package/dist/es/routes/entityStorageAuthenticationAdminRoutes.js +362 -0
  28. package/dist/es/routes/entityStorageAuthenticationAdminRoutes.js.map +1 -0
  29. package/dist/es/routes/entityStorageAuthenticationAuditRoutes.js +174 -0
  30. package/dist/es/routes/entityStorageAuthenticationAuditRoutes.js.map +1 -0
  31. package/dist/es/routes/entityStorageAuthenticationRoutes.js +18 -19
  32. package/dist/es/routes/entityStorageAuthenticationRoutes.js.map +1 -1
  33. package/dist/es/schema.js +4 -0
  34. package/dist/es/schema.js.map +1 -1
  35. package/dist/es/services/entityStorageAuthenticationAdminService.js +164 -58
  36. package/dist/es/services/entityStorageAuthenticationAdminService.js.map +1 -1
  37. package/dist/es/services/entityStorageAuthenticationAuditService.js +179 -0
  38. package/dist/es/services/entityStorageAuthenticationAuditService.js.map +1 -0
  39. package/dist/es/services/entityStorageAuthenticationRateService.js +213 -0
  40. package/dist/es/services/entityStorageAuthenticationRateService.js.map +1 -0
  41. package/dist/es/services/entityStorageAuthenticationService.js +200 -19
  42. package/dist/es/services/entityStorageAuthenticationService.js.map +1 -1
  43. package/dist/es/utils/passwordHelper.js +45 -16
  44. package/dist/es/utils/passwordHelper.js.map +1 -1
  45. package/dist/es/utils/tokenHelper.js +50 -10
  46. package/dist/es/utils/tokenHelper.js.map +1 -1
  47. package/dist/types/entities/authenticationAuditEntry.d.ts +49 -0
  48. package/dist/types/entities/authenticationRateEntry.d.ts +17 -0
  49. package/dist/types/entities/authenticationUser.d.ts +8 -0
  50. package/dist/types/index.d.ts +11 -1
  51. package/dist/types/models/IAuthHeaderProcessorConstructorOptions.d.ts +10 -0
  52. package/dist/types/models/IEntityStorageAuthenticationAdminServiceConstructorOptions.d.ts +5 -0
  53. package/dist/types/models/IEntityStorageAuthenticationAuditServiceConfig.d.ts +9 -0
  54. package/dist/types/models/IEntityStorageAuthenticationAuditServiceConstructorOptions.d.ts +15 -0
  55. package/dist/types/models/IEntityStorageAuthenticationRateServiceConfig.d.ts +10 -0
  56. package/dist/types/models/IEntityStorageAuthenticationRateServiceConstructorOptions.d.ts +25 -0
  57. package/dist/types/models/IEntityStorageAuthenticationServiceConfig.d.ts +22 -1
  58. package/dist/types/models/IEntityStorageAuthenticationServiceConstructorOptions.d.ts +13 -3
  59. package/dist/types/processors/authHeaderProcessor.d.ts +4 -2
  60. package/dist/types/restEntryPoints.d.ts +3 -0
  61. package/dist/types/routes/entityStorageAuthenticationAdminRoutes.d.ts +61 -0
  62. package/dist/types/routes/entityStorageAuthenticationAuditRoutes.d.ts +29 -0
  63. package/dist/types/services/entityStorageAuthenticationAdminService.d.ts +26 -9
  64. package/dist/types/services/entityStorageAuthenticationAuditService.d.ts +53 -0
  65. package/dist/types/services/entityStorageAuthenticationRateService.d.ts +60 -0
  66. package/dist/types/services/entityStorageAuthenticationService.d.ts +10 -5
  67. package/dist/types/utils/passwordHelper.d.ts +13 -5
  68. package/dist/types/utils/tokenHelper.d.ts +10 -4
  69. package/docs/changelog.md +845 -85
  70. package/docs/examples.md +178 -1
  71. package/docs/reference/classes/AuthHeaderProcessor.md +15 -11
  72. package/docs/reference/classes/AuthenticationAuditEntry.md +101 -0
  73. package/docs/reference/classes/AuthenticationRateEntry.md +37 -0
  74. package/docs/reference/classes/AuthenticationUser.md +21 -5
  75. package/docs/reference/classes/EntityStorageAuthenticationAdminService.md +80 -20
  76. package/docs/reference/classes/EntityStorageAuthenticationAuditService.md +157 -0
  77. package/docs/reference/classes/EntityStorageAuthenticationRateService.md +227 -0
  78. package/docs/reference/classes/EntityStorageAuthenticationService.md +37 -17
  79. package/docs/reference/classes/PasswordHelper.md +37 -12
  80. package/docs/reference/classes/TokenHelper.md +49 -13
  81. package/docs/reference/functions/authenticationAdminCreateUser.md +31 -0
  82. package/docs/reference/functions/authenticationAdminGetUser.md +31 -0
  83. package/docs/reference/functions/authenticationAdminGetUserByIdentity.md +31 -0
  84. package/docs/reference/functions/authenticationAdminRemoveUser.md +31 -0
  85. package/docs/reference/functions/authenticationAdminUpdateUser.md +31 -0
  86. package/docs/reference/functions/authenticationAdminUpdateUserPassword.md +31 -0
  87. package/docs/reference/functions/authenticationAuditCreate.md +31 -0
  88. package/docs/reference/functions/authenticationAuditQuery.md +31 -0
  89. package/docs/reference/functions/generateRestRoutesAuthenticationAdmin.md +25 -0
  90. package/docs/reference/functions/generateRestRoutesAuthenticationAudit.md +25 -0
  91. package/docs/reference/index.md +20 -0
  92. package/docs/reference/interfaces/IAuthHeaderProcessorConfig.md +4 -4
  93. package/docs/reference/interfaces/IAuthHeaderProcessorConstructorOptions.md +32 -4
  94. package/docs/reference/interfaces/IEntityStorageAuthenticationAdminServiceConfig.md +2 -2
  95. package/docs/reference/interfaces/IEntityStorageAuthenticationAdminServiceConstructorOptions.md +18 -4
  96. package/docs/reference/interfaces/IEntityStorageAuthenticationAuditServiceConfig.md +11 -0
  97. package/docs/reference/interfaces/IEntityStorageAuthenticationAuditServiceConstructorOptions.md +25 -0
  98. package/docs/reference/interfaces/IEntityStorageAuthenticationRateServiceConfig.md +17 -0
  99. package/docs/reference/interfaces/IEntityStorageAuthenticationRateServiceConstructorOptions.md +53 -0
  100. package/docs/reference/interfaces/IEntityStorageAuthenticationServiceConfig.md +61 -5
  101. package/docs/reference/interfaces/IEntityStorageAuthenticationServiceConstructorOptions.md +38 -10
  102. package/docs/reference/variables/restEntryPoints.md +2 -0
  103. package/docs/reference/variables/tagsAuthenticationAdmin.md +5 -0
  104. package/docs/reference/variables/tagsAuthenticationAudit.md +5 -0
  105. package/locales/en.json +23 -6
  106. package/package.json +17 -16
@@ -1,5 +1,7 @@
1
+ import { AuthAuditEvent } from "@twin.org/api-auth-entity-storage-models";
1
2
  import { ContextIdHelper, ContextIdKeys, ContextIdStore } from "@twin.org/context";
2
- import { ComponentFactory, Converter, GeneralError, Guards, Is, UnauthorizedError } from "@twin.org/core";
3
+ import { Coerce, ComponentFactory, Converter, GeneralError, Guards, Is, NotFoundError, UnauthorizedError } from "@twin.org/core";
4
+ import { PasswordGenerator, PasswordValidator } from "@twin.org/crypto";
3
5
  import { EntityStorageConnectorFactory } from "@twin.org/entity-storage-models";
4
6
  import { VaultConnectorFactory } from "@twin.org/vault-models";
5
7
  import { PasswordHelper } from "../utils/passwordHelper.js";
@@ -18,10 +20,45 @@ export class EntityStorageAuthenticationService {
18
20
  */
19
21
  static _DEFAULT_TTL_MINUTES = 60;
20
22
  /**
21
- * The user admin service.
23
+ * Default maximum login attempts in a rate window.
22
24
  * @internal
23
25
  */
24
- _authenticationAdminService;
26
+ static _DEFAULT_LOGIN_RATE_MAX_ATTEMPTS = 5;
27
+ /**
28
+ * Default login rate window in minutes.
29
+ * @internal
30
+ */
31
+ static _DEFAULT_LOGIN_RATE_WINDOW_MINUTES = 15;
32
+ /**
33
+ * Default maximum password change attempts in a rate window.
34
+ * @internal
35
+ */
36
+ static _DEFAULT_PASSWORD_CHANGE_RATE_MAX_ATTEMPTS = 5;
37
+ /**
38
+ * Default password change rate window in minutes.
39
+ * @internal
40
+ */
41
+ static _DEFAULT_PASSWORD_CHANGE_RATE_WINDOW_MINUTES = 15;
42
+ /**
43
+ * Default maximum token refresh attempts in a rate window.
44
+ * @internal
45
+ */
46
+ static _DEFAULT_TOKEN_REFRESH_RATE_MAX_ATTEMPTS = 30;
47
+ /**
48
+ * Default token refresh rate window in minutes.
49
+ * @internal
50
+ */
51
+ static _DEFAULT_TOKEN_REFRESH_RATE_WINDOW_MINUTES = 60;
52
+ /**
53
+ * The audit service.
54
+ * @internal
55
+ */
56
+ _authenticationAuditService;
57
+ /**
58
+ * The rate service.
59
+ * @internal
60
+ */
61
+ _authenticationRateService;
25
62
  /**
26
63
  * The entity storage for users.
27
64
  * @internal
@@ -42,6 +79,31 @@ export class EntityStorageAuthenticationService {
42
79
  * @internal
43
80
  */
44
81
  _defaultTtlMinutes;
82
+ /**
83
+ * The minimum password length for validation.
84
+ * @internal
85
+ */
86
+ _minPasswordLength;
87
+ /**
88
+ * Rate limit configuration for login failures.
89
+ * @internal
90
+ */
91
+ _loginRateLimit;
92
+ /**
93
+ * Rate limit configuration for password changes.
94
+ * @internal
95
+ */
96
+ _passwordChangeRateLimit;
97
+ /**
98
+ * Rate limit configuration for token refresh.
99
+ * @internal
100
+ */
101
+ _tokenRefreshRateLimit;
102
+ /**
103
+ * The component to retrieve tenant information.
104
+ * @internal
105
+ */
106
+ _tenantAdminComponent;
45
107
  /**
46
108
  * The node identity.
47
109
  * @internal
@@ -54,10 +116,31 @@ export class EntityStorageAuthenticationService {
54
116
  constructor(options) {
55
117
  this._userEntityStorage = EntityStorageConnectorFactory.get(options?.userEntityStorageType ?? "authentication-user");
56
118
  this._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
57
- this._authenticationAdminService = ComponentFactory.get(options?.authenticationAdminServiceType ?? "authentication-admin");
119
+ this._authenticationAuditService = ComponentFactory.getIfExists(options?.authenticationAuditServiceType ?? "authentication-audit");
120
+ this._authenticationRateService = ComponentFactory.get(options?.authenticationRateServiceType ?? "authentication-rate");
121
+ this._tenantAdminComponent = ComponentFactory.getIfExists(options?.tenantAdminComponentType ?? "tenant-admin");
58
122
  this._signingKeyName = options?.config?.signingKeyName ?? "auth-signing";
59
123
  this._defaultTtlMinutes =
60
124
  options?.config?.defaultTtlMinutes ?? EntityStorageAuthenticationService._DEFAULT_TTL_MINUTES;
125
+ this._minPasswordLength = options?.config?.minPasswordLength;
126
+ this._loginRateLimit = {
127
+ maxAttempts: options?.config?.loginRateLimit?.maxAttempts ??
128
+ EntityStorageAuthenticationService._DEFAULT_LOGIN_RATE_MAX_ATTEMPTS,
129
+ windowMinutes: options?.config?.loginRateLimit?.windowMinutes ??
130
+ EntityStorageAuthenticationService._DEFAULT_LOGIN_RATE_WINDOW_MINUTES
131
+ };
132
+ this._passwordChangeRateLimit = {
133
+ maxAttempts: options?.config?.passwordChangeRateLimit?.maxAttempts ??
134
+ EntityStorageAuthenticationService._DEFAULT_PASSWORD_CHANGE_RATE_MAX_ATTEMPTS,
135
+ windowMinutes: options?.config?.passwordChangeRateLimit?.windowMinutes ??
136
+ EntityStorageAuthenticationService._DEFAULT_PASSWORD_CHANGE_RATE_WINDOW_MINUTES
137
+ };
138
+ this._tokenRefreshRateLimit = {
139
+ maxAttempts: options?.config?.tokenRefreshRateLimit?.maxAttempts ??
140
+ EntityStorageAuthenticationService._DEFAULT_TOKEN_REFRESH_RATE_MAX_ATTEMPTS,
141
+ windowMinutes: options?.config?.tokenRefreshRateLimit?.windowMinutes ??
142
+ EntityStorageAuthenticationService._DEFAULT_TOKEN_REFRESH_RATE_WINDOW_MINUTES
143
+ };
61
144
  }
62
145
  /**
63
146
  * Returns the class name of the component.
@@ -69,12 +152,25 @@ export class EntityStorageAuthenticationService {
69
152
  /**
70
153
  * The service needs to be started when the application is initialized.
71
154
  * @param nodeLoggingComponentType The node logging component type.
72
- * @returns Nothing.
155
+ * @returns A promise that resolves when rate-limit actions have been registered and the node identity cached.
73
156
  */
74
157
  async start(nodeLoggingComponentType) {
75
158
  const contextIds = await ContextIdStore.getContextIds();
76
159
  ContextIdHelper.guard(contextIds, ContextIdKeys.Node);
77
160
  this._nodeId = contextIds[ContextIdKeys.Node];
161
+ await this._authenticationRateService.registerAction("login", this._loginRateLimit);
162
+ await this._authenticationRateService.registerAction("password-change", this._passwordChangeRateLimit);
163
+ await this._authenticationRateService.registerAction("token-refresh", this._tokenRefreshRateLimit);
164
+ }
165
+ /**
166
+ * The component needs to be stopped when the node is closed.
167
+ * @param nodeLoggingComponentType The node logging component type.
168
+ * @returns A promise that resolves when all rate-limit actions have been unregistered.
169
+ */
170
+ async stop(nodeLoggingComponentType) {
171
+ await this._authenticationRateService.unregisterAction("login");
172
+ await this._authenticationRateService.unregisterAction("password-change");
173
+ await this._authenticationRateService.unregisterAction("token-refresh");
78
174
  }
79
175
  /**
80
176
  * Perform a login for the user.
@@ -85,36 +181,68 @@ export class EntityStorageAuthenticationService {
85
181
  async login(email, password) {
86
182
  Guards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, "email", email);
87
183
  Guards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, "password", password);
184
+ if (!Is.stringValue(this._nodeId)) {
185
+ throw new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, "nodeIdNotSet");
186
+ }
187
+ let loginUser;
188
+ let loginTenantId;
189
+ let tokenAndExpiry;
88
190
  try {
191
+ await this._authenticationRateService.check("login", email);
89
192
  const user = await this._userEntityStorage.get(email);
90
193
  if (!user) {
91
194
  throw new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, "userNotFound");
92
195
  }
93
196
  const saltBytes = Converter.base64ToBytes(user.salt);
94
197
  const passwordBytes = Converter.utf8ToBytes(password);
95
- const hashedPassword = await PasswordHelper.hashPassword(passwordBytes, saltBytes);
96
- if (hashedPassword !== user.password) {
198
+ const hashedPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);
199
+ if (!PasswordValidator.comparePasswordHashes(hashedPassword, user.password)) {
97
200
  throw new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, "passwordMismatch");
98
201
  }
99
202
  // This might be undefined if the login is performed in a single tenant context
100
- // if is verified during the token processing, tenant id will be matched against
203
+ // it is verified during the token processing, tenant id will be matched against
101
204
  // the context
102
205
  const contextIds = await ContextIdStore.getContextIds();
103
- const tenantId = contextIds?.[ContextIdKeys.Tenant];
104
- const tokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, `${this._nodeId}/${this._signingKeyName}`, user.identity, user.organization, tenantId, this._defaultTtlMinutes);
105
- return tokenAndExpiry;
206
+ loginTenantId = contextIds?.[ContextIdKeys.Tenant];
207
+ tokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, this._nodeId, this._signingKeyName, user.identity, user.organization, loginTenantId, this._defaultTtlMinutes, user.scope, user.passwordVersion ?? 0);
208
+ loginUser = user;
106
209
  }
107
210
  catch (error) {
211
+ await this._authenticationAuditService?.create({
212
+ actorId: email,
213
+ event: AuthAuditEvent.LoginFailure
214
+ });
108
215
  throw new UnauthorizedError(EntityStorageAuthenticationService.CLASS_NAME, "loginFailed", undefined, error);
109
216
  }
217
+ await this._authenticationRateService.clear("login", email);
218
+ await this._authenticationAuditService?.create({
219
+ actorId: email,
220
+ event: AuthAuditEvent.LoginSuccess,
221
+ data: {
222
+ userIdentity: loginUser.identity,
223
+ organizationIdentity: loginUser.organization,
224
+ tenantId: loginTenantId,
225
+ scope: loginUser.scope.split(",")
226
+ }
227
+ });
228
+ return tokenAndExpiry;
110
229
  }
111
230
  /**
112
231
  * Logout the current user.
113
232
  * @param token The token to logout, if it uses a mechanism with public access.
114
- * @returns Nothing.
233
+ * @returns A promise that resolves when the logout audit entry has been recorded.
115
234
  */
116
235
  async logout(token) {
117
- // Nothing to do here.
236
+ // Nothing to do here, as we are stateless.
237
+ // The cookie will be revoked by the REST route handling
238
+ const contextIds = await ContextIdStore.getContextIds();
239
+ const identifier = contextIds?.[ContextIdKeys.User];
240
+ if (Is.stringValue(identifier)) {
241
+ await this._authenticationAuditService?.create({
242
+ actorId: identifier,
243
+ event: AuthAuditEvent.Logout
244
+ });
245
+ }
118
246
  }
119
247
  /**
120
248
  * Refresh the token.
@@ -122,20 +250,73 @@ export class EntityStorageAuthenticationService {
122
250
  * @returns The refreshed token, if it uses a mechanism with public access.
123
251
  */
124
252
  async refresh(token) {
253
+ if (!Is.stringValue(this._nodeId)) {
254
+ throw new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, "nodeIdNotSet");
255
+ }
256
+ let refreshPasswordVersion;
257
+ let tenantId;
125
258
  // If the verify fails on the current token then it will throw an exception.
126
- const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeId}/${this._signingKeyName}`, token);
127
- const refreshTokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, `${this._nodeId}/${this._signingKeyName}`, headerAndPayload.payload.sub ?? "", Is.stringValue(headerAndPayload.payload.org) ? headerAndPayload.payload.org : "", Is.stringValue(headerAndPayload.payload.tid) ? headerAndPayload.payload.tid : "", this._defaultTtlMinutes);
259
+ const headerAndPayload = await TokenHelper.verify(this._vaultConnector, this._nodeId, this._signingKeyName, token, undefined, async (sub, org, tid, passwordVersion) => {
260
+ const validParts = [];
261
+ tenantId = tid;
262
+ if (Is.stringValue(tenantId)) {
263
+ const tenant = await this._tenantAdminComponent?.get(tenantId);
264
+ if (tenant?.id === tenantId) {
265
+ validParts.push("tenant");
266
+ }
267
+ }
268
+ // We use the tenant id from the token, if the user is not in that
269
+ // partition then the get will fail. Only override the tenant key when
270
+ // tid is present — setting it to undefined would drop the active partition.
271
+ const baseContext = (await ContextIdStore.getContextIds()) ?? {};
272
+ const contextIdsForUserLookup = Is.stringValue(tid)
273
+ ? { ...baseContext, [ContextIdKeys.Tenant]: tid }
274
+ : baseContext;
275
+ // Wrap the user lookup in the request context so partitioned storage uses the correct tenant.
276
+ const user = await ContextIdStore.run(contextIdsForUserLookup, async () => this._userEntityStorage.get(sub, "identity"));
277
+ refreshPasswordVersion = user?.passwordVersion;
278
+ if (user?.identity === sub && (passwordVersion ?? 0) === (refreshPasswordVersion ?? 0)) {
279
+ validParts.push("user");
280
+ }
281
+ if (user?.organization === org) {
282
+ validParts.push("organization");
283
+ }
284
+ return validParts;
285
+ });
286
+ const refreshSub = headerAndPayload.payload.sub ?? "";
287
+ await this._authenticationRateService.check("token-refresh", refreshSub);
288
+ const payloadOrg = Coerce.string(headerAndPayload.payload.org);
289
+ const payloadScope = Coerce.string(headerAndPayload.payload?.scope);
290
+ const refreshTokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, this._nodeId, this._signingKeyName, refreshSub, payloadOrg, tenantId, this._defaultTtlMinutes, payloadScope, refreshPasswordVersion ?? 0);
291
+ await this._authenticationAuditService?.create({
292
+ actorId: refreshSub,
293
+ event: AuthAuditEvent.TokenRefreshed,
294
+ data: {
295
+ organizationIdentity: payloadOrg,
296
+ tenantId,
297
+ scope: payloadScope?.split(",").filter(scope => scope.length > 0),
298
+ version: refreshPasswordVersion ?? 0
299
+ }
300
+ });
128
301
  return refreshTokenAndExpiry;
129
302
  }
130
303
  /**
131
304
  * Update the user's password.
132
- * @param email The email address of the user to update.
133
305
  * @param currentPassword The current password for the user.
134
306
  * @param newPassword The new password for the user.
135
- * @returns Nothing.
307
+ * @returns A promise that resolves when the password has been updated and the rate limit cleared.
136
308
  */
137
- async updatePassword(email, currentPassword, newPassword) {
138
- return this._authenticationAdminService.updatePassword(email, newPassword, currentPassword);
309
+ async updatePassword(currentPassword, newPassword) {
310
+ const contextIds = await ContextIdStore.getContextIds();
311
+ ContextIdHelper.guard(contextIds, ContextIdKeys.User);
312
+ const userIdentity = contextIds[ContextIdKeys.User];
313
+ await this._authenticationRateService.check("password-change", userIdentity);
314
+ const user = await this._userEntityStorage.get(userIdentity, "identity");
315
+ if (!Is.object(user)) {
316
+ throw new NotFoundError(EntityStorageAuthenticationService.CLASS_NAME, "userNotFound", userIdentity);
317
+ }
318
+ await PasswordHelper.updatePassword(this._userEntityStorage, this._authenticationAuditService, user, newPassword, currentPassword, this._minPasswordLength);
319
+ await this._authenticationRateService.clear("password-change", userIdentity);
139
320
  }
140
321
  }
141
322
  //# sourceMappingURL=entityStorageAuthenticationService.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"entityStorageAuthenticationService.js","sourceRoot":"","sources":["../../../src/services/entityStorageAuthenticationService.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,EACN,gBAAgB,EAChB,SAAS,EACT,YAAY,EACZ,MAAM,EACN,EAAE,EACF,iBAAiB,EACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,6BAA6B,EAE7B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAwB,MAAM,wBAAwB,CAAC;AAGrF,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,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C","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type {\n\tIAuthenticationAdminComponent,\n\tIAuthenticationComponent\n} from \"@twin.org/api-auth-entity-storage-models\";\nimport { ContextIdHelper, ContextIdKeys, ContextIdStore } from \"@twin.org/context\";\nimport {\n\tComponentFactory,\n\tConverter,\n\tGeneralError,\n\tGuards,\n\tIs,\n\tUnauthorizedError\n} from \"@twin.org/core\";\nimport {\n\tEntityStorageConnectorFactory,\n\ttype IEntityStorageConnector\n} from \"@twin.org/entity-storage-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { VaultConnectorFactory, type IVaultConnector } from \"@twin.org/vault-models\";\nimport type { AuthenticationUser } from \"../entities/authenticationUser.js\";\nimport type { IEntityStorageAuthenticationServiceConstructorOptions } from \"../models/IEntityStorageAuthenticationServiceConstructorOptions.js\";\nimport { PasswordHelper } from \"../utils/passwordHelper.js\";\nimport { TokenHelper } from \"../utils/tokenHelper.js\";\n\n/**\n * Implementation of the authentication component using entity storage.\n */\nexport class EntityStorageAuthenticationService implements IAuthenticationComponent {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<EntityStorageAuthenticationService>();\n\n\t/**\n\t * Default TTL in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TTL_MINUTES: number = 60;\n\n\t/**\n\t * The user admin service.\n\t * @internal\n\t */\n\tprivate readonly _authenticationAdminService: IAuthenticationAdminComponent;\n\n\t/**\n\t * The entity storage for users.\n\t * @internal\n\t */\n\tprivate readonly _userEntityStorage: IEntityStorageConnector<AuthenticationUser>;\n\n\t/**\n\t * The vault for the keys.\n\t * @internal\n\t */\n\tprivate readonly _vaultConnector: IVaultConnector;\n\n\t/**\n\t * The name of the key to retrieve from the vault for signing JWT.\n\t * @internal\n\t */\n\tprivate readonly _signingKeyName: string;\n\n\t/**\n\t * The default TTL for the token.\n\t * @internal\n\t */\n\tprivate readonly _defaultTtlMinutes: number;\n\n\t/**\n\t * The node identity.\n\t * @internal\n\t */\n\tprivate _nodeId?: string;\n\n\t/**\n\t * Create a new instance of EntityStorageAuthentication.\n\t * @param options The dependencies for the identity connector.\n\t */\n\tconstructor(options?: IEntityStorageAuthenticationServiceConstructorOptions) {\n\t\tthis._userEntityStorage = EntityStorageConnectorFactory.get(\n\t\t\toptions?.userEntityStorageType ?? \"authentication-user\"\n\t\t);\n\n\t\tthis._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? \"vault\");\n\n\t\tthis._authenticationAdminService = ComponentFactory.get<IAuthenticationAdminComponent>(\n\t\t\toptions?.authenticationAdminServiceType ?? \"authentication-admin\"\n\t\t);\n\n\t\tthis._signingKeyName = options?.config?.signingKeyName ?? \"auth-signing\";\n\t\tthis._defaultTtlMinutes =\n\t\t\toptions?.config?.defaultTtlMinutes ?? EntityStorageAuthenticationService._DEFAULT_TTL_MINUTES;\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn EntityStorageAuthenticationService.CLASS_NAME;\n\t}\n\n\t/**\n\t * The service needs to be started when the application is initialized.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns Nothing.\n\t */\n\tpublic async start(nodeLoggingComponentType?: string): Promise<void> {\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tContextIdHelper.guard(contextIds, ContextIdKeys.Node);\n\t\tthis._nodeId = contextIds[ContextIdKeys.Node];\n\t}\n\n\t/**\n\t * Perform a login for the user.\n\t * @param email The email address for the user.\n\t * @param password The password for the user.\n\t * @returns The authentication token for the user, if it uses a mechanism with public access.\n\t */\n\tpublic async login(\n\t\temail: string,\n\t\tpassword: string\n\t): Promise<{\n\t\ttoken?: string;\n\t\texpiry: number;\n\t}> {\n\t\tGuards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, nameof(email), email);\n\t\tGuards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, nameof(password), password);\n\n\t\ttry {\n\t\t\tconst user = await this._userEntityStorage.get(email);\n\t\t\tif (!user) {\n\t\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"userNotFound\");\n\t\t\t}\n\n\t\t\tconst saltBytes = Converter.base64ToBytes(user.salt);\n\t\t\tconst passwordBytes = Converter.utf8ToBytes(password);\n\n\t\t\tconst hashedPassword = await PasswordHelper.hashPassword(passwordBytes, saltBytes);\n\n\t\t\tif (hashedPassword !== user.password) {\n\t\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"passwordMismatch\");\n\t\t\t}\n\n\t\t\t// This might be undefined if the login is performed in a single tenant context\n\t\t\t// if is verified during the token processing, tenant id will be matched against\n\t\t\t// the context\n\t\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\t\tconst tenantId = contextIds?.[ContextIdKeys.Tenant];\n\n\t\t\tconst tokenAndExpiry = await TokenHelper.createToken(\n\t\t\t\tthis._vaultConnector,\n\t\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\t\tuser.identity,\n\t\t\t\tuser.organization,\n\t\t\t\ttenantId,\n\t\t\t\tthis._defaultTtlMinutes\n\t\t\t);\n\n\t\t\treturn tokenAndExpiry;\n\t\t} catch (error) {\n\t\t\tthrow new UnauthorizedError(\n\t\t\t\tEntityStorageAuthenticationService.CLASS_NAME,\n\t\t\t\t\"loginFailed\",\n\t\t\t\tundefined,\n\t\t\t\terror\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Logout the current user.\n\t * @param token The token to logout, if it uses a mechanism with public access.\n\t * @returns Nothing.\n\t */\n\tpublic async logout(token?: string): Promise<void> {\n\t\t// Nothing to do here.\n\t}\n\n\t/**\n\t * Refresh the token.\n\t * @param token The token to refresh, if it uses a mechanism with public access.\n\t * @returns The refreshed token, if it uses a mechanism with public access.\n\t */\n\tpublic async refresh(token?: string): Promise<{\n\t\ttoken?: string;\n\t\texpiry: number;\n\t}> {\n\t\t// If the verify fails on the current token then it will throw an exception.\n\t\tconst headerAndPayload = await TokenHelper.verify(\n\t\t\tthis._vaultConnector,\n\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\ttoken\n\t\t);\n\n\t\tconst refreshTokenAndExpiry = await TokenHelper.createToken(\n\t\t\tthis._vaultConnector,\n\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\theaderAndPayload.payload.sub ?? \"\",\n\t\t\tIs.stringValue(headerAndPayload.payload.org) ? headerAndPayload.payload.org : \"\",\n\t\t\tIs.stringValue(headerAndPayload.payload.tid) ? headerAndPayload.payload.tid : \"\",\n\t\t\tthis._defaultTtlMinutes\n\t\t);\n\n\t\treturn refreshTokenAndExpiry;\n\t}\n\n\t/**\n\t * Update the user's password.\n\t * @param email The email address of the user to update.\n\t * @param currentPassword The current password for the user.\n\t * @param newPassword The new password for the user.\n\t * @returns Nothing.\n\t */\n\tpublic async updatePassword(\n\t\temail: string,\n\t\tcurrentPassword: string,\n\t\tnewPassword: string\n\t): Promise<void> {\n\t\treturn this._authenticationAdminService.updatePassword(email, newPassword, currentPassword);\n\t}\n}\n"]}
1
+ {"version":3,"file":"entityStorageAuthenticationService.js","sourceRoot":"","sources":["../../../src/services/entityStorageAuthenticationService.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAE1E,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,EACN,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,YAAY,EACZ,MAAM,EACN,EAAE,EACF,aAAa,EACb,iBAAiB,EACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EACN,6BAA6B,EAE7B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAwB,MAAM,wBAAwB,CAAC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right 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type {\n\tIAuthenticationRateActionConfig,\n\tIAuthenticationRateComponent,\n\tIAuthenticationAuditComponent,\n\tIAuthenticationComponent\n} from \"@twin.org/api-auth-entity-storage-models\";\nimport { AuthAuditEvent } from \"@twin.org/api-auth-entity-storage-models\";\nimport type { ITenantAdminComponent } from \"@twin.org/api-models\";\nimport { ContextIdHelper, ContextIdKeys, ContextIdStore } from \"@twin.org/context\";\nimport {\n\tCoerce,\n\tComponentFactory,\n\tConverter,\n\tGeneralError,\n\tGuards,\n\tIs,\n\tNotFoundError,\n\tUnauthorizedError\n} from \"@twin.org/core\";\nimport { PasswordGenerator, PasswordValidator } from \"@twin.org/crypto\";\nimport {\n\tEntityStorageConnectorFactory,\n\ttype IEntityStorageConnector\n} from \"@twin.org/entity-storage-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { VaultConnectorFactory, type IVaultConnector } from \"@twin.org/vault-models\";\nimport type { AuthenticationUser } from \"../entities/authenticationUser.js\";\nimport type { IEntityStorageAuthenticationServiceConstructorOptions } from \"../models/IEntityStorageAuthenticationServiceConstructorOptions.js\";\nimport { PasswordHelper } from \"../utils/passwordHelper.js\";\nimport { TokenHelper } from \"../utils/tokenHelper.js\";\n\n/**\n * Implementation of the authentication component using entity storage.\n */\nexport class EntityStorageAuthenticationService implements IAuthenticationComponent {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<EntityStorageAuthenticationService>();\n\n\t/**\n\t * Default TTL in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TTL_MINUTES: number = 60;\n\n\t/**\n\t * Default maximum login attempts in a rate window.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_LOGIN_RATE_MAX_ATTEMPTS: number = 5;\n\n\t/**\n\t * Default login rate window in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_LOGIN_RATE_WINDOW_MINUTES: number = 15;\n\n\t/**\n\t * Default maximum password change attempts in a rate window.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_PASSWORD_CHANGE_RATE_MAX_ATTEMPTS: number = 5;\n\n\t/**\n\t * Default password change rate window in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_PASSWORD_CHANGE_RATE_WINDOW_MINUTES: number = 15;\n\n\t/**\n\t * Default maximum token refresh attempts in a rate window.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TOKEN_REFRESH_RATE_MAX_ATTEMPTS: number = 30;\n\n\t/**\n\t * Default token refresh rate window in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TOKEN_REFRESH_RATE_WINDOW_MINUTES: number = 60;\n\n\t/**\n\t * The audit service.\n\t * @internal\n\t */\n\tprivate readonly _authenticationAuditService?: IAuthenticationAuditComponent;\n\n\t/**\n\t * The rate service.\n\t * @internal\n\t */\n\tprivate readonly _authenticationRateService: IAuthenticationRateComponent;\n\n\t/**\n\t * The entity storage for users.\n\t * @internal\n\t */\n\tprivate readonly _userEntityStorage: IEntityStorageConnector<AuthenticationUser>;\n\n\t/**\n\t * The vault for the keys.\n\t * @internal\n\t */\n\tprivate readonly _vaultConnector: IVaultConnector;\n\n\t/**\n\t * The name of the key to retrieve from the vault for signing JWT.\n\t * @internal\n\t */\n\tprivate readonly _signingKeyName: string;\n\n\t/**\n\t * The default TTL for the token.\n\t * @internal\n\t */\n\tprivate readonly _defaultTtlMinutes: number;\n\n\t/**\n\t * The minimum password length for validation.\n\t * @internal\n\t */\n\tprivate readonly _minPasswordLength?: number;\n\n\t/**\n\t * Rate limit configuration for login failures.\n\t * @internal\n\t */\n\tprivate readonly _loginRateLimit: IAuthenticationRateActionConfig;\n\n\t/**\n\t * Rate limit configuration for password changes.\n\t * @internal\n\t */\n\tprivate readonly _passwordChangeRateLimit: IAuthenticationRateActionConfig;\n\n\t/**\n\t * Rate limit configuration for token refresh.\n\t * @internal\n\t */\n\tprivate readonly _tokenRefreshRateLimit: IAuthenticationRateActionConfig;\n\n\t/**\n\t * The component to retrieve tenant information.\n\t * @internal\n\t */\n\tprivate readonly _tenantAdminComponent?: ITenantAdminComponent;\n\n\t/**\n\t * The node identity.\n\t * @internal\n\t */\n\tprivate _nodeId?: string;\n\n\t/**\n\t * Create a new instance of EntityStorageAuthentication.\n\t * @param options The dependencies for the identity connector.\n\t */\n\tconstructor(options?: IEntityStorageAuthenticationServiceConstructorOptions) {\n\t\tthis._userEntityStorage = EntityStorageConnectorFactory.get(\n\t\t\toptions?.userEntityStorageType ?? \"authentication-user\"\n\t\t);\n\n\t\tthis._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? \"vault\");\n\n\t\tthis._authenticationAuditService = ComponentFactory.getIfExists<IAuthenticationAuditComponent>(\n\t\t\toptions?.authenticationAuditServiceType ?? \"authentication-audit\"\n\t\t);\n\n\t\tthis._authenticationRateService = ComponentFactory.get<IAuthenticationRateComponent>(\n\t\t\toptions?.authenticationRateServiceType ?? \"authentication-rate\"\n\t\t);\n\n\t\tthis._tenantAdminComponent = ComponentFactory.getIfExists<ITenantAdminComponent>(\n\t\t\toptions?.tenantAdminComponentType ?? \"tenant-admin\"\n\t\t);\n\n\t\tthis._signingKeyName = options?.config?.signingKeyName ?? \"auth-signing\";\n\t\tthis._defaultTtlMinutes =\n\t\t\toptions?.config?.defaultTtlMinutes ?? EntityStorageAuthenticationService._DEFAULT_TTL_MINUTES;\n\t\tthis._minPasswordLength = options?.config?.minPasswordLength;\n\t\tthis._loginRateLimit = {\n\t\t\tmaxAttempts:\n\t\t\t\toptions?.config?.loginRateLimit?.maxAttempts ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_LOGIN_RATE_MAX_ATTEMPTS,\n\t\t\twindowMinutes:\n\t\t\t\toptions?.config?.loginRateLimit?.windowMinutes ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_LOGIN_RATE_WINDOW_MINUTES\n\t\t};\n\t\tthis._passwordChangeRateLimit = {\n\t\t\tmaxAttempts:\n\t\t\t\toptions?.config?.passwordChangeRateLimit?.maxAttempts ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_PASSWORD_CHANGE_RATE_MAX_ATTEMPTS,\n\t\t\twindowMinutes:\n\t\t\t\toptions?.config?.passwordChangeRateLimit?.windowMinutes ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_PASSWORD_CHANGE_RATE_WINDOW_MINUTES\n\t\t};\n\t\tthis._tokenRefreshRateLimit = {\n\t\t\tmaxAttempts:\n\t\t\t\toptions?.config?.tokenRefreshRateLimit?.maxAttempts ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_TOKEN_REFRESH_RATE_MAX_ATTEMPTS,\n\t\t\twindowMinutes:\n\t\t\t\toptions?.config?.tokenRefreshRateLimit?.windowMinutes ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_TOKEN_REFRESH_RATE_WINDOW_MINUTES\n\t\t};\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn EntityStorageAuthenticationService.CLASS_NAME;\n\t}\n\n\t/**\n\t * The service needs to be started when the application is initialized.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns A promise that resolves when rate-limit actions have been registered and the node identity cached.\n\t */\n\tpublic async start(nodeLoggingComponentType?: string): Promise<void> {\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tContextIdHelper.guard(contextIds, ContextIdKeys.Node);\n\t\tthis._nodeId = contextIds[ContextIdKeys.Node];\n\n\t\tawait this._authenticationRateService.registerAction(\"login\", this._loginRateLimit);\n\t\tawait this._authenticationRateService.registerAction(\n\t\t\t\"password-change\",\n\t\t\tthis._passwordChangeRateLimit\n\t\t);\n\t\tawait this._authenticationRateService.registerAction(\n\t\t\t\"token-refresh\",\n\t\t\tthis._tokenRefreshRateLimit\n\t\t);\n\t}\n\n\t/**\n\t * The component needs to be stopped when the node is closed.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns A promise that resolves when all rate-limit actions have been unregistered.\n\t */\n\tpublic async stop(nodeLoggingComponentType?: string): Promise<void> {\n\t\tawait this._authenticationRateService.unregisterAction(\"login\");\n\t\tawait this._authenticationRateService.unregisterAction(\"password-change\");\n\t\tawait this._authenticationRateService.unregisterAction(\"token-refresh\");\n\t}\n\n\t/**\n\t * Perform a login for the user.\n\t * @param email The email address for the user.\n\t * @param password The password for the user.\n\t * @returns The authentication token for the user, if it uses a mechanism with public access.\n\t */\n\tpublic async login(\n\t\temail: string,\n\t\tpassword: string\n\t): Promise<{\n\t\ttoken?: string;\n\t\texpiry: number;\n\t}> {\n\t\tGuards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, nameof(email), email);\n\t\tGuards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, nameof(password), password);\n\n\t\tif (!Is.stringValue(this._nodeId)) {\n\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"nodeIdNotSet\");\n\t\t}\n\n\t\tlet loginUser: AuthenticationUser | undefined;\n\t\tlet loginTenantId: string | undefined;\n\t\tlet tokenAndExpiry: { token?: string; expiry: number } | undefined;\n\n\t\ttry {\n\t\t\tawait this._authenticationRateService.check(\"login\", email);\n\n\t\t\tconst user = await this._userEntityStorage.get(email);\n\t\t\tif (!user) {\n\t\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"userNotFound\");\n\t\t\t}\n\n\t\t\tconst saltBytes = Converter.base64ToBytes(user.salt);\n\t\t\tconst passwordBytes = Converter.utf8ToBytes(password);\n\n\t\t\tconst hashedPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);\n\n\t\t\tif (!PasswordValidator.comparePasswordHashes(hashedPassword, user.password)) {\n\t\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"passwordMismatch\");\n\t\t\t}\n\n\t\t\t// This might be undefined if the login is performed in a single tenant context\n\t\t\t// it is verified during the token processing, tenant id will be matched against\n\t\t\t// the context\n\t\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\t\tloginTenantId = contextIds?.[ContextIdKeys.Tenant];\n\n\t\t\ttokenAndExpiry = await TokenHelper.createToken(\n\t\t\t\tthis._vaultConnector,\n\t\t\t\tthis._nodeId,\n\t\t\t\tthis._signingKeyName,\n\t\t\t\tuser.identity,\n\t\t\t\tuser.organization,\n\t\t\t\tloginTenantId,\n\t\t\t\tthis._defaultTtlMinutes,\n\t\t\t\tuser.scope,\n\t\t\t\tuser.passwordVersion ?? 0\n\t\t\t);\n\t\t\tloginUser = user;\n\t\t} catch (error) {\n\t\t\tawait this._authenticationAuditService?.create({\n\t\t\t\tactorId: email,\n\t\t\t\tevent: AuthAuditEvent.LoginFailure\n\t\t\t});\n\n\t\t\tthrow new UnauthorizedError(\n\t\t\t\tEntityStorageAuthenticationService.CLASS_NAME,\n\t\t\t\t\"loginFailed\",\n\t\t\t\tundefined,\n\t\t\t\terror\n\t\t\t);\n\t\t}\n\n\t\tawait this._authenticationRateService.clear(\"login\", email);\n\n\t\tawait this._authenticationAuditService?.create({\n\t\t\tactorId: email,\n\t\t\tevent: AuthAuditEvent.LoginSuccess,\n\t\t\tdata: {\n\t\t\t\tuserIdentity: loginUser.identity,\n\t\t\t\torganizationIdentity: loginUser.organization,\n\t\t\t\ttenantId: loginTenantId,\n\t\t\t\tscope: loginUser.scope.split(\",\")\n\t\t\t}\n\t\t});\n\n\t\treturn tokenAndExpiry;\n\t}\n\n\t/**\n\t * Logout the current user.\n\t * @param token The token to logout, if it uses a mechanism with public access.\n\t * @returns A promise that resolves when the logout audit entry has been recorded.\n\t */\n\tpublic async logout(token?: string): Promise<void> {\n\t\t// Nothing to do here, as we are stateless.\n\t\t// The cookie will be revoked by the REST route handling\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tconst identifier = contextIds?.[ContextIdKeys.User];\n\t\tif (Is.stringValue(identifier)) {\n\t\t\tawait this._authenticationAuditService?.create({\n\t\t\t\tactorId: identifier,\n\t\t\t\tevent: AuthAuditEvent.Logout\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Refresh the token.\n\t * @param token The token to refresh, if it uses a mechanism with public access.\n\t * @returns The refreshed token, if it uses a mechanism with public access.\n\t */\n\tpublic async refresh(token?: string): Promise<{\n\t\ttoken?: string;\n\t\texpiry: number;\n\t}> {\n\t\tif (!Is.stringValue(this._nodeId)) {\n\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"nodeIdNotSet\");\n\t\t}\n\n\t\tlet refreshPasswordVersion: number | undefined;\n\t\tlet tenantId: string | undefined;\n\n\t\t// If the verify fails on the current token then it will throw an exception.\n\t\tconst headerAndPayload = await TokenHelper.verify(\n\t\t\tthis._vaultConnector,\n\t\t\tthis._nodeId,\n\t\t\tthis._signingKeyName,\n\t\t\ttoken,\n\t\t\tundefined,\n\t\t\tasync (sub, org, tid, passwordVersion) => {\n\t\t\t\tconst validParts = [];\n\n\t\t\t\ttenantId = tid;\n\n\t\t\t\tif (Is.stringValue(tenantId)) {\n\t\t\t\t\tconst tenant = await this._tenantAdminComponent?.get(tenantId);\n\t\t\t\t\tif (tenant?.id === tenantId) {\n\t\t\t\t\t\tvalidParts.push(\"tenant\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// We use the tenant id from the token, if the user is not in that\n\t\t\t\t// partition then the get will fail. Only override the tenant key when\n\t\t\t\t// tid is present — setting it to undefined would drop the active partition.\n\t\t\t\tconst baseContext = (await ContextIdStore.getContextIds()) ?? {};\n\t\t\t\tconst contextIdsForUserLookup = Is.stringValue(tid)\n\t\t\t\t\t? { ...baseContext, [ContextIdKeys.Tenant]: tid }\n\t\t\t\t\t: baseContext;\n\n\t\t\t\t// Wrap the user lookup in the request context so partitioned storage uses the correct tenant.\n\t\t\t\tconst user = await ContextIdStore.run(contextIdsForUserLookup, async () =>\n\t\t\t\t\tthis._userEntityStorage.get(sub, \"identity\")\n\t\t\t\t);\n\n\t\t\t\trefreshPasswordVersion = user?.passwordVersion;\n\t\t\t\tif (user?.identity === sub && (passwordVersion ?? 0) === (refreshPasswordVersion ?? 0)) {\n\t\t\t\t\tvalidParts.push(\"user\");\n\t\t\t\t}\n\t\t\t\tif (user?.organization === org) {\n\t\t\t\t\tvalidParts.push(\"organization\");\n\t\t\t\t}\n\t\t\t\treturn validParts;\n\t\t\t}\n\t\t);\n\n\t\tconst refreshSub = headerAndPayload.payload.sub ?? \"\";\n\t\tawait this._authenticationRateService.check(\"token-refresh\", refreshSub);\n\n\t\tconst payloadOrg = Coerce.string(headerAndPayload.payload.org);\n\t\tconst payloadScope = Coerce.string(headerAndPayload.payload?.scope);\n\n\t\tconst refreshTokenAndExpiry = await TokenHelper.createToken(\n\t\t\tthis._vaultConnector,\n\t\t\tthis._nodeId,\n\t\t\tthis._signingKeyName,\n\t\t\trefreshSub,\n\t\t\tpayloadOrg,\n\t\t\ttenantId,\n\t\t\tthis._defaultTtlMinutes,\n\t\t\tpayloadScope,\n\t\t\trefreshPasswordVersion ?? 0\n\t\t);\n\n\t\tawait this._authenticationAuditService?.create({\n\t\t\tactorId: refreshSub,\n\t\t\tevent: AuthAuditEvent.TokenRefreshed,\n\t\t\tdata: {\n\t\t\t\torganizationIdentity: payloadOrg,\n\t\t\t\ttenantId,\n\t\t\t\tscope: payloadScope?.split(\",\").filter(scope => scope.length > 0),\n\t\t\t\tversion: refreshPasswordVersion ?? 0\n\t\t\t}\n\t\t});\n\n\t\treturn refreshTokenAndExpiry;\n\t}\n\n\t/**\n\t * Update the user's password.\n\t * @param currentPassword The current password for the user.\n\t * @param newPassword The new password for the user.\n\t * @returns A promise that resolves when the password has been updated and the rate limit cleared.\n\t */\n\tpublic async updatePassword(currentPassword: string, newPassword: string): Promise<void> {\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tContextIdHelper.guard(contextIds, ContextIdKeys.User);\n\n\t\tconst userIdentity = contextIds[ContextIdKeys.User];\n\t\tawait this._authenticationRateService.check(\"password-change\", userIdentity);\n\n\t\tconst user = await this._userEntityStorage.get(userIdentity, \"identity\");\n\t\tif (!Is.object<AuthenticationUser>(user)) {\n\t\t\tthrow new NotFoundError(\n\t\t\t\tEntityStorageAuthenticationService.CLASS_NAME,\n\t\t\t\t\"userNotFound\",\n\t\t\t\tuserIdentity\n\t\t\t);\n\t\t}\n\n\t\tawait PasswordHelper.updatePassword(\n\t\t\tthis._userEntityStorage,\n\t\t\tthis._authenticationAuditService,\n\t\t\tuser,\n\t\t\tnewPassword,\n\t\t\tcurrentPassword,\n\t\t\tthis._minPasswordLength\n\t\t);\n\n\t\tawait this._authenticationRateService.clear(\"password-change\", userIdentity);\n\t}\n}\n"]}
@@ -1,7 +1,6 @@
1
- // Copyright 2024 IOTA Stiftung.
2
- // SPDX-License-Identifier: Apache-2.0.
3
- import { Converter, Guards } from "@twin.org/core";
4
- import { Blake2b } from "@twin.org/crypto";
1
+ import { AuthAuditEvent } from "@twin.org/api-auth-entity-storage-models";
2
+ import { Converter, GeneralError, Is, RandomHelper } from "@twin.org/core";
3
+ import { PasswordGenerator, PasswordValidator } from "@twin.org/crypto";
5
4
  /**
6
5
  * Helper class for password operations.
7
6
  */
@@ -11,19 +10,49 @@ export class PasswordHelper {
11
10
  */
12
11
  static CLASS_NAME = "PasswordHelper";
13
12
  /**
14
- * Hash the password for the user.
15
- * @param passwordBytes The password bytes.
16
- * @param saltBytes The salt bytes.
17
- * @returns The hashed password.
13
+ * Update the password for a user.
14
+ * Validates password strength, verifies the current password if provided, then hashes and stores the new password and raises an audit event.
15
+ * @param userEntityStorage The entity storage for users.
16
+ * @param authenticationAuditService The optional audit service.
17
+ * @param user The user whose password is being updated.
18
+ * @param newPassword The new password to set.
19
+ * @param currentPassword The current password to verify against, if supplied.
20
+ * @param minPasswordLength Optional minimum password length for validation.
21
+ * @returns A promise that resolves when the new password has been stored and the audit entry recorded.
18
22
  */
19
- static async hashPassword(passwordBytes, saltBytes) {
20
- Guards.uint8Array(PasswordHelper.CLASS_NAME, "passwordBytes", passwordBytes);
21
- Guards.uint8Array(PasswordHelper.CLASS_NAME, "saltBytes", saltBytes);
22
- const combined = new Uint8Array(saltBytes.length + passwordBytes.length);
23
- combined.set(saltBytes);
24
- combined.set(passwordBytes, saltBytes.length);
25
- const hashedPassword = Blake2b.sum256(combined);
26
- return Converter.bytesToBase64(hashedPassword);
23
+ static async updatePassword(userEntityStorage, authenticationAuditService, user, newPassword, currentPassword, minPasswordLength) {
24
+ PasswordValidator.validatePassword(newPassword, {
25
+ minLength: minPasswordLength
26
+ });
27
+ if (Is.stringValue(currentPassword)) {
28
+ const saltBytes = Converter.base64ToBytes(user.salt);
29
+ const passwordBytes = Converter.utf8ToBytes(currentPassword);
30
+ const hashedCurrentPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);
31
+ if (!PasswordValidator.comparePasswordHashes(hashedCurrentPassword, user.password)) {
32
+ throw new GeneralError(PasswordHelper.CLASS_NAME, "currentPasswordMismatch");
33
+ }
34
+ }
35
+ const saltBytes = RandomHelper.generate(16);
36
+ const passwordBytes = Converter.utf8ToBytes(newPassword);
37
+ const hashedPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);
38
+ const updatedUser = {
39
+ email: user.email,
40
+ salt: Converter.bytesToBase64(saltBytes),
41
+ password: hashedPassword,
42
+ identity: user.identity,
43
+ organization: user.organization,
44
+ scope: user.scope,
45
+ passwordVersion: (user.passwordVersion ?? 0) + 1
46
+ };
47
+ await userEntityStorage.set(updatedUser);
48
+ await authenticationAuditService?.create({
49
+ actorId: user.email,
50
+ event: AuthAuditEvent.PasswordChanged,
51
+ data: {
52
+ userIdentity: updatedUser.identity,
53
+ organizationIdentity: updatedUser.organization
54
+ }
55
+ });
27
56
  }
28
57
  }
29
58
  //# sourceMappingURL=passwordHelper.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"passwordHelper.js","sourceRoot":"","sources":["../../../src/utils/passwordHelper.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAG3C;;GAEG;AACH,MAAM,OAAO,cAAc;IAC1B;;OAEG;IACI,MAAM,CAAU,UAAU,oBAAoC;IAErE;;;;;OAKG;IACI,MAAM,CAAC,KAAK,CAAC,YAAY,CAC/B,aAAyB,EACzB,SAAqB;QAErB,MAAM,CAAC,UAAU,CAAC,cAAc,CAAC,UAAU,mBAAyB,aAAa,CAAC,CAAC;QACnF,MAAM,CAAC,UAAU,CAAC,cAAc,CAAC,UAAU,eAAqB,SAAS,CAAC,CAAC;QAE3E,MAAM,QAAQ,GAAG,IAAI,UAAU,CAAC,SAAS,CAAC,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;QACzE,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QACxB,QAAQ,CAAC,GAAG,CAAC,aAAa,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;QAE9C,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAEhD,OAAO,SAAS,CAAC,aAAa,CAAC,cAAc,CAAC,CAAC;IAChD,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { Converter, Guards } from \"@twin.org/core\";\nimport { Blake2b } from \"@twin.org/crypto\";\nimport { nameof } from \"@twin.org/nameof\";\n\n/**\n * Helper class for password operations.\n */\nexport class PasswordHelper {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<PasswordHelper>();\n\n\t/**\n\t * Hash the password for the user.\n\t * @param passwordBytes The password bytes.\n\t * @param saltBytes The salt bytes.\n\t * @returns The hashed password.\n\t */\n\tpublic static async hashPassword(\n\t\tpasswordBytes: Uint8Array,\n\t\tsaltBytes: Uint8Array\n\t): Promise<string> {\n\t\tGuards.uint8Array(PasswordHelper.CLASS_NAME, nameof(passwordBytes), passwordBytes);\n\t\tGuards.uint8Array(PasswordHelper.CLASS_NAME, nameof(saltBytes), saltBytes);\n\n\t\tconst combined = new Uint8Array(saltBytes.length + passwordBytes.length);\n\t\tcombined.set(saltBytes);\n\t\tcombined.set(passwordBytes, saltBytes.length);\n\n\t\tconst hashedPassword = Blake2b.sum256(combined);\n\n\t\treturn Converter.bytesToBase64(hashedPassword);\n\t}\n}\n"]}
1
+ {"version":3,"file":"passwordHelper.js","sourceRoot":"","sources":["../../../src/utils/passwordHelper.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAKxE;;GAEG;AACH,MAAM,OAAO,cAAc;IAC1B;;OAEG;IACI,MAAM,CAAU,UAAU,oBAAoC;IAErE;;;;;;;;;;OAUG;IACI,MAAM,CAAC,KAAK,CAAC,cAAc,CACjC,iBAA8D,EAC9D,0BAAqE,EACrE,IAAwB,EACxB,WAAmB,EACnB,eAAwB,EACxB,iBAA0B;QAE1B,iBAAiB,CAAC,gBAAgB,CAAC,WAAW,EAAE;YAC/C,SAAS,EAAE,iBAAiB;SAC5B,CAAC,CAAC;QAEH,IAAI,EAAE,CAAC,WAAW,CAAC,eAAe,CAAC,EAAE,CAAC;YACrC,MAAM,SAAS,GAAG,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACrD,MAAM,aAAa,GAAG,SAAS,CAAC,WAAW,CAAC,eAAe,CAAC,CAAC;YAC7D,MAAM,qBAAqB,GAAG,MAAM,iBAAiB,CAAC,YAAY,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;YAC7F,IAAI,CAAC,iBAAiB,CAAC,qBAAqB,CAAC,qBAAqB,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACpF,MAAM,IAAI,YAAY,CAAC,cAAc,CAAC,UAAU,EAAE,yBAAyB,CAAC,CAAC;YAC9E,CAAC;QACF,CAAC;QAED,MAAM,SAAS,GAAG,YAAY,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAC5C,MAAM,aAAa,GAAG,SAAS,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;QACzD,MAAM,cAAc,GAAG,MAAM,iBAAiB,CAAC,YAAY,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;QAEtF,MAAM,WAAW,GAAuB;YACvC,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,IAAI,EAAE,SAAS,CAAC,aAAa,CAAC,SAAS,CAAC;YACxC,QAAQ,EAAE,cAAc;YACxB,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,eAAe,EAAE,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC,CAAC,GAAG,CAAC;SAChD,CAAC;QAEF,MAAM,iBAAiB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACzC,MAAM,0BAA0B,EAAE,MAAM,CAAC;YACxC,OAAO,EAAE,IAAI,CAAC,KAAK;YACnB,KAAK,EAAE,cAAc,CAAC,eAAe;YACrC,IAAI,EAAE;gBACL,YAAY,EAAE,WAAW,CAAC,QAAQ;gBAClC,oBAAoB,EAAE,WAAW,CAAC,YAAY;aAC9C;SACD,CAAC,CAAC;IACJ,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IAuthenticationAuditComponent } from \"@twin.org/api-auth-entity-storage-models\";\nimport { AuthAuditEvent } from \"@twin.org/api-auth-entity-storage-models\";\nimport { Converter, GeneralError, Is, RandomHelper } from \"@twin.org/core\";\nimport { PasswordGenerator, PasswordValidator } from \"@twin.org/crypto\";\nimport type { IEntityStorageConnector } from \"@twin.org/entity-storage-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport type { AuthenticationUser } from \"../entities/authenticationUser.js\";\n\n/**\n * Helper class for password operations.\n */\nexport class PasswordHelper {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<PasswordHelper>();\n\n\t/**\n\t * Update the password for a user.\n\t * Validates password strength, verifies the current password if provided, then hashes and stores the new password and raises an audit event.\n\t * @param userEntityStorage The entity storage for users.\n\t * @param authenticationAuditService The optional audit service.\n\t * @param user The user whose password is being updated.\n\t * @param newPassword The new password to set.\n\t * @param currentPassword The current password to verify against, if supplied.\n\t * @param minPasswordLength Optional minimum password length for validation.\n\t * @returns A promise that resolves when the new password has been stored and the audit entry recorded.\n\t */\n\tpublic static async updatePassword(\n\t\tuserEntityStorage: IEntityStorageConnector<AuthenticationUser>,\n\t\tauthenticationAuditService: IAuthenticationAuditComponent | undefined,\n\t\tuser: AuthenticationUser,\n\t\tnewPassword: string,\n\t\tcurrentPassword?: string,\n\t\tminPasswordLength?: number\n\t): Promise<void> {\n\t\tPasswordValidator.validatePassword(newPassword, {\n\t\t\tminLength: minPasswordLength\n\t\t});\n\n\t\tif (Is.stringValue(currentPassword)) {\n\t\t\tconst saltBytes = Converter.base64ToBytes(user.salt);\n\t\t\tconst passwordBytes = Converter.utf8ToBytes(currentPassword);\n\t\t\tconst hashedCurrentPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);\n\t\t\tif (!PasswordValidator.comparePasswordHashes(hashedCurrentPassword, user.password)) {\n\t\t\t\tthrow new GeneralError(PasswordHelper.CLASS_NAME, \"currentPasswordMismatch\");\n\t\t\t}\n\t\t}\n\n\t\tconst saltBytes = RandomHelper.generate(16);\n\t\tconst passwordBytes = Converter.utf8ToBytes(newPassword);\n\t\tconst hashedPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);\n\n\t\tconst updatedUser: AuthenticationUser = {\n\t\t\temail: user.email,\n\t\t\tsalt: Converter.bytesToBase64(saltBytes),\n\t\t\tpassword: hashedPassword,\n\t\t\tidentity: user.identity,\n\t\t\torganization: user.organization,\n\t\t\tscope: user.scope,\n\t\t\tpasswordVersion: (user.passwordVersion ?? 0) + 1\n\t\t};\n\n\t\tawait userEntityStorage.set(updatedUser);\n\t\tawait authenticationAuditService?.create({\n\t\t\tactorId: user.email,\n\t\t\tevent: AuthAuditEvent.PasswordChanged,\n\t\t\tdata: {\n\t\t\t\tuserIdentity: updatedUser.identity,\n\t\t\t\torganizationIdentity: updatedUser.organization\n\t\t\t}\n\t\t});\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  // Copyright 2024 IOTA Stiftung.
2
2
  // SPDX-License-Identifier: Apache-2.0.
3
- import { Is, UnauthorizedError } from "@twin.org/core";
3
+ import { Coerce, Is, UnauthorizedError } from "@twin.org/core";
4
4
  import { VaultConnectorHelper } from "@twin.org/vault-models";
5
5
  import { CookieHelper, HeaderHelper, HeaderTypes, Jwt } from "@twin.org/web";
6
6
  /**
@@ -14,22 +14,29 @@ export class TokenHelper {
14
14
  /**
15
15
  * Create a new token.
16
16
  * @param vaultConnector The vault connector.
17
- * @param signingKeyName The signing key name.
17
+ * @param nodeId The node identifier, embedded as the JWT issuer claim.
18
+ * @param signingKeyName The signing key name, embedded as the JWT key identifier.
18
19
  * @param userIdentity The subject for the token.
19
20
  * @param organizationIdentity The organization for the token.
20
21
  * @param tenantId The tenant id for the token.
21
22
  * @param ttlMinutes The time to live for the token in minutes.
23
+ * @param scope The scopes for the token.
24
+ * @param passwordVersion The user's current password version counter, embedded in the token so that a password change invalidates existing tokens.
22
25
  * @returns The new token and its expiry date.
23
26
  */
24
- static async createToken(vaultConnector, signingKeyName, userIdentity, organizationIdentity, tenantId, ttlMinutes) {
27
+ static async createToken(vaultConnector, nodeId, signingKeyName, userIdentity, organizationIdentity, tenantId, ttlMinutes, scope, passwordVersion) {
25
28
  const nowSeconds = Math.trunc(Date.now() / 1000);
26
29
  const ttlSeconds = ttlMinutes * 60;
27
- const jwt = await Jwt.encodeWithSigner({ alg: "EdDSA" }, {
30
+ const vaultKeyName = `${nodeId}/${signingKeyName}`;
31
+ const jwt = await Jwt.encodeWithSigner({ alg: "EdDSA", kid: signingKeyName }, {
32
+ iss: nodeId,
28
33
  sub: userIdentity,
29
34
  org: organizationIdentity,
30
35
  tid: tenantId,
31
- exp: nowSeconds + ttlSeconds
32
- }, async (header, payload) => VaultConnectorHelper.jwtSigner(vaultConnector, signingKeyName, header, payload));
36
+ exp: nowSeconds + ttlSeconds,
37
+ scope,
38
+ pver: passwordVersion
39
+ }, async (header, payload) => VaultConnectorHelper.jwtSigner(vaultConnector, vaultKeyName, header, payload));
33
40
  return {
34
41
  token: jwt,
35
42
  expiry: (nowSeconds + ttlSeconds) * 1000
@@ -38,18 +45,28 @@ export class TokenHelper {
38
45
  /**
39
46
  * Verify the token.
40
47
  * @param vaultConnector The vault connector.
41
- * @param signingKeyName The signing key name.
48
+ * @param nodeId The node identifier, expected to match the JWT issuer claim.
49
+ * @param signingKeyName The signing key name, expected to match the JWT key identifier.
42
50
  * @param token The token to verify.
51
+ * @param requiredScopes The required scopes.
52
+ * @param verifyUser A function to verify the user identity and organization. The password version counter embedded in the token (pver claim) is passed so callers can detect if the password has changed since the token was issued.
43
53
  * @returns The verified details.
44
54
  * @throws UnauthorizedError if the token is missing, invalid or expired.
45
55
  */
46
- static async verify(vaultConnector, signingKeyName, token) {
56
+ static async verify(vaultConnector, nodeId, signingKeyName, token, requiredScopes, verifyUser) {
47
57
  if (!Is.stringValue(token)) {
48
58
  throw new UnauthorizedError(TokenHelper.CLASS_NAME, "missing");
49
59
  }
50
- const decoded = await Jwt.verifyWithVerifier(token, async (t) => VaultConnectorHelper.jwtVerifier(vaultConnector, signingKeyName, t));
60
+ const vaultKeyName = `${nodeId}/${signingKeyName}`;
61
+ const decoded = await Jwt.verifyWithVerifier(token, async (t) => VaultConnectorHelper.jwtVerifier(vaultConnector, vaultKeyName, t));
51
62
  // If some of the header/payload data is not properly populated then it is unauthorized.
52
- if (!Is.stringValue(decoded.payload.sub)) {
63
+ if (decoded.header.kid !== signingKeyName) {
64
+ throw new UnauthorizedError(TokenHelper.CLASS_NAME, "headerKeyIdMismatch");
65
+ }
66
+ else if (decoded.payload.iss !== nodeId) {
67
+ throw new UnauthorizedError(TokenHelper.CLASS_NAME, "payloadIssuerMismatch");
68
+ }
69
+ else if (!Is.stringValue(decoded.payload.sub)) {
53
70
  throw new UnauthorizedError(TokenHelper.CLASS_NAME, "payloadMissingSubject");
54
71
  }
55
72
  else if (!Is.stringValue(decoded.payload.org)) {
@@ -59,6 +76,29 @@ export class TokenHelper {
59
76
  decoded.payload.exp < Math.trunc(Date.now() / 1000)) {
60
77
  throw new UnauthorizedError(TokenHelper.CLASS_NAME, "expired");
61
78
  }
79
+ if (Is.function(verifyUser)) {
80
+ const tid = Coerce.string(decoded.payload.tid);
81
+ const userVerified = await verifyUser(decoded.payload.sub, decoded.payload.org, tid, Coerce.integer(decoded.payload.pver));
82
+ if (!userVerified.includes("user")) {
83
+ throw new UnauthorizedError(TokenHelper.CLASS_NAME, "userNotVerified");
84
+ }
85
+ else if (!userVerified.includes("organization")) {
86
+ throw new UnauthorizedError(TokenHelper.CLASS_NAME, "organizationNotVerified");
87
+ }
88
+ else if (Is.stringValue(tid) && !userVerified.includes("tenant")) {
89
+ throw new UnauthorizedError(TokenHelper.CLASS_NAME, "tenantNotVerified");
90
+ }
91
+ }
92
+ if (Is.arrayValue(requiredScopes)) {
93
+ const tokenScopes = Is.stringValue(decoded.payload.scope)
94
+ ? decoded.payload.scope.split(",")
95
+ : [];
96
+ for (const requiredScope of requiredScopes) {
97
+ if (!tokenScopes.includes(requiredScope)) {
98
+ throw new UnauthorizedError(TokenHelper.CLASS_NAME, "insufficientScopes");
99
+ }
100
+ }
101
+ }
62
102
  return {
63
103
  header: decoded.header,
64
104
  payload: decoded.payload