@adminforth/two-factors-auth 7.2.0 → 7.3.0

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.
@@ -67,8 +67,8 @@ export function registerTwoFaEndpoints(server, handlers) {
67
67
  },
68
68
  noAuth: false,
69
69
  request_schema: verifyTotpBodySchema,
70
- handler: (_a) => __awaiter(this, [_a], void 0, function* ({ adminUser, body, response }) {
71
- return handlers.verifyTotp({ adminUser, body, response });
70
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ adminUser, body, response, cookies, headers, requestUrl, query }) {
71
+ return handlers.verifyTotp({ adminUser, body, response, cookies, headers, requestUrl, query });
72
72
  }),
73
73
  });
74
74
  }
@@ -49,9 +49,13 @@ export declare function createTwoFaHandlers(ctx: any): {
49
49
  skipAllowed: boolean;
50
50
  gracePeriod: any;
51
51
  }>;
52
- verifyTotp: ({ adminUser, body, response }: {
52
+ verifyTotp: ({ adminUser, body, response, cookies, headers, requestUrl, query }: {
53
53
  adminUser: any;
54
54
  body: any;
55
55
  response: any;
56
+ cookies: any;
57
+ headers: any;
58
+ requestUrl: any;
59
+ query: any;
56
60
  }) => Promise<any>;
57
61
  };
@@ -62,7 +62,7 @@ export function createTwoFaHandlers(ctx) {
62
62
  }
63
63
  }
64
64
  else {
65
- const verificationResult = yield ctx.totpService.verifyUserCode(decoded.pk, body.code);
65
+ const verificationResult = yield ctx.totpService.verifyUserCode(decoded.pk, body.code, extra);
66
66
  verified = 'ok' in verificationResult && verificationResult.ok;
67
67
  if (!verified) {
68
68
  verificationError = (_c = verificationResult.error) !== null && _c !== void 0 ? _c : verificationError;
@@ -164,10 +164,11 @@ export function createTwoFaHandlers(ctx) {
164
164
  && (yield ctx.cookieService.isMfaGraceValid(headers, cookies, true));
165
165
  return { skipAllowed: false, gracePeriod };
166
166
  }),
167
- verifyTotp: (_a) => __awaiter(this, [_a], void 0, function* ({ adminUser, body, response }) {
167
+ verifyTotp: (_a) => __awaiter(this, [_a], void 0, function* ({ adminUser, body, response, cookies, headers, requestUrl, query }) {
168
168
  if (!(body === null || body === void 0 ? void 0 : body.code))
169
169
  return respondWithStatus({ error: 'Code is required' }, response, HttpStatus.BAD_REQUEST);
170
- const verificationResult = yield ctx.totpService.verifyAdminUserCode(adminUser, body.code);
170
+ const extra = { body, headers, cookies, query, requestUrl, response };
171
+ const verificationResult = yield ctx.totpService.verifyAdminUserCode(adminUser, body.code, extra);
171
172
  if (!verificationResult.ok) {
172
173
  return respondWithStatus(verificationResult, response, HttpStatus.FORBIDDEN);
173
174
  }
@@ -1,4 +1,4 @@
1
- import { type AdminUser, type IAdminForth } from "adminforth";
1
+ import { type AdminUser, type HttpExtra, type IAdminForth } from "adminforth";
2
2
  import type { PluginOptions } from "../types.js";
3
3
  import { UserRepository } from "../repositories/userRepository.js";
4
4
  import type { VerificationFailure, VerificationResult } from "../utils/types.js";
@@ -12,8 +12,8 @@ export declare class TotpService {
12
12
  generateSecret(issuerName: string, userName: string): string;
13
13
  verifySecret(secret: string, code: string): boolean;
14
14
  private findCodeStep;
15
- verifyUserCode(userPk: string, code: string): Promise<VerificationResult>;
16
- verifyAdminUserCode(adminUser: AdminUser, code: string): Promise<{
15
+ verifyUserCode(userPk: string, code: string, extra?: HttpExtra): Promise<VerificationResult>;
16
+ verifyAdminUserCode(adminUser: AdminUser, code: string, extra: HttpExtra): Promise<{
17
17
  ok: true;
18
18
  verifiedCodeToken: string;
19
19
  } | VerificationFailure>;
@@ -33,9 +33,9 @@ export class TotpService {
33
33
  const match = twofactor.verifyToken(secret, code, this.options.timeStepWindow);
34
34
  return match && Math.floor(Date.now() / 1000 / TOTP_STEP_SECONDS) + match.delta;
35
35
  }
36
- verifyUserCode(userPk, code) {
36
+ verifyUserCode(userPk, code, extra) {
37
37
  return __awaiter(this, void 0, void 0, function* () {
38
- var _a;
38
+ var _a, _b, _c, _d, _e;
39
39
  const attemptsAllowed = yield Promise.all(this.codeAttemptLimiters.map((limiter) => limiter.consume(userPk)));
40
40
  if (!attemptsAllowed.every(Boolean)) {
41
41
  return { error: "Too many attempts to enter the code. Try again later.", code: TwoFactorErrorCode.RATE_LIMITED };
@@ -46,19 +46,23 @@ export class TotpService {
46
46
  const secret = this.userRepository.getSecret(user);
47
47
  if (!secret)
48
48
  return { error: "2FA is not set up for this user", code: TwoFactorErrorCode.NOT_SET_UP };
49
+ const hookParams = { pk: userPk, dbUser: user, adminforth: this.adminforth, extra };
49
50
  const step = this.findCodeStep(secret, code);
50
- if (step === null)
51
+ if (step === null) {
52
+ yield ((_b = (_a = this.options).onOtpFailed) === null || _b === void 0 ? void 0 : _b.call(_a, hookParams));
51
53
  return { error: "Wrong or expired OTP code", code: TwoFactorErrorCode.INVALID };
52
- if (step <= ((_a = this.lastUsedCodeSteps.get(userPk)) !== null && _a !== void 0 ? _a : -Infinity)) {
54
+ }
55
+ if (step <= ((_c = this.lastUsedCodeSteps.get(userPk)) !== null && _c !== void 0 ? _c : -Infinity)) {
53
56
  return { error: "This code has already been used. Wait for the next one.", code: TwoFactorErrorCode.INVALID };
54
57
  }
55
58
  this.lastUsedCodeSteps.set(userPk, step);
59
+ yield ((_e = (_d = this.options).onOtpSucceeded) === null || _e === void 0 ? void 0 : _e.call(_d, hookParams));
56
60
  return { ok: true };
57
61
  });
58
62
  }
59
- verifyAdminUserCode(adminUser, code) {
63
+ verifyAdminUserCode(adminUser, code, extra) {
60
64
  return __awaiter(this, void 0, void 0, function* () {
61
- const result = yield this.verifyUserCode(this.userRepository.getUserPk(adminUser), code);
65
+ const result = yield this.verifyUserCode(this.userRepository.getUserPk(adminUser), code, extra);
62
66
  if ('error' in result)
63
67
  return result;
64
68
  return { ok: true, verifiedCodeToken: this.adminforth.auth.issueJWT({ pk: adminUser.pk }, VERIFIED_CODE_JWT_TYPE, VERIFIED_CODE_TOKEN_TTL) };
@@ -44,7 +44,7 @@ export function verifyMfaConfirmation(ctx, confirmationResult, opts) {
44
44
  };
45
45
  if (mode === "totp") {
46
46
  const { result: code } = confirmationResult;
47
- const verificationResult = yield ctx.totpService.verifyUserCode(opts.userPk, code);
47
+ const verificationResult = yield ctx.totpService.verifyUserCode(opts.userPk, code, opts.extra);
48
48
  return 'error' in verificationResult ? verificationResult : confirmed();
49
49
  }
50
50
  else if (mode === "verifiedTotp") {
package/dist/types.d.ts CHANGED
@@ -1,5 +1,24 @@
1
- import { AdminUser, KeyValueAdapter } from "adminforth";
1
+ import { AdminUser, KeyValueAdapter, HttpExtra, IAdminForth } from "adminforth";
2
2
  import { type PluginsCommonOptions, PeriodString, RateLimitString } from "adminforth";
3
+ export type OtpHookParams = {
4
+ /**
5
+ * Primary key of the user who entered the TOTP code.
6
+ */
7
+ pk: string;
8
+ /**
9
+ * Record of the user from the users resource.
10
+ */
11
+ dbUser: Record<string, any>;
12
+ /**
13
+ * Adminforth instance.
14
+ */
15
+ adminforth: IAdminForth;
16
+ /**
17
+ * Extra HTTP information of the request which checked the code, e.g. to get client IP.
18
+ * Not passed when `verify` is called without `extra`.
19
+ */
20
+ extra?: HttpExtra;
21
+ };
3
22
  export interface PluginOptions extends PluginsCommonOptions {
4
23
  /**
5
24
  * Name of the field in the auth resource which will store 2FA secret.
@@ -31,6 +50,17 @@ export interface PluginOptions extends PluginsCommonOptions {
31
50
  * Default: ['30/1m', '300/1h', '1000/1d']
32
51
  */
33
52
  totpRateLimit?: RateLimitString[];
53
+ /**
54
+ * 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.
56
+ * Use it to count failed attempts, e.g. to block the user after several failures in a row.
57
+ */
58
+ onOtpFailed?: (params: OtpHookParams) => Promise<void>;
59
+ /**
60
+ * Called after a user entered a correct TOTP code, at login or for step-up verification.
61
+ * Use it e.g. to reset the counter of failed attempts.
62
+ */
63
+ onOtpSucceeded?: (params: OtpHookParams) => Promise<void>;
34
64
  customBrandPrefix?: string;
35
65
  /**
36
66
  * Passkeys (WebAuthn) configuration.
@@ -69,8 +69,8 @@ export function registerTwoFaEndpoints(server: IHttpServer, handlers: any): void
69
69
  },
70
70
  noAuth: false,
71
71
  request_schema: verifyTotpBodySchema,
72
- handler: async ({ adminUser, body, response }) => {
73
- return handlers.verifyTotp({ adminUser, body, response });
72
+ handler: async ({ adminUser, body, response, cookies, headers, requestUrl, query }) => {
73
+ return handlers.verifyTotp({ adminUser, body, response, cookies, headers, requestUrl, query });
74
74
  },
75
75
  });
76
76
  }
@@ -54,7 +54,7 @@ export function createTwoFaHandlers(ctx: any) {
54
54
  verificationError = res.error ?? 'Invalid passkey';
55
55
  }
56
56
  } else {
57
- const verificationResult = await ctx.totpService.verifyUserCode(decoded.pk, body.code);
57
+ const verificationResult = await ctx.totpService.verifyUserCode(decoded.pk, body.code, extra);
58
58
  verified = 'ok' in verificationResult && verificationResult.ok;
59
59
  if (!verified) {
60
60
  verificationError = verificationResult.error ?? verificationError;
@@ -173,10 +173,11 @@ export function createTwoFaHandlers(ctx: any) {
173
173
  return { skipAllowed: false, gracePeriod };
174
174
  },
175
175
 
176
- verifyTotp: async ({ adminUser, body, response }) => {
176
+ verifyTotp: async ({ adminUser, body, response, cookies, headers, requestUrl, query }) => {
177
177
  if (!body?.code) return respondWithStatus({ error: 'Code is required' }, response, HttpStatus.BAD_REQUEST);
178
178
 
179
- const verificationResult = await ctx.totpService.verifyAdminUserCode(adminUser, body.code);
179
+ const extra = { body, headers, cookies, query, requestUrl, response };
180
+ const verificationResult = await ctx.totpService.verifyAdminUserCode(adminUser, body.code, extra);
180
181
  if (!verificationResult.ok) {
181
182
  return respondWithStatus(verificationResult, response, HttpStatus.FORBIDDEN);
182
183
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/two-factors-auth",
3
- "version": "7.2.0",
3
+ "version": "7.3.0",
4
4
  "description": "AdminForth plugin for two factors authentication",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,4 +1,4 @@
1
- import { RateLimiter, type AdminUser, type IAdminForth, type RateLimitString } from "adminforth";
1
+ import { RateLimiter, type AdminUser, type HttpExtra, type IAdminForth, type RateLimitString } from "adminforth";
2
2
  import twofactor from 'node-2fa';
3
3
  import type { PluginOptions } from "../types.js";
4
4
  import { UserRepository } from "../repositories/userRepository.js";
@@ -33,7 +33,7 @@ export class TotpService {
33
33
  return match && Math.floor(Date.now() / 1000 / TOTP_STEP_SECONDS) + match.delta;
34
34
  }
35
35
 
36
- public async verifyUserCode(userPk: string, code: string): Promise<VerificationResult> {
36
+ public async verifyUserCode(userPk: string, code: string, extra?: HttpExtra): Promise<VerificationResult> {
37
37
  const attemptsAllowed = await Promise.all(this.codeAttemptLimiters.map((limiter) => limiter.consume(userPk)));
38
38
  if (!attemptsAllowed.every(Boolean)) {
39
39
  return { error: "Too many attempts to enter the code. Try again later.", code: TwoFactorErrorCode.RATE_LIMITED };
@@ -45,18 +45,23 @@ export class TotpService {
45
45
  const secret = this.userRepository.getSecret(user);
46
46
  if (!secret) return { error: "2FA is not set up for this user", code: TwoFactorErrorCode.NOT_SET_UP };
47
47
 
48
+ const hookParams = { pk: userPk, dbUser: user, adminforth: this.adminforth, extra };
48
49
  const step = this.findCodeStep(secret, code);
49
- if (step === null) return { error: "Wrong or expired OTP code", code: TwoFactorErrorCode.INVALID };
50
+ if (step === null) {
51
+ await this.options.onOtpFailed?.(hookParams);
52
+ return { error: "Wrong or expired OTP code", code: TwoFactorErrorCode.INVALID };
53
+ }
50
54
 
51
55
  if (step <= (this.lastUsedCodeSteps.get(userPk) ?? -Infinity)) {
52
56
  return { error: "This code has already been used. Wait for the next one.", code: TwoFactorErrorCode.INVALID };
53
57
  }
54
58
  this.lastUsedCodeSteps.set(userPk, step);
59
+ await this.options.onOtpSucceeded?.(hookParams);
55
60
  return { ok: true };
56
61
  }
57
62
 
58
- public async verifyAdminUserCode(adminUser: AdminUser, code: string): Promise<{ ok: true; verifiedCodeToken: string } | VerificationFailure> {
59
- const result = await this.verifyUserCode(this.userRepository.getUserPk(adminUser), code);
63
+ public async verifyAdminUserCode(adminUser: AdminUser, code: string, extra: HttpExtra): Promise<{ ok: true; verifiedCodeToken: string } | VerificationFailure> {
64
+ const result = await this.verifyUserCode(this.userRepository.getUserPk(adminUser), code, extra);
60
65
  if ('error' in result) return result;
61
66
  return { ok: true, verifiedCodeToken: this.adminforth.auth.issueJWT({ pk: adminUser.pk }, VERIFIED_CODE_JWT_TYPE, VERIFIED_CODE_TOKEN_TTL) };
62
67
  }
@@ -74,7 +74,7 @@ export async function verifyMfaConfirmation(
74
74
 
75
75
  if (mode === "totp") {
76
76
  const { result: code } = confirmationResult as TotpConfirmationResult;
77
- const verificationResult = await ctx.totpService.verifyUserCode(opts.userPk, code);
77
+ const verificationResult = await ctx.totpService.verifyUserCode(opts.userPk, code, opts.extra);
78
78
  return 'error' in verificationResult ? verificationResult : confirmed();
79
79
  } else if (mode === "verifiedTotp") {
80
80
  const { result: token } = confirmationResult as VerifiedTotpConfirmationResult;
@@ -37,6 +37,28 @@ test('uses totpRateLimit from plugin options instead of the default limits', asy
37
37
  assert.equal((await service.verifyUserCode('user-1', 'wrong')).code, TwoFactorErrorCode.RATE_LIMITED);
38
38
  });
39
39
 
40
+ test('calls onOtpFailed for a wrong code and onOtpSucceeded for a correct one, but not for rate limited or reused codes', async (t) => {
41
+ t.mock.timers.enable({ apis: ['Date'], now: 1_000 * 30_000 });
42
+ const calls = [];
43
+ const extra = { headers: { 'x-forwarded-for': '1.2.3.4' } };
44
+ const service = createService({
45
+ totpRateLimit: ['3/1m'],
46
+ onOtpFailed: async (params) => { calls.push(['failed', params]); },
47
+ onOtpSucceeded: async (params) => { calls.push(['succeeded', params]); },
48
+ });
49
+ const code = twofactor.generateToken(SECRET).token;
50
+
51
+ await service.verifyUserCode('user-1', 'wrong', extra);
52
+ await service.verifyUserCode('user-1', code, extra);
53
+ await service.verifyUserCode('user-1', code, extra);
54
+ await service.verifyUserCode('user-1', 'wrong', extra);
55
+
56
+ assert.deepEqual(calls.map(([event]) => event), ['failed', 'succeeded']);
57
+ assert.equal(calls[0][1].pk, 'user-1');
58
+ assert.deepEqual(calls[0][1].dbUser, { pk: 'user-1' });
59
+ assert.equal(calls[0][1].extra, extra);
60
+ });
61
+
40
62
  test('a correct code gives a token that confirms the code only for its user', async () => {
41
63
  const service = createService();
42
64
  const { verifiedCodeToken } = await service.verifyAdminUserCode({ pk: 'user-1' }, twofactor.generateToken(SECRET).token);
package/types.ts CHANGED
@@ -1,6 +1,26 @@
1
- import { AdminUser, KeyValueAdapter } from "adminforth";
1
+ import { AdminUser, KeyValueAdapter, HttpExtra, IAdminForth } from "adminforth";
2
2
  import {type PluginsCommonOptions, PeriodString, RateLimitString } from "adminforth";
3
3
 
4
+ export type OtpHookParams = {
5
+ /**
6
+ * Primary key of the user who entered the TOTP code.
7
+ */
8
+ pk: string;
9
+ /**
10
+ * Record of the user from the users resource.
11
+ */
12
+ dbUser: Record<string, any>;
13
+ /**
14
+ * Adminforth instance.
15
+ */
16
+ adminforth: IAdminForth;
17
+ /**
18
+ * Extra HTTP information of the request which checked the code, e.g. to get client IP.
19
+ * Not passed when `verify` is called without `extra`.
20
+ */
21
+ extra?: HttpExtra;
22
+ };
23
+
4
24
  export interface PluginOptions extends PluginsCommonOptions {
5
25
 
6
26
  /**
@@ -38,6 +58,19 @@ export interface PluginOptions extends PluginsCommonOptions {
38
58
  */
39
59
  totpRateLimit?: RateLimitString[];
40
60
 
61
+ /**
62
+ * 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.
64
+ * Use it to count failed attempts, e.g. to block the user after several failures in a row.
65
+ */
66
+ onOtpFailed?: (params: OtpHookParams) => Promise<void>;
67
+
68
+ /**
69
+ * Called after a user entered a correct TOTP code, at login or for step-up verification.
70
+ * Use it e.g. to reset the counter of failed attempts.
71
+ */
72
+ onOtpSucceeded?: (params: OtpHookParams) => Promise<void>;
73
+
41
74
  customBrandPrefix?: string;
42
75
 
43
76
  /**