@twin.org/api-auth-entity-storage-service 0.0.2-next.9 → 0.0.3-next.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/es/entities/authenticationUser.js +53 -0
  2. package/dist/es/entities/authenticationUser.js.map +1 -0
  3. package/dist/es/index.js +18 -0
  4. package/dist/es/index.js.map +1 -0
  5. package/dist/es/models/IAuthHeaderProcessorConfig.js +4 -0
  6. package/dist/es/models/IAuthHeaderProcessorConfig.js.map +1 -0
  7. package/dist/es/models/IAuthHeaderProcessorConstructorOptions.js +2 -0
  8. package/dist/es/models/IAuthHeaderProcessorConstructorOptions.js.map +1 -0
  9. package/dist/es/models/IEntityStorageAuthenticationAdminServiceConfig.js +4 -0
  10. package/dist/es/models/IEntityStorageAuthenticationAdminServiceConfig.js.map +1 -0
  11. package/dist/es/models/IEntityStorageAuthenticationAdminServiceConstructorOptions.js +2 -0
  12. package/dist/es/models/IEntityStorageAuthenticationAdminServiceConstructorOptions.js.map +1 -0
  13. package/dist/es/models/IEntityStorageAuthenticationServiceConfig.js +4 -0
  14. package/dist/es/models/IEntityStorageAuthenticationServiceConfig.js.map +1 -0
  15. package/dist/es/models/IEntityStorageAuthenticationServiceConstructorOptions.js +2 -0
  16. package/dist/es/models/IEntityStorageAuthenticationServiceConstructorOptions.js.map +1 -0
  17. package/dist/es/processors/authHeaderProcessor.js +134 -0
  18. package/dist/es/processors/authHeaderProcessor.js.map +1 -0
  19. package/dist/es/restEntryPoints.js +10 -0
  20. package/dist/es/restEntryPoints.js.map +1 -0
  21. package/dist/es/routes/entityStorageAuthenticationRoutes.js +252 -0
  22. package/dist/es/routes/entityStorageAuthenticationRoutes.js.map +1 -0
  23. package/dist/es/schema.js +11 -0
  24. package/dist/es/schema.js.map +1 -0
  25. package/dist/es/services/entityStorageAuthenticationAdminService.js +146 -0
  26. package/dist/es/services/entityStorageAuthenticationAdminService.js.map +1 -0
  27. package/dist/es/services/entityStorageAuthenticationService.js +141 -0
  28. package/dist/es/services/entityStorageAuthenticationService.js.map +1 -0
  29. package/dist/es/utils/passwordHelper.js +29 -0
  30. package/dist/es/utils/passwordHelper.js.map +1 -0
  31. package/dist/es/utils/tokenHelper.js +94 -0
  32. package/dist/es/utils/tokenHelper.js.map +1 -0
  33. package/dist/types/entities/authenticationUser.d.ts +4 -0
  34. package/dist/types/index.d.ts +15 -15
  35. package/dist/types/models/IAuthHeaderProcessorConstructorOptions.d.ts +1 -1
  36. package/dist/types/models/IEntityStorageAuthenticationAdminServiceConstructorOptions.d.ts +1 -1
  37. package/dist/types/models/IEntityStorageAuthenticationServiceConstructorOptions.d.ts +1 -1
  38. package/dist/types/processors/authHeaderProcessor.d.ts +14 -9
  39. package/dist/types/services/entityStorageAuthenticationAdminService.d.ts +10 -4
  40. package/dist/types/services/entityStorageAuthenticationService.d.ts +9 -5
  41. package/dist/types/utils/passwordHelper.d.ts +4 -0
  42. package/dist/types/utils/tokenHelper.d.ts +8 -2
  43. package/docs/changelog.md +268 -0
  44. package/docs/reference/classes/AuthHeaderProcessor.md +28 -20
  45. package/docs/reference/classes/AuthenticationUser.md +8 -0
  46. package/docs/reference/classes/EntityStorageAuthenticationAdminService.md +25 -5
  47. package/docs/reference/classes/EntityStorageAuthenticationService.md +20 -12
  48. package/docs/reference/classes/PasswordHelper.md +8 -0
  49. package/docs/reference/classes/TokenHelper.md +27 -7
  50. package/locales/en.json +6 -6
  51. package/package.json +29 -11
  52. package/dist/cjs/index.cjs +0 -811
  53. package/dist/esm/index.mjs +0 -797
@@ -1,811 +0,0 @@
1
- 'use strict';
2
-
3
- var entity = require('@twin.org/entity');
4
- var apiModels = require('@twin.org/api-models');
5
- var core = require('@twin.org/core');
6
- var vaultModels = require('@twin.org/vault-models');
7
- var web = require('@twin.org/web');
8
- var entityStorageModels = require('@twin.org/entity-storage-models');
9
- var crypto = require('@twin.org/crypto');
10
-
11
- // Copyright 2024 IOTA Stiftung.
12
- // SPDX-License-Identifier: Apache-2.0.
13
- /**
14
- * Class defining the storage for user login credentials.
15
- */
16
- exports.AuthenticationUser = class AuthenticationUser {
17
- /**
18
- * The user e-mail address.
19
- */
20
- email;
21
- /**
22
- * The encrypted password for the user.
23
- */
24
- password;
25
- /**
26
- * The salt for the password.
27
- */
28
- salt;
29
- /**
30
- * The user identity.
31
- */
32
- identity;
33
- };
34
- __decorate([
35
- entity.property({ type: "string", isPrimary: true }),
36
- __metadata("design:type", String)
37
- ], exports.AuthenticationUser.prototype, "email", void 0);
38
- __decorate([
39
- entity.property({ type: "string" }),
40
- __metadata("design:type", String)
41
- ], exports.AuthenticationUser.prototype, "password", void 0);
42
- __decorate([
43
- entity.property({ type: "string" }),
44
- __metadata("design:type", String)
45
- ], exports.AuthenticationUser.prototype, "salt", void 0);
46
- __decorate([
47
- entity.property({ type: "string" }),
48
- __metadata("design:type", String)
49
- ], exports.AuthenticationUser.prototype, "identity", void 0);
50
- exports.AuthenticationUser = __decorate([
51
- entity.entity()
52
- ], exports.AuthenticationUser);
53
-
54
- // Copyright 2024 IOTA Stiftung.
55
- // SPDX-License-Identifier: Apache-2.0.
56
- /**
57
- * Helper class for token operations.
58
- */
59
- class TokenHelper {
60
- /**
61
- * Runtime name for the class.
62
- * @internal
63
- */
64
- static _CLASS_NAME = "TokenHelper";
65
- /**
66
- * Create a new token.
67
- * @param vaultConnector The vault connector.
68
- * @param signingKeyName The signing key name.
69
- * @param subject The subject for the token.
70
- * @param ttlMinutes The time to live for the token in minutes.
71
- * @returns The new token and its expiry date.
72
- */
73
- static async createToken(vaultConnector, signingKeyName, subject, ttlMinutes) {
74
- const nowSeconds = Math.trunc(Date.now() / 1000);
75
- const ttlSeconds = ttlMinutes * 60;
76
- const jwt = await web.Jwt.encodeWithSigner({ alg: "EdDSA" }, {
77
- sub: subject,
78
- exp: nowSeconds + ttlSeconds
79
- }, async (header, payload) => vaultModels.VaultConnectorHelper.jwtSigner(vaultConnector, signingKeyName, header, payload));
80
- return {
81
- token: jwt,
82
- expiry: (nowSeconds + ttlSeconds) * 1000
83
- };
84
- }
85
- /**
86
- * Verify the token.
87
- * @param vaultConnector The vault connector.
88
- * @param signingKeyName The signing key name.
89
- * @param token The token to verify.
90
- * @returns The verified details.
91
- * @throws UnauthorizedError if the token is missing, invalid or expired.
92
- */
93
- static async verify(vaultConnector, signingKeyName, token) {
94
- if (!core.Is.stringValue(token)) {
95
- throw new core.UnauthorizedError(this._CLASS_NAME, "missing");
96
- }
97
- const decoded = await web.Jwt.verifyWithVerifier(token, async (t) => vaultModels.VaultConnectorHelper.jwtVerifier(vaultConnector, signingKeyName, t));
98
- // If some of the header/payload data is not properly populated then it is unauthorized.
99
- if (!core.Is.stringValue(decoded.payload.sub)) {
100
- throw new core.UnauthorizedError(this._CLASS_NAME, "payloadMissingSubject");
101
- }
102
- else if (!core.Is.empty(decoded.payload?.exp) &&
103
- decoded.payload.exp < Math.trunc(Date.now() / 1000)) {
104
- throw new core.UnauthorizedError(this._CLASS_NAME, "expired");
105
- }
106
- return {
107
- header: decoded.header,
108
- payload: decoded.payload
109
- };
110
- }
111
- /**
112
- * Extract the auth token from the headers, either from the authorization header or the cookie header.
113
- * @param headers The headers to extract the token from.
114
- * @param cookieName The name of the cookie to extract the token from.
115
- * @returns The token if found.
116
- */
117
- static extractTokenFromHeaders(headers, cookieName) {
118
- const authHeader = headers?.[web.HeaderTypes.Authorization];
119
- const cookiesHeader = headers?.[web.HeaderTypes.Cookie];
120
- if (core.Is.string(authHeader) && authHeader.startsWith("Bearer ")) {
121
- return {
122
- token: authHeader.slice(7).trim(),
123
- location: "authorization"
124
- };
125
- }
126
- else if (core.Is.notEmpty(cookiesHeader) && core.Is.stringValue(cookieName)) {
127
- const cookies = core.Is.arrayValue(cookiesHeader) ? cookiesHeader : [cookiesHeader];
128
- for (const cookie of cookies) {
129
- if (core.Is.stringValue(cookie)) {
130
- const accessTokenCookie = cookie
131
- .split(";")
132
- .map(c => c.trim())
133
- .find(c => c.startsWith(cookieName));
134
- if (core.Is.stringValue(accessTokenCookie)) {
135
- return {
136
- token: accessTokenCookie.slice(cookieName.length + 1).trim(),
137
- location: "cookie"
138
- };
139
- }
140
- }
141
- }
142
- }
143
- }
144
- }
145
-
146
- // Copyright 2024 IOTA Stiftung.
147
- // SPDX-License-Identifier: Apache-2.0.
148
- /**
149
- * Handle a JWT token in the authorization header or cookies and validate it to populate request context identity.
150
- */
151
- class AuthHeaderProcessor {
152
- /**
153
- * The default name for the access token as a cookie.
154
- * @internal
155
- */
156
- static DEFAULT_COOKIE_NAME = "access_token";
157
- /**
158
- * Runtime name for the class.
159
- */
160
- CLASS_NAME = "AuthHeaderProcessor";
161
- /**
162
- * The vault for the keys.
163
- * @internal
164
- */
165
- _vaultConnector;
166
- /**
167
- * The name of the key to retrieve from the vault for signing JWT.
168
- * @internal
169
- */
170
- _signingKeyName;
171
- /**
172
- * The name of the cookie to use for the token.
173
- * @internal
174
- */
175
- _cookieName;
176
- /**
177
- * The node identity.
178
- * @internal
179
- */
180
- _nodeIdentity;
181
- /**
182
- * Create a new instance of AuthCookiePreProcessor.
183
- * @param options Options for the processor.
184
- */
185
- constructor(options) {
186
- this._vaultConnector = vaultModels.VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
187
- this._signingKeyName = options?.config?.signingKeyName ?? "auth-signing";
188
- this._cookieName = options?.config?.cookieName ?? AuthHeaderProcessor.DEFAULT_COOKIE_NAME;
189
- }
190
- /**
191
- * The service needs to be started when the application is initialized.
192
- * @param nodeIdentity The identity of the node.
193
- * @param nodeLoggingComponentType The node logging component type.
194
- * @returns Nothing.
195
- */
196
- async start(nodeIdentity, nodeLoggingComponentType) {
197
- core.Guards.string(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
198
- this._nodeIdentity = nodeIdentity;
199
- }
200
- /**
201
- * Pre process the REST request for the specified route.
202
- * @param request The incoming request.
203
- * @param response The outgoing response.
204
- * @param route The route to process.
205
- * @param requestIdentity The identity context for the request.
206
- * @param processorState The state handed through the processors.
207
- */
208
- async pre(request, response, route, requestIdentity, processorState) {
209
- if (!core.Is.empty(route) && !(route.skipAuth ?? false)) {
210
- try {
211
- const tokenAndLocation = TokenHelper.extractTokenFromHeaders(request.headers, this._cookieName);
212
- const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, tokenAndLocation?.token);
213
- requestIdentity.userIdentity = headerAndPayload.payload?.sub;
214
- processorState.authToken = tokenAndLocation?.token;
215
- processorState.authTokenLocation = tokenAndLocation?.location;
216
- }
217
- catch (err) {
218
- const error = core.BaseError.fromError(err);
219
- apiModels.HttpErrorHelper.buildResponse(response, error, web.HttpStatusCode.unauthorized);
220
- }
221
- }
222
- }
223
- /**
224
- * Post process the REST request for the specified route.
225
- * @param request The incoming request.
226
- * @param response The outgoing response.
227
- * @param route The route to process.
228
- * @param requestIdentity The identity context for the request.
229
- * @param processorState The state handed through the processors.
230
- */
231
- async post(request, response, route, requestIdentity, processorState) {
232
- const responseAuthOperation = processorState?.authOperation;
233
- // We don't populate the cookie if the incoming request was from an authorization header.
234
- if (!core.Is.empty(route) &&
235
- core.Is.stringValue(responseAuthOperation) &&
236
- processorState.authTokenLocation !== "authorization") {
237
- if ((responseAuthOperation === "login" || responseAuthOperation === "refresh") &&
238
- core.Is.stringValue(response.body?.token)) {
239
- response.headers ??= {};
240
- response.headers[web.HeaderTypes.SetCookie] =
241
- `${this._cookieName}=${response.body.token}; Secure; HttpOnly; SameSite=None; Path=/`;
242
- delete response.body.token;
243
- }
244
- else if (responseAuthOperation === "logout") {
245
- response.headers ??= {};
246
- response.headers[web.HeaderTypes.SetCookie] =
247
- `${this._cookieName}=; Max-Age=0; Secure; HttpOnly; SameSite=None; Path=/`;
248
- }
249
- }
250
- }
251
- }
252
-
253
- /**
254
- * The source used when communicating about these routes.
255
- */
256
- const ROUTES_SOURCE = "authenticationRoutes";
257
- /**
258
- * The tag to associate with the routes.
259
- */
260
- const tagsAuthentication = [
261
- {
262
- name: "Authentication",
263
- description: "Authentication endpoints for the REST server."
264
- }
265
- ];
266
- /**
267
- * The REST routes for authentication.
268
- * @param baseRouteName Prefix to prepend to the paths.
269
- * @param componentName The name of the component to use in the routes stored in the ComponentFactory.
270
- * @returns The generated routes.
271
- */
272
- function generateRestRoutesAuthentication(baseRouteName, componentName) {
273
- const loginRoute = {
274
- operationId: "authenticationLogin",
275
- summary: "Login to the server",
276
- tag: tagsAuthentication[0].name,
277
- method: "POST",
278
- path: `${baseRouteName}/login`,
279
- handler: async (httpRequestContext, request) => authenticationLogin(httpRequestContext, componentName, request),
280
- requestType: {
281
- type: "ILoginRequest",
282
- examples: [
283
- {
284
- id: "loginRequestExample",
285
- description: "The request to login to the server.",
286
- request: {
287
- body: {
288
- email: "user@example.com",
289
- password: "MyPassword123!"
290
- }
291
- }
292
- }
293
- ]
294
- },
295
- responseType: [
296
- {
297
- type: "ILoginResponse",
298
- examples: [
299
- {
300
- id: "loginResponseExample",
301
- description: "The response for the login request.",
302
- response: {
303
- body: {
304
- token: "eyJhbGciOiJIU...sw5c",
305
- expiry: 1722514341067
306
- }
307
- }
308
- }
309
- ]
310
- },
311
- {
312
- type: "IUnauthorizedResponse"
313
- }
314
- ],
315
- skipAuth: true
316
- };
317
- const logoutRoute = {
318
- operationId: "authenticationLogout",
319
- summary: "Logout from the server",
320
- tag: tagsAuthentication[0].name,
321
- method: "GET",
322
- path: `${baseRouteName}/logout`,
323
- handler: async (httpRequestContext, request) => authenticationLogout(httpRequestContext, componentName, request),
324
- requestType: {
325
- type: "ILogoutRequest",
326
- examples: [
327
- {
328
- id: "logoutRequestExample",
329
- description: "The request to logout from the server.",
330
- request: {
331
- query: {
332
- token: "eyJhbGciOiJIU...sw5c"
333
- }
334
- }
335
- }
336
- ]
337
- },
338
- responseType: [
339
- {
340
- type: "INoContentResponse"
341
- }
342
- ],
343
- skipAuth: true
344
- };
345
- const refreshTokenRoute = {
346
- operationId: "authenticationRefreshToken",
347
- summary: "Refresh an authentication token",
348
- tag: tagsAuthentication[0].name,
349
- method: "GET",
350
- path: `${baseRouteName}/refresh`,
351
- handler: async (httpRequestContext, request) => authenticationRefreshToken(httpRequestContext, componentName, request),
352
- requestType: {
353
- type: "IRefreshTokenRequest",
354
- examples: [
355
- {
356
- id: "refreshTokenRequestExample",
357
- description: "The request to refresh an auth token.",
358
- request: {
359
- query: {
360
- token: "eyJhbGciOiJIU...sw5c"
361
- }
362
- }
363
- }
364
- ]
365
- },
366
- responseType: [
367
- {
368
- type: "IRefreshTokenResponse",
369
- examples: [
370
- {
371
- id: "refreshTokenResponseExample",
372
- description: "The response for the refresh token request.",
373
- response: {
374
- body: {
375
- token: "eyJhbGciOiJIU...sw5c",
376
- expiry: 1722514341067
377
- }
378
- }
379
- }
380
- ]
381
- },
382
- {
383
- type: "IUnauthorizedResponse"
384
- }
385
- ]
386
- };
387
- const updatePasswordRoute = {
388
- operationId: "authenticationUpdatePassword",
389
- summary: "Update the user's password",
390
- tag: tagsAuthentication[0].name,
391
- method: "PUT",
392
- path: `${baseRouteName}/:email/password`,
393
- handler: async (httpRequestContext, request) => authenticationUpdatePassword(httpRequestContext, componentName, request),
394
- requestType: {
395
- type: "IUpdatePasswordRequest",
396
- examples: [
397
- {
398
- id: "updatePasswordRequestExample",
399
- description: "The request to update the user's password.",
400
- request: {
401
- pathParams: {
402
- email: "john:example.com"
403
- },
404
- body: {
405
- currentPassword: "MyNewPassword123!",
406
- newPassword: "MyNewPassword123!"
407
- }
408
- }
409
- }
410
- ]
411
- },
412
- responseType: [
413
- {
414
- type: "INoContentResponse"
415
- },
416
- {
417
- type: "IUnauthorizedResponse"
418
- }
419
- ]
420
- };
421
- return [loginRoute, logoutRoute, refreshTokenRoute, updatePasswordRoute];
422
- }
423
- /**
424
- * Login to the server.
425
- * @param httpRequestContext The request context for the API.
426
- * @param componentName The name of the component to use in the routes.
427
- * @param request The request.
428
- * @returns The response object with additional http response properties.
429
- */
430
- async function authenticationLogin(httpRequestContext, componentName, request) {
431
- core.Guards.object(ROUTES_SOURCE, "request", request);
432
- core.Guards.object(ROUTES_SOURCE, "request.body", request.body);
433
- const component = core.ComponentFactory.get(componentName);
434
- const result = await component.login(request.body.email, request.body.password);
435
- // Need to give a hint to any auth processors about the operation
436
- // in case they need to manipulate the response
437
- httpRequestContext.processorState.authOperation = "login";
438
- return {
439
- body: result
440
- };
441
- }
442
- /**
443
- * Logout from the server.
444
- * @param httpRequestContext The request context for the API.
445
- * @param componentName The name of the component to use in the routes.
446
- * @param request The request.
447
- * @returns The response object with additional http response properties.
448
- */
449
- async function authenticationLogout(httpRequestContext, componentName, request) {
450
- core.Guards.object(ROUTES_SOURCE, "request", request);
451
- const component = core.ComponentFactory.get(componentName);
452
- await component.logout(request.query?.token);
453
- // Need to give a hint to any auth processors about the operation
454
- // in case they need to manipulate the response
455
- httpRequestContext.processorState.authOperation = "logout";
456
- return {
457
- statusCode: web.HttpStatusCode.noContent
458
- };
459
- }
460
- /**
461
- * Refresh the login token.
462
- * @param httpRequestContext The request context for the API.
463
- * @param componentName The name of the component to use in the routes.
464
- * @param request The request.
465
- * @returns The response object with additional http response properties.
466
- */
467
- async function authenticationRefreshToken(httpRequestContext, componentName, request) {
468
- core.Guards.object(ROUTES_SOURCE, "request", request);
469
- const component = core.ComponentFactory.get(componentName);
470
- // If the token is not in the query, then maybe an auth processor has extracted it
471
- // and stored it in the processor state
472
- const token = request.query?.token ?? httpRequestContext.processorState.authToken;
473
- const result = await component.refresh(token);
474
- // Need to give a hint to any auth processors about the operation
475
- // in case they need to manipulate the response
476
- httpRequestContext.processorState.authOperation = "refresh";
477
- return {
478
- body: result
479
- };
480
- }
481
- /**
482
- * Update the user's password.
483
- * @param httpRequestContext The request context for the API.
484
- * @param componentName The name of the component to use in the routes.
485
- * @param request The request.
486
- * @returns The response object with additional http response properties.
487
- */
488
- async function authenticationUpdatePassword(httpRequestContext, componentName, request) {
489
- core.Guards.object(ROUTES_SOURCE, "request", request);
490
- core.Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
491
- core.Guards.object(ROUTES_SOURCE, "request.body", request.body);
492
- const component = core.ComponentFactory.get(componentName);
493
- await component.updatePassword(request.pathParams.email, request.body.currentPassword, request.body.newPassword);
494
- return {
495
- statusCode: web.HttpStatusCode.noContent
496
- };
497
- }
498
-
499
- const restEntryPoints = [
500
- {
501
- name: "authentication",
502
- defaultBaseRoute: "authentication",
503
- tags: tagsAuthentication,
504
- generateRoutes: generateRestRoutesAuthentication
505
- }
506
- ];
507
-
508
- // Copyright 2024 IOTA Stiftung.
509
- // SPDX-License-Identifier: Apache-2.0.
510
- /**
511
- * Initialize the schema for the authentication service.
512
- */
513
- function initSchema() {
514
- entity.EntitySchemaFactory.register("AuthenticationUser", () => entity.EntitySchemaHelper.getSchema(exports.AuthenticationUser));
515
- }
516
-
517
- // Copyright 2024 IOTA Stiftung.
518
- // SPDX-License-Identifier: Apache-2.0.
519
- /**
520
- * Helper class for password operations.
521
- */
522
- class PasswordHelper {
523
- /**
524
- * Runtime name for the class.
525
- * @internal
526
- */
527
- static _CLASS_NAME = "PasswordHelper";
528
- /**
529
- * Hash the password for the user.
530
- * @param passwordBytes The password bytes.
531
- * @param saltBytes The salt bytes.
532
- * @returns The hashed password.
533
- */
534
- static async hashPassword(passwordBytes, saltBytes) {
535
- core.Guards.uint8Array(PasswordHelper._CLASS_NAME, "passwordBytes", passwordBytes);
536
- core.Guards.uint8Array(PasswordHelper._CLASS_NAME, "saltBytes", saltBytes);
537
- const combined = new Uint8Array(saltBytes.length + passwordBytes.length);
538
- combined.set(saltBytes);
539
- combined.set(passwordBytes, saltBytes.length);
540
- const hashedPassword = crypto.Blake2b.sum256(combined);
541
- return core.Converter.bytesToBase64(hashedPassword);
542
- }
543
- }
544
-
545
- /**
546
- * Implementation of the authentication component using entity storage.
547
- */
548
- class EntityStorageAuthenticationAdminService {
549
- /**
550
- * The minimum password length.
551
- * @internal
552
- */
553
- static _DEFAULT_MIN_PASSWORD_LENGTH = 8;
554
- /**
555
- * Runtime name for the class.
556
- */
557
- CLASS_NAME = "EntityStorageAuthenticationAdminService";
558
- /**
559
- * The entity storage for users.
560
- * @internal
561
- */
562
- _userEntityStorage;
563
- /**
564
- * The minimum password length.
565
- * @internal
566
- */
567
- _minPasswordLength;
568
- /**
569
- * Create a new instance of EntityStorageAuthentication.
570
- * @param options The dependencies for the identity connector.
571
- */
572
- constructor(options) {
573
- this._userEntityStorage = entityStorageModels.EntityStorageConnectorFactory.get(options?.userEntityStorageType ?? "authentication-user");
574
- this._minPasswordLength =
575
- options?.config?.minPasswordLength ??
576
- EntityStorageAuthenticationAdminService._DEFAULT_MIN_PASSWORD_LENGTH;
577
- }
578
- /**
579
- * Create a login for the user.
580
- * @param email The email address for the user.
581
- * @param password The password for the user.
582
- * @param identity The DID to associate with the account.
583
- * @returns Nothing.
584
- */
585
- async create(email, password, identity) {
586
- core.Guards.stringValue(this.CLASS_NAME, "email", email);
587
- core.Guards.stringValue(this.CLASS_NAME, "password", password);
588
- try {
589
- if (password.length < this._minPasswordLength) {
590
- throw new core.GeneralError(this.CLASS_NAME, "passwordTooShort", {
591
- minLength: this._minPasswordLength
592
- });
593
- }
594
- const user = await this._userEntityStorage.get(email);
595
- if (user) {
596
- throw new core.GeneralError(this.CLASS_NAME, "userExists");
597
- }
598
- const saltBytes = core.RandomHelper.generate(16);
599
- const passwordBytes = core.Converter.utf8ToBytes(password);
600
- const hashedPassword = await PasswordHelper.hashPassword(passwordBytes, saltBytes);
601
- const newUser = {
602
- email,
603
- salt: core.Converter.bytesToBase64(saltBytes),
604
- password: hashedPassword,
605
- identity
606
- };
607
- await this._userEntityStorage.set(newUser);
608
- }
609
- catch (error) {
610
- throw new core.GeneralError(this.CLASS_NAME, "createUserFailed", undefined, error);
611
- }
612
- }
613
- /**
614
- * Remove the current user.
615
- * @param email The email address of the user to remove.
616
- * @returns Nothing.
617
- */
618
- async remove(email) {
619
- core.Guards.stringValue(this.CLASS_NAME, "email", email);
620
- try {
621
- const user = await this._userEntityStorage.get(email);
622
- if (!user) {
623
- throw new core.NotFoundError(this.CLASS_NAME, "userNotFound", email);
624
- }
625
- await this._userEntityStorage.remove(email);
626
- }
627
- catch (error) {
628
- throw new core.GeneralError(this.CLASS_NAME, "removeUserFailed", undefined, error);
629
- }
630
- }
631
- /**
632
- * Update the user's password.
633
- * @param email The email address of the user to update.
634
- * @param newPassword The new password for the user.
635
- * @param currentPassword The current password, optional, if supplied will check against existing.
636
- * @returns Nothing.
637
- */
638
- async updatePassword(email, newPassword, currentPassword) {
639
- core.Guards.stringValue(this.CLASS_NAME, "email", email);
640
- core.Guards.stringValue(this.CLASS_NAME, "newPassword", newPassword);
641
- try {
642
- if (newPassword.length < this._minPasswordLength) {
643
- throw new core.GeneralError(this.CLASS_NAME, "passwordTooShort", {
644
- minLength: this._minPasswordLength
645
- });
646
- }
647
- const user = await this._userEntityStorage.get(email);
648
- if (!user) {
649
- throw new core.NotFoundError(this.CLASS_NAME, "userNotFound", email);
650
- }
651
- if (core.Is.stringValue(currentPassword)) {
652
- const saltBytes = core.Converter.base64ToBytes(user.salt);
653
- const passwordBytes = core.Converter.utf8ToBytes(currentPassword);
654
- const hashedPassword = await PasswordHelper.hashPassword(passwordBytes, saltBytes);
655
- if (hashedPassword !== user.password) {
656
- throw new core.GeneralError(this.CLASS_NAME, "currentPasswordMismatch");
657
- }
658
- }
659
- const saltBytes = core.RandomHelper.generate(16);
660
- const passwordBytes = core.Converter.utf8ToBytes(newPassword);
661
- const hashedPassword = await PasswordHelper.hashPassword(passwordBytes, saltBytes);
662
- const updatedUser = {
663
- email,
664
- salt: core.Converter.bytesToBase64(saltBytes),
665
- password: hashedPassword,
666
- identity: user.identity
667
- };
668
- await this._userEntityStorage.set(updatedUser);
669
- }
670
- catch (error) {
671
- throw new core.GeneralError(this.CLASS_NAME, "updatePasswordFailed", undefined, error);
672
- }
673
- }
674
- }
675
-
676
- /**
677
- * Implementation of the authentication component using entity storage.
678
- */
679
- class EntityStorageAuthenticationService {
680
- /**
681
- * Default TTL in minutes.
682
- * @internal
683
- */
684
- static _DEFAULT_TTL_MINUTES = 60;
685
- /**
686
- * Runtime name for the class.
687
- */
688
- CLASS_NAME = "EntityStorageAuthenticationService";
689
- /**
690
- * The user admin service.
691
- * @internal
692
- */
693
- _authenticationAdminService;
694
- /**
695
- * The entity storage for users.
696
- * @internal
697
- */
698
- _userEntityStorage;
699
- /**
700
- * The vault for the keys.
701
- * @internal
702
- */
703
- _vaultConnector;
704
- /**
705
- * The name of the key to retrieve from the vault for signing JWT.
706
- * @internal
707
- */
708
- _signingKeyName;
709
- /**
710
- * The default TTL for the token.
711
- * @internal
712
- */
713
- _defaultTtlMinutes;
714
- /**
715
- * The node identity.
716
- * @internal
717
- */
718
- _nodeIdentity;
719
- /**
720
- * Create a new instance of EntityStorageAuthentication.
721
- * @param options The dependencies for the identity connector.
722
- */
723
- constructor(options) {
724
- this._userEntityStorage = entityStorageModels.EntityStorageConnectorFactory.get(options?.userEntityStorageType ?? "authentication-user");
725
- this._vaultConnector = vaultModels.VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
726
- this._authenticationAdminService = core.ComponentFactory.get(options?.authenticationAdminServiceType ?? "authentication-admin");
727
- this._signingKeyName = options?.config?.signingKeyName ?? "auth-signing";
728
- this._defaultTtlMinutes =
729
- options?.config?.defaultTtlMinutes ?? EntityStorageAuthenticationService._DEFAULT_TTL_MINUTES;
730
- }
731
- /**
732
- * The service needs to be started when the application is initialized.
733
- * @param nodeIdentity The identity of the node.
734
- * @param nodeLoggingComponentType The node logging component type.
735
- * @returns Nothing.
736
- */
737
- async start(nodeIdentity, nodeLoggingComponentType) {
738
- core.Guards.string(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
739
- this._nodeIdentity = nodeIdentity;
740
- }
741
- /**
742
- * Perform a login for the user.
743
- * @param email The email address for the user.
744
- * @param password The password for the user.
745
- * @returns The authentication token for the user, if it uses a mechanism with public access.
746
- */
747
- async login(email, password) {
748
- core.Guards.stringValue(this.CLASS_NAME, "email", email);
749
- core.Guards.stringValue(this.CLASS_NAME, "password", password);
750
- try {
751
- const user = await this._userEntityStorage.get(email);
752
- if (!user) {
753
- throw new core.GeneralError(this.CLASS_NAME, "userNotFound");
754
- }
755
- const saltBytes = core.Converter.base64ToBytes(user.salt);
756
- const passwordBytes = core.Converter.utf8ToBytes(password);
757
- const hashedPassword = await PasswordHelper.hashPassword(passwordBytes, saltBytes);
758
- if (hashedPassword !== user.password) {
759
- throw new core.GeneralError(this.CLASS_NAME, "passwordMismatch");
760
- }
761
- const tokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, user.identity, this._defaultTtlMinutes);
762
- return tokenAndExpiry;
763
- }
764
- catch (error) {
765
- throw new core.UnauthorizedError(this.CLASS_NAME, "loginFailed", error);
766
- }
767
- }
768
- /**
769
- * Logout the current user.
770
- * @param token The token to logout, if it uses a mechanism with public access.
771
- * @returns Nothing.
772
- */
773
- async logout(token) {
774
- // Nothing to do here.
775
- }
776
- /**
777
- * Refresh the token.
778
- * @param token The token to refresh, if it uses a mechanism with public access.
779
- * @returns The refreshed token, if it uses a mechanism with public access.
780
- */
781
- async refresh(token) {
782
- // If the verify fails on the current token then it will throw an exception.
783
- const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, token);
784
- const refreshTokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, headerAndPayload.payload.sub ?? "", this._defaultTtlMinutes);
785
- return refreshTokenAndExpiry;
786
- }
787
- /**
788
- * Update the user's password.
789
- * @param email The email address of the user to update.
790
- * @param currentPassword The current password for the user.
791
- * @param newPassword The new password for the user.
792
- * @returns Nothing.
793
- */
794
- async updatePassword(email, currentPassword, newPassword) {
795
- return this._authenticationAdminService.updatePassword(email, newPassword, currentPassword);
796
- }
797
- }
798
-
799
- exports.AuthHeaderProcessor = AuthHeaderProcessor;
800
- exports.EntityStorageAuthenticationAdminService = EntityStorageAuthenticationAdminService;
801
- exports.EntityStorageAuthenticationService = EntityStorageAuthenticationService;
802
- exports.PasswordHelper = PasswordHelper;
803
- exports.TokenHelper = TokenHelper;
804
- exports.authenticationLogin = authenticationLogin;
805
- exports.authenticationLogout = authenticationLogout;
806
- exports.authenticationRefreshToken = authenticationRefreshToken;
807
- exports.authenticationUpdatePassword = authenticationUpdatePassword;
808
- exports.generateRestRoutesAuthentication = generateRestRoutesAuthentication;
809
- exports.initSchema = initSchema;
810
- exports.restEntryPoints = restEntryPoints;
811
- exports.tagsAuthentication = tagsAuthentication;