@adminforth/two-factors-auth 7.3.1 → 7.4.1
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/services/totpService.js +13 -6
- package/dist/types.d.ts +12 -1
- package/package.json +1 -1
- package/services/totpService.ts +13 -3
- package/tests/totpService.test.mjs +27 -1
- package/types.ts +10 -1
|
@@ -14,14 +14,15 @@ const DEFAULT_TOTP_RATE_LIMIT = ['30/1m', '300/1h', '1000/1d'];
|
|
|
14
14
|
const VERIFIED_CODE_JWT_TYPE = 'verifiedTotpCode';
|
|
15
15
|
const VERIFIED_CODE_TOKEN_TTL = '1m';
|
|
16
16
|
const TOTP_STEP_SECONDS = 30;
|
|
17
|
+
const RATE_LIMITED_ERROR = "Too many attempts to enter the code. Try again later.";
|
|
17
18
|
export class TotpService {
|
|
18
19
|
constructor(options, userRepository, adminforth) {
|
|
19
20
|
var _a;
|
|
20
21
|
this.options = options;
|
|
21
22
|
this.userRepository = userRepository;
|
|
22
23
|
this.adminforth = adminforth;
|
|
23
|
-
this.codeAttemptLimiters = ((_a = this.options.totpRateLimit) !== null && _a !== void 0 ? _a : DEFAULT_TOTP_RATE_LIMIT).map((rate) => new RateLimiter(rate));
|
|
24
24
|
this.lastUsedCodeSteps = new Map();
|
|
25
|
+
this.codeAttemptLimiters = ((_a = options.totpRateLimit) !== null && _a !== void 0 ? _a : DEFAULT_TOTP_RATE_LIMIT).map((rate) => new RateLimiter(rate));
|
|
25
26
|
}
|
|
26
27
|
generateSecret(issuerName, userName) {
|
|
27
28
|
return twofactor.generateSecret({ name: issuerName, account: userName }).secret;
|
|
@@ -35,10 +36,10 @@ export class TotpService {
|
|
|
35
36
|
}
|
|
36
37
|
verifyUserCode(userPk, code, extra) {
|
|
37
38
|
return __awaiter(this, void 0, void 0, function* () {
|
|
38
|
-
var _a, _b, _c, _d, _e;
|
|
39
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
39
40
|
const attemptsAllowed = yield Promise.all(this.codeAttemptLimiters.map((limiter) => limiter.consume(userPk)));
|
|
40
41
|
if (!attemptsAllowed.every(Boolean)) {
|
|
41
|
-
return { error:
|
|
42
|
+
return { error: RATE_LIMITED_ERROR, code: TwoFactorErrorCode.RATE_LIMITED };
|
|
42
43
|
}
|
|
43
44
|
const user = yield this.userRepository.getAuthUser(userPk);
|
|
44
45
|
if (!user)
|
|
@@ -47,21 +48,27 @@ export class TotpService {
|
|
|
47
48
|
if (!secret)
|
|
48
49
|
return { error: "2FA is not set up for this user", code: TwoFactorErrorCode.NOT_SET_UP };
|
|
49
50
|
const hookParams = { pk: userPk, dbUser: user, adminforth: this.adminforth, extra };
|
|
51
|
+
const otpCheck = yield ((_b = (_a = this.options).beforeOtpCheck) === null || _b === void 0 ? void 0 : _b.call(_a, hookParams));
|
|
52
|
+
if (otpCheck && !otpCheck.allowed) {
|
|
53
|
+
yield this.refundCodeAttempt(userPk);
|
|
54
|
+
return { error: (_c = otpCheck.error) !== null && _c !== void 0 ? _c : RATE_LIMITED_ERROR, code: TwoFactorErrorCode.RATE_LIMITED };
|
|
55
|
+
}
|
|
50
56
|
const step = this.findCodeStep(secret, code);
|
|
51
57
|
if (step === null) {
|
|
52
|
-
yield ((
|
|
58
|
+
yield ((_e = (_d = this.options).onOtpFailed) === null || _e === void 0 ? void 0 : _e.call(_d, hookParams));
|
|
53
59
|
return { error: "Wrong or expired OTP code", code: TwoFactorErrorCode.INVALID };
|
|
54
60
|
}
|
|
55
|
-
if (step <= ((
|
|
61
|
+
if (step <= ((_f = this.lastUsedCodeSteps.get(userPk)) !== null && _f !== void 0 ? _f : -Infinity)) {
|
|
56
62
|
return { error: "This code has already been used. Wait for the next one.", code: TwoFactorErrorCode.INVALID };
|
|
57
63
|
}
|
|
58
64
|
this.lastUsedCodeSteps.set(userPk, step);
|
|
59
65
|
yield this.refundCodeAttempt(userPk);
|
|
60
|
-
yield ((
|
|
66
|
+
yield ((_h = (_g = this.options).onOtpSucceeded) === null || _h === void 0 ? void 0 : _h.call(_g, hookParams));
|
|
61
67
|
return { ok: true };
|
|
62
68
|
});
|
|
63
69
|
}
|
|
64
70
|
// attempt is consumed before the check so parallel requests can't bypass the limit, and given back when the code is correct
|
|
71
|
+
// or rejected by beforeOtpCheck, so an attacker whose IP the app blocked can't use up the user's limit and lock the user out
|
|
65
72
|
refundCodeAttempt(userPk) {
|
|
66
73
|
return __awaiter(this, void 0, void 0, function* () {
|
|
67
74
|
yield Promise.all(this.codeAttemptLimiters.map((limiter) => limiter.rateLimiter.reward(userPk, 1)));
|
package/dist/types.d.ts
CHANGED
|
@@ -50,9 +50,20 @@ export interface PluginOptions extends PluginsCommonOptions {
|
|
|
50
50
|
* Default: ['30/1m', '300/1h', '1000/1d']
|
|
51
51
|
*/
|
|
52
52
|
totpRateLimit?: RateLimitString[];
|
|
53
|
+
/**
|
|
54
|
+
* Called before a TOTP code is checked, at login and for step-up verification.
|
|
55
|
+
* Return `{ allowed: false }` to reject the attempt without checking the code, e.g. to limit attempts by IP.
|
|
56
|
+
* A rejected attempt fails with the `TWO_FACTOR_RATE_LIMITED` code and the returned `error`,
|
|
57
|
+
* does not call {@link PluginOptions.onOtpFailed} and does not count towards {@link PluginOptions.totpRateLimit}.
|
|
58
|
+
* Not called for attempts rejected by {@link PluginOptions.totpRateLimit}.
|
|
59
|
+
*/
|
|
60
|
+
beforeOtpCheck?: (params: OtpHookParams) => Promise<{
|
|
61
|
+
allowed: boolean;
|
|
62
|
+
error?: string;
|
|
63
|
+
}>;
|
|
53
64
|
/**
|
|
54
65
|
* Called after a user entered a wrong TOTP code, at login or for step-up verification.
|
|
55
|
-
* Not called for attempts rejected by {@link PluginOptions.totpRateLimit} and for a reused code.
|
|
66
|
+
* Not called for attempts rejected by {@link PluginOptions.totpRateLimit} or {@link PluginOptions.beforeOtpCheck}, and for a reused code.
|
|
56
67
|
* Use it to count failed attempts, e.g. to block the user after several failures in a row.
|
|
57
68
|
*/
|
|
58
69
|
onOtpFailed?: (params: OtpHookParams) => Promise<void>;
|
package/package.json
CHANGED
package/services/totpService.ts
CHANGED
|
@@ -9,16 +9,19 @@ const DEFAULT_TOTP_RATE_LIMIT: RateLimitString[] = ['30/1m', '300/1h', '1000/1d'
|
|
|
9
9
|
const VERIFIED_CODE_JWT_TYPE = 'verifiedTotpCode';
|
|
10
10
|
const VERIFIED_CODE_TOKEN_TTL = '1m';
|
|
11
11
|
const TOTP_STEP_SECONDS = 30;
|
|
12
|
+
const RATE_LIMITED_ERROR = "Too many attempts to enter the code. Try again later.";
|
|
12
13
|
|
|
13
14
|
export class TotpService {
|
|
14
|
-
private readonly codeAttemptLimiters
|
|
15
|
+
private readonly codeAttemptLimiters: RateLimiter[];
|
|
15
16
|
private readonly lastUsedCodeSteps = new Map<string, number>();
|
|
16
17
|
|
|
17
18
|
constructor(
|
|
18
19
|
private readonly options: PluginOptions,
|
|
19
20
|
private readonly userRepository: UserRepository,
|
|
20
21
|
private readonly adminforth: IAdminForth,
|
|
21
|
-
) {
|
|
22
|
+
) {
|
|
23
|
+
this.codeAttemptLimiters = (options.totpRateLimit ?? DEFAULT_TOTP_RATE_LIMIT).map((rate) => new RateLimiter(rate));
|
|
24
|
+
}
|
|
22
25
|
|
|
23
26
|
public generateSecret(issuerName: string, userName: string): string {
|
|
24
27
|
return twofactor.generateSecret({ name: issuerName, account: userName }).secret;
|
|
@@ -36,7 +39,7 @@ export class TotpService {
|
|
|
36
39
|
public async verifyUserCode(userPk: string, code: string, extra?: HttpExtra): Promise<VerificationResult> {
|
|
37
40
|
const attemptsAllowed = await Promise.all(this.codeAttemptLimiters.map((limiter) => limiter.consume(userPk)));
|
|
38
41
|
if (!attemptsAllowed.every(Boolean)) {
|
|
39
|
-
return { error:
|
|
42
|
+
return { error: RATE_LIMITED_ERROR, code: TwoFactorErrorCode.RATE_LIMITED };
|
|
40
43
|
}
|
|
41
44
|
|
|
42
45
|
const user = await this.userRepository.getAuthUser(userPk);
|
|
@@ -46,6 +49,12 @@ export class TotpService {
|
|
|
46
49
|
if (!secret) return { error: "2FA is not set up for this user", code: TwoFactorErrorCode.NOT_SET_UP };
|
|
47
50
|
|
|
48
51
|
const hookParams = { pk: userPk, dbUser: user, adminforth: this.adminforth, extra };
|
|
52
|
+
const otpCheck = await this.options.beforeOtpCheck?.(hookParams);
|
|
53
|
+
if (otpCheck && !otpCheck.allowed) {
|
|
54
|
+
await this.refundCodeAttempt(userPk);
|
|
55
|
+
return { error: otpCheck.error ?? RATE_LIMITED_ERROR, code: TwoFactorErrorCode.RATE_LIMITED };
|
|
56
|
+
}
|
|
57
|
+
|
|
49
58
|
const step = this.findCodeStep(secret, code);
|
|
50
59
|
if (step === null) {
|
|
51
60
|
await this.options.onOtpFailed?.(hookParams);
|
|
@@ -62,6 +71,7 @@ export class TotpService {
|
|
|
62
71
|
}
|
|
63
72
|
|
|
64
73
|
// attempt is consumed before the check so parallel requests can't bypass the limit, and given back when the code is correct
|
|
74
|
+
// or rejected by beforeOtpCheck, so an attacker whose IP the app blocked can't use up the user's limit and lock the user out
|
|
65
75
|
private async refundCodeAttempt(userPk: string): Promise<void> {
|
|
66
76
|
await Promise.all(this.codeAttemptLimiters.map((limiter) => limiter.rateLimiter.reward(userPk, 1)));
|
|
67
77
|
}
|
|
@@ -42,7 +42,7 @@ test('calls onOtpFailed for a wrong code and onOtpSucceeded for a correct one, b
|
|
|
42
42
|
const calls = [];
|
|
43
43
|
const extra = { headers: { 'x-forwarded-for': '1.2.3.4' } };
|
|
44
44
|
const service = createService({
|
|
45
|
-
totpRateLimit: ['
|
|
45
|
+
totpRateLimit: ['2/1m'],
|
|
46
46
|
onOtpFailed: async (params) => { calls.push(['failed', params]); },
|
|
47
47
|
onOtpSucceeded: async (params) => { calls.push(['succeeded', params]); },
|
|
48
48
|
});
|
|
@@ -59,6 +59,32 @@ test('calls onOtpFailed for a wrong code and onOtpSucceeded for a correct one, b
|
|
|
59
59
|
assert.equal(calls[0][1].extra, extra);
|
|
60
60
|
});
|
|
61
61
|
|
|
62
|
+
test('beforeOtpCheck rejects an attempt without checking the code and without using up the user limit', async (t) => {
|
|
63
|
+
t.mock.timers.enable({ apis: ['Date'], now: 1_000 * 30_000 });
|
|
64
|
+
const calls = [];
|
|
65
|
+
const extra = { headers: { 'x-forwarded-for': '1.2.3.4' } };
|
|
66
|
+
let allowed = false;
|
|
67
|
+
const service = createService({
|
|
68
|
+
totpRateLimit: ['1/1m'],
|
|
69
|
+
beforeOtpCheck: async (params) => {
|
|
70
|
+
calls.push(['before', params]);
|
|
71
|
+
return allowed ? { allowed } : { allowed, error: 'Too many wrong codes from your IP' };
|
|
72
|
+
},
|
|
73
|
+
onOtpFailed: async (params) => { calls.push(['failed', params]); },
|
|
74
|
+
});
|
|
75
|
+
const rejected = { error: 'Too many wrong codes from your IP', code: TwoFactorErrorCode.RATE_LIMITED };
|
|
76
|
+
|
|
77
|
+
assert.deepEqual(await service.verifyUserCode('user-1', twofactor.generateToken(SECRET).token, extra), rejected);
|
|
78
|
+
assert.deepEqual(await service.verifyUserCode('user-1', 'wrong', extra), rejected);
|
|
79
|
+
allowed = true;
|
|
80
|
+
assert.equal((await service.verifyUserCode('user-1', 'wrong', extra)).code, TwoFactorErrorCode.INVALID);
|
|
81
|
+
assert.equal((await service.verifyUserCode('user-1', 'wrong', extra)).code, TwoFactorErrorCode.RATE_LIMITED);
|
|
82
|
+
|
|
83
|
+
assert.deepEqual(calls.map(([event]) => event), ['before', 'before', 'before', 'failed']);
|
|
84
|
+
assert.equal(calls[0][1].pk, 'user-1');
|
|
85
|
+
assert.equal(calls[0][1].extra, extra);
|
|
86
|
+
});
|
|
87
|
+
|
|
62
88
|
test('a correct code gives a token that confirms the code only for its user', async () => {
|
|
63
89
|
const service = createService();
|
|
64
90
|
const { verifiedCodeToken } = await service.verifyAdminUserCode({ pk: 'user-1' }, twofactor.generateToken(SECRET).token);
|
package/types.ts
CHANGED
|
@@ -58,9 +58,18 @@ export interface PluginOptions extends PluginsCommonOptions {
|
|
|
58
58
|
*/
|
|
59
59
|
totpRateLimit?: RateLimitString[];
|
|
60
60
|
|
|
61
|
+
/**
|
|
62
|
+
* Called before a TOTP code is checked, at login and for step-up verification.
|
|
63
|
+
* Return `{ allowed: false }` to reject the attempt without checking the code, e.g. to limit attempts by IP.
|
|
64
|
+
* A rejected attempt fails with the `TWO_FACTOR_RATE_LIMITED` code and the returned `error`,
|
|
65
|
+
* does not call {@link PluginOptions.onOtpFailed} and does not count towards {@link PluginOptions.totpRateLimit}.
|
|
66
|
+
* Not called for attempts rejected by {@link PluginOptions.totpRateLimit}.
|
|
67
|
+
*/
|
|
68
|
+
beforeOtpCheck?: (params: OtpHookParams) => Promise<{ allowed: boolean; error?: string }>;
|
|
69
|
+
|
|
61
70
|
/**
|
|
62
71
|
* Called after a user entered a wrong TOTP code, at login or for step-up verification.
|
|
63
|
-
* Not called for attempts rejected by {@link PluginOptions.totpRateLimit} and for a reused code.
|
|
72
|
+
* Not called for attempts rejected by {@link PluginOptions.totpRateLimit} or {@link PluginOptions.beforeOtpCheck}, and for a reused code.
|
|
64
73
|
* Use it to count failed attempts, e.g. to block the user after several failures in a row.
|
|
65
74
|
*/
|
|
66
75
|
onOtpFailed?: (params: OtpHookParams) => Promise<void>;
|