@adminforth/two-factors-auth 7.4.2 → 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,029 bytes received 324 bytes 600,706.00 bytes/sec
25
- total size is 298,778 speedup is 0.99
24
+ sent 300,780 bytes received 324 bytes 602,208.00 bytes/sec
25
+ total size is 299,529 speedup is 0.99
@@ -30,6 +30,9 @@
30
30
 
31
31
  async function handleLoginWithPasskey() {
32
32
  const passkeyOptions = await getPasskey();
33
+ if (!passkeyOptions) {
34
+ return;
35
+ }
33
36
  try {
34
37
  const resp = await callAdminForthApi({
35
38
  method: 'POST',
@@ -88,6 +88,8 @@
88
88
 
89
89
  const isAwaiting2FAResult = ref(false);
90
90
  let allowAddNewSessions = true;
91
+ // the modal is open or its answer is being sent, a new prompt joins this loop instead of starting another one
92
+ let isConfirmingSessions = false;
91
93
  const ALLOW_NEW_SESSIONS_PERIOD = 1000;
92
94
  const MAX_ACTIONS_PER_CONFIRMATION = 20;
93
95
  const sessionsToResolve = ref<AutoVerifySession[]>([]);
@@ -112,6 +114,12 @@
112
114
  websocket.subscribe(user2FaTopic, async (session: AutoVerifySession) => {
113
115
  if (!allowAddNewSessions) {
114
116
  alert({message: t('Some process or user tries to add new actions to confirm. Action was blocked'), variant: 'warning'});
117
+ // without a confirmationResult the server fails the blocked request at once, not after its timeout
118
+ callAdminForthApi({
119
+ method: "POST",
120
+ path: "/plugin/passkeys/resolveVerifyAuto",
121
+ body: { sessionsIds: [session.sessionId] },
122
+ });
115
123
  return;
116
124
  }
117
125
  if (sessionsToResolve.value.length < MAX_ACTIONS_PER_CONFIRMATION) {
@@ -119,13 +127,15 @@
119
127
  } else {
120
128
  queuedSessions.push(session);
121
129
  }
122
- if (isAwaiting2FAResult.value) {
130
+ if (isConfirmingSessions) {
123
131
  return;
124
132
  }
133
+ isConfirmingSessions = true;
125
134
  while (sessionsToResolve.value.length) {
126
135
  await confirmSessions();
127
- sessionsToResolve.value = queuedSessions.splice(0, MAX_ACTIONS_PER_CONFIRMATION);
136
+ sessionsToResolve.value.push(...queuedSessions.splice(0, MAX_ACTIONS_PER_CONFIRMATION - sessionsToResolve.value.length));
128
137
  }
138
+ isConfirmingSessions = false;
129
139
  allowAddNewSessions = true;
130
140
  });
131
141
  websocket.subscribe(`${user2FaTopic}/resolve`, async (data: {sessionId: string}) => {
@@ -150,11 +160,12 @@
150
160
  }
151
161
  }
152
162
  isAwaiting2FAResult.value = false;
163
+ const sessionsIds = sessionsToResolve.value.map((session) => session.sessionId);
153
164
  try {
154
165
  const response = await callAdminForthApi({
155
166
  method: "POST",
156
167
  path: "/plugin/passkeys/resolveVerifyAuto",
157
- body: { confirmationResult, sessionsIds: sessionsToResolve.value.map((session) => session.sessionId) }
168
+ body: { confirmationResult, sessionsIds }
158
169
  });
159
170
  if (!response.ok && response.code === 'VERIFICATION_CANCELLED'){
160
171
  alert({message: t('Verification session finished or cancelled.'), variant: 'warning'});
@@ -164,6 +175,8 @@
164
175
  } catch (error) {
165
176
  console.error('Error resolving automatic 2FA verification:', error);
166
177
  }
178
+ // prompts that came while the answer was being sent were not in it, they get their own confirmation
179
+ sessionsToResolve.value = sessionsToResolve.value.filter((session) => !sessionsIds.includes(session.sessionId));
167
180
  }
168
181
 
169
182
  const emit = defineEmits<{
@@ -279,6 +292,10 @@
279
292
  } finally {
280
293
  isFetchingPasskey.value = false;
281
294
  }
295
+ // the browser prompt was dismissed or failed with an alert, the modal stays open for a retry
296
+ if (!passkeyData) {
297
+ return null;
298
+ }
282
299
  modelShow.value = false;
283
300
  const dataToReturn = {
284
301
  mode: "passkey",
@@ -354,15 +371,11 @@
354
371
  }
355
372
 
356
373
  async function checkIfSkipAllowModal(): Promise<{ skipAllowed: boolean; gracePeriod?: boolean }> {
357
- try {
358
- return await callAdminForthApi({
359
- method: "GET",
360
- path: "/plugin/twofa/skip-allow-modal",
361
- });
362
- } catch (error) {
363
- console.error('Error checking skip allow modal:', error);
364
- return { skipAllowed: false };
365
- }
374
+ // the API helper resolves null instead of throwing when the request fails, show the modal then
375
+ return (await callAdminForthApi({
376
+ method: "GET",
377
+ path: "/plugin/twofa/skip-allow-modal",
378
+ })) ?? { skipAllowed: false };
366
379
  }
367
380
 
368
381
  </script>
package/custom/utils.js CHANGED
@@ -72,7 +72,6 @@
72
72
  }
73
73
  const credential = await authenticate(options);
74
74
  if (!credential) {
75
- isFetchingPasskey.value = false;
76
75
  return;
77
76
  }
78
77
  const result = JSON.stringify(credential);
@@ -99,7 +98,6 @@
99
98
  } else {
100
99
  const message = response.error || 'Error creating sign-in request.';
101
100
  adminforth.alert({message, variant: 'warning'});
102
- codeError.value = message;
103
101
  }
104
102
  }
105
103
 
@@ -125,13 +123,11 @@
125
123
  // User cancelled or ignored the browser passkey prompt.
126
124
  return null;
127
125
  } else if (name === 'InvalidStateError' || name === 'OperationError' || /pending/i.test(message)) {
128
- adminforth.alert({ message: t('Another security prompt is already open. Please try again.'), variant: 'warning' });
129
- codeError.value = t('A previous passkey attempt was still pending. Please try again.');
126
+ adminforth.alert({ message: 'Another security prompt is already open. Please try again.', variant: 'warning' });
130
127
  return null;
131
128
  } else {
132
129
  console.error('Error during authentication:', error);
133
130
  adminforth.alert({message: `Error during authentication: ${error}`, variant: 'warning'});
134
- codeError.value = 'Error during authentication.';
135
131
  return null;
136
132
  }
137
133
  }
@@ -30,6 +30,9 @@
30
30
 
31
31
  async function handleLoginWithPasskey() {
32
32
  const passkeyOptions = await getPasskey();
33
+ if (!passkeyOptions) {
34
+ return;
35
+ }
33
36
  try {
34
37
  const resp = await callAdminForthApi({
35
38
  method: 'POST',
@@ -88,6 +88,8 @@
88
88
 
89
89
  const isAwaiting2FAResult = ref(false);
90
90
  let allowAddNewSessions = true;
91
+ // the modal is open or its answer is being sent, a new prompt joins this loop instead of starting another one
92
+ let isConfirmingSessions = false;
91
93
  const ALLOW_NEW_SESSIONS_PERIOD = 1000;
92
94
  const MAX_ACTIONS_PER_CONFIRMATION = 20;
93
95
  const sessionsToResolve = ref<AutoVerifySession[]>([]);
@@ -112,6 +114,12 @@
112
114
  websocket.subscribe(user2FaTopic, async (session: AutoVerifySession) => {
113
115
  if (!allowAddNewSessions) {
114
116
  alert({message: t('Some process or user tries to add new actions to confirm. Action was blocked'), variant: 'warning'});
117
+ // without a confirmationResult the server fails the blocked request at once, not after its timeout
118
+ callAdminForthApi({
119
+ method: "POST",
120
+ path: "/plugin/passkeys/resolveVerifyAuto",
121
+ body: { sessionsIds: [session.sessionId] },
122
+ });
115
123
  return;
116
124
  }
117
125
  if (sessionsToResolve.value.length < MAX_ACTIONS_PER_CONFIRMATION) {
@@ -119,13 +127,15 @@
119
127
  } else {
120
128
  queuedSessions.push(session);
121
129
  }
122
- if (isAwaiting2FAResult.value) {
130
+ if (isConfirmingSessions) {
123
131
  return;
124
132
  }
133
+ isConfirmingSessions = true;
125
134
  while (sessionsToResolve.value.length) {
126
135
  await confirmSessions();
127
- sessionsToResolve.value = queuedSessions.splice(0, MAX_ACTIONS_PER_CONFIRMATION);
136
+ sessionsToResolve.value.push(...queuedSessions.splice(0, MAX_ACTIONS_PER_CONFIRMATION - sessionsToResolve.value.length));
128
137
  }
138
+ isConfirmingSessions = false;
129
139
  allowAddNewSessions = true;
130
140
  });
131
141
  websocket.subscribe(`${user2FaTopic}/resolve`, async (data: {sessionId: string}) => {
@@ -150,11 +160,12 @@
150
160
  }
151
161
  }
152
162
  isAwaiting2FAResult.value = false;
163
+ const sessionsIds = sessionsToResolve.value.map((session) => session.sessionId);
153
164
  try {
154
165
  const response = await callAdminForthApi({
155
166
  method: "POST",
156
167
  path: "/plugin/passkeys/resolveVerifyAuto",
157
- body: { confirmationResult, sessionsIds: sessionsToResolve.value.map((session) => session.sessionId) }
168
+ body: { confirmationResult, sessionsIds }
158
169
  });
159
170
  if (!response.ok && response.code === 'VERIFICATION_CANCELLED'){
160
171
  alert({message: t('Verification session finished or cancelled.'), variant: 'warning'});
@@ -164,6 +175,8 @@
164
175
  } catch (error) {
165
176
  console.error('Error resolving automatic 2FA verification:', error);
166
177
  }
178
+ // prompts that came while the answer was being sent were not in it, they get their own confirmation
179
+ sessionsToResolve.value = sessionsToResolve.value.filter((session) => !sessionsIds.includes(session.sessionId));
167
180
  }
168
181
 
169
182
  const emit = defineEmits<{
@@ -279,6 +292,10 @@
279
292
  } finally {
280
293
  isFetchingPasskey.value = false;
281
294
  }
295
+ // the browser prompt was dismissed or failed with an alert, the modal stays open for a retry
296
+ if (!passkeyData) {
297
+ return null;
298
+ }
282
299
  modelShow.value = false;
283
300
  const dataToReturn = {
284
301
  mode: "passkey",
@@ -354,15 +371,11 @@
354
371
  }
355
372
 
356
373
  async function checkIfSkipAllowModal(): Promise<{ skipAllowed: boolean; gracePeriod?: boolean }> {
357
- try {
358
- return await callAdminForthApi({
359
- method: "GET",
360
- path: "/plugin/twofa/skip-allow-modal",
361
- });
362
- } catch (error) {
363
- console.error('Error checking skip allow modal:', error);
364
- return { skipAllowed: false };
365
- }
374
+ // the API helper resolves null instead of throwing when the request fails, show the modal then
375
+ return (await callAdminForthApi({
376
+ method: "GET",
377
+ path: "/plugin/twofa/skip-allow-modal",
378
+ })) ?? { skipAllowed: false };
366
379
  }
367
380
 
368
381
  </script>
@@ -72,7 +72,6 @@
72
72
  }
73
73
  const credential = await authenticate(options);
74
74
  if (!credential) {
75
- isFetchingPasskey.value = false;
76
75
  return;
77
76
  }
78
77
  const result = JSON.stringify(credential);
@@ -99,7 +98,6 @@
99
98
  } else {
100
99
  const message = response.error || 'Error creating sign-in request.';
101
100
  adminforth.alert({message, variant: 'warning'});
102
- codeError.value = message;
103
101
  }
104
102
  }
105
103
 
@@ -125,13 +123,11 @@
125
123
  // User cancelled or ignored the browser passkey prompt.
126
124
  return null;
127
125
  } else if (name === 'InvalidStateError' || name === 'OperationError' || /pending/i.test(message)) {
128
- adminforth.alert({ message: t('Another security prompt is already open. Please try again.'), variant: 'warning' });
129
- codeError.value = t('A previous passkey attempt was still pending. Please try again.');
126
+ adminforth.alert({ message: 'Another security prompt is already open. Please try again.', variant: 'warning' });
130
127
  return null;
131
128
  } else {
132
129
  console.error('Error during authentication:', error);
133
130
  adminforth.alert({message: `Error during authentication: ${error}`, variant: 'warning'});
134
- codeError.value = 'Error during authentication.';
135
131
  return null;
136
132
  }
137
133
  }
package/dist/index.js CHANGED
@@ -96,6 +96,10 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
96
96
  }));
97
97
  if (contextualResult)
98
98
  return contextualResult;
99
+ // users who do not need 2FA pass without a modal, so they never wait for a browser tab
100
+ const skipResult = yield this.verify(undefined, { adminUser, userPk: adminUser.pk });
101
+ if (!('error' in skipResult))
102
+ return skipResult;
99
103
  const websocketClientId = getRequestWebsocketClientId === null || getRequestWebsocketClientId === void 0 ? void 0 : getRequestWebsocketClientId();
100
104
  if (!websocketClientId) {
101
105
  return {
@@ -107,7 +111,15 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
107
111
  const sessionId = crypto.randomUUID();
108
112
  const jwt = this.adminforth.auth.issueJWT({ sessionId, adminUserPk: adminUser.pk }, 'auto2FA', '5m');
109
113
  const resultPromise = this.waitForResponse(jwt, 5 * 60 * 1000);
110
- this.adminforth.websocket.publish(`/user2fa/${adminUser.pk}/${websocketClientId}`, { sessionId: jwt, actionDescription });
114
+ const delivered = yield this.adminforth.websocket.publish(`/user2fa/${adminUser.pk}/${websocketClientId}`, { sessionId: jwt, actionDescription });
115
+ // older cores resolve publish with nothing, then keep waiting for the tab as before
116
+ if (delivered === 0) {
117
+ this.resolveResponse(jwt, {
118
+ ok: false,
119
+ error: 'Could not show the 2FA prompt in this browser tab. Reload the page and try again.',
120
+ code: TwoFactorErrorCode.DELIVERY_FAILED,
121
+ });
122
+ }
111
123
  const result = yield resultPromise;
112
124
  this.adminforth.websocket.publish(`/user2fa/${adminUser.pk}/${websocketClientId}/resolve`, { sessionId: jwt });
113
125
  return result;
@@ -268,8 +280,9 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
268
280
  if (typeof this.options.twoFaSecretFieldName !== 'string') {
269
281
  throw new Error('twoFaSecretFieldName must be a string');
270
282
  }
283
+ // otpauth searches an infinite window until any code matches
271
284
  if (this.options.timeStepWindow === undefined
272
- || typeof this.options.timeStepWindow !== 'number'
285
+ || !Number.isInteger(this.options.timeStepWindow)
273
286
  || this.options.timeStepWindow < 0)
274
287
  this.options.timeStepWindow = 1;
275
288
  this.authResource = resourceConfig;
@@ -298,7 +311,7 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
298
311
  }
299
312
  const userCanSkipSetup = this.options.usersFilterToAllowSkipSetup ? this.options.usersFilterToAllowSkipSetup(adminUser) : false;
300
313
  if (!secret) {
301
- newSecret = this.totpService.generateSecret(issuerName, userName);
314
+ newSecret = this.totpService.generateSecret();
302
315
  this.cookieService.setTotpTemporary(extra.response, { userName, newSecret, issuer: issuerName, pk: userPk, userCanSkipSetup, sessionDuration });
303
316
  return {
304
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* () {
@@ -17,6 +17,7 @@ export declare enum TwoFactorErrorCode {
17
17
  BROWSER_CONTEXT_REQUIRED = "BROWSER_CONTEXT_REQUIRED",
18
18
  CANCELLED = "VERIFICATION_CANCELLED",
19
19
  TIMEOUT = "VERIFICATION_TIMEOUT",
20
+ DELIVERY_FAILED = "VERIFICATION_DELIVERY_FAILED",
20
21
  INVALID_SESSION = "INVALID_VERIFICATION_SESSION",
21
22
  INTERNAL_ERROR = "INTERNAL_ERROR"
22
23
  }
@@ -17,6 +17,7 @@ export var TwoFactorErrorCode;
17
17
  TwoFactorErrorCode["BROWSER_CONTEXT_REQUIRED"] = "BROWSER_CONTEXT_REQUIRED";
18
18
  TwoFactorErrorCode["CANCELLED"] = "VERIFICATION_CANCELLED";
19
19
  TwoFactorErrorCode["TIMEOUT"] = "VERIFICATION_TIMEOUT";
20
+ TwoFactorErrorCode["DELIVERY_FAILED"] = "VERIFICATION_DELIVERY_FAILED";
20
21
  TwoFactorErrorCode["INVALID_SESSION"] = "INVALID_VERIFICATION_SESSION";
21
22
  TwoFactorErrorCode["INTERNAL_ERROR"] = "INTERNAL_ERROR";
22
23
  })(TwoFactorErrorCode || (TwoFactorErrorCode = {}));
package/index.ts CHANGED
@@ -112,6 +112,9 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
112
112
  extra,
113
113
  }));
114
114
  if (contextualResult) return contextualResult;
115
+ // users who do not need 2FA pass without a modal, so they never wait for a browser tab
116
+ const skipResult = await this.verify(undefined, { adminUser, userPk: adminUser.pk! });
117
+ if (!('error' in skipResult)) return skipResult;
115
118
  const websocketClientId = getRequestWebsocketClientId?.();
116
119
  if (!websocketClientId) {
117
120
  return {
@@ -124,7 +127,15 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
124
127
  const jwt = this.adminforth.auth.issueJWT({sessionId, adminUserPk: adminUser.pk}, 'auto2FA', '5m');
125
128
  const resultPromise = this.waitForResponse(jwt, 5 * 60 * 1000);
126
129
 
127
- this.adminforth.websocket.publish(`/user2fa/${adminUser.pk}/${websocketClientId}`, { sessionId: jwt, actionDescription });
130
+ const delivered = await this.adminforth.websocket.publish(`/user2fa/${adminUser.pk}/${websocketClientId}`, { sessionId: jwt, actionDescription });
131
+ // older cores resolve publish with nothing, then keep waiting for the tab as before
132
+ if (delivered === 0) {
133
+ this.resolveResponse(jwt, {
134
+ ok: false,
135
+ error: 'Could not show the 2FA prompt in this browser tab. Reload the page and try again.',
136
+ code: TwoFactorErrorCode.DELIVERY_FAILED,
137
+ });
138
+ }
128
139
 
129
140
  const result = await resultPromise;
130
141
 
@@ -316,9 +327,10 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
316
327
  if (typeof this.options.twoFaSecretFieldName !=='string'){
317
328
  throw new Error('twoFaSecretFieldName must be a string')
318
329
  }
330
+ // otpauth searches an infinite window until any code matches
319
331
  if (
320
332
  this.options.timeStepWindow === undefined
321
- || typeof this.options.timeStepWindow !== 'number'
333
+ || !Number.isInteger(this.options.timeStepWindow)
322
334
  || this.options.timeStepWindow < 0
323
335
  )
324
336
  this.options.timeStepWindow = 1;
@@ -352,7 +364,7 @@ export default class TwoFactorsAuthPlugin extends AdminForthPlugin {
352
364
  const userCanSkipSetup = this.options.usersFilterToAllowSkipSetup ? this.options.usersFilterToAllowSkipSetup(adminUser) : false;
353
365
 
354
366
  if (!secret){
355
- newSecret = this.totpService.generateSecret(issuerName, userName);
367
+ newSecret = this.totpService.generateSecret();
356
368
  this.cookieService.setTotpTemporary(extra.response, {userName, newSecret, issuer:issuerName, pk:userPk, userCanSkipSetup, sessionDuration });
357
369
 
358
370
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/two-factors-auth",
3
- "version": "7.4.2",
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": {
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^22.10.7",
36
- "adminforth": "^4.22.0",
36
+ "adminforth": "^4.26.0",
37
37
  "semantic-release": "^24.2.1",
38
38
  "semantic-release-slack-bot": "^4.0.2",
39
39
  "typescript": "^5.7.3"
@@ -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
+ });
@@ -0,0 +1,49 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { runWithRequestContext } from 'adminforth';
4
+ import TwoFactorsAuthPlugin from '../dist/index.js';
5
+ import { MfaRequestContext } from '../dist/services/mfaRequestContext.js';
6
+
7
+ const user = { pk: 'user-1' };
8
+
9
+ function fakePlugin({ verifyResult, delivered }) {
10
+ const published = [];
11
+ const plugin = Object.assign(Object.create(TwoFactorsAuthPlugin.prototype), {
12
+ pending: new Map(),
13
+ mfaRequestContext: new MfaRequestContext(),
14
+ verify: async () => verifyResult,
15
+ adminforth: {
16
+ auth: { issueJWT: () => 'jwt' },
17
+ websocket: { publish: async (topic) => { published.push(topic); return delivered; } },
18
+ },
19
+ });
20
+ return { plugin, published };
21
+ }
22
+
23
+ const inTab = (fn) => runWithRequestContext({ websocketClientId: 'tab-1' }, fn);
24
+
25
+ test('verifyAuto fails fast when no browser tab received the prompt', { timeout: 1000 }, async () => {
26
+ const { plugin } = fakePlugin({ verifyResult: { error: 'Required', code: 'TWO_FACTOR_REQUIRED' }, delivered: 0 });
27
+
28
+ const result = await inTab(() => plugin.verifyAuto(user));
29
+
30
+ assert.equal(result.ok, false);
31
+ assert.equal(result.code, 'VERIFICATION_DELIVERY_FAILED');
32
+ });
33
+
34
+ test('verifyAuto does not prompt users who do not need 2FA', async () => {
35
+ const { plugin, published } = fakePlugin({ verifyResult: { ok: true }, delivered: 1 });
36
+
37
+ assert.deepEqual(await inTab(() => plugin.verifyAuto(user)), { ok: true });
38
+ assert.deepEqual(published, []);
39
+ });
40
+
41
+ test('verifyAuto keeps waiting for the tab on an older core whose publish resolves nothing', { timeout: 1000 }, async () => {
42
+ const { plugin } = fakePlugin({ verifyResult: { error: 'Required', code: 'TWO_FACTOR_REQUIRED' }, delivered: undefined });
43
+
44
+ const pending = inTab(() => plugin.verifyAuto(user));
45
+ await new Promise(setImmediate);
46
+ plugin.resolveResponse('jwt', { ok: true });
47
+
48
+ assert.deepEqual(await pending, { ok: true });
49
+ });
package/utils/errors.ts CHANGED
@@ -19,6 +19,7 @@ export enum TwoFactorErrorCode {
19
19
  BROWSER_CONTEXT_REQUIRED = 'BROWSER_CONTEXT_REQUIRED',
20
20
  CANCELLED = 'VERIFICATION_CANCELLED',
21
21
  TIMEOUT = 'VERIFICATION_TIMEOUT',
22
+ DELIVERY_FAILED = 'VERIFICATION_DELIVERY_FAILED',
22
23
  INVALID_SESSION = 'INVALID_VERIFICATION_SESSION',
23
24
  INTERNAL_ERROR = 'INTERNAL_ERROR',
24
25
  }