@twin.org/api-auth-entity-storage-service 0.0.3-next.22 → 0.0.3-next.24
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/dist/es/entities/authenticationAuditEntry.js +101 -0
- package/dist/es/entities/authenticationAuditEntry.js.map +1 -0
- package/dist/es/entities/authenticationRateEntry.js +37 -0
- package/dist/es/entities/authenticationRateEntry.js.map +1 -0
- package/dist/es/index.js +10 -0
- package/dist/es/index.js.map +1 -1
- package/dist/es/models/IAuthHeaderProcessorConstructorOptions.js.map +1 -1
- package/dist/es/models/IEntityStorageAuthenticationAdminServiceConstructorOptions.js.map +1 -1
- package/dist/es/models/IEntityStorageAuthenticationAuditServiceConfig.js +4 -0
- package/dist/es/models/IEntityStorageAuthenticationAuditServiceConfig.js.map +1 -0
- package/dist/es/models/IEntityStorageAuthenticationAuditServiceConstructorOptions.js +2 -0
- package/dist/es/models/IEntityStorageAuthenticationAuditServiceConstructorOptions.js.map +1 -0
- package/dist/es/models/IEntityStorageAuthenticationRateServiceConfig.js +2 -0
- package/dist/es/models/IEntityStorageAuthenticationRateServiceConfig.js.map +1 -0
- package/dist/es/models/IEntityStorageAuthenticationRateServiceConstructorOptions.js +2 -0
- package/dist/es/models/IEntityStorageAuthenticationRateServiceConstructorOptions.js.map +1 -0
- package/dist/es/models/IEntityStorageAuthenticationServiceConfig.js +0 -2
- package/dist/es/models/IEntityStorageAuthenticationServiceConfig.js.map +1 -1
- package/dist/es/models/IEntityStorageAuthenticationServiceConstructorOptions.js.map +1 -1
- package/dist/es/processors/authHeaderProcessor.js +18 -4
- package/dist/es/processors/authHeaderProcessor.js.map +1 -1
- package/dist/es/restEntryPoints.js +7 -0
- package/dist/es/restEntryPoints.js.map +1 -1
- package/dist/es/routes/entityStorageAuthenticationAuditRoutes.js +174 -0
- package/dist/es/routes/entityStorageAuthenticationAuditRoutes.js.map +1 -0
- package/dist/es/schema.js +4 -0
- package/dist/es/schema.js.map +1 -1
- package/dist/es/services/entityStorageAuthenticationAdminService.js +53 -27
- package/dist/es/services/entityStorageAuthenticationAdminService.js.map +1 -1
- package/dist/es/services/entityStorageAuthenticationAuditService.js +178 -0
- package/dist/es/services/entityStorageAuthenticationAuditService.js.map +1 -0
- package/dist/es/services/entityStorageAuthenticationRateService.js +202 -0
- package/dist/es/services/entityStorageAuthenticationRateService.js.map +1 -0
- package/dist/es/services/entityStorageAuthenticationService.js +156 -11
- package/dist/es/services/entityStorageAuthenticationService.js.map +1 -1
- package/dist/es/utils/passwordHelper.js +57 -0
- package/dist/es/utils/passwordHelper.js.map +1 -0
- package/dist/es/utils/tokenHelper.js +11 -1
- package/dist/es/utils/tokenHelper.js.map +1 -1
- package/dist/types/entities/authenticationAuditEntry.d.ts +49 -0
- package/dist/types/entities/authenticationRateEntry.d.ts +17 -0
- package/dist/types/index.d.ts +10 -0
- package/dist/types/models/IAuthHeaderProcessorConstructorOptions.d.ts +5 -0
- package/dist/types/models/IEntityStorageAuthenticationAdminServiceConstructorOptions.d.ts +5 -0
- package/dist/types/models/IEntityStorageAuthenticationAuditServiceConfig.d.ts +9 -0
- package/dist/types/models/IEntityStorageAuthenticationAuditServiceConstructorOptions.d.ts +15 -0
- package/dist/types/models/IEntityStorageAuthenticationRateServiceConfig.d.ts +10 -0
- package/dist/types/models/IEntityStorageAuthenticationRateServiceConstructorOptions.d.ts +20 -0
- package/dist/types/models/IEntityStorageAuthenticationServiceConfig.d.ts +22 -1
- package/dist/types/models/IEntityStorageAuthenticationServiceConstructorOptions.d.ts +8 -3
- package/dist/types/routes/entityStorageAuthenticationAuditRoutes.d.ts +29 -0
- package/dist/types/services/entityStorageAuthenticationAuditService.d.ts +59 -0
- package/dist/types/services/entityStorageAuthenticationRateService.d.ts +60 -0
- package/dist/types/services/entityStorageAuthenticationService.d.ts +6 -0
- package/dist/types/utils/passwordHelper.d.ts +24 -0
- package/dist/types/utils/tokenHelper.d.ts +2 -1
- package/docs/changelog.md +32 -0
- package/docs/reference/classes/AuthenticationAuditEntry.md +101 -0
- package/docs/reference/classes/AuthenticationRateEntry.md +37 -0
- package/docs/reference/classes/EntityStorageAuthenticationAdminService.md +4 -4
- package/docs/reference/classes/EntityStorageAuthenticationAuditService.md +157 -0
- package/docs/reference/classes/EntityStorageAuthenticationRateService.md +227 -0
- package/docs/reference/classes/EntityStorageAuthenticationService.md +26 -0
- package/docs/reference/classes/PasswordHelper.md +74 -0
- package/docs/reference/classes/TokenHelper.md +7 -1
- package/docs/reference/functions/authenticationAuditCreate.md +31 -0
- package/docs/reference/functions/authenticationAuditQuery.md +31 -0
- package/docs/reference/functions/generateRestRoutesAuthenticationAudit.md +25 -0
- package/docs/reference/index.md +13 -0
- package/docs/reference/interfaces/IAuthHeaderProcessorConstructorOptions.md +14 -0
- package/docs/reference/interfaces/IEntityStorageAuthenticationAdminServiceConstructorOptions.md +14 -0
- package/docs/reference/interfaces/IEntityStorageAuthenticationAuditServiceConfig.md +11 -0
- package/docs/reference/interfaces/IEntityStorageAuthenticationAuditServiceConstructorOptions.md +25 -0
- package/docs/reference/interfaces/IEntityStorageAuthenticationRateServiceConfig.md +17 -0
- package/docs/reference/interfaces/IEntityStorageAuthenticationRateServiceConstructorOptions.md +39 -0
- package/docs/reference/interfaces/IEntityStorageAuthenticationServiceConfig.md +57 -1
- package/docs/reference/interfaces/IEntityStorageAuthenticationServiceConstructorOptions.md +18 -4
- package/docs/reference/variables/tagsAuthenticationAudit.md +5 -0
- package/locales/en.json +13 -2
- package/package.json +5 -4
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { TooManyRequestsError } from "@twin.org/api-models";
|
|
2
|
+
import { ComponentFactory, Converter, GeneralError, Guards, Is } from "@twin.org/core";
|
|
3
|
+
import { Sha256 } from "@twin.org/crypto";
|
|
4
|
+
import { ComparisonOperator } from "@twin.org/entity";
|
|
5
|
+
import { EntityStorageConnectorFactory } from "@twin.org/entity-storage-models";
|
|
6
|
+
/**
|
|
7
|
+
* Implementation of the authentication rate component using entity storage.
|
|
8
|
+
*/
|
|
9
|
+
export class EntityStorageAuthenticationRateService {
|
|
10
|
+
/**
|
|
11
|
+
* Runtime name for the class.
|
|
12
|
+
*/
|
|
13
|
+
static CLASS_NAME = "EntityStorageAuthenticationRateService";
|
|
14
|
+
/**
|
|
15
|
+
* Cleanup task id.
|
|
16
|
+
* @internal
|
|
17
|
+
*/
|
|
18
|
+
static _CLEANUP_TASK_ID = "authentication-rate-cleanup";
|
|
19
|
+
/**
|
|
20
|
+
* Default cleanup interval in minutes.
|
|
21
|
+
* @internal
|
|
22
|
+
*/
|
|
23
|
+
static _DEFAULT_CLEANUP_INTERVAL_MINUTES = 5;
|
|
24
|
+
/**
|
|
25
|
+
* Number of entries to retrieve in each cleanup page.
|
|
26
|
+
* @internal
|
|
27
|
+
*/
|
|
28
|
+
static _CLEANUP_PAGE_SIZE = 250;
|
|
29
|
+
/**
|
|
30
|
+
* The entity storage for authentication rate entries.
|
|
31
|
+
* @internal
|
|
32
|
+
*/
|
|
33
|
+
_authenticationRateEntryStorage;
|
|
34
|
+
/**
|
|
35
|
+
* The rate limits for each action.
|
|
36
|
+
* @internal
|
|
37
|
+
*/
|
|
38
|
+
_actionConfigs;
|
|
39
|
+
/**
|
|
40
|
+
* The task scheduler.
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
_taskScheduler;
|
|
44
|
+
/**
|
|
45
|
+
* The cleanup interval in minutes.
|
|
46
|
+
* @internal
|
|
47
|
+
*/
|
|
48
|
+
_cleanupIntervalMinutes;
|
|
49
|
+
/**
|
|
50
|
+
* Create a new instance of EntityStorageAuthenticationRateService.
|
|
51
|
+
* @param options The constructor options.
|
|
52
|
+
*/
|
|
53
|
+
constructor(options) {
|
|
54
|
+
this._authenticationRateEntryStorage = EntityStorageConnectorFactory.get(options?.authenticationRateEntryStorageType ?? "authentication-rate-entry");
|
|
55
|
+
this._actionConfigs = {};
|
|
56
|
+
this._taskScheduler = ComponentFactory.get(options?.taskSchedulerComponentType ?? "task-scheduler");
|
|
57
|
+
this._cleanupIntervalMinutes =
|
|
58
|
+
options?.config?.cleanupIntervalMinutes ??
|
|
59
|
+
EntityStorageAuthenticationRateService._DEFAULT_CLEANUP_INTERVAL_MINUTES;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Register or update rate-limit configuration for an action.
|
|
63
|
+
* @param action The action name.
|
|
64
|
+
* @param config The action configuration.
|
|
65
|
+
* @returns Nothing.
|
|
66
|
+
*/
|
|
67
|
+
async registerAction(action, config) {
|
|
68
|
+
Guards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, "action", action);
|
|
69
|
+
Guards.object(EntityStorageAuthenticationRateService.CLASS_NAME, "config", config);
|
|
70
|
+
this._actionConfigs[action] = {
|
|
71
|
+
maxAttempts: config.maxAttempts,
|
|
72
|
+
windowMinutes: config.windowMinutes
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Unregister rate-limit configuration for an action.
|
|
77
|
+
* @param action The action name.
|
|
78
|
+
* @returns Nothing.
|
|
79
|
+
*/
|
|
80
|
+
async unregisterAction(action) {
|
|
81
|
+
Guards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, "action", action);
|
|
82
|
+
delete this._actionConfigs[action];
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Returns the class name of the component.
|
|
86
|
+
* @returns The class name of the component.
|
|
87
|
+
*/
|
|
88
|
+
className() {
|
|
89
|
+
return EntityStorageAuthenticationRateService.CLASS_NAME;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The service needs to be started when the application is initialized.
|
|
93
|
+
* @param nodeLoggingComponentType The node logging component type.
|
|
94
|
+
* @returns Nothing.
|
|
95
|
+
*/
|
|
96
|
+
async start(nodeLoggingComponentType) {
|
|
97
|
+
await this._taskScheduler.addTask(EntityStorageAuthenticationRateService._CLEANUP_TASK_ID, [
|
|
98
|
+
{
|
|
99
|
+
intervalMinutes: this._cleanupIntervalMinutes
|
|
100
|
+
}
|
|
101
|
+
], async () => this.cleanupExpiredEntries());
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The component needs to be stopped when the node is closed.
|
|
105
|
+
* @param nodeLoggingComponentType The node logging component type.
|
|
106
|
+
* @returns Nothing.
|
|
107
|
+
*/
|
|
108
|
+
async stop(nodeLoggingComponentType) {
|
|
109
|
+
await this._taskScheduler.removeTask(EntityStorageAuthenticationRateService._CLEANUP_TASK_ID);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Check the authentication rate for a given action and identifier.
|
|
113
|
+
* @param action The action to be checked.
|
|
114
|
+
* @param identifier The identifier to be checked.
|
|
115
|
+
* @returns The rate entry id.
|
|
116
|
+
*/
|
|
117
|
+
async check(action, identifier) {
|
|
118
|
+
Guards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, "action", action);
|
|
119
|
+
Guards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, "identifier", identifier);
|
|
120
|
+
const actionConfig = this._actionConfigs[action];
|
|
121
|
+
if (!Is.object(actionConfig)) {
|
|
122
|
+
throw new GeneralError(EntityStorageAuthenticationRateService.CLASS_NAME, "actionConfigMissing", {
|
|
123
|
+
action
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
const hashedIdentifier = Converter.bytesToHex(Sha256.sum256(Converter.utf8ToBytes(identifier)));
|
|
127
|
+
const compositeId = `|${action}|${hashedIdentifier}|`;
|
|
128
|
+
const now = Date.now();
|
|
129
|
+
const nowIso = new Date(now).toISOString();
|
|
130
|
+
const windowMs = actionConfig.windowMinutes * 60 * 1000;
|
|
131
|
+
const cutoff = now - windowMs;
|
|
132
|
+
// Resolve the existing rate entry for this action + identifier pair.
|
|
133
|
+
const existing = await this._authenticationRateEntryStorage.get(compositeId);
|
|
134
|
+
// Keep only attempts inside the configured sliding window.
|
|
135
|
+
const activeTimestamps = (existing?.timestamps ?? []).filter(timestamp => new Date(timestamp).getTime() > cutoff);
|
|
136
|
+
if (activeTimestamps.length >= actionConfig.maxAttempts) {
|
|
137
|
+
const oldestTimestamp = new Date(activeTimestamps[0]).getTime();
|
|
138
|
+
const nextRequestTime = new Date(oldestTimestamp + windowMs).toISOString();
|
|
139
|
+
const retryAfterSeconds = Math.ceil((oldestTimestamp + windowMs - now) / 1000);
|
|
140
|
+
throw new TooManyRequestsError(EntityStorageAuthenticationRateService.CLASS_NAME, "rateLimitExceeded", activeTimestamps.length, nextRequestTime, {
|
|
141
|
+
action,
|
|
142
|
+
retryAfterSeconds
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
activeTimestamps.push(nowIso);
|
|
146
|
+
await this._authenticationRateEntryStorage.set({
|
|
147
|
+
id: compositeId,
|
|
148
|
+
timestamps: activeTimestamps,
|
|
149
|
+
dateModified: nowIso
|
|
150
|
+
});
|
|
151
|
+
return compositeId;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Clear the authentication rate entry for the given action and identifier.
|
|
155
|
+
* @param action The action to clear.
|
|
156
|
+
* @param identifier The identifier to clear.
|
|
157
|
+
* @returns Nothing.
|
|
158
|
+
*/
|
|
159
|
+
async clear(action, identifier) {
|
|
160
|
+
Guards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, "action", action);
|
|
161
|
+
Guards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, "identifier", identifier);
|
|
162
|
+
const hashedIdentifier = Converter.bytesToHex(Sha256.sum256(Converter.utf8ToBytes(identifier)));
|
|
163
|
+
const compositeId = `|${action}|${hashedIdentifier}|`;
|
|
164
|
+
await this._authenticationRateEntryStorage.remove(compositeId);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Cleanup expired rate limit entries.
|
|
168
|
+
* @returns Nothing.
|
|
169
|
+
* @internal
|
|
170
|
+
*/
|
|
171
|
+
async cleanupExpiredEntries() {
|
|
172
|
+
const now = Date.now();
|
|
173
|
+
for (const action of Object.keys(this._actionConfigs)) {
|
|
174
|
+
const actionConfig = this._actionConfigs[action];
|
|
175
|
+
const windowMs = actionConfig.windowMinutes * 60 * 1000;
|
|
176
|
+
const cutoffIso = new Date(now - windowMs).toISOString();
|
|
177
|
+
let cursor;
|
|
178
|
+
do {
|
|
179
|
+
// Query by composite rate entry id prefix and expiry window for this action.
|
|
180
|
+
const result = await this._authenticationRateEntryStorage.query({
|
|
181
|
+
conditions: [
|
|
182
|
+
{
|
|
183
|
+
property: "id",
|
|
184
|
+
value: `|${action}|`,
|
|
185
|
+
comparison: ComparisonOperator.Includes
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
property: "dateModified",
|
|
189
|
+
value: cutoffIso,
|
|
190
|
+
comparison: ComparisonOperator.LessThanOrEqual
|
|
191
|
+
}
|
|
192
|
+
]
|
|
193
|
+
}, undefined, undefined, cursor, EntityStorageAuthenticationRateService._CLEANUP_PAGE_SIZE);
|
|
194
|
+
for (const entity of result.entities) {
|
|
195
|
+
await this._authenticationRateEntryStorage.remove(entity.id);
|
|
196
|
+
}
|
|
197
|
+
cursor = result.cursor;
|
|
198
|
+
} while (!Is.empty(cursor));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
//# sourceMappingURL=entityStorageAuthenticationRateService.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entityStorageAuthenticationRateService.js","sourceRoot":"","sources":["../../../src/services/entityStorageAuthenticationRateService.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,gBAAgB,CAAC;AACvF,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EACN,6BAA6B,EAE7B,MAA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AAE,IAAI;4BACd,KAAK,EAAE,IAAI,MAAM,GAAG;4BACpB,UAAU,EAAE,kBAAkB,CAAC,QAAQ;yBACvC;wBACD;4BACC,QAAQ,EAAE,cAAc;4BACxB,KAAK,EAAE,SAAS;4BAChB,UAAU,EAAE,kBAAkB,CAAC,eAAe;yBAC9C;qBACD;iBACD,EACD,SAAS,EACT,SAAS,EACT,MAAM,EACN,sCAAsC,CAAC,kBAAkB,CACzD,CAAC;gBAEF,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,QAAqC,EAAE,CAAC;oBACnE,MAAM,IAAI,CAAC,+BAA+B,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC9D,CAAC;gBAED,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;YACxB,CAAC,QAAQ,CAAC,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE;QAC7B,CAAC;IACF,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type {\n\tIAuthenticationRateActionConfig,\n\tIAuthenticationRateComponent\n} from \"@twin.org/api-auth-entity-storage-models\";\nimport { TooManyRequestsError } from \"@twin.org/api-models\";\nimport type { ITaskSchedulerComponent } from \"@twin.org/background-task-models\";\nimport { ComponentFactory, Converter, GeneralError, Guards, Is } from \"@twin.org/core\";\nimport { Sha256 } from \"@twin.org/crypto\";\nimport { ComparisonOperator } from \"@twin.org/entity\";\nimport {\n\tEntityStorageConnectorFactory,\n\ttype IEntityStorageConnector\n} from \"@twin.org/entity-storage-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport type { AuthenticationRateEntry } from \"../entities/authenticationRateEntry.js\";\nimport type { IEntityStorageAuthenticationRateServiceConstructorOptions } from \"../models/IEntityStorageAuthenticationRateServiceConstructorOptions.js\";\n\n/**\n * Implementation of the authentication rate component using entity storage.\n */\nexport class EntityStorageAuthenticationRateService implements IAuthenticationRateComponent {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<EntityStorageAuthenticationRateService>();\n\n\t/**\n\t * Cleanup task id.\n\t * @internal\n\t */\n\tprivate static readonly _CLEANUP_TASK_ID = \"authentication-rate-cleanup\";\n\n\t/**\n\t * Default cleanup interval in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_CLEANUP_INTERVAL_MINUTES = 5;\n\n\t/**\n\t * Number of entries to retrieve in each cleanup page.\n\t * @internal\n\t */\n\tprivate static readonly _CLEANUP_PAGE_SIZE = 250;\n\n\t/**\n\t * The entity storage for authentication rate entries.\n\t * @internal\n\t */\n\tprivate readonly _authenticationRateEntryStorage: IEntityStorageConnector<AuthenticationRateEntry>;\n\n\t/**\n\t * The rate limits for each action.\n\t * @internal\n\t */\n\tprivate readonly _actionConfigs: { [action: string]: IAuthenticationRateActionConfig };\n\n\t/**\n\t * The task scheduler.\n\t * @internal\n\t */\n\tprivate readonly _taskScheduler: ITaskSchedulerComponent;\n\n\t/**\n\t * The cleanup interval in minutes.\n\t * @internal\n\t */\n\tprivate readonly _cleanupIntervalMinutes: number;\n\n\t/**\n\t * Create a new instance of EntityStorageAuthenticationRateService.\n\t * @param options The constructor options.\n\t */\n\tconstructor(options?: IEntityStorageAuthenticationRateServiceConstructorOptions) {\n\t\tthis._authenticationRateEntryStorage = EntityStorageConnectorFactory.get(\n\t\t\toptions?.authenticationRateEntryStorageType ?? \"authentication-rate-entry\"\n\t\t);\n\t\tthis._actionConfigs = {};\n\t\tthis._taskScheduler = ComponentFactory.get<ITaskSchedulerComponent>(\n\t\t\toptions?.taskSchedulerComponentType ?? \"task-scheduler\"\n\t\t);\n\t\tthis._cleanupIntervalMinutes =\n\t\t\toptions?.config?.cleanupIntervalMinutes ??\n\t\t\tEntityStorageAuthenticationRateService._DEFAULT_CLEANUP_INTERVAL_MINUTES;\n\t}\n\n\t/**\n\t * Register or update rate-limit configuration for an action.\n\t * @param action The action name.\n\t * @param config The action configuration.\n\t * @returns Nothing.\n\t */\n\tpublic async registerAction(\n\t\taction: string,\n\t\tconfig: IAuthenticationRateActionConfig\n\t): Promise<void> {\n\t\tGuards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, nameof(action), action);\n\t\tGuards.object<IAuthenticationRateActionConfig>(\n\t\t\tEntityStorageAuthenticationRateService.CLASS_NAME,\n\t\t\tnameof(config),\n\t\t\tconfig\n\t\t);\n\n\t\tthis._actionConfigs[action] = {\n\t\t\tmaxAttempts: config.maxAttempts,\n\t\t\twindowMinutes: config.windowMinutes\n\t\t};\n\t}\n\n\t/**\n\t * Unregister rate-limit configuration for an action.\n\t * @param action The action name.\n\t * @returns Nothing.\n\t */\n\tpublic async unregisterAction(action: string): Promise<void> {\n\t\tGuards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, nameof(action), action);\n\n\t\tdelete this._actionConfigs[action];\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn EntityStorageAuthenticationRateService.CLASS_NAME;\n\t}\n\n\t/**\n\t * The service needs to be started when the application is initialized.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns Nothing.\n\t */\n\tpublic async start(nodeLoggingComponentType?: string): Promise<void> {\n\t\tawait this._taskScheduler.addTask(\n\t\t\tEntityStorageAuthenticationRateService._CLEANUP_TASK_ID,\n\t\t\t[\n\t\t\t\t{\n\t\t\t\t\tintervalMinutes: this._cleanupIntervalMinutes\n\t\t\t\t}\n\t\t\t],\n\t\t\tasync () => this.cleanupExpiredEntries()\n\t\t);\n\t}\n\n\t/**\n\t * The component needs to be stopped when the node is closed.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns Nothing.\n\t */\n\tpublic async stop(nodeLoggingComponentType?: string): Promise<void> {\n\t\tawait this._taskScheduler.removeTask(EntityStorageAuthenticationRateService._CLEANUP_TASK_ID);\n\t}\n\n\t/**\n\t * Check the authentication rate for a given action and identifier.\n\t * @param action The action to be checked.\n\t * @param identifier The identifier to be checked.\n\t * @returns The rate entry id.\n\t */\n\tpublic async check(action: string, identifier: string): Promise<string> {\n\t\tGuards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, nameof(action), action);\n\t\tGuards.stringValue(\n\t\t\tEntityStorageAuthenticationRateService.CLASS_NAME,\n\t\t\tnameof(identifier),\n\t\t\tidentifier\n\t\t);\n\n\t\tconst actionConfig = this._actionConfigs[action];\n\n\t\tif (!Is.object(actionConfig)) {\n\t\t\tthrow new GeneralError(\n\t\t\t\tEntityStorageAuthenticationRateService.CLASS_NAME,\n\t\t\t\t\"actionConfigMissing\",\n\t\t\t\t{\n\t\t\t\t\taction\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\tconst hashedIdentifier = Converter.bytesToHex(Sha256.sum256(Converter.utf8ToBytes(identifier)));\n\t\tconst compositeId = `|${action}|${hashedIdentifier}|`;\n\n\t\tconst now = Date.now();\n\t\tconst nowIso = new Date(now).toISOString();\n\t\tconst windowMs = actionConfig.windowMinutes * 60 * 1000;\n\t\tconst cutoff = now - windowMs;\n\n\t\t// Resolve the existing rate entry for this action + identifier pair.\n\t\tconst existing = await this._authenticationRateEntryStorage.get(compositeId);\n\t\t// Keep only attempts inside the configured sliding window.\n\t\tconst activeTimestamps = (existing?.timestamps ?? []).filter(\n\t\t\ttimestamp => new Date(timestamp).getTime() > cutoff\n\t\t);\n\n\t\tif (activeTimestamps.length >= actionConfig.maxAttempts) {\n\t\t\tconst oldestTimestamp = new Date(activeTimestamps[0]).getTime();\n\t\t\tconst nextRequestTime = new Date(oldestTimestamp + windowMs).toISOString();\n\t\t\tconst retryAfterSeconds = Math.ceil((oldestTimestamp + windowMs - now) / 1000);\n\n\t\t\tthrow new TooManyRequestsError(\n\t\t\t\tEntityStorageAuthenticationRateService.CLASS_NAME,\n\t\t\t\t\"rateLimitExceeded\",\n\t\t\t\tactiveTimestamps.length,\n\t\t\t\tnextRequestTime,\n\t\t\t\t{\n\t\t\t\t\taction,\n\t\t\t\t\tretryAfterSeconds\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\tactiveTimestamps.push(nowIso);\n\n\t\tawait this._authenticationRateEntryStorage.set({\n\t\t\tid: compositeId,\n\t\t\ttimestamps: activeTimestamps,\n\t\t\tdateModified: nowIso\n\t\t});\n\n\t\treturn compositeId;\n\t}\n\n\t/**\n\t * Clear the authentication rate entry for the given action and identifier.\n\t * @param action The action to clear.\n\t * @param identifier The identifier to clear.\n\t * @returns Nothing.\n\t */\n\tpublic async clear(action: string, identifier: string): Promise<void> {\n\t\tGuards.stringValue(EntityStorageAuthenticationRateService.CLASS_NAME, nameof(action), action);\n\t\tGuards.stringValue(\n\t\t\tEntityStorageAuthenticationRateService.CLASS_NAME,\n\t\t\tnameof(identifier),\n\t\t\tidentifier\n\t\t);\n\n\t\tconst hashedIdentifier = Converter.bytesToHex(Sha256.sum256(Converter.utf8ToBytes(identifier)));\n\t\tconst compositeId = `|${action}|${hashedIdentifier}|`;\n\n\t\tawait this._authenticationRateEntryStorage.remove(compositeId);\n\t}\n\n\t/**\n\t * Cleanup expired rate limit entries.\n\t * @returns Nothing.\n\t * @internal\n\t */\n\tprivate async cleanupExpiredEntries(): Promise<void> {\n\t\tconst now = Date.now();\n\n\t\tfor (const action of Object.keys(this._actionConfigs)) {\n\t\t\tconst actionConfig = this._actionConfigs[action];\n\t\t\tconst windowMs = actionConfig.windowMinutes * 60 * 1000;\n\t\t\tconst cutoffIso = new Date(now - windowMs).toISOString();\n\t\t\tlet cursor: string | undefined;\n\n\t\t\tdo {\n\t\t\t\t// Query by composite rate entry id prefix and expiry window for this action.\n\t\t\t\tconst result = await this._authenticationRateEntryStorage.query(\n\t\t\t\t\t{\n\t\t\t\t\t\tconditions: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tproperty: \"id\",\n\t\t\t\t\t\t\t\tvalue: `|${action}|`,\n\t\t\t\t\t\t\t\tcomparison: ComparisonOperator.Includes\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tproperty: \"dateModified\",\n\t\t\t\t\t\t\t\tvalue: cutoffIso,\n\t\t\t\t\t\t\t\tcomparison: ComparisonOperator.LessThanOrEqual\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\tcursor,\n\t\t\t\t\tEntityStorageAuthenticationRateService._CLEANUP_PAGE_SIZE\n\t\t\t\t);\n\n\t\t\t\tfor (const entity of result.entities as AuthenticationRateEntry[]) {\n\t\t\t\t\tawait this._authenticationRateEntryStorage.remove(entity.id);\n\t\t\t\t}\n\n\t\t\t\tcursor = result.cursor;\n\t\t\t} while (!Is.empty(cursor));\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { AuthAuditEvent } from "@twin.org/api-auth-entity-storage-models";
|
|
1
2
|
import { ContextIdHelper, ContextIdKeys, ContextIdStore } from "@twin.org/context";
|
|
2
3
|
import { Coerce, ComponentFactory, Converter, GeneralError, Guards, Is, NotFoundError, UnauthorizedError } from "@twin.org/core";
|
|
3
4
|
import { PasswordGenerator, PasswordValidator } from "@twin.org/crypto";
|
|
4
5
|
import { EntityStorageConnectorFactory } from "@twin.org/entity-storage-models";
|
|
5
6
|
import { VaultConnectorFactory } from "@twin.org/vault-models";
|
|
7
|
+
import { PasswordHelper } from "../utils/passwordHelper.js";
|
|
6
8
|
import { TokenHelper } from "../utils/tokenHelper.js";
|
|
7
9
|
/**
|
|
8
10
|
* Implementation of the authentication component using entity storage.
|
|
@@ -18,10 +20,45 @@ export class EntityStorageAuthenticationService {
|
|
|
18
20
|
*/
|
|
19
21
|
static _DEFAULT_TTL_MINUTES = 60;
|
|
20
22
|
/**
|
|
21
|
-
*
|
|
23
|
+
* Default maximum login attempts in a rate window.
|
|
22
24
|
* @internal
|
|
23
25
|
*/
|
|
24
|
-
|
|
26
|
+
static _DEFAULT_LOGIN_RATE_MAX_ATTEMPTS = 5;
|
|
27
|
+
/**
|
|
28
|
+
* Default login rate window in minutes.
|
|
29
|
+
* @internal
|
|
30
|
+
*/
|
|
31
|
+
static _DEFAULT_LOGIN_RATE_WINDOW_MINUTES = 15;
|
|
32
|
+
/**
|
|
33
|
+
* Default maximum password change attempts in a rate window.
|
|
34
|
+
* @internal
|
|
35
|
+
*/
|
|
36
|
+
static _DEFAULT_PASSWORD_CHANGE_RATE_MAX_ATTEMPTS = 5;
|
|
37
|
+
/**
|
|
38
|
+
* Default password change rate window in minutes.
|
|
39
|
+
* @internal
|
|
40
|
+
*/
|
|
41
|
+
static _DEFAULT_PASSWORD_CHANGE_RATE_WINDOW_MINUTES = 15;
|
|
42
|
+
/**
|
|
43
|
+
* Default maximum token refresh attempts in a rate window.
|
|
44
|
+
* @internal
|
|
45
|
+
*/
|
|
46
|
+
static _DEFAULT_TOKEN_REFRESH_RATE_MAX_ATTEMPTS = 30;
|
|
47
|
+
/**
|
|
48
|
+
* Default token refresh rate window in minutes.
|
|
49
|
+
* @internal
|
|
50
|
+
*/
|
|
51
|
+
static _DEFAULT_TOKEN_REFRESH_RATE_WINDOW_MINUTES = 60;
|
|
52
|
+
/**
|
|
53
|
+
* The audit service.
|
|
54
|
+
* @internal
|
|
55
|
+
*/
|
|
56
|
+
_authenticationAuditService;
|
|
57
|
+
/**
|
|
58
|
+
* The rate service.
|
|
59
|
+
* @internal
|
|
60
|
+
*/
|
|
61
|
+
_authenticationRateService;
|
|
25
62
|
/**
|
|
26
63
|
* The entity storage for users.
|
|
27
64
|
* @internal
|
|
@@ -42,6 +79,26 @@ export class EntityStorageAuthenticationService {
|
|
|
42
79
|
* @internal
|
|
43
80
|
*/
|
|
44
81
|
_defaultTtlMinutes;
|
|
82
|
+
/**
|
|
83
|
+
* The minimum password length for validation.
|
|
84
|
+
* @internal
|
|
85
|
+
*/
|
|
86
|
+
_minPasswordLength;
|
|
87
|
+
/**
|
|
88
|
+
* Rate limit configuration for login failures.
|
|
89
|
+
* @internal
|
|
90
|
+
*/
|
|
91
|
+
_loginRateLimit;
|
|
92
|
+
/**
|
|
93
|
+
* Rate limit configuration for password changes.
|
|
94
|
+
* @internal
|
|
95
|
+
*/
|
|
96
|
+
_passwordChangeRateLimit;
|
|
97
|
+
/**
|
|
98
|
+
* Rate limit configuration for token refresh.
|
|
99
|
+
* @internal
|
|
100
|
+
*/
|
|
101
|
+
_tokenRefreshRateLimit;
|
|
45
102
|
/**
|
|
46
103
|
* The node identity.
|
|
47
104
|
* @internal
|
|
@@ -54,10 +111,30 @@ export class EntityStorageAuthenticationService {
|
|
|
54
111
|
constructor(options) {
|
|
55
112
|
this._userEntityStorage = EntityStorageConnectorFactory.get(options?.userEntityStorageType ?? "authentication-user");
|
|
56
113
|
this._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
|
|
57
|
-
this.
|
|
114
|
+
this._authenticationAuditService = ComponentFactory.getIfExists(options?.authenticationAuditServiceType ?? "authentication-audit");
|
|
115
|
+
this._authenticationRateService = ComponentFactory.get(options?.authenticationRateServiceType ?? "authentication-rate");
|
|
58
116
|
this._signingKeyName = options?.config?.signingKeyName ?? "auth-signing";
|
|
59
117
|
this._defaultTtlMinutes =
|
|
60
118
|
options?.config?.defaultTtlMinutes ?? EntityStorageAuthenticationService._DEFAULT_TTL_MINUTES;
|
|
119
|
+
this._minPasswordLength = options?.config?.minPasswordLength;
|
|
120
|
+
this._loginRateLimit = {
|
|
121
|
+
maxAttempts: options?.config?.loginRateLimit?.maxAttempts ??
|
|
122
|
+
EntityStorageAuthenticationService._DEFAULT_LOGIN_RATE_MAX_ATTEMPTS,
|
|
123
|
+
windowMinutes: options?.config?.loginRateLimit?.windowMinutes ??
|
|
124
|
+
EntityStorageAuthenticationService._DEFAULT_LOGIN_RATE_WINDOW_MINUTES
|
|
125
|
+
};
|
|
126
|
+
this._passwordChangeRateLimit = {
|
|
127
|
+
maxAttempts: options?.config?.passwordChangeRateLimit?.maxAttempts ??
|
|
128
|
+
EntityStorageAuthenticationService._DEFAULT_PASSWORD_CHANGE_RATE_MAX_ATTEMPTS,
|
|
129
|
+
windowMinutes: options?.config?.passwordChangeRateLimit?.windowMinutes ??
|
|
130
|
+
EntityStorageAuthenticationService._DEFAULT_PASSWORD_CHANGE_RATE_WINDOW_MINUTES
|
|
131
|
+
};
|
|
132
|
+
this._tokenRefreshRateLimit = {
|
|
133
|
+
maxAttempts: options?.config?.tokenRefreshRateLimit?.maxAttempts ??
|
|
134
|
+
EntityStorageAuthenticationService._DEFAULT_TOKEN_REFRESH_RATE_MAX_ATTEMPTS,
|
|
135
|
+
windowMinutes: options?.config?.tokenRefreshRateLimit?.windowMinutes ??
|
|
136
|
+
EntityStorageAuthenticationService._DEFAULT_TOKEN_REFRESH_RATE_WINDOW_MINUTES
|
|
137
|
+
};
|
|
61
138
|
}
|
|
62
139
|
/**
|
|
63
140
|
* Returns the class name of the component.
|
|
@@ -75,6 +152,19 @@ export class EntityStorageAuthenticationService {
|
|
|
75
152
|
const contextIds = await ContextIdStore.getContextIds();
|
|
76
153
|
ContextIdHelper.guard(contextIds, ContextIdKeys.Node);
|
|
77
154
|
this._nodeId = contextIds[ContextIdKeys.Node];
|
|
155
|
+
await this._authenticationRateService.registerAction("login", this._loginRateLimit);
|
|
156
|
+
await this._authenticationRateService.registerAction("password-change", this._passwordChangeRateLimit);
|
|
157
|
+
await this._authenticationRateService.registerAction("token-refresh", this._tokenRefreshRateLimit);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* The component needs to be stopped when the node is closed.
|
|
161
|
+
* @param nodeLoggingComponentType The node logging component type.
|
|
162
|
+
* @returns Nothing.
|
|
163
|
+
*/
|
|
164
|
+
async stop(nodeLoggingComponentType) {
|
|
165
|
+
await this._authenticationRateService.unregisterAction("login");
|
|
166
|
+
await this._authenticationRateService.unregisterAction("password-change");
|
|
167
|
+
await this._authenticationRateService.unregisterAction("token-refresh");
|
|
78
168
|
}
|
|
79
169
|
/**
|
|
80
170
|
* Perform a login for the user.
|
|
@@ -85,7 +175,11 @@ export class EntityStorageAuthenticationService {
|
|
|
85
175
|
async login(email, password) {
|
|
86
176
|
Guards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, "email", email);
|
|
87
177
|
Guards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, "password", password);
|
|
178
|
+
let loginUser;
|
|
179
|
+
let loginTenantId;
|
|
180
|
+
let tokenAndExpiry;
|
|
88
181
|
try {
|
|
182
|
+
await this._authenticationRateService.check("login", email);
|
|
89
183
|
const user = await this._userEntityStorage.get(email);
|
|
90
184
|
if (!user) {
|
|
91
185
|
throw new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, "userNotFound");
|
|
@@ -100,13 +194,29 @@ export class EntityStorageAuthenticationService {
|
|
|
100
194
|
// if is verified during the token processing, tenant id will be matched against
|
|
101
195
|
// the context
|
|
102
196
|
const contextIds = await ContextIdStore.getContextIds();
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
197
|
+
loginTenantId = contextIds?.[ContextIdKeys.Tenant];
|
|
198
|
+
tokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, `${this._nodeId}/${this._signingKeyName}`, user.identity, user.organization, loginTenantId, this._defaultTtlMinutes, user.scope);
|
|
199
|
+
loginUser = user;
|
|
106
200
|
}
|
|
107
201
|
catch (error) {
|
|
202
|
+
await this._authenticationAuditService?.create({
|
|
203
|
+
actorId: email,
|
|
204
|
+
event: AuthAuditEvent.LoginFailure
|
|
205
|
+
});
|
|
108
206
|
throw new UnauthorizedError(EntityStorageAuthenticationService.CLASS_NAME, "loginFailed", undefined, error);
|
|
109
207
|
}
|
|
208
|
+
await this._authenticationRateService.clear("login", email);
|
|
209
|
+
await this._authenticationAuditService?.create({
|
|
210
|
+
actorId: email,
|
|
211
|
+
event: AuthAuditEvent.LoginSuccess,
|
|
212
|
+
data: {
|
|
213
|
+
userIdentity: loginUser.identity,
|
|
214
|
+
organizationIdentity: loginUser.organization,
|
|
215
|
+
tenantId: loginTenantId,
|
|
216
|
+
scope: loginUser.scope.split(",")
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
return tokenAndExpiry;
|
|
110
220
|
}
|
|
111
221
|
/**
|
|
112
222
|
* Logout the current user.
|
|
@@ -116,6 +226,14 @@ export class EntityStorageAuthenticationService {
|
|
|
116
226
|
async logout(token) {
|
|
117
227
|
// Nothing to do here, as we are stateless.
|
|
118
228
|
// The cookie will be revoked by the REST route handling
|
|
229
|
+
const contextIds = await ContextIdStore.getContextIds();
|
|
230
|
+
const identifier = contextIds?.[ContextIdKeys.User];
|
|
231
|
+
if (Is.stringValue(identifier)) {
|
|
232
|
+
await this._authenticationAuditService?.create({
|
|
233
|
+
actorId: identifier,
|
|
234
|
+
event: AuthAuditEvent.Logout
|
|
235
|
+
});
|
|
236
|
+
}
|
|
119
237
|
}
|
|
120
238
|
/**
|
|
121
239
|
* Refresh the token.
|
|
@@ -124,8 +242,32 @@ export class EntityStorageAuthenticationService {
|
|
|
124
242
|
*/
|
|
125
243
|
async refresh(token) {
|
|
126
244
|
// If the verify fails on the current token then it will throw an exception.
|
|
127
|
-
const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeId}/${this._signingKeyName}`, token)
|
|
128
|
-
|
|
245
|
+
const headerAndPayload = await TokenHelper.verify(this._vaultConnector, `${this._nodeId}/${this._signingKeyName}`, token, undefined, async (userIdentity, organizationIdentity) => {
|
|
246
|
+
const validParts = [];
|
|
247
|
+
const user = await this._userEntityStorage.get(userIdentity, "identity");
|
|
248
|
+
if (user?.identity === userIdentity) {
|
|
249
|
+
validParts.push("user");
|
|
250
|
+
}
|
|
251
|
+
if (user?.organization === organizationIdentity) {
|
|
252
|
+
validParts.push("organization");
|
|
253
|
+
}
|
|
254
|
+
return validParts;
|
|
255
|
+
});
|
|
256
|
+
const refreshSub = headerAndPayload.payload.sub ?? "";
|
|
257
|
+
await this._authenticationRateService.check("token-refresh", refreshSub);
|
|
258
|
+
const refreshTokenAndExpiry = await TokenHelper.createToken(this._vaultConnector, `${this._nodeId}/${this._signingKeyName}`, refreshSub, Is.stringValue(headerAndPayload.payload.org) ? headerAndPayload.payload.org : "", Is.stringValue(headerAndPayload.payload.tid) ? headerAndPayload.payload.tid : "", this._defaultTtlMinutes, Coerce.string(headerAndPayload.payload?.scope));
|
|
259
|
+
const refreshScope = Coerce.string(headerAndPayload.payload?.scope) ?? "";
|
|
260
|
+
await this._authenticationAuditService?.create({
|
|
261
|
+
actorId: refreshSub,
|
|
262
|
+
event: AuthAuditEvent.TokenRefreshed,
|
|
263
|
+
data: {
|
|
264
|
+
organizationIdentity: Is.stringValue(headerAndPayload.payload.org)
|
|
265
|
+
? headerAndPayload.payload.org
|
|
266
|
+
: "",
|
|
267
|
+
tenantId: Is.stringValue(headerAndPayload.payload.tid) ? headerAndPayload.payload.tid : "",
|
|
268
|
+
scope: refreshScope.split(",").filter(scope => scope.length > 0)
|
|
269
|
+
}
|
|
270
|
+
});
|
|
129
271
|
return refreshTokenAndExpiry;
|
|
130
272
|
}
|
|
131
273
|
/**
|
|
@@ -137,11 +279,14 @@ export class EntityStorageAuthenticationService {
|
|
|
137
279
|
async updatePassword(currentPassword, newPassword) {
|
|
138
280
|
const contextIds = await ContextIdStore.getContextIds();
|
|
139
281
|
ContextIdHelper.guard(contextIds, ContextIdKeys.User);
|
|
140
|
-
const
|
|
282
|
+
const userIdentity = contextIds[ContextIdKeys.User];
|
|
283
|
+
await this._authenticationRateService.check("password-change", userIdentity);
|
|
284
|
+
const user = await this._userEntityStorage.get(userIdentity, "identity");
|
|
141
285
|
if (!Is.object(user)) {
|
|
142
|
-
throw new NotFoundError(EntityStorageAuthenticationService.CLASS_NAME, "userNotFound",
|
|
286
|
+
throw new NotFoundError(EntityStorageAuthenticationService.CLASS_NAME, "userNotFound", userIdentity);
|
|
143
287
|
}
|
|
144
|
-
|
|
288
|
+
await PasswordHelper.updatePassword(this._userEntityStorage, this._authenticationAuditService, user, newPassword, currentPassword, this._minPasswordLength);
|
|
289
|
+
await this._authenticationRateService.clear("password-change", userIdentity);
|
|
145
290
|
}
|
|
146
291
|
}
|
|
147
292
|
//# sourceMappingURL=entityStorageAuthenticationService.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entityStorageAuthenticationService.js","sourceRoot":"","sources":["../../../src/services/entityStorageAuthenticationService.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,EACN,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,YAAY,EACZ,MAAM,EACN,EAAE,EACF,aAAa,EACb,iBAAiB,EACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EACN,6BAA6B,EAE7B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAwB,MAAM,wBAAwB,CAAC;AAGrF,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEtD;;GAEG;AACH,MAAM,OAAO,kCAAkC;IAC9C;;OAEG;IACI,MAAM,CAAU,UAAU,wCAAwD;IAEzF;;;OAGG;IACK,MAAM,CAAU,oBAAoB,GAAW,EAAE,CAAC;IAE1D;;;OAGG;IACc,2BAA2B,CAAgC;IAE5E;;;OAGG;IACc,kBAAkB,CAA8C;IAEjF;;;OAGG;IACc,eAAe,CAAkB;IAElD;;;OAGG;IACc,eAAe,CAAS;IAEzC;;;OAGG;IACc,kBAAkB,CAAS;IAE5C;;;OAGG;IACK,OAAO,CAAU;IAEzB;;;OAGG;IACH,YAAY,OAA+D;QAC1E,IAAI,CAAC,kBAAkB,GAAG,6BAA6B,CAAC,GAAG,CAC1D,OAAO,EAAE,qBAAqB,IAAI,qBAAqB,CACvD,CAAC;QAEF,IAAI,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AC,cAAc,CACrD,IAAI,CAAC,KAAK,EACV,WAAW,EACX,eAAe,CACf,CAAC;IACH,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type {\n\tIAuthenticationAdminComponent,\n\tIAuthenticationComponent\n} from \"@twin.org/api-auth-entity-storage-models\";\nimport { ContextIdHelper, ContextIdKeys, ContextIdStore } from \"@twin.org/context\";\nimport {\n\tCoerce,\n\tComponentFactory,\n\tConverter,\n\tGeneralError,\n\tGuards,\n\tIs,\n\tNotFoundError,\n\tUnauthorizedError\n} from \"@twin.org/core\";\nimport { PasswordGenerator, PasswordValidator } from \"@twin.org/crypto\";\nimport {\n\tEntityStorageConnectorFactory,\n\ttype IEntityStorageConnector\n} from \"@twin.org/entity-storage-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { VaultConnectorFactory, type IVaultConnector } from \"@twin.org/vault-models\";\nimport type { AuthenticationUser } from \"../entities/authenticationUser.js\";\nimport type { IEntityStorageAuthenticationServiceConstructorOptions } from \"../models/IEntityStorageAuthenticationServiceConstructorOptions.js\";\nimport { TokenHelper } from \"../utils/tokenHelper.js\";\n\n/**\n * Implementation of the authentication component using entity storage.\n */\nexport class EntityStorageAuthenticationService implements IAuthenticationComponent {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<EntityStorageAuthenticationService>();\n\n\t/**\n\t * Default TTL in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TTL_MINUTES: number = 60;\n\n\t/**\n\t * The user admin service.\n\t * @internal\n\t */\n\tprivate readonly _authenticationAdminService: IAuthenticationAdminComponent;\n\n\t/**\n\t * The entity storage for users.\n\t * @internal\n\t */\n\tprivate readonly _userEntityStorage: IEntityStorageConnector<AuthenticationUser>;\n\n\t/**\n\t * The vault for the keys.\n\t * @internal\n\t */\n\tprivate readonly _vaultConnector: IVaultConnector;\n\n\t/**\n\t * The name of the key to retrieve from the vault for signing JWT.\n\t * @internal\n\t */\n\tprivate readonly _signingKeyName: string;\n\n\t/**\n\t * The default TTL for the token.\n\t * @internal\n\t */\n\tprivate readonly _defaultTtlMinutes: number;\n\n\t/**\n\t * The node identity.\n\t * @internal\n\t */\n\tprivate _nodeId?: string;\n\n\t/**\n\t * Create a new instance of EntityStorageAuthentication.\n\t * @param options The dependencies for the identity connector.\n\t */\n\tconstructor(options?: IEntityStorageAuthenticationServiceConstructorOptions) {\n\t\tthis._userEntityStorage = EntityStorageConnectorFactory.get(\n\t\t\toptions?.userEntityStorageType ?? \"authentication-user\"\n\t\t);\n\n\t\tthis._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? \"vault\");\n\n\t\tthis._authenticationAdminService = ComponentFactory.get<IAuthenticationAdminComponent>(\n\t\t\toptions?.authenticationAdminServiceType ?? \"authentication-admin\"\n\t\t);\n\n\t\tthis._signingKeyName = options?.config?.signingKeyName ?? \"auth-signing\";\n\t\tthis._defaultTtlMinutes =\n\t\t\toptions?.config?.defaultTtlMinutes ?? EntityStorageAuthenticationService._DEFAULT_TTL_MINUTES;\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn EntityStorageAuthenticationService.CLASS_NAME;\n\t}\n\n\t/**\n\t * The service needs to be started when the application is initialized.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns Nothing.\n\t */\n\tpublic async start(nodeLoggingComponentType?: string): Promise<void> {\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tContextIdHelper.guard(contextIds, ContextIdKeys.Node);\n\t\tthis._nodeId = contextIds[ContextIdKeys.Node];\n\t}\n\n\t/**\n\t * Perform a login for the user.\n\t * @param email The email address for the user.\n\t * @param password The password for the user.\n\t * @returns The authentication token for the user, if it uses a mechanism with public access.\n\t */\n\tpublic async login(\n\t\temail: string,\n\t\tpassword: string\n\t): Promise<{\n\t\ttoken?: string;\n\t\texpiry: number;\n\t}> {\n\t\tGuards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, nameof(email), email);\n\t\tGuards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, nameof(password), password);\n\n\t\ttry {\n\t\t\tconst user = await this._userEntityStorage.get(email);\n\t\t\tif (!user) {\n\t\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"userNotFound\");\n\t\t\t}\n\n\t\t\tconst saltBytes = Converter.base64ToBytes(user.salt);\n\t\t\tconst passwordBytes = Converter.utf8ToBytes(password);\n\n\t\t\tconst hashedPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);\n\n\t\t\tif (!PasswordValidator.comparePasswordHashes(hashedPassword, user.password)) {\n\t\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"passwordMismatch\");\n\t\t\t}\n\n\t\t\t// This might be undefined if the login is performed in a single tenant context\n\t\t\t// if is verified during the token processing, tenant id will be matched against\n\t\t\t// the context\n\t\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\t\tconst tenantId = contextIds?.[ContextIdKeys.Tenant];\n\n\t\t\tconst tokenAndExpiry = await TokenHelper.createToken(\n\t\t\t\tthis._vaultConnector,\n\t\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\t\tuser.identity,\n\t\t\t\tuser.organization,\n\t\t\t\ttenantId,\n\t\t\t\tthis._defaultTtlMinutes,\n\t\t\t\tuser.scope\n\t\t\t);\n\n\t\t\treturn tokenAndExpiry;\n\t\t} catch (error) {\n\t\t\tthrow new UnauthorizedError(\n\t\t\t\tEntityStorageAuthenticationService.CLASS_NAME,\n\t\t\t\t\"loginFailed\",\n\t\t\t\tundefined,\n\t\t\t\terror\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Logout the current user.\n\t * @param token The token to logout, if it uses a mechanism with public access.\n\t * @returns Nothing.\n\t */\n\tpublic async logout(token?: string): Promise<void> {\n\t\t// Nothing to do here, as we are stateless.\n\t\t// The cookie will be revoked by the REST route handling\n\t}\n\n\t/**\n\t * Refresh the token.\n\t * @param token The token to refresh, if it uses a mechanism with public access.\n\t * @returns The refreshed token, if it uses a mechanism with public access.\n\t */\n\tpublic async refresh(token?: string): Promise<{\n\t\ttoken?: string;\n\t\texpiry: number;\n\t}> {\n\t\t// If the verify fails on the current token then it will throw an exception.\n\t\tconst headerAndPayload = await TokenHelper.verify(\n\t\t\tthis._vaultConnector,\n\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\ttoken\n\t\t);\n\n\t\tconst refreshTokenAndExpiry = await TokenHelper.createToken(\n\t\t\tthis._vaultConnector,\n\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\theaderAndPayload.payload.sub ?? \"\",\n\t\t\tIs.stringValue(headerAndPayload.payload.org) ? headerAndPayload.payload.org : \"\",\n\t\t\tIs.stringValue(headerAndPayload.payload.tid) ? headerAndPayload.payload.tid : \"\",\n\t\t\tthis._defaultTtlMinutes,\n\t\t\tCoerce.string(headerAndPayload.payload?.scope)\n\t\t);\n\n\t\treturn refreshTokenAndExpiry;\n\t}\n\n\t/**\n\t * Update the user's password.\n\t * @param currentPassword The current password for the user.\n\t * @param newPassword The new password for the user.\n\t * @returns Nothing.\n\t */\n\tpublic async updatePassword(currentPassword: string, newPassword: string): Promise<void> {\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tContextIdHelper.guard(contextIds, ContextIdKeys.User);\n\n\t\tconst user = await this._userEntityStorage.get(contextIds[ContextIdKeys.User]);\n\t\tif (!Is.object<AuthenticationUser>(user)) {\n\t\t\tthrow new NotFoundError(\n\t\t\t\tEntityStorageAuthenticationService.CLASS_NAME,\n\t\t\t\t\"userNotFound\",\n\t\t\t\tcontextIds[ContextIdKeys.User]\n\t\t\t);\n\t\t}\n\n\t\treturn this._authenticationAdminService.updatePassword(\n\t\t\tuser.email,\n\t\t\tnewPassword,\n\t\t\tcurrentPassword\n\t\t);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"entityStorageAuthenticationService.js","sourceRoot":"","sources":["../../../src/services/entityStorageAuthenticationService.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnF,OAAO,EACN,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,YAAY,EACZ,MAAM,EACN,EAAE,EACF,aAAa,EACb,iBAAiB,EACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EACN,6BAA6B,EAE7B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,qBAAqB,EAAwB,MAAM,wBAAwB,CAAC;AAGrF,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAEtD;;GAEG;AACH,MAAM,OAAO,kCAAkC;IAC9C;;OAEG;IACI,MAAM,CAAU,UAAU,wCAAwD;IAEzF;;;OAGG;IACK,MAAM,CAAU,oBAAoB,GAAW,EAAE,CAAC;IAE1D;;;OAGG;IACK,MAAM,CAAU,gCAAgC,GAAW,CAAC,CAAC;IAErE;;;OAGG;IACK,MAAM,CAAU,kCAAkC,GAAW,EAAE,CAAC;IAExE;;;OAGG;IACK,MAAM,CAAU,0CAA0C,GAAW,CAAC,CAAC;IAE/E;;;OAGG;IACK,MAAM,CAAU,4CAA4C,GAAW,EAAE,CAAC;IAElF;;;OAGG;IACK,MAAM,CAAU,wCAAwC,GAAW,EAAE,CAAC;IAE9E;;;OAGG;IACK,MAAM,CAAU,0CAA0C,GAAW,EAAE,CAAC;IAEhF;;;OAGG;IACc,2BAA2B,CAAiC;IAE7E;;;OAGG;IACc,0BAA0B,CAA+B;IAE1E;;;OAGG;IACc,kBAAkB,CAA8C;IAEjF;;;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WAAmB;QACvE,MAAM,UAAU,GAAG,MAAM,cAAc,CAAC,aAAa,EAAE,CAAC;QACxD,eAAe,CAAC,KAAK,CAAC,UAAU,EAAE,aAAa,CAAC,IAAI,CAAC,CAAC;QAEtD,MAAM,YAAY,GAAG,UAAU,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;QACpD,MAAM,IAAI,CAAC,0BAA0B,CAAC,KAAK,CAAC,iBAAiB,EAAE,YAAY,CAAC,CAAC;QAE7E,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACzE,IAAI,CAAC,EAAE,CAAC,MAAM,CAAqB,IAAI,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,aAAa,CACtB,kCAAkC,CAAC,UAAU,EAC7C,cAAc,EACd,YAAY,CACZ,CAAC;QACH,CAAC;QAED,MAAM,cAAc,CAAC,cAAc,CAClC,IAAI,CAAC,kBAAkB,EACvB,IAAI,CAAC,2BAA2B,EAChC,IAAI,EACJ,WAAW,EACX,eAAe,EACf,IAAI,CAAC,kBAAkB,CACvB,CAAC;QAEF,MAAM,IAAI,CAAC,0BAA0B,CAAC,KAAK,CAAC,iBAAiB,EAAE,YAAY,CAAC,CAAC;IAC9E,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type {\n\tIAuthenticationRateActionConfig,\n\tIAuthenticationRateComponent,\n\tIAuthenticationAuditComponent,\n\tIAuthenticationComponent\n} from \"@twin.org/api-auth-entity-storage-models\";\nimport { AuthAuditEvent } from \"@twin.org/api-auth-entity-storage-models\";\nimport { ContextIdHelper, ContextIdKeys, ContextIdStore } from \"@twin.org/context\";\nimport {\n\tCoerce,\n\tComponentFactory,\n\tConverter,\n\tGeneralError,\n\tGuards,\n\tIs,\n\tNotFoundError,\n\tUnauthorizedError\n} from \"@twin.org/core\";\nimport { PasswordGenerator, PasswordValidator } from \"@twin.org/crypto\";\nimport {\n\tEntityStorageConnectorFactory,\n\ttype IEntityStorageConnector\n} from \"@twin.org/entity-storage-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { VaultConnectorFactory, type IVaultConnector } from \"@twin.org/vault-models\";\nimport type { AuthenticationUser } from \"../entities/authenticationUser.js\";\nimport type { IEntityStorageAuthenticationServiceConstructorOptions } from \"../models/IEntityStorageAuthenticationServiceConstructorOptions.js\";\nimport { PasswordHelper } from \"../utils/passwordHelper.js\";\nimport { TokenHelper } from \"../utils/tokenHelper.js\";\n\n/**\n * Implementation of the authentication component using entity storage.\n */\nexport class EntityStorageAuthenticationService implements IAuthenticationComponent {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<EntityStorageAuthenticationService>();\n\n\t/**\n\t * Default TTL in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TTL_MINUTES: number = 60;\n\n\t/**\n\t * Default maximum login attempts in a rate window.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_LOGIN_RATE_MAX_ATTEMPTS: number = 5;\n\n\t/**\n\t * Default login rate window in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_LOGIN_RATE_WINDOW_MINUTES: number = 15;\n\n\t/**\n\t * Default maximum password change attempts in a rate window.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_PASSWORD_CHANGE_RATE_MAX_ATTEMPTS: number = 5;\n\n\t/**\n\t * Default password change rate window in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_PASSWORD_CHANGE_RATE_WINDOW_MINUTES: number = 15;\n\n\t/**\n\t * Default maximum token refresh attempts in a rate window.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TOKEN_REFRESH_RATE_MAX_ATTEMPTS: number = 30;\n\n\t/**\n\t * Default token refresh rate window in minutes.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TOKEN_REFRESH_RATE_WINDOW_MINUTES: number = 60;\n\n\t/**\n\t * The audit service.\n\t * @internal\n\t */\n\tprivate readonly _authenticationAuditService?: IAuthenticationAuditComponent;\n\n\t/**\n\t * The rate service.\n\t * @internal\n\t */\n\tprivate readonly _authenticationRateService: IAuthenticationRateComponent;\n\n\t/**\n\t * The entity storage for users.\n\t * @internal\n\t */\n\tprivate readonly _userEntityStorage: IEntityStorageConnector<AuthenticationUser>;\n\n\t/**\n\t * The vault for the keys.\n\t * @internal\n\t */\n\tprivate readonly _vaultConnector: IVaultConnector;\n\n\t/**\n\t * The name of the key to retrieve from the vault for signing JWT.\n\t * @internal\n\t */\n\tprivate readonly _signingKeyName: string;\n\n\t/**\n\t * The default TTL for the token.\n\t * @internal\n\t */\n\tprivate readonly _defaultTtlMinutes: number;\n\n\t/**\n\t * The minimum password length for validation.\n\t * @internal\n\t */\n\tprivate readonly _minPasswordLength?: number;\n\n\t/**\n\t * Rate limit configuration for login failures.\n\t * @internal\n\t */\n\tprivate readonly _loginRateLimit: IAuthenticationRateActionConfig;\n\n\t/**\n\t * Rate limit configuration for password changes.\n\t * @internal\n\t */\n\tprivate readonly _passwordChangeRateLimit: IAuthenticationRateActionConfig;\n\n\t/**\n\t * Rate limit configuration for token refresh.\n\t * @internal\n\t */\n\tprivate readonly _tokenRefreshRateLimit: IAuthenticationRateActionConfig;\n\n\t/**\n\t * The node identity.\n\t * @internal\n\t */\n\tprivate _nodeId?: string;\n\n\t/**\n\t * Create a new instance of EntityStorageAuthentication.\n\t * @param options The dependencies for the identity connector.\n\t */\n\tconstructor(options?: IEntityStorageAuthenticationServiceConstructorOptions) {\n\t\tthis._userEntityStorage = EntityStorageConnectorFactory.get(\n\t\t\toptions?.userEntityStorageType ?? \"authentication-user\"\n\t\t);\n\n\t\tthis._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? \"vault\");\n\n\t\tthis._authenticationAuditService = ComponentFactory.getIfExists<IAuthenticationAuditComponent>(\n\t\t\toptions?.authenticationAuditServiceType ?? \"authentication-audit\"\n\t\t);\n\n\t\tthis._authenticationRateService = ComponentFactory.get<IAuthenticationRateComponent>(\n\t\t\toptions?.authenticationRateServiceType ?? \"authentication-rate\"\n\t\t);\n\n\t\tthis._signingKeyName = options?.config?.signingKeyName ?? \"auth-signing\";\n\t\tthis._defaultTtlMinutes =\n\t\t\toptions?.config?.defaultTtlMinutes ?? EntityStorageAuthenticationService._DEFAULT_TTL_MINUTES;\n\t\tthis._minPasswordLength = options?.config?.minPasswordLength;\n\t\tthis._loginRateLimit = {\n\t\t\tmaxAttempts:\n\t\t\t\toptions?.config?.loginRateLimit?.maxAttempts ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_LOGIN_RATE_MAX_ATTEMPTS,\n\t\t\twindowMinutes:\n\t\t\t\toptions?.config?.loginRateLimit?.windowMinutes ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_LOGIN_RATE_WINDOW_MINUTES\n\t\t};\n\t\tthis._passwordChangeRateLimit = {\n\t\t\tmaxAttempts:\n\t\t\t\toptions?.config?.passwordChangeRateLimit?.maxAttempts ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_PASSWORD_CHANGE_RATE_MAX_ATTEMPTS,\n\t\t\twindowMinutes:\n\t\t\t\toptions?.config?.passwordChangeRateLimit?.windowMinutes ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_PASSWORD_CHANGE_RATE_WINDOW_MINUTES\n\t\t};\n\t\tthis._tokenRefreshRateLimit = {\n\t\t\tmaxAttempts:\n\t\t\t\toptions?.config?.tokenRefreshRateLimit?.maxAttempts ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_TOKEN_REFRESH_RATE_MAX_ATTEMPTS,\n\t\t\twindowMinutes:\n\t\t\t\toptions?.config?.tokenRefreshRateLimit?.windowMinutes ??\n\t\t\t\tEntityStorageAuthenticationService._DEFAULT_TOKEN_REFRESH_RATE_WINDOW_MINUTES\n\t\t};\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn EntityStorageAuthenticationService.CLASS_NAME;\n\t}\n\n\t/**\n\t * The service needs to be started when the application is initialized.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns Nothing.\n\t */\n\tpublic async start(nodeLoggingComponentType?: string): Promise<void> {\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tContextIdHelper.guard(contextIds, ContextIdKeys.Node);\n\t\tthis._nodeId = contextIds[ContextIdKeys.Node];\n\n\t\tawait this._authenticationRateService.registerAction(\"login\", this._loginRateLimit);\n\t\tawait this._authenticationRateService.registerAction(\n\t\t\t\"password-change\",\n\t\t\tthis._passwordChangeRateLimit\n\t\t);\n\t\tawait this._authenticationRateService.registerAction(\n\t\t\t\"token-refresh\",\n\t\t\tthis._tokenRefreshRateLimit\n\t\t);\n\t}\n\n\t/**\n\t * The component needs to be stopped when the node is closed.\n\t * @param nodeLoggingComponentType The node logging component type.\n\t * @returns Nothing.\n\t */\n\tpublic async stop(nodeLoggingComponentType?: string): Promise<void> {\n\t\tawait this._authenticationRateService.unregisterAction(\"login\");\n\t\tawait this._authenticationRateService.unregisterAction(\"password-change\");\n\t\tawait this._authenticationRateService.unregisterAction(\"token-refresh\");\n\t}\n\n\t/**\n\t * Perform a login for the user.\n\t * @param email The email address for the user.\n\t * @param password The password for the user.\n\t * @returns The authentication token for the user, if it uses a mechanism with public access.\n\t */\n\tpublic async login(\n\t\temail: string,\n\t\tpassword: string\n\t): Promise<{\n\t\ttoken?: string;\n\t\texpiry: number;\n\t}> {\n\t\tGuards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, nameof(email), email);\n\t\tGuards.stringValue(EntityStorageAuthenticationService.CLASS_NAME, nameof(password), password);\n\n\t\tlet loginUser: AuthenticationUser | undefined;\n\t\tlet loginTenantId: string | undefined;\n\t\tlet tokenAndExpiry: { token?: string; expiry: number } | undefined;\n\n\t\ttry {\n\t\t\tawait this._authenticationRateService.check(\"login\", email);\n\n\t\t\tconst user = await this._userEntityStorage.get(email);\n\t\t\tif (!user) {\n\t\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"userNotFound\");\n\t\t\t}\n\n\t\t\tconst saltBytes = Converter.base64ToBytes(user.salt);\n\t\t\tconst passwordBytes = Converter.utf8ToBytes(password);\n\n\t\t\tconst hashedPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);\n\n\t\t\tif (!PasswordValidator.comparePasswordHashes(hashedPassword, user.password)) {\n\t\t\t\tthrow new GeneralError(EntityStorageAuthenticationService.CLASS_NAME, \"passwordMismatch\");\n\t\t\t}\n\n\t\t\t// This might be undefined if the login is performed in a single tenant context\n\t\t\t// if is verified during the token processing, tenant id will be matched against\n\t\t\t// the context\n\t\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\t\tloginTenantId = contextIds?.[ContextIdKeys.Tenant];\n\n\t\t\ttokenAndExpiry = await TokenHelper.createToken(\n\t\t\t\tthis._vaultConnector,\n\t\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\t\tuser.identity,\n\t\t\t\tuser.organization,\n\t\t\t\tloginTenantId,\n\t\t\t\tthis._defaultTtlMinutes,\n\t\t\t\tuser.scope\n\t\t\t);\n\t\t\tloginUser = user;\n\t\t} catch (error) {\n\t\t\tawait this._authenticationAuditService?.create({\n\t\t\t\tactorId: email,\n\t\t\t\tevent: AuthAuditEvent.LoginFailure\n\t\t\t});\n\n\t\t\tthrow new UnauthorizedError(\n\t\t\t\tEntityStorageAuthenticationService.CLASS_NAME,\n\t\t\t\t\"loginFailed\",\n\t\t\t\tundefined,\n\t\t\t\terror\n\t\t\t);\n\t\t}\n\n\t\tawait this._authenticationRateService.clear(\"login\", email);\n\n\t\tawait this._authenticationAuditService?.create({\n\t\t\tactorId: email,\n\t\t\tevent: AuthAuditEvent.LoginSuccess,\n\t\t\tdata: {\n\t\t\t\tuserIdentity: loginUser.identity,\n\t\t\t\torganizationIdentity: loginUser.organization,\n\t\t\t\ttenantId: loginTenantId,\n\t\t\t\tscope: loginUser.scope.split(\",\")\n\t\t\t}\n\t\t});\n\n\t\treturn tokenAndExpiry;\n\t}\n\n\t/**\n\t * Logout the current user.\n\t * @param token The token to logout, if it uses a mechanism with public access.\n\t * @returns Nothing.\n\t */\n\tpublic async logout(token?: string): Promise<void> {\n\t\t// Nothing to do here, as we are stateless.\n\t\t// The cookie will be revoked by the REST route handling\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tconst identifier = contextIds?.[ContextIdKeys.User];\n\t\tif (Is.stringValue(identifier)) {\n\t\t\tawait this._authenticationAuditService?.create({\n\t\t\t\tactorId: identifier,\n\t\t\t\tevent: AuthAuditEvent.Logout\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Refresh the token.\n\t * @param token The token to refresh, if it uses a mechanism with public access.\n\t * @returns The refreshed token, if it uses a mechanism with public access.\n\t */\n\tpublic async refresh(token?: string): Promise<{\n\t\ttoken?: string;\n\t\texpiry: number;\n\t}> {\n\t\t// If the verify fails on the current token then it will throw an exception.\n\t\tconst headerAndPayload = await TokenHelper.verify(\n\t\t\tthis._vaultConnector,\n\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\ttoken,\n\t\t\tundefined,\n\t\t\tasync (userIdentity, organizationIdentity) => {\n\t\t\t\tconst validParts = [];\n\t\t\t\tconst user = await this._userEntityStorage.get(userIdentity, \"identity\");\n\t\t\t\tif (user?.identity === userIdentity) {\n\t\t\t\t\tvalidParts.push(\"user\");\n\t\t\t\t}\n\t\t\t\tif (user?.organization === organizationIdentity) {\n\t\t\t\t\tvalidParts.push(\"organization\");\n\t\t\t\t}\n\t\t\t\treturn validParts;\n\t\t\t}\n\t\t);\n\n\t\tconst refreshSub = headerAndPayload.payload.sub ?? \"\";\n\t\tawait this._authenticationRateService.check(\"token-refresh\", refreshSub);\n\n\t\tconst refreshTokenAndExpiry = await TokenHelper.createToken(\n\t\t\tthis._vaultConnector,\n\t\t\t`${this._nodeId}/${this._signingKeyName}`,\n\t\t\trefreshSub,\n\t\t\tIs.stringValue(headerAndPayload.payload.org) ? headerAndPayload.payload.org : \"\",\n\t\t\tIs.stringValue(headerAndPayload.payload.tid) ? headerAndPayload.payload.tid : \"\",\n\t\t\tthis._defaultTtlMinutes,\n\t\t\tCoerce.string(headerAndPayload.payload?.scope)\n\t\t);\n\t\tconst refreshScope = Coerce.string(headerAndPayload.payload?.scope) ?? \"\";\n\n\t\tawait this._authenticationAuditService?.create({\n\t\t\tactorId: refreshSub,\n\t\t\tevent: AuthAuditEvent.TokenRefreshed,\n\t\t\tdata: {\n\t\t\t\torganizationIdentity: Is.stringValue(headerAndPayload.payload.org)\n\t\t\t\t\t? headerAndPayload.payload.org\n\t\t\t\t\t: \"\",\n\t\t\t\ttenantId: Is.stringValue(headerAndPayload.payload.tid) ? headerAndPayload.payload.tid : \"\",\n\t\t\t\tscope: refreshScope.split(\",\").filter(scope => scope.length > 0)\n\t\t\t}\n\t\t});\n\n\t\treturn refreshTokenAndExpiry;\n\t}\n\n\t/**\n\t * Update the user's password.\n\t * @param currentPassword The current password for the user.\n\t * @param newPassword The new password for the user.\n\t * @returns Nothing.\n\t */\n\tpublic async updatePassword(currentPassword: string, newPassword: string): Promise<void> {\n\t\tconst contextIds = await ContextIdStore.getContextIds();\n\t\tContextIdHelper.guard(contextIds, ContextIdKeys.User);\n\n\t\tconst userIdentity = contextIds[ContextIdKeys.User];\n\t\tawait this._authenticationRateService.check(\"password-change\", userIdentity);\n\n\t\tconst user = await this._userEntityStorage.get(userIdentity, \"identity\");\n\t\tif (!Is.object<AuthenticationUser>(user)) {\n\t\t\tthrow new NotFoundError(\n\t\t\t\tEntityStorageAuthenticationService.CLASS_NAME,\n\t\t\t\t\"userNotFound\",\n\t\t\t\tuserIdentity\n\t\t\t);\n\t\t}\n\n\t\tawait PasswordHelper.updatePassword(\n\t\t\tthis._userEntityStorage,\n\t\t\tthis._authenticationAuditService,\n\t\t\tuser,\n\t\t\tnewPassword,\n\t\t\tcurrentPassword,\n\t\t\tthis._minPasswordLength\n\t\t);\n\n\t\tawait this._authenticationRateService.clear(\"password-change\", userIdentity);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { AuthAuditEvent } from "@twin.org/api-auth-entity-storage-models";
|
|
2
|
+
import { Converter, GeneralError, Is, RandomHelper } from "@twin.org/core";
|
|
3
|
+
import { PasswordGenerator, PasswordValidator } from "@twin.org/crypto";
|
|
4
|
+
/**
|
|
5
|
+
* Helper class for password operations.
|
|
6
|
+
*/
|
|
7
|
+
export class PasswordHelper {
|
|
8
|
+
/**
|
|
9
|
+
* Runtime name for the class.
|
|
10
|
+
*/
|
|
11
|
+
static CLASS_NAME = "PasswordHelper";
|
|
12
|
+
/**
|
|
13
|
+
* Update the password for a user.
|
|
14
|
+
* Validates password strength, verifies the current password if provided, then hashes and stores the new password and raises an audit event.
|
|
15
|
+
* @param userEntityStorage The entity storage for users.
|
|
16
|
+
* @param authenticationAuditService The optional audit service.
|
|
17
|
+
* @param user The user whose password is being updated.
|
|
18
|
+
* @param newPassword The new password to set.
|
|
19
|
+
* @param currentPassword The current password to verify against, if supplied.
|
|
20
|
+
* @param minPasswordLength Optional minimum password length for validation.
|
|
21
|
+
* @returns Nothing.
|
|
22
|
+
*/
|
|
23
|
+
static async updatePassword(userEntityStorage, authenticationAuditService, user, newPassword, currentPassword, minPasswordLength) {
|
|
24
|
+
PasswordValidator.validatePassword(newPassword, {
|
|
25
|
+
minLength: minPasswordLength
|
|
26
|
+
});
|
|
27
|
+
if (Is.stringValue(currentPassword)) {
|
|
28
|
+
const saltBytes = Converter.base64ToBytes(user.salt);
|
|
29
|
+
const passwordBytes = Converter.utf8ToBytes(currentPassword);
|
|
30
|
+
const hashedCurrentPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);
|
|
31
|
+
if (!PasswordValidator.comparePasswordHashes(hashedCurrentPassword, user.password)) {
|
|
32
|
+
throw new GeneralError(PasswordHelper.CLASS_NAME, "currentPasswordMismatch");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const saltBytes = RandomHelper.generate(16);
|
|
36
|
+
const passwordBytes = Converter.utf8ToBytes(newPassword);
|
|
37
|
+
const hashedPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);
|
|
38
|
+
const updatedUser = {
|
|
39
|
+
email: user.email,
|
|
40
|
+
salt: Converter.bytesToBase64(saltBytes),
|
|
41
|
+
password: hashedPassword,
|
|
42
|
+
identity: user.identity,
|
|
43
|
+
organization: user.organization,
|
|
44
|
+
scope: user.scope
|
|
45
|
+
};
|
|
46
|
+
await userEntityStorage.set(updatedUser);
|
|
47
|
+
await authenticationAuditService?.create({
|
|
48
|
+
actorId: user.email,
|
|
49
|
+
event: AuthAuditEvent.PasswordChanged,
|
|
50
|
+
data: {
|
|
51
|
+
userIdentity: updatedUser.identity,
|
|
52
|
+
organizationIdentity: updatedUser.organization
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=passwordHelper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"passwordHelper.js","sourceRoot":"","sources":["../../../src/utils/passwordHelper.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAKxE;;GAEG;AACH,MAAM,OAAO,cAAc;IAC1B;;OAEG;IACI,MAAM,CAAU,UAAU,oBAAoC;IAErE;;;;;;;;;;OAUG;IACI,MAAM,CAAC,KAAK,CAAC,cAAc,CACjC,iBAA8D,EAC9D,0BAAqE,EACrE,IAAwB,EACxB,WAAmB,EACnB,eAAwB,EACxB,iBA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Ac,CAAC,eAAe;YACrC,IAAI,EAAE;gBACL,YAAY,EAAE,WAAW,CAAC,QAAQ;gBAClC,oBAAoB,EAAE,WAAW,CAAC,YAAY;aAC9C;SACD,CAAC,CAAC;IACJ,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IAuthenticationAuditComponent } from \"@twin.org/api-auth-entity-storage-models\";\nimport { AuthAuditEvent } from \"@twin.org/api-auth-entity-storage-models\";\nimport { Converter, GeneralError, Is, RandomHelper } from \"@twin.org/core\";\nimport { PasswordGenerator, PasswordValidator } from \"@twin.org/crypto\";\nimport type { IEntityStorageConnector } from \"@twin.org/entity-storage-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport type { AuthenticationUser } from \"../entities/authenticationUser.js\";\n\n/**\n * Helper class for password operations.\n */\nexport class PasswordHelper {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<PasswordHelper>();\n\n\t/**\n\t * Update the password for a user.\n\t * Validates password strength, verifies the current password if provided, then hashes and stores the new password and raises an audit event.\n\t * @param userEntityStorage The entity storage for users.\n\t * @param authenticationAuditService The optional audit service.\n\t * @param user The user whose password is being updated.\n\t * @param newPassword The new password to set.\n\t * @param currentPassword The current password to verify against, if supplied.\n\t * @param minPasswordLength Optional minimum password length for validation.\n\t * @returns Nothing.\n\t */\n\tpublic static async updatePassword(\n\t\tuserEntityStorage: IEntityStorageConnector<AuthenticationUser>,\n\t\tauthenticationAuditService: IAuthenticationAuditComponent | undefined,\n\t\tuser: AuthenticationUser,\n\t\tnewPassword: string,\n\t\tcurrentPassword?: string,\n\t\tminPasswordLength?: number\n\t): Promise<void> {\n\t\tPasswordValidator.validatePassword(newPassword, {\n\t\t\tminLength: minPasswordLength\n\t\t});\n\n\t\tif (Is.stringValue(currentPassword)) {\n\t\t\tconst saltBytes = Converter.base64ToBytes(user.salt);\n\t\t\tconst passwordBytes = Converter.utf8ToBytes(currentPassword);\n\t\t\tconst hashedCurrentPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);\n\t\t\tif (!PasswordValidator.comparePasswordHashes(hashedCurrentPassword, user.password)) {\n\t\t\t\tthrow new GeneralError(PasswordHelper.CLASS_NAME, \"currentPasswordMismatch\");\n\t\t\t}\n\t\t}\n\n\t\tconst saltBytes = RandomHelper.generate(16);\n\t\tconst passwordBytes = Converter.utf8ToBytes(newPassword);\n\t\tconst hashedPassword = await PasswordGenerator.hashPassword(passwordBytes, saltBytes);\n\n\t\tconst updatedUser: AuthenticationUser = {\n\t\t\temail: user.email,\n\t\t\tsalt: Converter.bytesToBase64(saltBytes),\n\t\t\tpassword: hashedPassword,\n\t\t\tidentity: user.identity,\n\t\t\torganization: user.organization,\n\t\t\tscope: user.scope\n\t\t};\n\n\t\tawait userEntityStorage.set(updatedUser);\n\t\tawait authenticationAuditService?.create({\n\t\t\tactorId: user.email,\n\t\t\tevent: AuthAuditEvent.PasswordChanged,\n\t\t\tdata: {\n\t\t\t\tuserIdentity: updatedUser.identity,\n\t\t\t\torganizationIdentity: updatedUser.organization\n\t\t\t}\n\t\t});\n\t}\n}\n"]}
|