@adminforth/two-factors-auth 7.1.0 → 7.2.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.
@@ -15,4 +15,9 @@ export declare class PasskeyRepository {
15
15
  updateMeta(passkeyRecord: AnyRecord, meta: AnyRecord): Promise<void>;
16
16
  update(passkeyRecord: AnyRecord, newRecord: AnyRecord, adminUser: AdminUser): Promise<void>;
17
17
  delete(passkeyRecord: AnyRecord, adminUser: AdminUser): Promise<void>;
18
+ /**
19
+ * Users manage their own passkeys and the plugin checks the ownership itself, so these are system
20
+ * writes on the user's behalf, which run the resource hooks (e.g. the audit log).
21
+ */
22
+ private ownerWriter;
18
23
  }
@@ -49,11 +49,10 @@ export class PasskeyRepository {
49
49
  }
50
50
  create(record, adminUser) {
51
51
  return __awaiter(this, void 0, void 0, function* () {
52
- yield this.adminforth.createResourceRecord({
53
- resource: this.getCredentialResource(),
54
- record,
55
- adminUser,
56
- });
52
+ const { error } = yield this.ownerWriter(adminUser).create(record);
53
+ if (error) {
54
+ throw new Error(error);
55
+ }
57
56
  });
58
57
  }
59
58
  updateMeta(passkeyRecord, meta) {
@@ -67,23 +66,24 @@ export class PasskeyRepository {
67
66
  }
68
67
  update(passkeyRecord, newRecord, adminUser) {
69
68
  return __awaiter(this, void 0, void 0, function* () {
70
- yield this.adminforth.updateResourceRecord({
71
- resource: this.getCredentialResource(),
72
- recordId: passkeyRecord[this.getCredentialResourcePkField()],
73
- oldRecord: passkeyRecord,
74
- updates: newRecord,
75
- adminUser,
76
- });
69
+ const { error } = yield this.ownerWriter(adminUser, { oldRecord: passkeyRecord })
70
+ .update(passkeyRecord[this.getCredentialResourcePkField()], newRecord);
71
+ if (error) {
72
+ throw new Error(error);
73
+ }
77
74
  });
78
75
  }
79
76
  delete(passkeyRecord, adminUser) {
80
77
  return __awaiter(this, void 0, void 0, function* () {
81
- yield this.adminforth.deleteResourceRecord({
82
- resource: this.getCredentialResource(),
83
- recordId: passkeyRecord[this.getCredentialResourcePkField()],
84
- record: passkeyRecord,
85
- adminUser,
86
- });
78
+ yield this.ownerWriter(adminUser, { record: passkeyRecord })
79
+ .delete(passkeyRecord[this.getCredentialResourcePkField()]);
87
80
  });
88
81
  }
82
+ /**
83
+ * Users manage their own passkeys and the plugin checks the ownership itself, so these are system
84
+ * writes on the user's behalf, which run the resource hooks (e.g. the audit log).
85
+ */
86
+ ownerWriter(adminUser, snapshot = {}) {
87
+ return this.adminforth.resource(this.options.passkeys.credentialResourceID).asSystem(Object.assign({ adminUser }, snapshot));
88
+ }
89
89
  }
@@ -10,16 +10,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import { RateLimiter } from "adminforth";
11
11
  import twofactor from 'node-2fa';
12
12
  import { TwoFactorErrorCode } from "../utils/errors.js";
13
- const CODE_ATTEMPT_RATE_LIMITS = ['30/1m', '300/1h', '1000/1d'];
13
+ 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
17
  export class TotpService {
18
18
  constructor(options, userRepository, adminforth) {
19
+ var _a;
19
20
  this.options = options;
20
21
  this.userRepository = userRepository;
21
22
  this.adminforth = adminforth;
22
- this.codeAttemptLimiters = CODE_ATTEMPT_RATE_LIMITS.map((rate) => new RateLimiter(rate));
23
+ this.codeAttemptLimiters = ((_a = this.options.totpRateLimit) !== null && _a !== void 0 ? _a : DEFAULT_TOTP_RATE_LIMIT).map((rate) => new RateLimiter(rate));
23
24
  this.lastUsedCodeSteps = new Map();
24
25
  }
25
26
  generateSecret(issuerName, userName) {
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AdminUser, KeyValueAdapter } from "adminforth";
2
- import { type PluginsCommonOptions, PeriodString } from "adminforth";
2
+ import { type PluginsCommonOptions, PeriodString, RateLimitString } from "adminforth";
3
3
  export interface PluginOptions extends PluginsCommonOptions {
4
4
  /**
5
5
  * Name of the field in the auth resource which will store 2FA secret.
@@ -24,6 +24,13 @@ export interface PluginOptions extends PluginsCommonOptions {
24
24
  * code and enter the code. Default is '5m'.
25
25
  */
26
26
  totpSetupValidityPeriod?: PeriodString;
27
+ /**
28
+ * Rate limits for TOTP code attempts of each user, counted by user (not by IP).
29
+ * Every TOTP check counts as an attempt: at login and for step-up verification.
30
+ * Format: "attempts/period", where period is "1s", "1m", "1h", or "1d".
31
+ * Default: ['30/1m', '300/1h', '1000/1d']
32
+ */
33
+ totpRateLimit?: RateLimitString[];
27
34
  customBrandPrefix?: string;
28
35
  /**
29
36
  * Passkeys (WebAuthn) configuration.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/two-factors-auth",
3
- "version": "7.1.0",
3
+ "version": "7.2.0",
4
4
  "description": "AdminForth plugin for two factors authentication",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -29,11 +29,11 @@
29
29
  "zod": "^4.3.6"
30
30
  },
31
31
  "peerDependencies": {
32
- "adminforth": "^4.7.3"
32
+ "adminforth": "^4.22.0"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^22.10.7",
36
- "adminforth": "^4.7.3",
36
+ "adminforth": "^4.22.0",
37
37
  "semantic-release": "^24.2.1",
38
38
  "semantic-release-slack-bot": "^4.0.2",
39
39
  "typescript": "^5.7.3"
@@ -42,11 +42,10 @@ export class PasskeyRepository {
42
42
  }
43
43
 
44
44
  public async create(record: AnyRecord, adminUser: AdminUser): Promise<void> {
45
- await this.adminforth.createResourceRecord({
46
- resource: this.getCredentialResource(),
47
- record,
48
- adminUser,
49
- });
45
+ const { error } = await this.ownerWriter(adminUser).create(record);
46
+ if (error) {
47
+ throw new Error(error);
48
+ }
50
49
  }
51
50
 
52
51
  public async updateMeta(passkeyRecord: AnyRecord, meta: AnyRecord): Promise<void> {
@@ -58,21 +57,23 @@ export class PasskeyRepository {
58
57
  }
59
58
 
60
59
  public async update(passkeyRecord: AnyRecord, newRecord: AnyRecord, adminUser: AdminUser): Promise<void> {
61
- await this.adminforth.updateResourceRecord({
62
- resource: this.getCredentialResource(),
63
- recordId: passkeyRecord[this.getCredentialResourcePkField()],
64
- oldRecord: passkeyRecord,
65
- updates: newRecord,
66
- adminUser,
67
- });
60
+ const { error } = await this.ownerWriter(adminUser, { oldRecord: passkeyRecord })
61
+ .update(passkeyRecord[this.getCredentialResourcePkField()], newRecord);
62
+ if (error) {
63
+ throw new Error(error);
64
+ }
68
65
  }
69
66
 
70
67
  public async delete(passkeyRecord: AnyRecord, adminUser: AdminUser): Promise<void> {
71
- await this.adminforth.deleteResourceRecord({
72
- resource: this.getCredentialResource(),
73
- recordId: passkeyRecord[this.getCredentialResourcePkField()],
74
- record: passkeyRecord,
75
- adminUser,
76
- });
68
+ await this.ownerWriter(adminUser, { record: passkeyRecord })
69
+ .delete(passkeyRecord[this.getCredentialResourcePkField()]);
70
+ }
71
+
72
+ /**
73
+ * Users manage their own passkeys and the plugin checks the ownership itself, so these are system
74
+ * writes on the user's behalf, which run the resource hooks (e.g. the audit log).
75
+ */
76
+ private ownerWriter(adminUser: AdminUser, snapshot: { record?: AnyRecord; oldRecord?: AnyRecord } = {}) {
77
+ return this.adminforth.resource(this.options.passkeys.credentialResourceID).asSystem({ adminUser, ...snapshot });
77
78
  }
78
79
  }
@@ -1,17 +1,17 @@
1
- import { RateLimiter, type AdminUser, type IAdminForth } from "adminforth";
1
+ import { RateLimiter, type AdminUser, 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";
5
5
  import { TwoFactorErrorCode } from "../utils/errors.js";
6
6
  import type { VerificationFailure, VerificationResult } from "../utils/types.js";
7
7
 
8
- const CODE_ATTEMPT_RATE_LIMITS = ['30/1m', '300/1h', '1000/1d'];
8
+ 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
12
 
13
13
  export class TotpService {
14
- private readonly codeAttemptLimiters = CODE_ATTEMPT_RATE_LIMITS.map((rate) => new RateLimiter(rate));
14
+ private readonly codeAttemptLimiters = (this.options.totpRateLimit ?? DEFAULT_TOTP_RATE_LIMIT).map((rate) => new RateLimiter(rate));
15
15
  private readonly lastUsedCodeSteps = new Map<string, number>();
16
16
 
17
17
  constructor(
@@ -7,7 +7,7 @@ import { TwoFactorErrorCode } from '../dist/utils/errors.js';
7
7
  const SECRET = 'JBSWY3DPEHPK3PXP';
8
8
  const userRepository = { getAuthUser: async (pk) => ({ pk }), getSecret: () => SECRET, getUserPk: (adminUser) => adminUser.pk };
9
9
 
10
- function createService() {
10
+ function createService(options = {}) {
11
11
  const jwts = new Map();
12
12
  const auth = {
13
13
  issueJWT: (payload, type) => {
@@ -17,7 +17,7 @@ function createService() {
17
17
  },
18
18
  verify: async (token, type) => (jwts.get(token)?.type === type ? jwts.get(token) : null),
19
19
  };
20
- return new TotpService({ timeStepWindow: 1 }, userRepository, { auth });
20
+ return new TotpService({ timeStepWindow: 1, ...options }, userRepository, { auth });
21
21
  }
22
22
 
23
23
  test('limits code attempts of each user to stop brute force of a stolen session', async () => {
@@ -29,6 +29,14 @@ test('limits code attempts of each user to stop brute force of a stolen session'
29
29
  assert.equal((await service.verifyUserCode('user-2', 'wrong')).code, TwoFactorErrorCode.INVALID);
30
30
  });
31
31
 
32
+ test('uses totpRateLimit from plugin options instead of the default limits', async () => {
33
+ const service = createService({ totpRateLimit: ['3/1m'] });
34
+ for (let attempt = 0; attempt < 3; attempt++) {
35
+ assert.equal((await service.verifyUserCode('user-1', 'wrong')).code, TwoFactorErrorCode.INVALID);
36
+ }
37
+ assert.equal((await service.verifyUserCode('user-1', 'wrong')).code, TwoFactorErrorCode.RATE_LIMITED);
38
+ });
39
+
32
40
  test('a correct code gives a token that confirms the code only for its user', async () => {
33
41
  const service = createService();
34
42
  const { verifiedCodeToken } = await service.verifyAdminUserCode({ pk: 'user-1' }, twofactor.generateToken(SECRET).token);
package/types.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AdminUser, KeyValueAdapter } from "adminforth";
2
- import {type PluginsCommonOptions, PeriodString } from "adminforth";
2
+ import {type PluginsCommonOptions, PeriodString, RateLimitString } from "adminforth";
3
3
 
4
4
  export interface PluginOptions extends PluginsCommonOptions {
5
5
 
@@ -30,6 +30,14 @@ export interface PluginOptions extends PluginsCommonOptions {
30
30
  */
31
31
  totpSetupValidityPeriod?: PeriodString; // e.g. '5m', '10m', '15m'. Default is '1m'
32
32
 
33
+ /**
34
+ * Rate limits for TOTP code attempts of each user, counted by user (not by IP).
35
+ * Every TOTP check counts as an attempt: at login and for step-up verification.
36
+ * Format: "attempts/period", where period is "1s", "1m", "1h", or "1d".
37
+ * Default: ['30/1m', '300/1h', '1000/1d']
38
+ */
39
+ totpRateLimit?: RateLimitString[];
40
+
33
41
  customBrandPrefix?: string;
34
42
 
35
43
  /**