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