@twin.org/api-auth-entity-storage-service 0.0.1-next.3 → 0.0.1-next.31

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.
@@ -71,13 +71,12 @@ class TokenHelper {
71
71
  * @returns The new token and its expiry date.
72
72
  */
73
73
  static async createToken(vaultConnector, signingKeyName, subject, ttlMinutes) {
74
- // Verify was a success so we can now generate a new token.
75
74
  const nowSeconds = Math.trunc(Date.now() / 1000);
76
75
  const ttlSeconds = ttlMinutes * 60;
77
- const jwt = await web.Jwt.encodeWithSigner({ alg: web.JwtAlgorithms.EdDSA }, {
76
+ const jwt = await web.Jwt.encodeWithSigner({ alg: "EdDSA" }, {
78
77
  sub: subject,
79
78
  exp: nowSeconds + ttlSeconds
80
- }, async (alg, key, payload) => vaultConnector.sign(signingKeyName, payload));
79
+ }, async (header, payload) => vaultModels.VaultConnectorHelper.jwtSigner(vaultConnector, signingKeyName, header, payload));
81
80
  return {
82
81
  token: jwt,
83
82
  expiry: (nowSeconds + ttlSeconds) * 1000
@@ -95,14 +94,10 @@ class TokenHelper {
95
94
  if (!core.Is.stringValue(token)) {
96
95
  throw new core.UnauthorizedError(this._CLASS_NAME, "missing");
97
96
  }
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");
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");
106
101
  }
107
102
  else if (!core.Is.empty(decoded.payload?.exp) &&
108
103
  decoded.payload.exp < Math.trunc(Date.now() / 1000)) {
@@ -120,12 +115,13 @@ class TokenHelper {
120
115
  * @returns The token if found.
121
116
  */
122
117
  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";
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
+ };
129
125
  }
130
126
  else if (core.Is.notEmpty(cookiesHeader) && core.Is.stringValue(cookieName)) {
131
127
  const cookies = core.Is.arrayValue(cookiesHeader) ? cookiesHeader : [cookiesHeader];
@@ -136,17 +132,14 @@ class TokenHelper {
136
132
  .map(c => c.trim())
137
133
  .find(c => c.startsWith(cookieName));
138
134
  if (core.Is.stringValue(accessTokenCookie)) {
139
- token = accessTokenCookie.slice(cookieName.length + 1).trim();
140
- location = "cookie";
141
- break;
135
+ return {
136
+ token: accessTokenCookie.slice(cookieName.length + 1).trim(),
137
+ location: "cookie"
138
+ };
142
139
  }
143
140
  }
144
141
  }
145
142
  }
146
- return {
147
- token,
148
- location
149
- };
150
143
  }
151
144
  }
152
145
 
@@ -156,6 +149,10 @@ class TokenHelper {
156
149
  * Handle a JWT token in the authorization header or cookies and validate it to populate request context identity.
157
150
  */
158
151
  class AuthHeaderProcessor {
152
+ /**
153
+ * The namespace supported by the processor.
154
+ */
155
+ static NAMESPACE = "auth-header";
159
156
  /**
160
157
  * The default name for the access token as a cookie.
161
158
  * @internal
@@ -188,8 +185,6 @@ class AuthHeaderProcessor {
188
185
  /**
189
186
  * Create a new instance of AuthCookiePreProcessor.
190
187
  * @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
188
  */
194
189
  constructor(options) {
195
190
  this._vaultConnector = vaultModels.VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
@@ -218,10 +213,10 @@ class AuthHeaderProcessor {
218
213
  if (!core.Is.empty(route) && !(route.skipAuth ?? false)) {
219
214
  try {
220
215
  const tokenAndLocation = TokenHelper.extractTokenFromHeaders(request.headers, this._cookieName);
221
- const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, tokenAndLocation.token);
216
+ const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, tokenAndLocation?.token);
222
217
  requestIdentity.userIdentity = headerAndPayload.payload?.sub;
223
- processorState.authToken = tokenAndLocation.token;
224
- processorState.authTokenLocation = tokenAndLocation.location;
218
+ processorState.authToken = tokenAndLocation?.token;
219
+ processorState.authTokenLocation = tokenAndLocation?.location;
225
220
  }
226
221
  catch (err) {
227
222
  const error = core.BaseError.fromError(err);
@@ -246,13 +241,13 @@ class AuthHeaderProcessor {
246
241
  if ((responseAuthOperation === "login" || responseAuthOperation === "refresh") &&
247
242
  core.Is.stringValue(response.body?.token)) {
248
243
  response.headers ??= {};
249
- response.headers["Set-Cookie"] =
244
+ response.headers[web.HeaderTypes.SetCookie] =
250
245
  `${this._cookieName}=${response.body.token}; Secure; HttpOnly; SameSite=None; Path=/`;
251
246
  delete response.body.token;
252
247
  }
253
248
  else if (responseAuthOperation === "logout") {
254
249
  response.headers ??= {};
255
- response.headers["Set-Cookie"] =
250
+ response.headers[web.HeaderTypes.SetCookie] =
256
251
  `${this._cookieName}=; Max-Age=0; Secure; HttpOnly; SameSite=None; Path=/`;
257
252
  }
258
253
  }
@@ -504,6 +499,10 @@ class PasswordHelper {
504
499
  * Implementation of the authentication component using entity storage.
505
500
  */
506
501
  class EntityStorageAuthenticationService {
502
+ /**
503
+ * The namespace supported by the authentication service.
504
+ */
505
+ static NAMESPACE = "authentication-entity-storage";
507
506
  /**
508
507
  * Default TTL in minutes.
509
508
  * @internal
@@ -541,9 +540,6 @@ class EntityStorageAuthenticationService {
541
540
  /**
542
541
  * Create a new instance of EntityStorageAuthentication.
543
542
  * @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
543
  */
548
544
  constructor(options) {
549
545
  this._userEntityStorage = entityStorageModels.EntityStorageConnectorFactory.get(options?.userEntityStorageType ?? "authentication-user");
@@ -1,8 +1,8 @@
1
1
  import { property, entity, EntitySchemaFactory, EntitySchemaHelper } from '@twin.org/entity';
2
2
  import { HttpErrorHelper } from '@twin.org/api-models';
3
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, HttpStatusCode } from '@twin.org/web';
4
+ import { VaultConnectorHelper, VaultConnectorFactory } from '@twin.org/vault-models';
5
+ import { Jwt, HeaderTypes, HttpStatusCode } from '@twin.org/web';
6
6
  import { EntityStorageConnectorFactory } from '@twin.org/entity-storage-models';
7
7
  import { Blake2b } from '@twin.org/crypto';
8
8
 
@@ -69,13 +69,12 @@ class TokenHelper {
69
69
  * @returns The new token and its expiry date.
70
70
  */
71
71
  static async createToken(vaultConnector, signingKeyName, subject, ttlMinutes) {
72
- // Verify was a success so we can now generate a new token.
73
72
  const nowSeconds = Math.trunc(Date.now() / 1000);
74
73
  const ttlSeconds = ttlMinutes * 60;
75
- const jwt = await Jwt.encodeWithSigner({ alg: JwtAlgorithms.EdDSA }, {
74
+ const jwt = await Jwt.encodeWithSigner({ alg: "EdDSA" }, {
76
75
  sub: subject,
77
76
  exp: nowSeconds + ttlSeconds
78
- }, async (alg, key, payload) => vaultConnector.sign(signingKeyName, payload));
77
+ }, async (header, payload) => VaultConnectorHelper.jwtSigner(vaultConnector, signingKeyName, header, payload));
79
78
  return {
80
79
  token: jwt,
81
80
  expiry: (nowSeconds + ttlSeconds) * 1000
@@ -93,14 +92,10 @@ class TokenHelper {
93
92
  if (!Is.stringValue(token)) {
94
93
  throw new UnauthorizedError(this._CLASS_NAME, "missing");
95
94
  }
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");
95
+ const decoded = await Jwt.verifyWithVerifier(token, async (t) => VaultConnectorHelper.jwtVerifier(vaultConnector, signingKeyName, t));
96
+ // If some of the header/payload data is not properly populated then it is unauthorized.
97
+ if (!Is.stringValue(decoded.payload.sub)) {
98
+ throw new UnauthorizedError(this._CLASS_NAME, "payloadMissingSubject");
104
99
  }
105
100
  else if (!Is.empty(decoded.payload?.exp) &&
106
101
  decoded.payload.exp < Math.trunc(Date.now() / 1000)) {
@@ -118,12 +113,13 @@ class TokenHelper {
118
113
  * @returns The token if found.
119
114
  */
120
115
  static extractTokenFromHeaders(headers, cookieName) {
121
- const cookiesHeader = headers?.cookie;
122
- let token;
123
- let location;
124
- if (Is.string(headers?.authorization) && headers.authorization.startsWith("Bearer ")) {
125
- token = headers.authorization.slice(7).trim();
126
- location = "authorization";
116
+ const authHeader = headers?.[HeaderTypes.Authorization];
117
+ const cookiesHeader = headers?.[HeaderTypes.Cookie];
118
+ if (Is.string(authHeader) && authHeader.startsWith("Bearer ")) {
119
+ return {
120
+ token: authHeader.slice(7).trim(),
121
+ location: "authorization"
122
+ };
127
123
  }
128
124
  else if (Is.notEmpty(cookiesHeader) && Is.stringValue(cookieName)) {
129
125
  const cookies = Is.arrayValue(cookiesHeader) ? cookiesHeader : [cookiesHeader];
@@ -134,17 +130,14 @@ class TokenHelper {
134
130
  .map(c => c.trim())
135
131
  .find(c => c.startsWith(cookieName));
136
132
  if (Is.stringValue(accessTokenCookie)) {
137
- token = accessTokenCookie.slice(cookieName.length + 1).trim();
138
- location = "cookie";
139
- break;
133
+ return {
134
+ token: accessTokenCookie.slice(cookieName.length + 1).trim(),
135
+ location: "cookie"
136
+ };
140
137
  }
141
138
  }
142
139
  }
143
140
  }
144
- return {
145
- token,
146
- location
147
- };
148
141
  }
149
142
  }
150
143
 
@@ -154,6 +147,10 @@ class TokenHelper {
154
147
  * Handle a JWT token in the authorization header or cookies and validate it to populate request context identity.
155
148
  */
156
149
  class AuthHeaderProcessor {
150
+ /**
151
+ * The namespace supported by the processor.
152
+ */
153
+ static NAMESPACE = "auth-header";
157
154
  /**
158
155
  * The default name for the access token as a cookie.
159
156
  * @internal
@@ -186,8 +183,6 @@ class AuthHeaderProcessor {
186
183
  /**
187
184
  * Create a new instance of AuthCookiePreProcessor.
188
185
  * @param options Options for the processor.
189
- * @param options.vaultConnectorType The vault for the private keys, defaults to "vault".
190
- * @param options.config The configuration for the processor.
191
186
  */
192
187
  constructor(options) {
193
188
  this._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
@@ -216,10 +211,10 @@ class AuthHeaderProcessor {
216
211
  if (!Is.empty(route) && !(route.skipAuth ?? false)) {
217
212
  try {
218
213
  const tokenAndLocation = TokenHelper.extractTokenFromHeaders(request.headers, this._cookieName);
219
- const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, tokenAndLocation.token);
214
+ const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeIdentity}/${this._signingKeyName}`, tokenAndLocation?.token);
220
215
  requestIdentity.userIdentity = headerAndPayload.payload?.sub;
221
- processorState.authToken = tokenAndLocation.token;
222
- processorState.authTokenLocation = tokenAndLocation.location;
216
+ processorState.authToken = tokenAndLocation?.token;
217
+ processorState.authTokenLocation = tokenAndLocation?.location;
223
218
  }
224
219
  catch (err) {
225
220
  const error = BaseError.fromError(err);
@@ -244,13 +239,13 @@ class AuthHeaderProcessor {
244
239
  if ((responseAuthOperation === "login" || responseAuthOperation === "refresh") &&
245
240
  Is.stringValue(response.body?.token)) {
246
241
  response.headers ??= {};
247
- response.headers["Set-Cookie"] =
242
+ response.headers[HeaderTypes.SetCookie] =
248
243
  `${this._cookieName}=${response.body.token}; Secure; HttpOnly; SameSite=None; Path=/`;
249
244
  delete response.body.token;
250
245
  }
251
246
  else if (responseAuthOperation === "logout") {
252
247
  response.headers ??= {};
253
- response.headers["Set-Cookie"] =
248
+ response.headers[HeaderTypes.SetCookie] =
254
249
  `${this._cookieName}=; Max-Age=0; Secure; HttpOnly; SameSite=None; Path=/`;
255
250
  }
256
251
  }
@@ -502,6 +497,10 @@ class PasswordHelper {
502
497
  * Implementation of the authentication component using entity storage.
503
498
  */
504
499
  class EntityStorageAuthenticationService {
500
+ /**
501
+ * The namespace supported by the authentication service.
502
+ */
503
+ static NAMESPACE = "authentication-entity-storage";
505
504
  /**
506
505
  * Default TTL in minutes.
507
506
  * @internal
@@ -539,9 +538,6 @@ class EntityStorageAuthenticationService {
539
538
  /**
540
539
  * Create a new instance of EntityStorageAuthentication.
541
540
  * @param options The dependencies for the identity connector.
542
- * @param options.userEntityStorageType The entity storage for the users, defaults to "authentication-user".
543
- * @param options.vaultConnectorType The vault for the private keys, defaults to "vault".
544
- * @param options.config The configuration for the authentication.
545
541
  */
546
542
  constructor(options) {
547
543
  this._userEntityStorage = EntityStorageConnectorFactory.get(options?.userEntityStorageType ?? "authentication-user");
@@ -1,6 +1,8 @@
1
1
  export * from "./entities/authenticationUser";
2
2
  export * from "./models/IAuthHeaderProcessorConfig";
3
+ export * from "./models/IAuthHeaderProcessorConstructorOptions";
3
4
  export * from "./models/IEntityStorageAuthenticationServiceConfig";
5
+ export * from "./models/IEntityStorageAuthenticationServiceConstructorOptions";
4
6
  export * from "./processors/authHeaderProcessor";
5
7
  export * from "./restEntryPoints";
6
8
  export * from "./routes/entityStorageAuthenticationRoutes";
@@ -0,0 +1,15 @@
1
+ import type { IAuthHeaderProcessorConfig } from "./IAuthHeaderProcessorConfig";
2
+ /**
3
+ * Options for the AuthHeaderProcessor constructor.
4
+ */
5
+ export interface IAuthHeaderProcessorConstructorOptions {
6
+ /**
7
+ * The vault for the private keys.
8
+ * @default vault
9
+ */
10
+ vaultConnectorType?: string;
11
+ /**
12
+ * The configuration for the processor.
13
+ */
14
+ config?: IAuthHeaderProcessorConfig;
15
+ }
@@ -0,0 +1,20 @@
1
+ import type { IEntityStorageAuthenticationServiceConfig } from "./IEntityStorageAuthenticationServiceConfig";
2
+ /**
3
+ * Options for the EntityStorageAuthenticationService constructor.
4
+ */
5
+ export interface IEntityStorageAuthenticationServiceConstructorOptions {
6
+ /**
7
+ * The entity storage for the users.
8
+ * @default authentication-user
9
+ */
10
+ userEntityStorageType?: string;
11
+ /**
12
+ * The vault for the private keys.
13
+ * @default vault
14
+ */
15
+ vaultConnectorType?: string;
16
+ /**
17
+ * The configuration for the authentication.
18
+ */
19
+ config?: IEntityStorageAuthenticationServiceConfig;
20
+ }
@@ -1,9 +1,13 @@
1
- import { type IHttpRequestIdentity, type IHttpResponse, type IHttpRestRouteProcessor, type IHttpServerRequest, type IRestRoute } from "@twin.org/api-models";
2
- import type { IAuthHeaderProcessorConfig } from "../models/IAuthHeaderProcessorConfig";
1
+ import { type IBaseRoute, type IBaseRouteProcessor, type IHttpRequestIdentity, type IHttpResponse, type IHttpServerRequest } from "@twin.org/api-models";
2
+ import type { IAuthHeaderProcessorConstructorOptions } from "../models/IAuthHeaderProcessorConstructorOptions";
3
3
  /**
4
4
  * Handle a JWT token in the authorization header or cookies and validate it to populate request context identity.
5
5
  */
6
- export declare class AuthHeaderProcessor implements IHttpRestRouteProcessor {
6
+ export declare class AuthHeaderProcessor implements IBaseRouteProcessor {
7
+ /**
8
+ * The namespace supported by the processor.
9
+ */
10
+ static readonly NAMESPACE: string;
7
11
  /**
8
12
  * Runtime name for the class.
9
13
  */
@@ -11,13 +15,8 @@ export declare class AuthHeaderProcessor implements IHttpRestRouteProcessor {
11
15
  /**
12
16
  * Create a new instance of AuthCookiePreProcessor.
13
17
  * @param options Options for the processor.
14
- * @param options.vaultConnectorType The vault for the private keys, defaults to "vault".
15
- * @param options.config The configuration for the processor.
16
18
  */
17
- constructor(options?: {
18
- vaultConnectorType?: string;
19
- config?: IAuthHeaderProcessorConfig;
20
- });
19
+ constructor(options?: IAuthHeaderProcessorConstructorOptions);
21
20
  /**
22
21
  * The service needs to be started when the application is initialized.
23
22
  * @param nodeIdentity The identity of the node.
@@ -33,7 +32,7 @@ export declare class AuthHeaderProcessor implements IHttpRestRouteProcessor {
33
32
  * @param requestIdentity The identity context for the request.
34
33
  * @param processorState The state handed through the processors.
35
34
  */
36
- pre(request: IHttpServerRequest, response: IHttpResponse, route: IRestRoute | undefined, requestIdentity: IHttpRequestIdentity, processorState: {
35
+ pre(request: IHttpServerRequest, response: IHttpResponse, route: IBaseRoute | undefined, requestIdentity: IHttpRequestIdentity, processorState: {
37
36
  [id: string]: unknown;
38
37
  }): Promise<void>;
39
38
  /**
@@ -44,7 +43,7 @@ export declare class AuthHeaderProcessor implements IHttpRestRouteProcessor {
44
43
  * @param requestIdentity The identity context for the request.
45
44
  * @param processorState The state handed through the processors.
46
45
  */
47
- post(request: IHttpServerRequest, response: IHttpResponse, route: IRestRoute | undefined, requestIdentity: IHttpRequestIdentity, processorState: {
46
+ post(request: IHttpServerRequest, response: IHttpResponse, route: IBaseRoute | undefined, requestIdentity: IHttpRequestIdentity, processorState: {
48
47
  [id: string]: unknown;
49
48
  }): Promise<void>;
50
49
  }
@@ -1,9 +1,13 @@
1
1
  import type { IAuthenticationComponent } from "@twin.org/api-auth-entity-storage-models";
2
- import type { IEntityStorageAuthenticationServiceConfig } from "../models/IEntityStorageAuthenticationServiceConfig";
2
+ import type { IEntityStorageAuthenticationServiceConstructorOptions } from "../models/IEntityStorageAuthenticationServiceConstructorOptions";
3
3
  /**
4
4
  * Implementation of the authentication component using entity storage.
5
5
  */
6
6
  export declare class EntityStorageAuthenticationService implements IAuthenticationComponent {
7
+ /**
8
+ * The namespace supported by the authentication service.
9
+ */
10
+ static readonly NAMESPACE: string;
7
11
  /**
8
12
  * Runtime name for the class.
9
13
  */
@@ -11,15 +15,8 @@ export declare class EntityStorageAuthenticationService implements IAuthenticati
11
15
  /**
12
16
  * Create a new instance of EntityStorageAuthentication.
13
17
  * @param options The dependencies for the identity connector.
14
- * @param options.userEntityStorageType The entity storage for the users, defaults to "authentication-user".
15
- * @param options.vaultConnectorType The vault for the private keys, defaults to "vault".
16
- * @param options.config The configuration for the authentication.
17
18
  */
18
- constructor(options?: {
19
- userEntityStorageType?: string;
20
- vaultConnectorType?: string;
21
- config?: IEntityStorageAuthenticationServiceConfig;
22
- });
19
+ constructor(options?: IEntityStorageAuthenticationServiceConstructorOptions);
23
20
  /**
24
21
  * The service needs to be started when the application is initialized.
25
22
  * @param nodeIdentity The identity of the node.
@@ -1,4 +1,4 @@
1
- import type { IVaultConnector } from "@twin.org/vault-models";
1
+ import { type IVaultConnector } from "@twin.org/vault-models";
2
2
  import { type IHttpHeaders, type IJwtHeader, type IJwtPayload } from "@twin.org/web";
3
3
  /**
4
4
  * Helper class for token operations.
@@ -35,7 +35,7 @@ export declare class TokenHelper {
35
35
  * @returns The token if found.
36
36
  */
37
37
  static extractTokenFromHeaders(headers?: IHttpHeaders, cookieName?: string): {
38
- token: string | undefined;
39
- location: "authorization" | "cookie" | undefined;
40
- };
38
+ token: string;
39
+ location: "authorization" | "cookie";
40
+ } | undefined;
41
41
  }
package/docs/changelog.md CHANGED
@@ -1,5 +1,5 @@
1
1
  # @twin.org/api-auth-entity-storage-service - Changelog
2
2
 
3
- ## v0.0.1-next.3
3
+ ## v0.0.1-next.31
4
4
 
5
5
  - Initial Release
@@ -4,7 +4,7 @@ Handle a JWT token in the authorization header or cookies and validate it to pop
4
4
 
5
5
  ## Implements
6
6
 
7
- - `IHttpRestRouteProcessor`
7
+ - `IBaseRouteProcessor`
8
8
 
9
9
  ## Constructors
10
10
 
@@ -16,23 +16,25 @@ Create a new instance of AuthCookiePreProcessor.
16
16
 
17
17
  #### Parameters
18
18
 
19
- **options?**
19
+ ##### options?
20
+
21
+ [`IAuthHeaderProcessorConstructorOptions`](../interfaces/IAuthHeaderProcessorConstructorOptions.md)
20
22
 
21
23
  Options for the processor.
22
24
 
23
- **options.vaultConnectorType?**: `string`
25
+ #### Returns
24
26
 
25
- The vault for the private keys, defaults to "vault".
27
+ [`AuthHeaderProcessor`](AuthHeaderProcessor.md)
26
28
 
27
- **options.config?**: [`IAuthHeaderProcessorConfig`](../interfaces/IAuthHeaderProcessorConfig.md)
29
+ ## Properties
28
30
 
29
- The configuration for the processor.
31
+ ### NAMESPACE
30
32
 
31
- #### Returns
33
+ > `readonly` `static` **NAMESPACE**: `string` = `"auth-header"`
32
34
 
33
- [`AuthHeaderProcessor`](AuthHeaderProcessor.md)
35
+ The namespace supported by the processor.
34
36
 
35
- ## Properties
37
+ ***
36
38
 
37
39
  ### CLASS\_NAME
38
40
 
@@ -42,7 +44,7 @@ Runtime name for the class.
42
44
 
43
45
  #### Implementation of
44
46
 
45
- `IHttpRestRouteProcessor.CLASS_NAME`
47
+ `IBaseRouteProcessor.CLASS_NAME`
46
48
 
47
49
  ## Methods
48
50
 
@@ -54,11 +56,15 @@ The service needs to be started when the application is initialized.
54
56
 
55
57
  #### Parameters
56
58
 
57
- **nodeIdentity**: `string`
59
+ ##### nodeIdentity
60
+
61
+ `string`
58
62
 
59
63
  The identity of the node.
60
64
 
61
- **nodeLoggingConnectorType?**: `string`
65
+ ##### nodeLoggingConnectorType?
66
+
67
+ `string`
62
68
 
63
69
  The node logging connector type, defaults to "node-logging".
64
70
 
@@ -70,7 +76,7 @@ Nothing.
70
76
 
71
77
  #### Implementation of
72
78
 
73
- `IHttpRestRouteProcessor.start`
79
+ `IBaseRouteProcessor.start`
74
80
 
75
81
  ***
76
82
 
@@ -82,23 +88,31 @@ Pre process the REST request for the specified route.
82
88
 
83
89
  #### Parameters
84
90
 
85
- **request**: `IHttpServerRequest`\<`any`\>
91
+ ##### request
92
+
93
+ `IHttpServerRequest`
86
94
 
87
95
  The incoming request.
88
96
 
89
- **response**: `IHttpResponse`\<`any`\>
97
+ ##### response
98
+
99
+ `IHttpResponse`
90
100
 
91
101
  The outgoing response.
92
102
 
93
- **route**: `undefined` \| `IRestRoute`\<`any`, `any`\>
103
+ ##### route
94
104
 
95
105
  The route to process.
96
106
 
97
- **requestIdentity**: `IHttpRequestIdentity`
107
+ `undefined` | `IBaseRoute`
108
+
109
+ ##### requestIdentity
110
+
111
+ `IHttpRequestIdentity`
98
112
 
99
113
  The identity context for the request.
100
114
 
101
- **processorState**
115
+ ##### processorState
102
116
 
103
117
  The state handed through the processors.
104
118
 
@@ -108,7 +122,7 @@ The state handed through the processors.
108
122
 
109
123
  #### Implementation of
110
124
 
111
- `IHttpRestRouteProcessor.pre`
125
+ `IBaseRouteProcessor.pre`
112
126
 
113
127
  ***
114
128
 
@@ -120,23 +134,31 @@ Post process the REST request for the specified route.
120
134
 
121
135
  #### Parameters
122
136
 
123
- **request**: `IHttpServerRequest`\<`any`\>
137
+ ##### request
138
+
139
+ `IHttpServerRequest`
124
140
 
125
141
  The incoming request.
126
142
 
127
- **response**: `IHttpResponse`\<`any`\>
143
+ ##### response
144
+
145
+ `IHttpResponse`
128
146
 
129
147
  The outgoing response.
130
148
 
131
- **route**: `undefined` \| `IRestRoute`\<`any`, `any`\>
149
+ ##### route
132
150
 
133
151
  The route to process.
134
152
 
135
- **requestIdentity**: `IHttpRequestIdentity`
153
+ `undefined` | `IBaseRoute`
154
+
155
+ ##### requestIdentity
156
+
157
+ `IHttpRequestIdentity`
136
158
 
137
159
  The identity context for the request.
138
160
 
139
- **processorState**
161
+ ##### processorState
140
162
 
141
163
  The state handed through the processors.
142
164
 
@@ -146,4 +168,4 @@ The state handed through the processors.
146
168
 
147
169
  #### Implementation of
148
170
 
149
- `IHttpRestRouteProcessor.post`
171
+ `IBaseRouteProcessor.post`
@@ -16,27 +16,25 @@ Create a new instance of EntityStorageAuthentication.
16
16
 
17
17
  #### Parameters
18
18
 
19
- **options?**
19
+ ##### options?
20
20
 
21
- The dependencies for the identity connector.
22
-
23
- • **options.userEntityStorageType?**: `string`
21
+ [`IEntityStorageAuthenticationServiceConstructorOptions`](../interfaces/IEntityStorageAuthenticationServiceConstructorOptions.md)
24
22
 
25
- The entity storage for the users, defaults to "authentication-user".
23
+ The dependencies for the identity connector.
26
24
 
27
- **options.vaultConnectorType?**: `string`
25
+ #### Returns
28
26
 
29
- The vault for the private keys, defaults to "vault".
27
+ [`EntityStorageAuthenticationService`](EntityStorageAuthenticationService.md)
30
28
 
31
- **options.config?**: [`IEntityStorageAuthenticationServiceConfig`](../interfaces/IEntityStorageAuthenticationServiceConfig.md)
29
+ ## Properties
32
30
 
33
- The configuration for the authentication.
31
+ ### NAMESPACE
34
32
 
35
- #### Returns
33
+ > `readonly` `static` **NAMESPACE**: `string` = `"authentication-entity-storage"`
36
34
 
37
- [`EntityStorageAuthenticationService`](EntityStorageAuthenticationService.md)
35
+ The namespace supported by the authentication service.
38
36
 
39
- ## Properties
37
+ ***
40
38
 
41
39
  ### CLASS\_NAME
42
40
 
@@ -58,11 +56,15 @@ The service needs to be started when the application is initialized.
58
56
 
59
57
  #### Parameters
60
58
 
61
- **nodeIdentity**: `string`
59
+ ##### nodeIdentity
60
+
61
+ `string`
62
62
 
63
63
  The identity of the node.
64
64
 
65
- **nodeLoggingConnectorType?**: `string`
65
+ ##### nodeLoggingConnectorType?
66
+
67
+ `string`
66
68
 
67
69
  The node logging connector type, defaults to "node-logging".
68
70
 
@@ -80,34 +82,30 @@ Nothing.
80
82
 
81
83
  ### login()
82
84
 
83
- > **login**(`email`, `password`): `Promise`\<`object`\>
85
+ > **login**(`email`, `password`): `Promise`\<\{ `token`: `string`; `expiry`: `number`; \}\>
84
86
 
85
87
  Perform a login for the user.
86
88
 
87
89
  #### Parameters
88
90
 
89
- **email**: `string`
91
+ ##### email
92
+
93
+ `string`
90
94
 
91
95
  The email address for the user.
92
96
 
93
- **password**: `string`
97
+ ##### password
98
+
99
+ `string`
94
100
 
95
101
  The password for the user.
96
102
 
97
103
  #### Returns
98
104
 
99
- `Promise`\<`object`\>
105
+ `Promise`\<\{ `token`: `string`; `expiry`: `number`; \}\>
100
106
 
101
107
  The authentication token for the user, if it uses a mechanism with public access.
102
108
 
103
- ##### token?
104
-
105
- > `optional` **token**: `string`
106
-
107
- ##### expiry
108
-
109
- > **expiry**: `number`
110
-
111
109
  #### Implementation of
112
110
 
113
111
  `IAuthenticationComponent.login`
@@ -122,7 +120,9 @@ Logout the current user.
122
120
 
123
121
  #### Parameters
124
122
 
125
- **token?**: `string`
123
+ ##### token?
124
+
125
+ `string`
126
126
 
127
127
  The token to logout, if it uses a mechanism with public access.
128
128
 
@@ -140,30 +140,24 @@ Nothing.
140
140
 
141
141
  ### refresh()
142
142
 
143
- > **refresh**(`token`?): `Promise`\<`object`\>
143
+ > **refresh**(`token`?): `Promise`\<\{ `token`: `string`; `expiry`: `number`; \}\>
144
144
 
145
145
  Refresh the token.
146
146
 
147
147
  #### Parameters
148
148
 
149
- **token?**: `string`
149
+ ##### token?
150
+
151
+ `string`
150
152
 
151
153
  The token to refresh, if it uses a mechanism with public access.
152
154
 
153
155
  #### Returns
154
156
 
155
- `Promise`\<`object`\>
157
+ `Promise`\<\{ `token`: `string`; `expiry`: `number`; \}\>
156
158
 
157
159
  The refreshed token, if it uses a mechanism with public access.
158
160
 
159
- ##### token
160
-
161
- > **token**: `string`
162
-
163
- ##### expiry
164
-
165
- > **expiry**: `number`
166
-
167
161
  #### Implementation of
168
162
 
169
163
  `IAuthenticationComponent.refresh`
@@ -22,11 +22,15 @@ Hash the password for the user.
22
22
 
23
23
  #### Parameters
24
24
 
25
- **passwordBytes**: `Uint8Array`
25
+ ##### passwordBytes
26
+
27
+ `Uint8Array`
26
28
 
27
29
  The password bytes.
28
30
 
29
- **saltBytes**: `Uint8Array`
31
+ ##### saltBytes
32
+
33
+ `Uint8Array`
30
34
 
31
35
  The salt bytes.
32
36
 
@@ -16,78 +16,76 @@ Helper class for token operations.
16
16
 
17
17
  ### createToken()
18
18
 
19
- > `static` **createToken**(`vaultConnector`, `signingKeyName`, `subject`, `ttlMinutes`): `Promise`\<`object`\>
19
+ > `static` **createToken**(`vaultConnector`, `signingKeyName`, `subject`, `ttlMinutes`): `Promise`\<\{ `token`: `string`; `expiry`: `number`; \}\>
20
20
 
21
21
  Create a new token.
22
22
 
23
23
  #### Parameters
24
24
 
25
- **vaultConnector**: `IVaultConnector`
25
+ ##### vaultConnector
26
+
27
+ `IVaultConnector`
26
28
 
27
29
  The vault connector.
28
30
 
29
- **signingKeyName**: `string`
31
+ ##### signingKeyName
32
+
33
+ `string`
30
34
 
31
35
  The signing key name.
32
36
 
33
- **subject**: `string`
37
+ ##### subject
38
+
39
+ `string`
34
40
 
35
41
  The subject for the token.
36
42
 
37
- **ttlMinutes**: `number`
43
+ ##### ttlMinutes
44
+
45
+ `number`
38
46
 
39
47
  The time to live for the token in minutes.
40
48
 
41
49
  #### Returns
42
50
 
43
- `Promise`\<`object`\>
51
+ `Promise`\<\{ `token`: `string`; `expiry`: `number`; \}\>
44
52
 
45
53
  The new token and its expiry date.
46
54
 
47
- ##### token
48
-
49
- > **token**: `string`
50
-
51
- ##### expiry
52
-
53
- > **expiry**: `number`
54
-
55
55
  ***
56
56
 
57
57
  ### verify()
58
58
 
59
- > `static` **verify**(`vaultConnector`, `signingKeyName`, `token`): `Promise`\<`object`\>
59
+ > `static` **verify**(`vaultConnector`, `signingKeyName`, `token`): `Promise`\<\{ `header`: `IJwtHeader`; `payload`: `IJwtPayload`; \}\>
60
60
 
61
61
  Verify the token.
62
62
 
63
63
  #### Parameters
64
64
 
65
- **vaultConnector**: `IVaultConnector`
65
+ ##### vaultConnector
66
+
67
+ `IVaultConnector`
66
68
 
67
69
  The vault connector.
68
70
 
69
- **signingKeyName**: `string`
71
+ ##### signingKeyName
72
+
73
+ `string`
70
74
 
71
75
  The signing key name.
72
76
 
73
- **token**: `undefined` \| `string`
77
+ ##### token
74
78
 
75
79
  The token to verify.
76
80
 
81
+ `undefined` | `string`
82
+
77
83
  #### Returns
78
84
 
79
- `Promise`\<`object`\>
85
+ `Promise`\<\{ `header`: `IJwtHeader`; `payload`: `IJwtPayload`; \}\>
80
86
 
81
87
  The verified details.
82
88
 
83
- ##### header
84
-
85
- > **header**: `IJwtHeader`
86
-
87
- ##### payload
88
-
89
- > **payload**: `IJwtPayload`
90
-
91
89
  #### Throws
92
90
 
93
91
  UnauthorizedError if the token is missing, invalid or expired.
@@ -96,30 +94,26 @@ UnauthorizedError if the token is missing, invalid or expired.
96
94
 
97
95
  ### extractTokenFromHeaders()
98
96
 
99
- > `static` **extractTokenFromHeaders**(`headers`?, `cookieName`?): `object`
97
+ > `static` **extractTokenFromHeaders**(`headers`?, `cookieName`?): `undefined` \| \{ `token`: `string`; `location`: `"authorization"` \| `"cookie"`; \}
100
98
 
101
99
  Extract the auth token from the headers, either from the authorization header or the cookie header.
102
100
 
103
101
  #### Parameters
104
102
 
105
- **headers?**: `IHttpHeaders`
103
+ ##### headers?
104
+
105
+ `IHttpHeaders`
106
106
 
107
107
  The headers to extract the token from.
108
108
 
109
- **cookieName?**: `string`
109
+ ##### cookieName?
110
+
111
+ `string`
110
112
 
111
113
  The name of the cookie to extract the token from.
112
114
 
113
115
  #### Returns
114
116
 
115
- `object`
117
+ `undefined` \| \{ `token`: `string`; `location`: `"authorization"` \| `"cookie"`; \}
116
118
 
117
119
  The token if found.
118
-
119
- ##### token
120
-
121
- > **token**: `undefined` \| `string`
122
-
123
- ##### location
124
-
125
- > **location**: `undefined` \| `"authorization"` \| `"cookie"`
@@ -6,15 +6,21 @@ Login to the server.
6
6
 
7
7
  ## Parameters
8
8
 
9
- **httpRequestContext**: `IHttpRequestContext`
9
+ ### httpRequestContext
10
+
11
+ `IHttpRequestContext`
10
12
 
11
13
  The request context for the API.
12
14
 
13
- **componentName**: `string`
15
+ ### componentName
16
+
17
+ `string`
14
18
 
15
19
  The name of the component to use in the routes.
16
20
 
17
- **request**: `ILoginRequest`
21
+ ### request
22
+
23
+ `ILoginRequest`
18
24
 
19
25
  The request.
20
26
 
@@ -6,15 +6,21 @@ Logout from the server.
6
6
 
7
7
  ## Parameters
8
8
 
9
- **httpRequestContext**: `IHttpRequestContext`
9
+ ### httpRequestContext
10
+
11
+ `IHttpRequestContext`
10
12
 
11
13
  The request context for the API.
12
14
 
13
- **componentName**: `string`
15
+ ### componentName
16
+
17
+ `string`
14
18
 
15
19
  The name of the component to use in the routes.
16
20
 
17
- **request**: `ILogoutRequest`
21
+ ### request
22
+
23
+ `ILogoutRequest`
18
24
 
19
25
  The request.
20
26
 
@@ -6,15 +6,21 @@ Refresh the login token.
6
6
 
7
7
  ## Parameters
8
8
 
9
- **httpRequestContext**: `IHttpRequestContext`
9
+ ### httpRequestContext
10
+
11
+ `IHttpRequestContext`
10
12
 
11
13
  The request context for the API.
12
14
 
13
- **componentName**: `string`
15
+ ### componentName
16
+
17
+ `string`
14
18
 
15
19
  The name of the component to use in the routes.
16
20
 
17
- **request**: `IRefreshTokenRequest`
21
+ ### request
22
+
23
+ `IRefreshTokenRequest`
18
24
 
19
25
  The request.
20
26
 
@@ -1,21 +1,25 @@
1
1
  # Function: generateRestRoutesAuthentication()
2
2
 
3
- > **generateRestRoutesAuthentication**(`baseRouteName`, `componentName`): `IRestRoute`[]
3
+ > **generateRestRoutesAuthentication**(`baseRouteName`, `componentName`): `IRestRoute`\<`any`, `any`\>[]
4
4
 
5
5
  The REST routes for authentication.
6
6
 
7
7
  ## Parameters
8
8
 
9
- **baseRouteName**: `string`
9
+ ### baseRouteName
10
+
11
+ `string`
10
12
 
11
13
  Prefix to prepend to the paths.
12
14
 
13
- **componentName**: `string`
15
+ ### componentName
16
+
17
+ `string`
14
18
 
15
19
  The name of the component to use in the routes stored in the ComponentFactory.
16
20
 
17
21
  ## Returns
18
22
 
19
- `IRestRoute`[]
23
+ `IRestRoute`\<`any`, `any`\>[]
20
24
 
21
25
  The generated routes.
@@ -11,7 +11,9 @@
11
11
  ## Interfaces
12
12
 
13
13
  - [IAuthHeaderProcessorConfig](interfaces/IAuthHeaderProcessorConfig.md)
14
+ - [IAuthHeaderProcessorConstructorOptions](interfaces/IAuthHeaderProcessorConstructorOptions.md)
14
15
  - [IEntityStorageAuthenticationServiceConfig](interfaces/IEntityStorageAuthenticationServiceConfig.md)
16
+ - [IEntityStorageAuthenticationServiceConstructorOptions](interfaces/IEntityStorageAuthenticationServiceConstructorOptions.md)
15
17
 
16
18
  ## Variables
17
19
 
@@ -0,0 +1,25 @@
1
+ # Interface: IAuthHeaderProcessorConstructorOptions
2
+
3
+ Options for the AuthHeaderProcessor constructor.
4
+
5
+ ## Properties
6
+
7
+ ### vaultConnectorType?
8
+
9
+ > `optional` **vaultConnectorType**: `string`
10
+
11
+ The vault for the private keys.
12
+
13
+ #### Default
14
+
15
+ ```ts
16
+ vault
17
+ ```
18
+
19
+ ***
20
+
21
+ ### config?
22
+
23
+ > `optional` **config**: [`IAuthHeaderProcessorConfig`](IAuthHeaderProcessorConfig.md)
24
+
25
+ The configuration for the processor.
@@ -0,0 +1,39 @@
1
+ # Interface: IEntityStorageAuthenticationServiceConstructorOptions
2
+
3
+ Options for the EntityStorageAuthenticationService constructor.
4
+
5
+ ## Properties
6
+
7
+ ### userEntityStorageType?
8
+
9
+ > `optional` **userEntityStorageType**: `string`
10
+
11
+ The entity storage for the users.
12
+
13
+ #### Default
14
+
15
+ ```ts
16
+ authentication-user
17
+ ```
18
+
19
+ ***
20
+
21
+ ### vaultConnectorType?
22
+
23
+ > `optional` **vaultConnectorType**: `string`
24
+
25
+ The vault for the private keys.
26
+
27
+ #### Default
28
+
29
+ ```ts
30
+ vault
31
+ ```
32
+
33
+ ***
34
+
35
+ ### config?
36
+
37
+ > `optional` **config**: [`IEntityStorageAuthenticationServiceConfig`](IEntityStorageAuthenticationServiceConfig.md)
38
+
39
+ The configuration for the authentication.
package/locales/en.json CHANGED
@@ -11,7 +11,7 @@
11
11
  },
12
12
  "tokenHelper": {
13
13
  "missing": "The JSON Web token could not be found in the authorization header",
14
- "invalid": "The JSON Web token signature could not be validated",
14
+ "payloadMissingSubject": "The JSON Web token payload does not contain a subject",
15
15
  "expired": "The JSON Web token has expired"
16
16
  }
17
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twin.org/api-auth-entity-storage-service",
3
- "version": "0.0.1-next.3",
3
+ "version": "0.0.1-next.31",
4
4
  "description": "Auth Entity Storage contract implementation and REST endpoint definitions",
5
5
  "repository": {
6
6
  "type": "git",
@@ -13,23 +13,10 @@
13
13
  "engines": {
14
14
  "node": ">=20.0.0"
15
15
  },
16
- "scripts": {
17
- "clean": "rimraf dist coverage",
18
- "build": "tspc",
19
- "test": "vitest --run --config ./vitest.config.ts --no-cache",
20
- "coverage": "vitest --run --coverage --config ./vitest.config.ts --no-cache",
21
- "bundle:esm": "rollup --config rollup.config.mjs --environment MODULE:esm",
22
- "bundle:cjs": "rollup --config rollup.config.mjs --environment MODULE:cjs",
23
- "bundle": "npm run bundle:esm && npm run bundle:cjs",
24
- "docs:clean": "rimraf docs/reference",
25
- "docs:generate": "typedoc",
26
- "docs": "npm run docs:clean && npm run docs:generate",
27
- "dist": "npm run clean && npm run build && npm run test && npm run bundle && npm run docs"
28
- },
29
16
  "dependencies": {
30
- "@twin.org/api-auth-entity-storage-models": "0.0.1-next.3",
31
- "@twin.org/api-core": "0.0.1-next.3",
32
- "@twin.org/api-models": "0.0.1-next.3",
17
+ "@twin.org/api-auth-entity-storage-models": "0.0.1-next.31",
18
+ "@twin.org/api-core": "0.0.1-next.31",
19
+ "@twin.org/api-models": "0.0.1-next.31",
33
20
  "@twin.org/core": "next",
34
21
  "@twin.org/crypto": "next",
35
22
  "@twin.org/entity": "next",
@@ -39,28 +26,14 @@
39
26
  "@twin.org/vault-models": "next",
40
27
  "@twin.org/web": "next"
41
28
  },
42
- "devDependencies": {
43
- "@twin.org/nameof-transformer": "next",
44
- "@vitest/coverage-v8": "2.1.1",
45
- "@types/node": "22.5.5",
46
- "copyfiles": "2.4.1",
47
- "rimraf": "6.0.1",
48
- "rollup": "4.21.3",
49
- "rollup-plugin-typescript2": "0.36.0",
50
- "ts-patch": "3.2.1",
51
- "typedoc": "0.26.7",
52
- "typedoc-plugin-markdown": "4.2.7",
53
- "typescript": "5.6.2",
54
- "vitest": "2.1.1"
55
- },
56
29
  "main": "./dist/cjs/index.cjs",
57
30
  "module": "./dist/esm/index.mjs",
58
31
  "types": "./dist/types/index.d.ts",
59
32
  "exports": {
60
33
  ".": {
34
+ "types": "./dist/types/index.d.ts",
61
35
  "require": "./dist/cjs/index.cjs",
62
- "import": "./dist/esm/index.mjs",
63
- "types": "./dist/types/index.d.ts"
36
+ "import": "./dist/esm/index.mjs"
64
37
  }
65
38
  },
66
39
  "files": [