@adminforth/two-factors-auth 7.4.3 → 7.4.4

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/build.log CHANGED
@@ -21,5 +21,5 @@ custom/tsconfig.json
21
21
  custom/use2faApi.ts
22
22
  custom/utils.js
23
23
 
24
- sent 300,763 bytes received 324 bytes 602,174.00 bytes/sec
24
+ sent 300,780 bytes received 324 bytes 602,208.00 bytes/sec
25
25
  total size is 299,529 speedup is 0.99
package/dist/index.js CHANGED
@@ -280,8 +280,9 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
280
280
  if (typeof this.options.twoFaSecretFieldName !== 'string') {
281
281
  throw new Error('twoFaSecretFieldName must be a string');
282
282
  }
283
+ // otpauth searches an infinite window until any code matches
283
284
  if (this.options.timeStepWindow === undefined
284
- || typeof this.options.timeStepWindow !== 'number'
285
+ || !Number.isInteger(this.options.timeStepWindow)
285
286
  || this.options.timeStepWindow < 0)
286
287
  this.options.timeStepWindow = 1;
287
288
  this.authResource = resourceConfig;
@@ -310,7 +311,7 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
310
311
  }
311
312
  const userCanSkipSetup = this.options.usersFilterToAllowSkipSetup ? this.options.usersFilterToAllowSkipSetup(adminUser) : false;
312
313
  if (!secret) {
313
- newSecret = this.totpService.generateSecret(issuerName, userName);
314
+ newSecret = this.totpService.generateSecret();
314
315
  this.cookieService.setTotpTemporary(extra.response, { userName, newSecret, issuer: issuerName, pk: userPk, userCanSkipSetup, sessionDuration });
315
316
  return {
316
317
  body: {
@@ -9,7 +9,7 @@ export declare class TotpService {
9
9
  private readonly codeAttemptLimiters;
10
10
  private readonly lastUsedCodeSteps;
11
11
  constructor(options: PluginOptions, userRepository: UserRepository, adminforth: IAdminForth);
12
- generateSecret(issuerName: string, userName: string): string;
12
+ generateSecret(): string;
13
13
  verifySecret(secret: string, code: string): boolean;
14
14
  private findCodeStep;
15
15
  verifyUserCode(userPk: string, code: string, extra?: HttpExtra): Promise<VerificationResult>;
@@ -8,13 +8,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { RateLimiter } from "adminforth";
11
- import twofactor from 'node-2fa';
11
+ import { Secret, TOTP } from "otpauth";
12
12
  import { TwoFactorErrorCode } from "../utils/errors.js";
13
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
- const TOTP_STEP_SECONDS = 30;
17
16
  const RATE_LIMITED_ERROR = "Too many attempts to enter the code. Try again later.";
17
+ // codes and secrets are shown in groups, "123 456" or "ABCD-EFGH"; node-2fa stripped them from both
18
+ const SEPARATORS = /\W+/g;
18
19
  export class TotpService {
19
20
  constructor(options, userRepository, adminforth) {
20
21
  var _a;
@@ -24,15 +25,26 @@ export class TotpService {
24
25
  this.lastUsedCodeSteps = new Map();
25
26
  this.codeAttemptLimiters = ((_a = options.totpRateLimit) !== null && _a !== void 0 ? _a : DEFAULT_TOTP_RATE_LIMIT).map((rate) => new RateLimiter(rate));
26
27
  }
27
- generateSecret(issuerName, userName) {
28
- return twofactor.generateSecret({ name: issuerName, account: userName }).secret;
28
+ generateSecret() {
29
+ return new Secret().base32;
29
30
  }
30
31
  verifySecret(secret, code) {
31
32
  return this.findCodeStep(secret, code) !== null;
32
33
  }
33
34
  findCodeStep(secret, code) {
34
- const match = twofactor.verifyToken(secret, code, this.options.timeStepWindow);
35
- return match && Math.floor(Date.now() / 1000 / TOTP_STEP_SECONDS) + match.delta;
35
+ // the code comes from a request body, where it can be missing or not a string
36
+ if (typeof code !== 'string') {
37
+ return null;
38
+ }
39
+ // one clock reading for the check and the step, so they agree at a step boundary
40
+ const timestamp = Date.now();
41
+ const delta = TOTP.validate({
42
+ token: code.replace(SEPARATORS, ''),
43
+ secret: Secret.fromBase32(secret.replace(SEPARATORS, '')),
44
+ window: this.options.timeStepWindow,
45
+ timestamp,
46
+ });
47
+ return delta === null ? null : TOTP.counter({ timestamp }) + delta;
36
48
  }
37
49
  verifyUserCode(userPk, code, extra) {
38
50
  return __awaiter(this, void 0, void 0, function* () {
package/index.ts CHANGED
@@ -327,9 +327,10 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
327
327
  if (typeof this.options.twoFaSecretFieldName !=='string'){
328
328
  throw new Error('twoFaSecretFieldName must be a string')
329
329
  }
330
+ // otpauth searches an infinite window until any code matches
330
331
  if (
331
332
  this.options.timeStepWindow === undefined
332
- || typeof this.options.timeStepWindow !== 'number'
333
+ || !Number.isInteger(this.options.timeStepWindow)
333
334
  || this.options.timeStepWindow < 0
334
335
  )
335
336
  this.options.timeStepWindow = 1;
@@ -363,7 +364,7 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
363
364
  const userCanSkipSetup = this.options.usersFilterToAllowSkipSetup ? this.options.usersFilterToAllowSkipSetup(adminUser) : false;
364
365
 
365
366
  if (!secret){
366
- newSecret = this.totpService.generateSecret(issuerName, userName);
367
+ newSecret = this.totpService.generateSecret();
367
368
  this.cookieService.setTotpTemporary(extra.response, {userName, newSecret, issuer:issuerName, pk:userPk, userCanSkipSetup, sessionDuration });
368
369
 
369
370
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/two-factors-auth",
3
- "version": "7.4.3",
3
+ "version": "7.4.4",
4
4
  "description": "AdminForth plugin for two factors authentication",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -25,7 +25,7 @@
25
25
  "license": "MIT",
26
26
  "dependencies": {
27
27
  "@simplewebauthn/server": "^13.2.1",
28
- "node-2fa": "^2.0.3",
28
+ "otpauth": "^9.6.0",
29
29
  "zod": "^4.3.6"
30
30
  },
31
31
  "peerDependencies": {
@@ -1,5 +1,5 @@
1
1
  import { RateLimiter, type AdminUser, type HttpExtra, type IAdminForth, type RateLimitString } from "adminforth";
2
- import twofactor from 'node-2fa';
2
+ import { Secret, TOTP } from "otpauth";
3
3
  import type { PluginOptions } from "../types.js";
4
4
  import { UserRepository } from "../repositories/userRepository.js";
5
5
  import { TwoFactorErrorCode } from "../utils/errors.js";
@@ -8,8 +8,9 @@ import type { VerificationFailure, VerificationResult } from "../utils/types.js"
8
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
- const TOTP_STEP_SECONDS = 30;
12
11
  const RATE_LIMITED_ERROR = "Too many attempts to enter the code. Try again later.";
12
+ // codes and secrets are shown in groups, "123 456" or "ABCD-EFGH"; node-2fa stripped them from both
13
+ const SEPARATORS = /\W+/g;
13
14
 
14
15
  export class TotpService {
15
16
  private readonly codeAttemptLimiters: RateLimiter[];
@@ -23,8 +24,8 @@ export class TotpService {
23
24
  this.codeAttemptLimiters = (options.totpRateLimit ?? DEFAULT_TOTP_RATE_LIMIT).map((rate) => new RateLimiter(rate));
24
25
  }
25
26
 
26
- public generateSecret(issuerName: string, userName: string): string {
27
- return twofactor.generateSecret({ name: issuerName, account: userName }).secret;
27
+ public generateSecret(): string {
28
+ return new Secret().base32;
28
29
  }
29
30
 
30
31
  public verifySecret(secret: string, code: string): boolean {
@@ -32,8 +33,19 @@ export class TotpService {
32
33
  }
33
34
 
34
35
  private findCodeStep(secret: string, code: string): number | null {
35
- const match = twofactor.verifyToken(secret, code, this.options.timeStepWindow);
36
- return match && Math.floor(Date.now() / 1000 / TOTP_STEP_SECONDS) + match.delta;
36
+ // the code comes from a request body, where it can be missing or not a string
37
+ if (typeof code !== 'string') {
38
+ return null;
39
+ }
40
+ // one clock reading for the check and the step, so they agree at a step boundary
41
+ const timestamp = Date.now();
42
+ const delta = TOTP.validate({
43
+ token: code.replace(SEPARATORS, ''),
44
+ secret: Secret.fromBase32(secret.replace(SEPARATORS, '')),
45
+ window: this.options.timeStepWindow,
46
+ timestamp,
47
+ });
48
+ return delta === null ? null : TOTP.counter({ timestamp }) + delta;
37
49
  }
38
50
 
39
51
  public async verifyUserCode(userPk: string, code: string, extra?: HttpExtra): Promise<VerificationResult> {
@@ -1,10 +1,12 @@
1
1
  import test from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
- import twofactor from 'node-2fa';
4
3
  import { TotpService } from '../dist/services/totpService.js';
5
4
  import { TwoFactorErrorCode } from '../dist/utils/errors.js';
6
5
 
7
6
  const SECRET = 'JBSWY3DPEHPK3PXP';
7
+ const STEP_MS = 30_000;
8
+ // codes of SECRET at the steps 1000-1002, computed with an independent RFC 4226 implementation
9
+ const CODES = { 1000: '120699', 1001: '082801', 1002: '676083' };
8
10
  const userRepository = { getAuthUser: async (pk) => ({ pk }), getSecret: () => SECRET, getUserPk: (adminUser) => adminUser.pk };
9
11
 
10
12
  function createService(options = {}) {
@@ -46,7 +48,7 @@ test('calls onOtpFailed for a wrong code and onOtpSucceeded for a correct one, b
46
48
  onOtpFailed: async (params) => { calls.push(['failed', params]); },
47
49
  onOtpSucceeded: async (params) => { calls.push(['succeeded', params]); },
48
50
  });
49
- const code = twofactor.generateToken(SECRET).token;
51
+ const code = CODES[1000];
50
52
 
51
53
  await service.verifyUserCode('user-1', 'wrong', extra);
52
54
  await service.verifyUserCode('user-1', code, extra);
@@ -74,7 +76,7 @@ test('beforeOtpCheck rejects an attempt without checking the code and without us
74
76
  });
75
77
  const rejected = { error: 'Too many wrong codes from your IP', code: TwoFactorErrorCode.RATE_LIMITED };
76
78
 
77
- assert.deepEqual(await service.verifyUserCode('user-1', twofactor.generateToken(SECRET).token, extra), rejected);
79
+ assert.deepEqual(await service.verifyUserCode('user-1', CODES[1000], extra), rejected);
78
80
  assert.deepEqual(await service.verifyUserCode('user-1', 'wrong', extra), rejected);
79
81
  allowed = true;
80
82
  assert.equal((await service.verifyUserCode('user-1', 'wrong', extra)).code, TwoFactorErrorCode.INVALID);
@@ -85,18 +87,18 @@ test('beforeOtpCheck rejects an attempt without checking the code and without us
85
87
  assert.equal(calls[0][1].extra, extra);
86
88
  });
87
89
 
88
- test('a correct code gives a token that confirms the code only for its user', async () => {
90
+ test('a correct code gives a token that confirms the code only for its user', async (t) => {
91
+ t.mock.timers.enable({ apis: ['Date'], now: 1_000 * STEP_MS });
89
92
  const service = createService();
90
- const { verifiedCodeToken } = await service.verifyAdminUserCode({ pk: 'user-1' }, twofactor.generateToken(SECRET).token);
93
+ const { verifiedCodeToken } = await service.verifyAdminUserCode({ pk: 'user-1' }, CODES[1000]);
91
94
  assert.equal(await service.isVerifiedCodeToken(verifiedCodeToken, 'user-1'), true);
92
95
  assert.equal(await service.isVerifiedCodeToken(verifiedCodeToken, 'user-2'), false);
93
96
  assert.equal(await service.isVerifiedCodeToken('forged', 'user-1'), false);
94
97
  });
95
98
 
96
- const STEP_MS = 30_000;
97
99
  const codeAt = (t, time) => {
98
100
  t.mock.timers.setTime(time);
99
- return twofactor.generateToken(SECRET).token;
101
+ return CODES[time / STEP_MS];
100
102
  };
101
103
 
102
104
  test('a code confirms only one request, so a phished code can not be replayed', async (t) => {
@@ -119,3 +121,58 @@ test('after a code is used, older codes from the window are rejected and the nex
119
121
  assert.equal((await service.verifyUserCode('user-1', olderCode)).code, TwoFactorErrorCode.INVALID);
120
122
  assert.deepEqual(await service.verifyUserCode('user-1', codeAt(t, 1_002 * STEP_MS)), { ok: true });
121
123
  });
124
+
125
+ // the key of the RFC 4226 and RFC 6238 test vectors, "12345678901234567890" in base32
126
+ const RFC_SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
127
+
128
+ test('RFC 6238 SHA-1 codes are accepted at their times, including the ones with leading zeros', (t) => {
129
+ t.mock.timers.enable({ apis: ['Date'], now: 0 });
130
+ const service = createService({ timeStepWindow: 0 });
131
+ const vectors = [[59, '287082'], [1111111109, '081804'], [1111111111, '050471'], [1234567890, '005924'], [2000000000, '279037'], [20000000000, '353130']];
132
+ for (const [seconds, code] of vectors) {
133
+ t.mock.timers.setTime(seconds * 1000);
134
+ assert.equal(service.verifySecret(RFC_SECRET, code), true);
135
+ }
136
+ });
137
+
138
+ // node-2fa cut the code to its last characters when the truncated 31-bit value had fewer than 6 digits
139
+ // (it gave "5" instead of "092555"), so the code of an authenticator app never matched: 1 step in 21474
140
+ test('a code whose truncated value is below 100000 is zero padded and accepted', (t) => {
141
+ t.mock.timers.enable({ apis: ['Date'], now: 0 });
142
+ const service = createService({ timeStepWindow: 0 });
143
+ for (const [step, code] of [[10281, '092555'], [732066, '007261'], [2011430, '000835']]) {
144
+ t.mock.timers.setTime(step * STEP_MS);
145
+ assert.equal(service.verifySecret(RFC_SECRET, code), true);
146
+ assert.equal(service.verifySecret(RFC_SECRET, String(Number(code))), false);
147
+ }
148
+ });
149
+
150
+ test('timeStepWindow is the number of steps before and after the current one which are accepted', (t) => {
151
+ t.mock.timers.enable({ apis: ['Date'], now: 1_001 * STEP_MS });
152
+ const exact = createService({ timeStepWindow: 0 });
153
+ const lenient = createService({ timeStepWindow: 1 });
154
+
155
+ assert.deepEqual([CODES[1000], CODES[1001], CODES[1002]].map((code) => exact.verifySecret(SECRET, code)), [false, true, false]);
156
+ assert.deepEqual([CODES[1000], CODES[1001], CODES[1002]].map((code) => lenient.verifySecret(SECRET, code)), [true, true, true]);
157
+ assert.equal(lenient.verifySecret(SECRET, '000000'), false);
158
+ });
159
+
160
+ test('a code or a secret written in groups is accepted, a missing or malformed code is a wrong code', async (t) => {
161
+ t.mock.timers.enable({ apis: ['Date'], now: 1_001 * STEP_MS });
162
+ const service = createService({ timeStepWindow: 0 });
163
+ assert.equal(service.verifySecret(SECRET, '082 801'), true);
164
+ assert.equal(service.verifySecret(SECRET, '082-801'), true);
165
+ assert.equal(service.verifySecret('jbsw-y3dp ehpk-3pxp\n', '082801'), true);
166
+ for (const code of [undefined, null, 82801, '', '08280', '0828011', 'abcdef']) {
167
+ assert.equal((await service.verifyUserCode(`user-${code}`, code)).code, TwoFactorErrorCode.INVALID);
168
+ }
169
+ });
170
+
171
+ test('generated secrets are random base32 keys of 160 bits which authenticator apps accept', () => {
172
+ const service = createService();
173
+ const secrets = new Set(Array.from({ length: 50 }, () => service.generateSecret()));
174
+ assert.equal(secrets.size, 50);
175
+ for (const secret of secrets) {
176
+ assert.match(secret, /^[A-Z2-7]{32}$/);
177
+ }
178
+ });