@solidxai/core 0.1.13-beta.19 → 0.1.13-beta.20
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/CHANGELOG.md +584 -0
- package/dist/constants/error-messages.d.ts +7 -0
- package/dist/constants/error-messages.d.ts.map +1 -1
- package/dist/constants/error-messages.js +7 -0
- package/dist/constants/error-messages.js.map +1 -1
- package/dist/constants/success-messages.d.ts +3 -0
- package/dist/constants/success-messages.d.ts.map +1 -1
- package/dist/constants/success-messages.js +3 -0
- package/dist/constants/success-messages.js.map +1 -1
- package/dist/controllers/mpin-authentication.controller.d.ts +44 -0
- package/dist/controllers/mpin-authentication.controller.d.ts.map +1 -0
- package/dist/controllers/mpin-authentication.controller.js +102 -0
- package/dist/controllers/mpin-authentication.controller.js.map +1 -0
- package/dist/dtos/change-mpin.dto.d.ts +6 -0
- package/dist/dtos/change-mpin.dto.d.ts.map +1 -0
- package/dist/dtos/change-mpin.dto.js +39 -0
- package/dist/dtos/change-mpin.dto.js.map +1 -0
- package/dist/dtos/mpin-login.dto.d.ts +5 -0
- package/dist/dtos/mpin-login.dto.d.ts.map +1 -0
- package/dist/dtos/mpin-login.dto.js +33 -0
- package/dist/dtos/mpin-login.dto.js.map +1 -0
- package/dist/dtos/setup-mpin.dto.d.ts +7 -0
- package/dist/dtos/setup-mpin.dto.d.ts.map +1 -0
- package/dist/dtos/setup-mpin.dto.js +47 -0
- package/dist/dtos/setup-mpin.dto.js.map +1 -0
- package/dist/entities/user-device-credential.entity.d.ts +18 -0
- package/dist/entities/user-device-credential.entity.d.ts.map +1 -0
- package/dist/entities/user-device-credential.entity.js +91 -0
- package/dist/entities/user-device-credential.entity.js.map +1 -0
- package/dist/helpers/solid-core-error-codes-provider.service.d.ts.map +1 -1
- package/dist/helpers/solid-core-error-codes-provider.service.js +45 -0
- package/dist/helpers/solid-core-error-codes-provider.service.js.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -1
- package/dist/repository/user-device-credential.repository.d.ts +12 -0
- package/dist/repository/user-device-credential.repository.d.ts.map +1 -0
- package/dist/repository/user-device-credential.repository.js +34 -0
- package/dist/repository/user-device-credential.repository.js.map +1 -0
- package/dist/seeders/seed-data/solid-core-metadata.json +158 -0
- package/dist/services/mpin.service.d.ts +67 -0
- package/dist/services/mpin.service.d.ts.map +1 -0
- package/dist/services/mpin.service.js +282 -0
- package/dist/services/mpin.service.js.map +1 -0
- package/dist/services/settings/default-settings-provider.service.d.ts +120 -0
- package/dist/services/settings/default-settings-provider.service.d.ts.map +1 -1
- package/dist/services/settings/default-settings-provider.service.js +66 -0
- package/dist/services/settings/default-settings-provider.service.js.map +1 -1
- package/dist/solid-core.module.d.ts.map +1 -1
- package/dist/solid-core.module.js +8 -0
- package/dist/solid-core.module.js.map +1 -1
- package/package.json +1 -1
- package/postman/mpin.postman_collection.json +1045 -0
- package/src/constants/error-messages.ts +14 -0
- package/src/constants/success-messages.ts +5 -0
- package/src/controllers/mpin-authentication.controller.ts +67 -0
- package/src/dtos/change-mpin.dto.ts +18 -0
- package/src/dtos/mpin-login.dto.ts +24 -0
- package/src/dtos/setup-mpin.dto.ts +51 -0
- package/src/entities/user-device-credential.entity.ts +130 -0
- package/src/helpers/solid-core-error-codes-provider.service.ts +53 -0
- package/src/index.ts +6 -0
- package/src/repository/user-device-credential.repository.ts +17 -0
- package/src/seeders/seed-data/solid-core-metadata.json +158 -0
- package/src/services/mpin.service.ts +447 -0
- package/src/services/settings/default-settings-provider.service.ts +71 -0
- package/src/solid-core.module.ts +8 -0
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BadRequestException,
|
|
3
|
+
Injectable,
|
|
4
|
+
Logger,
|
|
5
|
+
NotFoundException,
|
|
6
|
+
UnauthorizedException,
|
|
7
|
+
} from '@nestjs/common';
|
|
8
|
+
import { createHash, randomBytes } from 'crypto';
|
|
9
|
+
import { ERROR_MESSAGES } from 'src/constants/error-messages';
|
|
10
|
+
import { SUCCESS_MESSAGES } from 'src/constants/success-messages';
|
|
11
|
+
import { ChangeMpinDto } from 'src/dtos/change-mpin.dto';
|
|
12
|
+
import { MpinLoginDto } from 'src/dtos/mpin-login.dto';
|
|
13
|
+
import { SetupMpinDto } from 'src/dtos/setup-mpin.dto';
|
|
14
|
+
import { UserDeviceCredential } from 'src/entities/user-device-credential.entity';
|
|
15
|
+
import { ActiveUserData } from 'src/interfaces/active-user-data.interface';
|
|
16
|
+
import { UserDeviceCredentialRepository } from 'src/repository/user-device-credential.repository';
|
|
17
|
+
import { UserRepository } from 'src/repository/user.repository';
|
|
18
|
+
import type { SolidCoreSetting } from 'src/services/settings/default-settings-provider.service';
|
|
19
|
+
import { AuthenticationService } from './authentication.service';
|
|
20
|
+
import { HashingService } from './hashing.service';
|
|
21
|
+
import { SettingService } from './setting.service';
|
|
22
|
+
import { UserActivityHistoryService } from './user-activity-history.service';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The most-chosen PINs in published analyses of breached sets. `1234` alone
|
|
26
|
+
* accounts for roughly a tenth of four-digit choices, so a list this short
|
|
27
|
+
* removes a disproportionate share of guessable values.
|
|
28
|
+
*/
|
|
29
|
+
const MPIN_DENYLIST = new Set([
|
|
30
|
+
'0000', '1111', '2222', '3333', '4444', '5555', '6666', '7777', '8888', '9999',
|
|
31
|
+
'1234', '4321', '1212', '2001', '1004', '2000', '6969', '2580',
|
|
32
|
+
'000000', '111111', '123456', '654321', '121212', '112233', '123123',
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
@Injectable()
|
|
36
|
+
export class MpinService {
|
|
37
|
+
private readonly logger = new Logger(MpinService.name);
|
|
38
|
+
|
|
39
|
+
constructor(
|
|
40
|
+
private readonly credentialRepository: UserDeviceCredentialRepository,
|
|
41
|
+
private readonly userRepository: UserRepository,
|
|
42
|
+
private readonly hashingService: HashingService,
|
|
43
|
+
private readonly settingService: SettingService,
|
|
44
|
+
private readonly authenticationService: AuthenticationService,
|
|
45
|
+
private readonly userActivityHistoryService: UserActivityHistoryService,
|
|
46
|
+
) { }
|
|
47
|
+
|
|
48
|
+
// ---------------------------------------------------------------- setup
|
|
49
|
+
|
|
50
|
+
async setupMpin(activeUser: ActiveUserData, dto: SetupMpinDto) {
|
|
51
|
+
this.assertEnabled();
|
|
52
|
+
this.assertMpinAcceptable(dto.mpin);
|
|
53
|
+
|
|
54
|
+
// The account comes from the access token, never from the body - a
|
|
55
|
+
// client can only ever create a credential for the user it is signed
|
|
56
|
+
// in as.
|
|
57
|
+
const user = await this.userRepository.findOne({ where: { id: activeUser.sub } });
|
|
58
|
+
if (!user) {
|
|
59
|
+
throw new NotFoundException(ERROR_MESSAGES.USER_NOT_FOUND);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Lower-cased because @IsUUID is case-insensitive: iOS renders a UUID
|
|
63
|
+
// uppercase (identifierForVendor.uuidString) while Android renders it
|
|
64
|
+
// lowercase, and both validate. Without normalising, the same physical
|
|
65
|
+
// device could present two spellings, miss this exact-match lookup and
|
|
66
|
+
// end up with two credential rows consuming two slots against the cap.
|
|
67
|
+
const deviceId = dto.deviceId.toLowerCase();
|
|
68
|
+
|
|
69
|
+
const existing = await this.credentialRepository.findOne({
|
|
70
|
+
where: { user: { id: user.id }, deviceId },
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// Re-running setup on the same device rotates the credential rather
|
|
74
|
+
// than adding a second one.
|
|
75
|
+
const record = existing ?? this.credentialRepository.create({
|
|
76
|
+
user,
|
|
77
|
+
deviceId,
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// Recomputed on every setup so a renamed user does not keep a stale
|
|
81
|
+
// key. It is an identifier for humans and tooling, never a lookup key,
|
|
82
|
+
// so drift here costs nothing operationally.
|
|
83
|
+
record.credentialKey = this.buildCredentialKey(user.username, deviceId);
|
|
84
|
+
|
|
85
|
+
const credentialRef = this.mintCredentialRef();
|
|
86
|
+
record.hashedCredentialRef = this.hashCredentialRef(credentialRef);
|
|
87
|
+
record.hashedMpin = await this.hashingService.hash(dto.mpin);
|
|
88
|
+
record.mpinScheme = this.hashingService.name();
|
|
89
|
+
record.mpinSchemeVersion = this.hashingService.currentVersion();
|
|
90
|
+
record.deviceName = dto.deviceName ?? null;
|
|
91
|
+
record.platform = dto.platform ?? null;
|
|
92
|
+
record.isActive = true;
|
|
93
|
+
record.failedAttempts = 0;
|
|
94
|
+
record.lockedUntil = null;
|
|
95
|
+
|
|
96
|
+
await this.evictOldestIfAtCap(user.id, existing?.id);
|
|
97
|
+
await this.credentialRepository.save(record);
|
|
98
|
+
|
|
99
|
+
// Returned once. Only its SHA-256 is stored, so it can never be
|
|
100
|
+
// re-issued - the client must persist it before reporting success.
|
|
101
|
+
return { credentialRef, message: SUCCESS_MESSAGES.MPIN_SETUP_SUCCESS };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async changeMpin(activeUser: ActiveUserData, dto: ChangeMpinDto) {
|
|
105
|
+
this.assertEnabled();
|
|
106
|
+
this.assertMpinAcceptable(dto.newMpin);
|
|
107
|
+
|
|
108
|
+
// Scoped to the caller, so holding someone else's handle is not enough
|
|
109
|
+
// to change their MPIN.
|
|
110
|
+
const credential = await this.credentialRepository.findOne({
|
|
111
|
+
where: {
|
|
112
|
+
hashedCredentialRef: this.hashCredentialRef(dto.credentialRef),
|
|
113
|
+
user: { id: activeUser.sub },
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
if (!credential || !credential.isActive) {
|
|
118
|
+
throw new UnauthorizedException(ERROR_MESSAGES.MPIN_INVALID);
|
|
119
|
+
}
|
|
120
|
+
this.assertNotLocked(credential);
|
|
121
|
+
|
|
122
|
+
const matches = await this.hashingService.compare(
|
|
123
|
+
dto.currentMpin,
|
|
124
|
+
credential.hashedMpin,
|
|
125
|
+
credential.mpinSchemeVersion,
|
|
126
|
+
);
|
|
127
|
+
if (!matches) {
|
|
128
|
+
throw await this.registerFailedAttempt(credential);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Rotate the handle alongside the MPIN: a changed credential should
|
|
132
|
+
// invalidate anything captured previously.
|
|
133
|
+
const credentialRef = this.mintCredentialRef();
|
|
134
|
+
credential.hashedCredentialRef = this.hashCredentialRef(credentialRef);
|
|
135
|
+
credential.hashedMpin = await this.hashingService.hash(dto.newMpin);
|
|
136
|
+
credential.mpinScheme = this.hashingService.name();
|
|
137
|
+
credential.mpinSchemeVersion = this.hashingService.currentVersion();
|
|
138
|
+
credential.failedAttempts = 0;
|
|
139
|
+
credential.lockedUntil = null;
|
|
140
|
+
await this.credentialRepository.save(credential);
|
|
141
|
+
|
|
142
|
+
return { credentialRef, message: SUCCESS_MESSAGES.MPIN_CHANGED_SUCCESS };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ---------------------------------------------------------------- login
|
|
146
|
+
|
|
147
|
+
async loginWithMpin(dto: MpinLoginDto) {
|
|
148
|
+
this.assertEnabled();
|
|
149
|
+
|
|
150
|
+
// A single indexed exact-match lookup. The row already names the user,
|
|
151
|
+
// so there is nothing to resolve and no identifier to enumerate with.
|
|
152
|
+
const credential = await this.credentialRepository.findOne({
|
|
153
|
+
where: { hashedCredentialRef: this.hashCredentialRef(dto.credentialRef) },
|
|
154
|
+
relations: { user: { roles: true } },
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// An unknown handle is reported exactly as a wrong MPIN is.
|
|
158
|
+
if (!credential || !credential.user) {
|
|
159
|
+
throw new UnauthorizedException(ERROR_MESSAGES.MPIN_INVALID);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// A dead credential is reported as such regardless of what MPIN was
|
|
163
|
+
// supplied. Gating this on a correct MPIN would be marginally more
|
|
164
|
+
// conservative, but it protects almost nothing - "this dead handle was
|
|
165
|
+
// once real" grants no capability - and it costs an asymmetry that
|
|
166
|
+
// reads as a bug: the attempt that causes deactivation reports
|
|
167
|
+
// MPIN_REVOKED, while the very next identical attempt would report
|
|
168
|
+
// MPIN_INVALID. The enumeration resistance that matters comes from the
|
|
169
|
+
// handle being unguessable, not from this branch.
|
|
170
|
+
if (!credential.isActive) {
|
|
171
|
+
throw new UnauthorizedException(ERROR_MESSAGES.MPIN_REVOKED);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Checked before the hash comparison, so attempts made during a lockout
|
|
175
|
+
// neither extend it nor cost a bcrypt call.
|
|
176
|
+
this.assertNotLocked(credential);
|
|
177
|
+
|
|
178
|
+
const matches = await this.hashingService.compare(
|
|
179
|
+
dto.mpin,
|
|
180
|
+
credential.hashedMpin,
|
|
181
|
+
credential.mpinSchemeVersion,
|
|
182
|
+
);
|
|
183
|
+
|
|
184
|
+
if (!matches) {
|
|
185
|
+
throw await this.registerFailedAttempt(credential);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
credential.failedAttempts = 0;
|
|
189
|
+
credential.lockedUntil = null;
|
|
190
|
+
credential.lastUsedAt = new Date();
|
|
191
|
+
if (this.hashingService.needsRehash(credential.hashedMpin, credential.mpinSchemeVersion)) {
|
|
192
|
+
credential.hashedMpin = await this.hashingService.hash(dto.mpin);
|
|
193
|
+
credential.mpinScheme = this.hashingService.name();
|
|
194
|
+
credential.mpinSchemeVersion = this.hashingService.currentVersion();
|
|
195
|
+
}
|
|
196
|
+
await this.credentialRepository.save(credential);
|
|
197
|
+
|
|
198
|
+
const user = credential.user;
|
|
199
|
+
await this.userActivityHistoryService.logEvent('login', user);
|
|
200
|
+
|
|
201
|
+
// A fresh token pair - never a replay of a stored refresh token. This
|
|
202
|
+
// is what makes MPIN survive logout and refresh-token expiry. The
|
|
203
|
+
// stable deviceId keeps repeat logins in one session bucket.
|
|
204
|
+
const tokens = await this.authenticationService.generateTokens(user, credential.deviceId);
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
user: {
|
|
208
|
+
id: user.id,
|
|
209
|
+
email: user.email,
|
|
210
|
+
mobile: user.mobile,
|
|
211
|
+
username: user.username,
|
|
212
|
+
forcePasswordChange: user.forcePasswordChange,
|
|
213
|
+
roles: (user.roles ?? []).map((role) => role.name),
|
|
214
|
+
},
|
|
215
|
+
...tokens,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ----------------------------------------------------- device management
|
|
220
|
+
|
|
221
|
+
async listDevices(activeUser: ActiveUserData) {
|
|
222
|
+
this.assertEnabled();
|
|
223
|
+
|
|
224
|
+
const credentials = await this.credentialRepository.find({
|
|
225
|
+
where: { user: { id: activeUser.sub }, isActive: true },
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
return credentials
|
|
229
|
+
.sort((a, b) => this.lastUsedMillis(b) - this.lastUsedMillis(a))
|
|
230
|
+
.map((credential) => this.toDeviceView(credential));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async revokeDevice(activeUser: ActiveUserData, id: number) {
|
|
234
|
+
this.assertEnabled();
|
|
235
|
+
|
|
236
|
+
const credential = await this.credentialRepository.findOne({
|
|
237
|
+
where: { id, user: { id: activeUser.sub } },
|
|
238
|
+
});
|
|
239
|
+
if (!credential) {
|
|
240
|
+
throw new NotFoundException(ERROR_MESSAGES.MPIN_CREDENTIAL_NOT_FOUND);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Soft-delete. The row survives so a correct MPIN can be answered with
|
|
244
|
+
// MPIN_REVOKED rather than a baffling MPIN_INVALID; only active rows
|
|
245
|
+
// count towards the device cap.
|
|
246
|
+
credential.isActive = false;
|
|
247
|
+
await this.credentialRepository.save(credential);
|
|
248
|
+
|
|
249
|
+
return { message: SUCCESS_MESSAGES.MPIN_DEVICE_REVOKED };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// -------------------------------------------------------------- internals
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Never exposes the stored hashes, independently of whatever serialiser
|
|
256
|
+
* configuration a consuming app runs. The entity also withholds them via
|
|
257
|
+
* @Exclude()/@Expose(), but building the response explicitly means a
|
|
258
|
+
* carelessly added decorator cannot leak a credential.
|
|
259
|
+
*/
|
|
260
|
+
private toDeviceView(credential: UserDeviceCredential) {
|
|
261
|
+
return {
|
|
262
|
+
id: credential.id,
|
|
263
|
+
deviceId: credential.deviceId,
|
|
264
|
+
deviceName: credential.deviceName,
|
|
265
|
+
platform: credential.platform,
|
|
266
|
+
isActive: credential.isActive,
|
|
267
|
+
failedAttempts: credential.failedAttempts,
|
|
268
|
+
lockedUntil: credential.lockedUntil,
|
|
269
|
+
lastUsedAt: credential.lastUsedAt,
|
|
270
|
+
createdAt: credential.createdAt,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private assertEnabled(): void {
|
|
275
|
+
if (!this.settingService.getConfigValue<SolidCoreSetting>('mpinEnabled')) {
|
|
276
|
+
// 404 rather than 403: a disabled feature should look absent.
|
|
277
|
+
throw new NotFoundException(ERROR_MESSAGES.MPIN_NOT_ENABLED);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private assertNotLocked(credential: UserDeviceCredential): void {
|
|
282
|
+
if (credential.lockedUntil && credential.lockedUntil.getTime() > Date.now()) {
|
|
283
|
+
throw new UnauthorizedException(ERROR_MESSAGES.MPIN_LOCKED);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private assertMpinAcceptable(mpin: string): void {
|
|
288
|
+
const pattern = String(
|
|
289
|
+
this.settingService.getConfigValue<SolidCoreSetting>('mpinRegex') ?? '^\\d{4,6}$',
|
|
290
|
+
);
|
|
291
|
+
|
|
292
|
+
// Fails closed. `matches` starts false and a malformed pattern - the
|
|
293
|
+
// setting is admin-editable free text - becomes a rejection rather
|
|
294
|
+
// than a skipped check, so a typo cannot silently let users set an
|
|
295
|
+
// MPIN weaker than policy allows.
|
|
296
|
+
let matches = false;
|
|
297
|
+
try {
|
|
298
|
+
matches = new RegExp(pattern).test(mpin);
|
|
299
|
+
} catch {
|
|
300
|
+
this.logger.error(`Invalid mpinRegex setting: ${pattern}`);
|
|
301
|
+
throw new BadRequestException(ERROR_MESSAGES.MPIN_FORMAT_INVALID);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (!matches) {
|
|
305
|
+
throw new BadRequestException(ERROR_MESSAGES.MPIN_FORMAT_INVALID);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Predictability is semantics, not shape - a regex expressing "not
|
|
309
|
+
// sequential" would be unreadable and easy to get subtly wrong.
|
|
310
|
+
if (this.isPredictable(mpin)) {
|
|
311
|
+
// Safe to distinguish, and 400 rather than 401: this only ever
|
|
312
|
+
// happens on a bearer-authenticated route, so it is a validation
|
|
313
|
+
// failure rather than an authentication one.
|
|
314
|
+
throw new BadRequestException(ERROR_MESSAGES.MPIN_TOO_PREDICTABLE);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
private isPredictable(mpin: string): boolean {
|
|
319
|
+
if (/^(\d)\1+$/.test(mpin)) {
|
|
320
|
+
return true;
|
|
321
|
+
}
|
|
322
|
+
if (this.isSequential(mpin)) {
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
return MPIN_DENYLIST.has(mpin);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
private isSequential(mpin: string): boolean {
|
|
329
|
+
let ascending = true;
|
|
330
|
+
let descending = true;
|
|
331
|
+
for (let i = 1; i < mpin.length; i++) {
|
|
332
|
+
const step = mpin.charCodeAt(i) - mpin.charCodeAt(i - 1);
|
|
333
|
+
if (step !== 1) ascending = false;
|
|
334
|
+
if (step !== -1) descending = false;
|
|
335
|
+
}
|
|
336
|
+
return ascending || descending;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Records a failure and escalates. `failedAttempts` is cumulative and
|
|
341
|
+
* resets only on success - never when a lockout expires - which is what
|
|
342
|
+
* makes the second threshold detectable without a separate counter.
|
|
343
|
+
*
|
|
344
|
+
* Returns the exception for the caller to throw, so the save is always
|
|
345
|
+
* awaited before the response leaves.
|
|
346
|
+
*/
|
|
347
|
+
private async registerFailedAttempt(
|
|
348
|
+
credential: UserDeviceCredential,
|
|
349
|
+
): Promise<UnauthorizedException> {
|
|
350
|
+
const lockThreshold = Number(
|
|
351
|
+
this.settingService.getConfigValue<SolidCoreSetting>('mpinMaxFailedAttempts'),
|
|
352
|
+
);
|
|
353
|
+
const deactivateThreshold = Number(
|
|
354
|
+
this.settingService.getConfigValue<SolidCoreSetting>('mpinMaxTotalFailedAttempts'),
|
|
355
|
+
);
|
|
356
|
+
const lockoutSeconds = Number(
|
|
357
|
+
this.settingService.getConfigValue<SolidCoreSetting>('mpinLockoutDuration'),
|
|
358
|
+
);
|
|
359
|
+
|
|
360
|
+
credential.failedAttempts += 1;
|
|
361
|
+
let error = new UnauthorizedException(ERROR_MESSAGES.MPIN_INVALID);
|
|
362
|
+
|
|
363
|
+
if (credential.isActive && deactivateThreshold > 0 && credential.failedAttempts >= deactivateThreshold) {
|
|
364
|
+
credential.isActive = false;
|
|
365
|
+
credential.lockedUntil = null;
|
|
366
|
+
// This attempt caused the deactivation, so it is reported. The
|
|
367
|
+
// caller reached the limit on a handle they demonstrably hold and
|
|
368
|
+
// caused this state themselves, so nothing is disclosed - and
|
|
369
|
+
// without it they would keep retrying a permanently dead credential.
|
|
370
|
+
error = new UnauthorizedException(ERROR_MESSAGES.MPIN_REVOKED);
|
|
371
|
+
} else if (credential.isActive && lockThreshold > 0 && credential.failedAttempts % lockThreshold === 0) {
|
|
372
|
+
credential.lockedUntil = new Date(Date.now() + lockoutSeconds * 1000);
|
|
373
|
+
error = new UnauthorizedException(ERROR_MESSAGES.MPIN_LOCKED);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
await this.credentialRepository.save(credential);
|
|
377
|
+
return error;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* The cap evicts rather than rejects. A reinstall wipes the client's
|
|
382
|
+
* deviceId, so the app generates a new one and setup adds a row instead of
|
|
383
|
+
* replacing the old, orphaned one. Rejecting at the cap would mean a user
|
|
384
|
+
* who reinstalls a few times could never set MPIN up again.
|
|
385
|
+
*/
|
|
386
|
+
private async evictOldestIfAtCap(userId: number, excludeId?: number): Promise<void> {
|
|
387
|
+
const cap = Number(
|
|
388
|
+
this.settingService.getConfigValue<SolidCoreSetting>('mpinMaxDevicesPerUser'),
|
|
389
|
+
);
|
|
390
|
+
if (!cap || cap <= 0) {
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const active = (await this.credentialRepository.find({
|
|
395
|
+
where: { user: { id: userId }, isActive: true },
|
|
396
|
+
})).filter((credential) => credential.id !== excludeId);
|
|
397
|
+
|
|
398
|
+
// One slot is about to be taken by the credential being written.
|
|
399
|
+
const overflow = active.length - (cap - 1);
|
|
400
|
+
if (overflow <= 0) {
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Sorted in JS rather than SQL because a never-used credential has a
|
|
405
|
+
// null lastUsedAt, and Postgres sorts nulls last on ASC - which would
|
|
406
|
+
// treat the least-used rows as the most recently used.
|
|
407
|
+
const doomed = active
|
|
408
|
+
.sort((a, b) => this.lastUsedMillis(a) - this.lastUsedMillis(b))
|
|
409
|
+
.slice(0, overflow);
|
|
410
|
+
|
|
411
|
+
for (const credential of doomed) {
|
|
412
|
+
credential.isActive = false;
|
|
413
|
+
}
|
|
414
|
+
await this.credentialRepository.save(doomed);
|
|
415
|
+
this.logger.log(
|
|
416
|
+
`Evicted ${doomed.length} MPIN credential(s) for user ${userId} at the device cap of ${cap}`,
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
private lastUsedMillis(credential: UserDeviceCredential): number {
|
|
421
|
+
return credential.lastUsedAt?.getTime() ?? credential.createdAt?.getTime() ?? 0;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* `<username>-<deviceId>`, the model's natural key.
|
|
426
|
+
*
|
|
427
|
+
* Not slugified: lodash `kebabCase` splits digit/letter boundaries, so it
|
|
428
|
+
* would shred a UUID into `3-f-7-b-8-a-10-...`. The username is lower-cased
|
|
429
|
+
* and stripped of whitespace, which is enough for a key that is only ever
|
|
430
|
+
* read, never parsed back into its parts.
|
|
431
|
+
*/
|
|
432
|
+
private buildCredentialKey(username: string, deviceId: string): string {
|
|
433
|
+
const normalizedUsername = (username ?? '').trim().toLowerCase().replace(/\s+/g, '-');
|
|
434
|
+
return `${normalizedUsername}-${deviceId}`;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private mintCredentialRef(): string {
|
|
438
|
+
return randomBytes(32).toString('hex');
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// SHA-256, not bcrypt: 256 bits of randomness has nothing to brute-force,
|
|
442
|
+
// so a slow hash would only add latency to every login. Same reasoning as
|
|
443
|
+
// ApiKeyService.hash.
|
|
444
|
+
private hashCredentialRef(credentialRef: string): string {
|
|
445
|
+
return createHash('sha256').update(credentialRef).digest('hex');
|
|
446
|
+
}
|
|
447
|
+
}
|
|
@@ -1249,6 +1249,77 @@ const getSolidCoreSettings = (isProd: boolean) =>
|
|
|
1249
1249
|
sortOrder: 200,
|
|
1250
1250
|
controlType: "boolean",
|
|
1251
1251
|
},
|
|
1252
|
+
{
|
|
1253
|
+
moduleName: "solid-core",
|
|
1254
|
+
key: "mpinEnabled",
|
|
1255
|
+
value: false,
|
|
1256
|
+
level: SettingLevel.SystemAdminEditable,
|
|
1257
|
+
label: "Enable MPIN Sign-in",
|
|
1258
|
+
group: "authentication-settings",
|
|
1259
|
+
sortOrder: 210,
|
|
1260
|
+
controlType: "boolean",
|
|
1261
|
+
helpText:
|
|
1262
|
+
"Allows users to set a short device PIN for faster sign-in. Every MPIN route returns 404 while this is off.",
|
|
1263
|
+
},
|
|
1264
|
+
{
|
|
1265
|
+
moduleName: "solid-core",
|
|
1266
|
+
key: "mpinRegex",
|
|
1267
|
+
value: process.env.IAM_MPIN_REGEX ?? "^\\d{4,6}$",
|
|
1268
|
+
level: SettingLevel.SystemAdminEditable,
|
|
1269
|
+
label: "MPIN Format",
|
|
1270
|
+
group: "authentication-settings",
|
|
1271
|
+
sortOrder: 211,
|
|
1272
|
+
controlType: "shortText",
|
|
1273
|
+
helpText:
|
|
1274
|
+
"Regular expression the MPIN must match. Sole authority on MPIN length - the default allows 4 to 6 digits. Predictable PINs (repeated or sequential digits) are rejected separately.",
|
|
1275
|
+
},
|
|
1276
|
+
{
|
|
1277
|
+
moduleName: "solid-core",
|
|
1278
|
+
key: "mpinMaxFailedAttempts",
|
|
1279
|
+
value: parseInt(process.env.IAM_MPIN_MAX_FAILED_ATTEMPTS ?? "5", 10),
|
|
1280
|
+
level: SettingLevel.SystemAdminEditable,
|
|
1281
|
+
label: "MPIN Attempts Before Lockout",
|
|
1282
|
+
group: "authentication-settings",
|
|
1283
|
+
sortOrder: 212,
|
|
1284
|
+
controlType: "numeric",
|
|
1285
|
+
helpText:
|
|
1286
|
+
"Cumulative failed attempts that trigger a temporary lockout. The counter resets only on a successful MPIN sign-in, not when the lockout expires.",
|
|
1287
|
+
},
|
|
1288
|
+
{
|
|
1289
|
+
moduleName: "solid-core",
|
|
1290
|
+
key: "mpinLockoutDuration",
|
|
1291
|
+
value: parseInt(process.env.IAM_MPIN_LOCKOUT_DURATION ?? "900", 10),
|
|
1292
|
+
level: SettingLevel.SystemAdminEditable,
|
|
1293
|
+
label: "MPIN Lockout Duration (seconds)",
|
|
1294
|
+
group: "authentication-settings",
|
|
1295
|
+
sortOrder: 213,
|
|
1296
|
+
controlType: "numeric",
|
|
1297
|
+
helpText: "How long the temporary lockout lasts.",
|
|
1298
|
+
},
|
|
1299
|
+
{
|
|
1300
|
+
moduleName: "solid-core",
|
|
1301
|
+
key: "mpinMaxTotalFailedAttempts",
|
|
1302
|
+
value: parseInt(process.env.IAM_MPIN_MAX_TOTAL_FAILED_ATTEMPTS ?? "10", 10),
|
|
1303
|
+
level: SettingLevel.SystemAdminEditable,
|
|
1304
|
+
label: "MPIN Attempts Before Permanent Deactivation",
|
|
1305
|
+
group: "authentication-settings",
|
|
1306
|
+
sortOrder: 214,
|
|
1307
|
+
controlType: "numeric",
|
|
1308
|
+
helpText:
|
|
1309
|
+
"Cumulative failed attempts that permanently disable MPIN on that device. Must exceed the lockout threshold. The account itself is never locked - the user signs in normally and sets MPIN up again.",
|
|
1310
|
+
},
|
|
1311
|
+
{
|
|
1312
|
+
moduleName: "solid-core",
|
|
1313
|
+
key: "mpinMaxDevicesPerUser",
|
|
1314
|
+
value: parseInt(process.env.IAM_MPIN_MAX_DEVICES_PER_USER ?? "5", 10),
|
|
1315
|
+
level: SettingLevel.SystemAdminEditable,
|
|
1316
|
+
label: "Max MPIN Devices Per User",
|
|
1317
|
+
group: "authentication-settings",
|
|
1318
|
+
sortOrder: 215,
|
|
1319
|
+
controlType: "numeric",
|
|
1320
|
+
helpText:
|
|
1321
|
+
"At the cap the least recently used credential is evicted rather than the setup rejected, so repeated app reinstalls cannot lock a user out of MPIN setup.",
|
|
1322
|
+
},
|
|
1252
1323
|
// queues-settings-provider.service.ts
|
|
1253
1324
|
{
|
|
1254
1325
|
moduleName: "solid-core",
|
package/src/solid-core.module.ts
CHANGED
|
@@ -97,6 +97,7 @@ import { GoogleAuthenticationController } from "./controllers/google-authenticat
|
|
|
97
97
|
import { MenuItemMetadataController } from "./controllers/menu-item-metadata.controller";
|
|
98
98
|
import { MqMessageQueueController } from "./controllers/mq-message-queue.controller";
|
|
99
99
|
import { MqMessageController } from "./controllers/mq-message.controller";
|
|
100
|
+
import { MpinAuthenticationController } from "./controllers/mpin-authentication.controller";
|
|
100
101
|
import { OTPAuthenticationController } from "./controllers/otp-authentication.controller";
|
|
101
102
|
import { ServiceController } from "./controllers/service.controller";
|
|
102
103
|
import { SmsTemplateController } from "./controllers/sms-template.controller";
|
|
@@ -166,6 +167,7 @@ import { TwilioSmsQueueSubscriberRedis } from "./jobs/redis/twilio-sms-subscribe
|
|
|
166
167
|
import { UserRegistrationListener } from "./listeners/user-registration.listener";
|
|
167
168
|
import { GoogleOauthStrategy } from "./passport-strategies/google-oauth.strategy";
|
|
168
169
|
import { ApiKeyService } from "./services/api-key.service";
|
|
170
|
+
import { MpinService } from "./services/mpin.service";
|
|
169
171
|
import { ActiveSessionStorageService } from "./services/active-session-storage.service";
|
|
170
172
|
import { AuthenticationService } from "./services/authentication.service";
|
|
171
173
|
import { MetadataValidationService } from "./services/metadata-validation.service";
|
|
@@ -246,6 +248,7 @@ import { Setting } from './entities/setting.entity';
|
|
|
246
248
|
import { UserActivityHistory } from './entities/user-activity-history.entity';
|
|
247
249
|
import { UserViewMetadata } from './entities/user-view-metadata.entity';
|
|
248
250
|
import { UserApiKey } from './entities/user-api-key.entity';
|
|
251
|
+
import { UserDeviceCredential } from './entities/user-device-credential.entity';
|
|
249
252
|
import { User } from './entities/user.entity';
|
|
250
253
|
import { HttpExceptionFilter } from './filters/http-exception.filter';
|
|
251
254
|
import { ModelMetadataHelperService } from './helpers/model-metadata-helper.service';
|
|
@@ -318,6 +321,7 @@ import { SmsTemplateRepository } from './repository/sms-template.repository';
|
|
|
318
321
|
import { UserActivityHistoryRepository } from './repository/user-activity-history.repository';
|
|
319
322
|
import { UserViewMetadataRepository } from './repository/user-view-metadata.repository';
|
|
320
323
|
import { UserApiKeyRepository } from './repository/user-api-key.repository';
|
|
324
|
+
import { UserDeviceCredentialRepository } from './repository/user-device-credential.repository';
|
|
321
325
|
import { UserRepository } from './repository/user.repository';
|
|
322
326
|
import { ViewMetadataRepository } from './repository/view-metadata.repository';
|
|
323
327
|
import { PermissionMetadataSeederService } from './seeders/permission-metadata-seeder.service';
|
|
@@ -500,6 +504,7 @@ import { SwitchNode } from './services/workflow/nodes/switch.node';
|
|
|
500
504
|
SmsTemplate,
|
|
501
505
|
User,
|
|
502
506
|
UserApiKey,
|
|
507
|
+
UserDeviceCredential,
|
|
503
508
|
UserActivityHistory,
|
|
504
509
|
UserViewMetadata,
|
|
505
510
|
ViewMetadata,
|
|
@@ -595,6 +600,7 @@ import { SwitchNode } from './services/workflow/nodes/switch.node';
|
|
|
595
600
|
GupshupWebhookController,
|
|
596
601
|
MetaCloudWhatsappWebhookController,
|
|
597
602
|
OTPAuthenticationController,
|
|
603
|
+
MpinAuthenticationController,
|
|
598
604
|
PermissionMetadataController,
|
|
599
605
|
RoleMetadataController,
|
|
600
606
|
SavedFiltersController,
|
|
@@ -760,6 +766,7 @@ import { SwitchNode } from './services/workflow/nodes/switch.node';
|
|
|
760
766
|
ApiKeyGuard,
|
|
761
767
|
MediaSignedUrlGuard,
|
|
762
768
|
ApiKeyService,
|
|
769
|
+
MpinService,
|
|
763
770
|
ActiveSessionStorageService,
|
|
764
771
|
AuthenticationService,
|
|
765
772
|
GoogleAuthenticationController,
|
|
@@ -829,6 +836,7 @@ import { SwitchNode } from './services/workflow/nodes/switch.node';
|
|
|
829
836
|
PermissionMetadataSeederService,
|
|
830
837
|
UserService,
|
|
831
838
|
UserApiKeyRepository,
|
|
839
|
+
UserDeviceCredentialRepository,
|
|
832
840
|
UserRepository,
|
|
833
841
|
SettingService,
|
|
834
842
|
ConcatComputedFieldProvider,
|