@twin.org/api-auth-entity-storage-service 0.0.1-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 (34) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -0
  3. package/dist/cjs/index.cjs +621 -0
  4. package/dist/esm/index.mjs +609 -0
  5. package/dist/types/entities/authenticationUser.d.ts +21 -0
  6. package/dist/types/index.d.ts +10 -0
  7. package/dist/types/models/IAuthHeaderProcessorConfig.d.ts +15 -0
  8. package/dist/types/models/IEntityStorageAuthenticationServiceConfig.d.ts +15 -0
  9. package/dist/types/processors/authHeaderProcessor.d.ts +50 -0
  10. package/dist/types/restEntryPoints.d.ts +2 -0
  11. package/dist/types/routes/entityStorageAuthenticationRoutes.d.ts +37 -0
  12. package/dist/types/schema.d.ts +4 -0
  13. package/dist/types/services/entityStorageAuthenticationService.d.ts +55 -0
  14. package/dist/types/utils/passwordHelper.d.ts +12 -0
  15. package/dist/types/utils/tokenHelper.d.ts +41 -0
  16. package/docs/changelog.md +5 -0
  17. package/docs/examples.md +1 -0
  18. package/docs/reference/classes/AuthHeaderProcessor.md +149 -0
  19. package/docs/reference/classes/AuthenticationUser.md +45 -0
  20. package/docs/reference/classes/EntityStorageAuthenticationService.md +169 -0
  21. package/docs/reference/classes/PasswordHelper.md +37 -0
  22. package/docs/reference/classes/TokenHelper.md +117 -0
  23. package/docs/reference/functions/authenticationLogin.md +25 -0
  24. package/docs/reference/functions/authenticationLogout.md +25 -0
  25. package/docs/reference/functions/authenticationRefreshToken.md +25 -0
  26. package/docs/reference/functions/generateRestRoutesAuthentication.md +21 -0
  27. package/docs/reference/functions/initSchema.md +9 -0
  28. package/docs/reference/index.md +27 -0
  29. package/docs/reference/interfaces/IAuthHeaderProcessorConfig.md +31 -0
  30. package/docs/reference/interfaces/IEntityStorageAuthenticationServiceConfig.md +31 -0
  31. package/docs/reference/variables/restEntryPoints.md +3 -0
  32. package/docs/reference/variables/tagsAuthentication.md +5 -0
  33. package/locales/en.json +18 -0
  34. package/package.json +46 -0
@@ -0,0 +1,609 @@
1
+ import { property, entity, EntitySchemaFactory, EntitySchemaHelper } from '@twin.org/entity';
2
+ import { HttpErrorHelper } from '@twin.org/api-models';
3
+ import { Is, UnauthorizedError, Guards, BaseError, ComponentFactory, Converter, GeneralError } from '@twin.org/core';
4
+ import { VaultConnectorFactory } from '@twin.org/vault-models';
5
+ import { Jwt, JwtAlgorithms, HeaderTypes, HttpStatusCode } from '@twin.org/web';
6
+ import { EntityStorageConnectorFactory } from '@twin.org/entity-storage-models';
7
+ import { Blake2b } from '@twin.org/crypto';
8
+
9
+ // Copyright 2024 IOTA Stiftung.
10
+ // SPDX-License-Identifier: Apache-2.0.
11
+ /**
12
+ * Class defining the storage for user login credentials.
13
+ */
14
+ let AuthenticationUser = class AuthenticationUser {
15
+ /**
16
+ * The user e-mail address.
17
+ */
18
+ email;
19
+ /**
20
+ * The encrypted password for the user.
21
+ */
22
+ password;
23
+ /**
24
+ * The salt for the password.
25
+ */
26
+ salt;
27
+ /**
28
+ * The user identity.
29
+ */
30
+ identity;
31
+ };
32
+ __decorate([
33
+ property({ type: "string", isPrimary: true }),
34
+ __metadata("design:type", String)
35
+ ], AuthenticationUser.prototype, "email", void 0);
36
+ __decorate([
37
+ property({ type: "string" }),
38
+ __metadata("design:type", String)
39
+ ], AuthenticationUser.prototype, "password", void 0);
40
+ __decorate([
41
+ property({ type: "string" }),
42
+ __metadata("design:type", String)
43
+ ], AuthenticationUser.prototype, "salt", void 0);
44
+ __decorate([
45
+ property({ type: "string" }),
46
+ __metadata("design:type", String)
47
+ ], AuthenticationUser.prototype, "identity", void 0);
48
+ AuthenticationUser = __decorate([
49
+ entity()
50
+ ], AuthenticationUser);
51
+
52
+ // Copyright 2024 IOTA Stiftung.
53
+ // SPDX-License-Identifier: Apache-2.0.
54
+ /**
55
+ * Helper class for token operations.
56
+ */
57
+ class TokenHelper {
58
+ /**
59
+ * Runtime name for the class.
60
+ * @internal
61
+ */
62
+ static _CLASS_NAME = "TokenHelper";
63
+ /**
64
+ * Create a new token.
65
+ * @param vaultConnector The vault connector.
66
+ * @param signingKeyName The signing key name.
67
+ * @param subject The subject for the token.
68
+ * @param ttlMinutes The time to live for the token in minutes.
69
+ * @returns The new token and its expiry date.
70
+ */
71
+ static async createToken(vaultConnector, signingKeyName, subject, ttlMinutes) {
72
+ // Verify was a success so we can now generate a new token.
73
+ const nowSeconds = Math.trunc(Date.now() / 1000);
74
+ const ttlSeconds = ttlMinutes * 60;
75
+ const jwt = await Jwt.encodeWithSigner({ alg: JwtAlgorithms.EdDSA }, {
76
+ sub: subject,
77
+ exp: nowSeconds + ttlSeconds
78
+ }, async (alg, key, payload) => vaultConnector.sign(signingKeyName, payload));
79
+ return {
80
+ token: jwt,
81
+ expiry: (nowSeconds + ttlSeconds) * 1000
82
+ };
83
+ }
84
+ /**
85
+ * Verify the token.
86
+ * @param vaultConnector The vault connector.
87
+ * @param signingKeyName The signing key name.
88
+ * @param token The token to verify.
89
+ * @returns The verified details.
90
+ * @throws UnauthorizedError if the token is missing, invalid or expired.
91
+ */
92
+ static async verify(vaultConnector, signingKeyName, token) {
93
+ if (!Is.stringValue(token)) {
94
+ throw new UnauthorizedError(this._CLASS_NAME, "missing");
95
+ }
96
+ const decoded = await Jwt.verifyWithVerifier(token, async (alg, key, payload, signature) => vaultConnector.verify(signingKeyName, payload, signature));
97
+ // If the signature validation failed or some of the header/payload data
98
+ // is not properly populated then it is unauthorized.
99
+ if (!decoded.verified ||
100
+ !Is.object(decoded.header) ||
101
+ !Is.object(decoded.payload) ||
102
+ !Is.stringValue(decoded.payload.sub)) {
103
+ throw new UnauthorizedError(this._CLASS_NAME, "invalidToken");
104
+ }
105
+ else if (!Is.empty(decoded.payload?.exp) &&
106
+ decoded.payload.exp < Math.trunc(Date.now() / 1000)) {
107
+ throw new UnauthorizedError(this._CLASS_NAME, "expired");
108
+ }
109
+ return {
110
+ header: decoded.header,
111
+ payload: decoded.payload
112
+ };
113
+ }
114
+ /**
115
+ * Extract the auth token from the headers, either from the authorization header or the cookie header.
116
+ * @param headers The headers to extract the token from.
117
+ * @param cookieName The name of the cookie to extract the token from.
118
+ * @returns The token if found.
119
+ */
120
+ static extractTokenFromHeaders(headers, cookieName) {
121
+ const authHeader = headers?.[HeaderTypes.Authorization];
122
+ const cookiesHeader = headers?.[HeaderTypes.Cookie];
123
+ if (Is.string(authHeader) && authHeader.startsWith("Bearer ")) {
124
+ return {
125
+ token: authHeader.slice(7).trim(),
126
+ location: "authorization"
127
+ };
128
+ }
129
+ else if (Is.notEmpty(cookiesHeader) && Is.stringValue(cookieName)) {
130
+ const cookies = Is.arrayValue(cookiesHeader) ? cookiesHeader : [cookiesHeader];
131
+ for (const cookie of cookies) {
132
+ if (Is.stringValue(cookie)) {
133
+ const accessTokenCookie = cookie
134
+ .split(";")
135
+ .map(c => c.trim())
136
+ .find(c => c.startsWith(cookieName));
137
+ if (Is.stringValue(accessTokenCookie)) {
138
+ return {
139
+ token: accessTokenCookie.slice(cookieName.length + 1).trim(),
140
+ location: "cookie"
141
+ };
142
+ }
143
+ }
144
+ }
145
+ }
146
+ }
147
+ }
148
+
149
+ // Copyright 2024 IOTA Stiftung.
150
+ // SPDX-License-Identifier: Apache-2.0.
151
+ /**
152
+ * Handle a JWT token in the authorization header or cookies and validate it to populate request context identity.
153
+ */
154
+ class AuthHeaderProcessor {
155
+ /**
156
+ * The default name for the access token as a cookie.
157
+ * @internal
158
+ */
159
+ static DEFAULT_COOKIE_NAME = "access_token";
160
+ /**
161
+ * Runtime name for the class.
162
+ */
163
+ CLASS_NAME = "AuthHeaderProcessor";
164
+ /**
165
+ * The vault for the keys.
166
+ * @internal
167
+ */
168
+ _vaultConnector;
169
+ /**
170
+ * The name of the key to retrieve from the vault for signing JWT.
171
+ * @internal
172
+ */
173
+ _signingKeyName;
174
+ /**
175
+ * The name of the cookie to use for the token.
176
+ * @internal
177
+ */
178
+ _cookieName;
179
+ /**
180
+ * The node identity.
181
+ * @internal
182
+ */
183
+ _nodeIdentity;
184
+ /**
185
+ * Create a new instance of AuthCookiePreProcessor.
186
+ * @param options Options for the processor.
187
+ * @param options.vaultConnectorType The vault for the private keys, defaults to "vault".
188
+ * @param options.config The configuration for the processor.
189
+ */
190
+ constructor(options) {
191
+ this._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
192
+ this._signingKeyName = options?.config?.signingKeyName ?? "auth-signing";
193
+ this._cookieName = options?.config?.cookieName ?? AuthHeaderProcessor.DEFAULT_COOKIE_NAME;
194
+ }
195
+ /**
196
+ * The service needs to be started when the application is initialized.
197
+ * @param nodeIdentity The identity of the node.
198
+ * @param nodeLoggingConnectorType The node logging connector type, defaults to "node-logging".
199
+ * @returns Nothing.
200
+ */
201
+ async start(nodeIdentity, nodeLoggingConnectorType) {
202
+ Guards.string(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
203
+ this._nodeIdentity = nodeIdentity;
204
+ }
205
+ /**
206
+ * Pre process the REST request for the specified route.
207
+ * @param request The incoming request.
208
+ * @param response The outgoing response.
209
+ * @param route The route to process.
210
+ * @param requestIdentity The identity context for the request.
211
+ * @param processorState The state handed through the processors.
212
+ */
213
+ async pre(request, response, route, requestIdentity, processorState) {
214
+ if (!Is.empty(route) && !(route.skipAuth ?? false)) {
215
+ try {
216
+ const tokenAndLocation = TokenHelper.extractTokenFromHeaders(request.headers, this._cookieName);
217
+ const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, tokenAndLocation?.token);
218
+ requestIdentity.userIdentity = headerAndPayload.payload?.sub;
219
+ processorState.authToken = tokenAndLocation?.token;
220
+ processorState.authTokenLocation = tokenAndLocation?.location;
221
+ }
222
+ catch (err) {
223
+ const error = BaseError.fromError(err);
224
+ HttpErrorHelper.buildResponse(response, error, HttpStatusCode.unauthorized);
225
+ }
226
+ }
227
+ }
228
+ /**
229
+ * Post process the REST request for the specified route.
230
+ * @param request The incoming request.
231
+ * @param response The outgoing response.
232
+ * @param route The route to process.
233
+ * @param requestIdentity The identity context for the request.
234
+ * @param processorState The state handed through the processors.
235
+ */
236
+ async post(request, response, route, requestIdentity, processorState) {
237
+ const responseAuthOperation = processorState?.authOperation;
238
+ // We don't populate the cookie if the incoming request was from an authorization header.
239
+ if (!Is.empty(route) &&
240
+ Is.stringValue(responseAuthOperation) &&
241
+ processorState.authTokenLocation !== "authorization") {
242
+ if ((responseAuthOperation === "login" || responseAuthOperation === "refresh") &&
243
+ Is.stringValue(response.body?.token)) {
244
+ response.headers ??= {};
245
+ response.headers["Set-Cookie"] =
246
+ `${this._cookieName}=${response.body.token}; Secure; HttpOnly; SameSite=None; Path=/`;
247
+ delete response.body.token;
248
+ }
249
+ else if (responseAuthOperation === "logout") {
250
+ response.headers ??= {};
251
+ response.headers["Set-Cookie"] =
252
+ `${this._cookieName}=; Max-Age=0; Secure; HttpOnly; SameSite=None; Path=/`;
253
+ }
254
+ }
255
+ }
256
+ }
257
+
258
+ /**
259
+ * The source used when communicating about these routes.
260
+ */
261
+ const ROUTES_SOURCE = "authenticationRoutes";
262
+ /**
263
+ * The tag to associate with the routes.
264
+ */
265
+ const tagsAuthentication = [
266
+ {
267
+ name: "Authentication",
268
+ description: "Authentication endpoints for the REST server."
269
+ }
270
+ ];
271
+ /**
272
+ * The REST routes for authentication.
273
+ * @param baseRouteName Prefix to prepend to the paths.
274
+ * @param componentName The name of the component to use in the routes stored in the ComponentFactory.
275
+ * @returns The generated routes.
276
+ */
277
+ function generateRestRoutesAuthentication(baseRouteName, componentName) {
278
+ const loginRoute = {
279
+ operationId: "authenticationLogin",
280
+ summary: "Login to the server",
281
+ tag: tagsAuthentication[0].name,
282
+ method: "POST",
283
+ path: `${baseRouteName}/login`,
284
+ handler: async (httpRequestContext, request) => authenticationLogin(httpRequestContext, componentName, request),
285
+ requestType: {
286
+ type: "ILoginRequest",
287
+ examples: [
288
+ {
289
+ id: "loginRequestExample",
290
+ description: "The request to login to the server.",
291
+ request: {
292
+ body: {
293
+ email: "user@example.com",
294
+ password: "MyPassword123!"
295
+ }
296
+ }
297
+ }
298
+ ]
299
+ },
300
+ responseType: [
301
+ {
302
+ type: "ILoginResponse",
303
+ examples: [
304
+ {
305
+ id: "loginResponseExample",
306
+ description: "The response for the login request.",
307
+ response: {
308
+ body: {
309
+ token: "eyJhbGciOiJIU...sw5c",
310
+ expiry: 1722514341067
311
+ }
312
+ }
313
+ }
314
+ ]
315
+ },
316
+ {
317
+ type: "IUnauthorizedResponse"
318
+ }
319
+ ],
320
+ skipAuth: true
321
+ };
322
+ const logoutRoute = {
323
+ operationId: "authenticationLogout",
324
+ summary: "Logout from the server",
325
+ tag: tagsAuthentication[0].name,
326
+ method: "GET",
327
+ path: `${baseRouteName}/logout`,
328
+ handler: async (httpRequestContext, request) => authenticationLogout(httpRequestContext, componentName, request),
329
+ requestType: {
330
+ type: "ILogoutRequest",
331
+ examples: [
332
+ {
333
+ id: "logoutRequestExample",
334
+ description: "The request to logout from the server.",
335
+ request: {
336
+ query: {
337
+ token: "eyJhbGciOiJIU...sw5c"
338
+ }
339
+ }
340
+ }
341
+ ]
342
+ },
343
+ responseType: [
344
+ {
345
+ type: "INoContentResponse"
346
+ }
347
+ ],
348
+ skipAuth: true
349
+ };
350
+ const refreshTokenRoute = {
351
+ operationId: "authenticationRefreshToken",
352
+ summary: "Refresh an authentication token",
353
+ tag: tagsAuthentication[0].name,
354
+ method: "GET",
355
+ path: `${baseRouteName}/refresh`,
356
+ handler: async (httpRequestContext, request) => authenticationRefreshToken(httpRequestContext, componentName, request),
357
+ requestType: {
358
+ type: "IRefreshTokenRequest",
359
+ examples: [
360
+ {
361
+ id: "refreshTokenRequestExample",
362
+ description: "The request to refresh an auth token.",
363
+ request: {
364
+ query: {
365
+ token: "eyJhbGciOiJIU...sw5c"
366
+ }
367
+ }
368
+ }
369
+ ]
370
+ },
371
+ responseType: [
372
+ {
373
+ type: "IRefreshTokenResponse",
374
+ examples: [
375
+ {
376
+ id: "refreshTokenResponseExample",
377
+ description: "The response for the refresh token request.",
378
+ response: {
379
+ body: {
380
+ token: "eyJhbGciOiJIU...sw5c",
381
+ expiry: 1722514341067
382
+ }
383
+ }
384
+ }
385
+ ]
386
+ },
387
+ {
388
+ type: "IUnauthorizedResponse"
389
+ }
390
+ ]
391
+ };
392
+ return [loginRoute, logoutRoute, refreshTokenRoute];
393
+ }
394
+ /**
395
+ * Login to the server.
396
+ * @param httpRequestContext The request context for the API.
397
+ * @param componentName The name of the component to use in the routes.
398
+ * @param request The request.
399
+ * @returns The response object with additional http response properties.
400
+ */
401
+ async function authenticationLogin(httpRequestContext, componentName, request) {
402
+ Guards.object(ROUTES_SOURCE, "request", request);
403
+ Guards.object(ROUTES_SOURCE, "request.body", request.body);
404
+ const component = ComponentFactory.get(componentName);
405
+ const result = await component.login(request.body.email, request.body.password);
406
+ // Need to give a hint to any auth processors about the operation
407
+ // in case they need to manipulate the response
408
+ httpRequestContext.processorState.authOperation = "login";
409
+ return {
410
+ body: result
411
+ };
412
+ }
413
+ /**
414
+ * Logout from the server.
415
+ * @param httpRequestContext The request context for the API.
416
+ * @param componentName The name of the component to use in the routes.
417
+ * @param request The request.
418
+ * @returns The response object with additional http response properties.
419
+ */
420
+ async function authenticationLogout(httpRequestContext, componentName, request) {
421
+ Guards.object(ROUTES_SOURCE, "request", request);
422
+ const component = ComponentFactory.get(componentName);
423
+ await component.logout(request.query?.token);
424
+ // Need to give a hint to any auth processors about the operation
425
+ // in case they need to manipulate the response
426
+ httpRequestContext.processorState.authOperation = "logout";
427
+ return {
428
+ statusCode: HttpStatusCode.noContent
429
+ };
430
+ }
431
+ /**
432
+ * Refresh the login token.
433
+ * @param httpRequestContext The request context for the API.
434
+ * @param componentName The name of the component to use in the routes.
435
+ * @param request The request.
436
+ * @returns The response object with additional http response properties.
437
+ */
438
+ async function authenticationRefreshToken(httpRequestContext, componentName, request) {
439
+ Guards.object(ROUTES_SOURCE, "request", request);
440
+ const component = ComponentFactory.get(componentName);
441
+ // If the token is not in the query, then maybe an auth processor has extracted it
442
+ // and stored it in the processor state
443
+ const token = request.query?.token ?? httpRequestContext.processorState.authToken;
444
+ const result = await component.refresh(token);
445
+ // Need to give a hint to any auth processors about the operation
446
+ // in case they need to manipulate the response
447
+ httpRequestContext.processorState.authOperation = "refresh";
448
+ return {
449
+ body: result
450
+ };
451
+ }
452
+
453
+ const restEntryPoints = [
454
+ {
455
+ name: "authentication",
456
+ defaultBaseRoute: "authentication",
457
+ tags: tagsAuthentication,
458
+ generateRoutes: generateRestRoutesAuthentication
459
+ }
460
+ ];
461
+
462
+ // Copyright 2024 IOTA Stiftung.
463
+ // SPDX-License-Identifier: Apache-2.0.
464
+ /**
465
+ * Initialize the schema for the authentication service.
466
+ */
467
+ function initSchema() {
468
+ EntitySchemaFactory.register("AuthenticationUser", () => EntitySchemaHelper.getSchema(AuthenticationUser));
469
+ }
470
+
471
+ // Copyright 2024 IOTA Stiftung.
472
+ // SPDX-License-Identifier: Apache-2.0.
473
+ /**
474
+ * Helper class for password operations.
475
+ */
476
+ class PasswordHelper {
477
+ /**
478
+ * Runtime name for the class.
479
+ * @internal
480
+ */
481
+ static _CLASS_NAME = "PasswordHelper";
482
+ /**
483
+ * Hash the password for the user.
484
+ * @param passwordBytes The password bytes.
485
+ * @param saltBytes The salt bytes.
486
+ * @returns The hashed password.
487
+ */
488
+ static async hashPassword(passwordBytes, saltBytes) {
489
+ Guards.uint8Array(PasswordHelper._CLASS_NAME, "passwordBytes", passwordBytes);
490
+ Guards.uint8Array(PasswordHelper._CLASS_NAME, "saltBytes", saltBytes);
491
+ const combined = new Uint8Array(saltBytes.length + passwordBytes.length);
492
+ combined.set(saltBytes);
493
+ combined.set(passwordBytes, saltBytes.length);
494
+ const hashedPassword = Blake2b.sum256(combined);
495
+ return Converter.bytesToBase64(hashedPassword);
496
+ }
497
+ }
498
+
499
+ /**
500
+ * Implementation of the authentication component using entity storage.
501
+ */
502
+ class EntityStorageAuthenticationService {
503
+ /**
504
+ * Default TTL in minutes.
505
+ * @internal
506
+ */
507
+ static _DEFAULT_TTL_MINUTES = 60;
508
+ /**
509
+ * Runtime name for the class.
510
+ */
511
+ CLASS_NAME = "EntityStorageAuthenticationService";
512
+ /**
513
+ * The entity storage for users.
514
+ * @internal
515
+ */
516
+ _userEntityStorage;
517
+ /**
518
+ * The vault for the keys.
519
+ * @internal
520
+ */
521
+ _vaultConnector;
522
+ /**
523
+ * The name of the key to retrieve from the vault for signing JWT.
524
+ * @internal
525
+ */
526
+ _signingKeyName;
527
+ /**
528
+ * The default TTL for the token.
529
+ * @internal
530
+ */
531
+ _defaultTtlMinutes;
532
+ /**
533
+ * The node identity.
534
+ * @internal
535
+ */
536
+ _nodeIdentity;
537
+ /**
538
+ * Create a new instance of EntityStorageAuthentication.
539
+ * @param options The dependencies for the identity connector.
540
+ * @param options.userEntityStorageType The entity storage for the users, defaults to "authentication-user".
541
+ * @param options.vaultConnectorType The vault for the private keys, defaults to "vault".
542
+ * @param options.config The configuration for the authentication.
543
+ */
544
+ constructor(options) {
545
+ this._userEntityStorage = EntityStorageConnectorFactory.get(options?.userEntityStorageType ?? "authentication-user");
546
+ this._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
547
+ this._signingKeyName = options?.config?.signingKeyName ?? "auth-signing";
548
+ this._defaultTtlMinutes =
549
+ options?.config?.defaultTtlMinutes ?? EntityStorageAuthenticationService._DEFAULT_TTL_MINUTES;
550
+ }
551
+ /**
552
+ * The service needs to be started when the application is initialized.
553
+ * @param nodeIdentity The identity of the node.
554
+ * @param nodeLoggingConnectorType The node logging connector type, defaults to "node-logging".
555
+ * @returns Nothing.
556
+ */
557
+ async start(nodeIdentity, nodeLoggingConnectorType) {
558
+ Guards.string(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
559
+ this._nodeIdentity = nodeIdentity;
560
+ }
561
+ /**
562
+ * Perform a login for the user.
563
+ * @param email The email address for the user.
564
+ * @param password The password for the user.
565
+ * @returns The authentication token for the user, if it uses a mechanism with public access.
566
+ */
567
+ async login(email, password) {
568
+ Guards.stringValue(this.CLASS_NAME, "email", email);
569
+ Guards.stringValue(this.CLASS_NAME, "password", password);
570
+ try {
571
+ const user = await this._userEntityStorage.get(email);
572
+ if (!user) {
573
+ throw new GeneralError(this.CLASS_NAME, "userNotFound");
574
+ }
575
+ const saltBytes = Converter.base64ToBytes(user.salt);
576
+ const passwordBytes = Converter.utf8ToBytes(password);
577
+ const hashedPassword = await PasswordHelper.hashPassword(passwordBytes, saltBytes);
578
+ if (hashedPassword !== user.password) {
579
+ throw new GeneralError(this.CLASS_NAME, "passwordMismatch");
580
+ }
581
+ const tokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, user.identity, this._defaultTtlMinutes);
582
+ return tokenAndExpiry;
583
+ }
584
+ catch (error) {
585
+ throw new UnauthorizedError(this.CLASS_NAME, "loginFailed", error);
586
+ }
587
+ }
588
+ /**
589
+ * Logout the current user.
590
+ * @param token The token to logout, if it uses a mechanism with public access.
591
+ * @returns Nothing.
592
+ */
593
+ async logout(token) {
594
+ // Nothing to do here.
595
+ }
596
+ /**
597
+ * Refresh the token.
598
+ * @param token The token to refresh, if it uses a mechanism with public access.
599
+ * @returns The refreshed token, if it uses a mechanism with public access.
600
+ */
601
+ async refresh(token) {
602
+ // If the verify fails on the current token then it will throw an exception.
603
+ const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, token);
604
+ const refreshTokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, headerAndPayload.payload.sub ?? "", this._defaultTtlMinutes);
605
+ return refreshTokenAndExpiry;
606
+ }
607
+ }
608
+
609
+ export { AuthHeaderProcessor, AuthenticationUser, EntityStorageAuthenticationService, PasswordHelper, TokenHelper, authenticationLogin, authenticationLogout, authenticationRefreshToken, generateRestRoutesAuthentication, initSchema, restEntryPoints, tagsAuthentication };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Class defining the storage for user login credentials.
3
+ */
4
+ export declare class AuthenticationUser {
5
+ /**
6
+ * The user e-mail address.
7
+ */
8
+ email: string;
9
+ /**
10
+ * The encrypted password for the user.
11
+ */
12
+ password: string;
13
+ /**
14
+ * The salt for the password.
15
+ */
16
+ salt: string;
17
+ /**
18
+ * The user identity.
19
+ */
20
+ identity: string;
21
+ }
@@ -0,0 +1,10 @@
1
+ export * from "./entities/authenticationUser";
2
+ export * from "./models/IAuthHeaderProcessorConfig";
3
+ export * from "./models/IEntityStorageAuthenticationServiceConfig";
4
+ export * from "./processors/authHeaderProcessor";
5
+ export * from "./restEntryPoints";
6
+ export * from "./routes/entityStorageAuthenticationRoutes";
7
+ export * from "./schema";
8
+ export * from "./services/entityStorageAuthenticationService";
9
+ export * from "./utils/passwordHelper";
10
+ export * from "./utils/tokenHelper";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Configuration for the authentication header processor
3
+ */
4
+ export interface IAuthHeaderProcessorConfig {
5
+ /**
6
+ * The name of the key to retrieve from the vault for signing JWT.
7
+ * @default auth-signing
8
+ */
9
+ signingKeyName?: string;
10
+ /**
11
+ * The name of the cookie to use for the token.
12
+ * @default access_token
13
+ */
14
+ cookieName?: string;
15
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Configuration for the entity storage authentication service.
3
+ */
4
+ export interface IEntityStorageAuthenticationServiceConfig {
5
+ /**
6
+ * The name of the key to retrieve from the vault for signing JWT.
7
+ * @default auth-signing
8
+ */
9
+ signingKeyName?: string;
10
+ /**
11
+ * The default time to live for the JWT.
12
+ * @default 1440
13
+ */
14
+ defaultTtlMinutes?: number;
15
+ }