@adminforth/two-factors-auth 7.4.1 → 7.4.3

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,763 bytes received 324 bytes 602,174.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
  }
@@ -29,5 +29,5 @@ export declare const renamePasskeyBodySchema: z.ZodObject<{
29
29
  }, z.core.$strict>;
30
30
  export declare const resolveVerifyAutoBodySchema: z.ZodObject<{
31
31
  sessionsIds: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString>>>;
32
- confirmationResult: z.ZodRecord<z.ZodString, z.ZodAny>;
32
+ confirmationResult: z.ZodOptional<z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodAny>>>;
33
33
  }, z.core.$strict>;
@@ -31,5 +31,6 @@ export const renamePasskeyBodySchema = z.object({
31
31
  }).strict();
32
32
  export const resolveVerifyAutoBodySchema = z.object({
33
33
  sessionsIds: z.array(z.string()).nullish(),
34
- confirmationResult: z.record(z.string(), z.any()),
34
+ // missing on Cancel in TwoFAModal; the handler then resolves the waiting sessions as cancelled
35
+ confirmationResult: z.record(z.string(), z.any()).nullish(),
35
36
  }).strict();
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;
@@ -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 = {}));
@@ -39,5 +39,6 @@ export const renamePasskeyBodySchema = z.object({
39
39
 
40
40
  export const resolveVerifyAutoBodySchema = z.object({
41
41
  sessionsIds: z.array(z.string()).nullish(),
42
- confirmationResult: z.record(z.string(), z.any()),
42
+ // missing on Cancel in TwoFAModal; the handler then resolves the waiting sessions as cancelled
43
+ confirmationResult: z.record(z.string(), z.any()).nullish(),
43
44
  }).strict();
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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/two-factors-auth",
3
- "version": "7.4.1",
3
+ "version": "7.4.3",
4
4
  "description": "AdminForth plugin for two factors authentication",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -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"
@@ -0,0 +1,9 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { resolveVerifyAutoBodySchema } from '../dist/endpoints/validation.js';
4
+
5
+ test('resolveVerifyAuto accepts a cancelled confirmation, so the handler can release the waiting request', () => {
6
+ // TwoFAModal sends confirmationResult: undefined on Cancel, JSON drops it
7
+ const cancelBody = JSON.parse(JSON.stringify({ confirmationResult: undefined, sessionsIds: ['session'] }));
8
+ assert.equal(resolveVerifyAutoBodySchema.safeParse(cancelBody).success, true);
9
+ });
@@ -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
  }