@adminforth/two-factors-auth 7.4.3 → 7.5.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.
- package/build.log +2 -2
- package/custom/TwoFactorsPasskeysSettings.vue +15 -13
- package/dist/custom/TwoFactorsPasskeysSettings.vue +15 -13
- package/dist/endpoints/registerPasskeyEndpoints.js +2 -2
- package/dist/endpoints/validation.d.ts +1 -0
- package/dist/endpoints/validation.js +1 -0
- package/dist/handlers/createPasskeyHandlers.d.ts +3 -1
- package/dist/handlers/createPasskeyHandlers.js +23 -13
- package/dist/index.js +3 -2
- package/dist/services/totpService.d.ts +1 -1
- package/dist/services/totpService.js +18 -6
- package/endpoints/registerPasskeyEndpoints.ts +2 -2
- package/endpoints/validation.ts +1 -0
- package/handlers/createPasskeyHandlers.ts +29 -17
- package/index.ts +3 -2
- package/package.json +2 -2
- package/services/totpService.ts +18 -6
- package/tests/totpService.test.mjs +64 -7
- package/tests/validation.test.mjs +6 -1
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,
|
|
25
|
-
total size is 299,
|
|
24
|
+
sent 300,893 bytes received 324 bytes 602,434.00 bytes/sec
|
|
25
|
+
total size is 299,642 speedup is 0.99
|
|
@@ -131,7 +131,7 @@
|
|
|
131
131
|
|
|
132
132
|
<script setup lang="ts">
|
|
133
133
|
import { callAdminForthApi, formatDateTime } from '@/utils';
|
|
134
|
-
import adminforth
|
|
134
|
+
import adminforth from '@/adminforth';
|
|
135
135
|
import { onMounted, ref, Ref } from 'vue';
|
|
136
136
|
import { useI18n } from 'vue-i18n';
|
|
137
137
|
import { Button, Card, Dialog, Tooltip, Spinner, Input } from '@/afcl';
|
|
@@ -287,29 +287,31 @@
|
|
|
287
287
|
}
|
|
288
288
|
|
|
289
289
|
async function confirmAndDelete(passkeyId: string) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
290
|
+
let confirmationResult: TwoFaConfirmationResult;
|
|
291
|
+
try {
|
|
292
|
+
confirmationResult = await twoFactorsAuth.get2FaConfirmationResult(
|
|
293
|
+
t('To remove passkey first verify yourself')
|
|
294
|
+
);
|
|
295
|
+
} catch {
|
|
296
|
+
// user cancelled 2FA dialog
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
deletePasskey(passkeyId, confirmationResult);
|
|
298
300
|
}
|
|
299
301
|
|
|
300
|
-
async function deletePasskey(passkeyId: string) {
|
|
302
|
+
async function deletePasskey(passkeyId: string, confirmationResult: TwoFaConfirmationResult) {
|
|
301
303
|
try {
|
|
302
304
|
const response = await callAdminForthApi({
|
|
303
305
|
path: '/plugin/passkeys/deletePasskey',
|
|
304
306
|
method: 'DELETE',
|
|
305
|
-
body: { passkeyId },
|
|
307
|
+
body: { passkeyId, confirmationResult },
|
|
306
308
|
});
|
|
307
309
|
if (response.ok) {
|
|
308
310
|
adminforth.alert({ message: t('Passkey deleted successfully!'), variant: 'success' });
|
|
309
311
|
getPasskeys();
|
|
310
312
|
} else {
|
|
311
|
-
console.error('Error deleting passkey:', response
|
|
312
|
-
adminforth.alert({ message: t('Error deleting passkey.'), variant: 'warning' });
|
|
313
|
+
console.error('Error deleting passkey:', response.error);
|
|
314
|
+
adminforth.alert({ message: response.error ?? t('Error deleting passkey.'), variant: 'warning' });
|
|
313
315
|
}
|
|
314
316
|
} catch (error) {
|
|
315
317
|
console.error('Error deleting passkey:', error);
|
|
@@ -131,7 +131,7 @@
|
|
|
131
131
|
|
|
132
132
|
<script setup lang="ts">
|
|
133
133
|
import { callAdminForthApi, formatDateTime } from '@/utils';
|
|
134
|
-
import adminforth
|
|
134
|
+
import adminforth from '@/adminforth';
|
|
135
135
|
import { onMounted, ref, Ref } from 'vue';
|
|
136
136
|
import { useI18n } from 'vue-i18n';
|
|
137
137
|
import { Button, Card, Dialog, Tooltip, Spinner, Input } from '@/afcl';
|
|
@@ -287,29 +287,31 @@
|
|
|
287
287
|
}
|
|
288
288
|
|
|
289
289
|
async function confirmAndDelete(passkeyId: string) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
290
|
+
let confirmationResult: TwoFaConfirmationResult;
|
|
291
|
+
try {
|
|
292
|
+
confirmationResult = await twoFactorsAuth.get2FaConfirmationResult(
|
|
293
|
+
t('To remove passkey first verify yourself')
|
|
294
|
+
);
|
|
295
|
+
} catch {
|
|
296
|
+
// user cancelled 2FA dialog
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
deletePasskey(passkeyId, confirmationResult);
|
|
298
300
|
}
|
|
299
301
|
|
|
300
|
-
async function deletePasskey(passkeyId: string) {
|
|
302
|
+
async function deletePasskey(passkeyId: string, confirmationResult: TwoFaConfirmationResult) {
|
|
301
303
|
try {
|
|
302
304
|
const response = await callAdminForthApi({
|
|
303
305
|
path: '/plugin/passkeys/deletePasskey',
|
|
304
306
|
method: 'DELETE',
|
|
305
|
-
body: { passkeyId },
|
|
307
|
+
body: { passkeyId, confirmationResult },
|
|
306
308
|
});
|
|
307
309
|
if (response.ok) {
|
|
308
310
|
adminforth.alert({ message: t('Passkey deleted successfully!'), variant: 'success' });
|
|
309
311
|
getPasskeys();
|
|
310
312
|
} else {
|
|
311
|
-
console.error('Error deleting passkey:', response
|
|
312
|
-
adminforth.alert({ message: t('Error deleting passkey.'), variant: 'warning' });
|
|
313
|
+
console.error('Error deleting passkey:', response.error);
|
|
314
|
+
adminforth.alert({ message: response.error ?? t('Error deleting passkey.'), variant: 'warning' });
|
|
313
315
|
}
|
|
314
316
|
} catch (error) {
|
|
315
317
|
console.error('Error deleting passkey:', error);
|
|
@@ -59,8 +59,8 @@ export function registerPasskeyEndpoints(server, handlers) {
|
|
|
59
59
|
},
|
|
60
60
|
noAuth: false,
|
|
61
61
|
request_schema: deletePasskeyBodySchema,
|
|
62
|
-
handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response }) {
|
|
63
|
-
return handlers.deletePasskey({ body, adminUser, response });
|
|
62
|
+
handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response, cookies, headers }) {
|
|
63
|
+
return handlers.deletePasskey({ body, adminUser, response, cookies, headers });
|
|
64
64
|
}),
|
|
65
65
|
});
|
|
66
66
|
server.endpoint({
|
|
@@ -22,6 +22,7 @@ export declare const finishRegistrationBodySchema: z.ZodObject<{
|
|
|
22
22
|
}, z.core.$strict>;
|
|
23
23
|
export declare const deletePasskeyBodySchema: z.ZodObject<{
|
|
24
24
|
passkeyId: z.ZodString;
|
|
25
|
+
confirmationResult: z.ZodRecord<z.ZodString, z.ZodAny>;
|
|
25
26
|
}, z.core.$strict>;
|
|
26
27
|
export declare const renamePasskeyBodySchema: z.ZodObject<{
|
|
27
28
|
passkeyId: z.ZodString;
|
|
@@ -24,6 +24,7 @@ export const finishRegistrationBodySchema = z.object({
|
|
|
24
24
|
}).strict();
|
|
25
25
|
export const deletePasskeyBodySchema = z.object({
|
|
26
26
|
passkeyId: z.string(),
|
|
27
|
+
confirmationResult: z.record(z.string(), z.any()),
|
|
27
28
|
}).strict();
|
|
28
29
|
export const renamePasskeyBodySchema = z.object({
|
|
29
30
|
passkeyId: z.string(),
|
|
@@ -20,10 +20,12 @@ export declare function createPasskeyHandlers(ctx: any): {
|
|
|
20
20
|
getPasskeys: ({ adminUser }: {
|
|
21
21
|
adminUser: any;
|
|
22
22
|
}) => Promise<any>;
|
|
23
|
-
deletePasskey: ({ body, adminUser, response }: {
|
|
23
|
+
deletePasskey: ({ body, adminUser, response, cookies, headers }: {
|
|
24
24
|
body: any;
|
|
25
25
|
adminUser: any;
|
|
26
26
|
response: any;
|
|
27
|
+
cookies: any;
|
|
28
|
+
headers: any;
|
|
27
29
|
}) => Promise<any>;
|
|
28
30
|
renamePasskey: ({ body, adminUser, response }: {
|
|
29
31
|
body: any;
|
|
@@ -9,21 +9,27 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
};
|
|
10
10
|
import { HttpStatus, TwoFactorErrorCode, errorMessage, respondWithStatus } from "../utils/errors.js";
|
|
11
11
|
export function createPasskeyHandlers(ctx) {
|
|
12
|
+
// returns a 403 response when the 2FA confirmation fails, nothing when it passes
|
|
13
|
+
const rejectUnconfirmed = (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response, cookies, headers }) {
|
|
14
|
+
const verificationResult = yield ctx.verifyMfaConfirmation(body === null || body === void 0 ? void 0 : body.confirmationResult, {
|
|
15
|
+
adminUser: adminUser,
|
|
16
|
+
userPk: adminUser.pk,
|
|
17
|
+
cookies: cookies,
|
|
18
|
+
response: response,
|
|
19
|
+
extra: {
|
|
20
|
+
headers,
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
if (!verificationResult || !('ok' in verificationResult)) {
|
|
24
|
+
return respondWithStatus({ ok: false, error: 'error' in verificationResult ? verificationResult.error : 'Verification failed' }, response, HttpStatus.FORBIDDEN);
|
|
25
|
+
}
|
|
26
|
+
});
|
|
12
27
|
return {
|
|
13
28
|
createRegistrationOptions: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response, cookies, headers }) {
|
|
14
29
|
const mode = body === null || body === void 0 ? void 0 : body.mode;
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
userPk: adminUser.pk,
|
|
19
|
-
cookies: cookies,
|
|
20
|
-
response: response,
|
|
21
|
-
extra: {
|
|
22
|
-
headers,
|
|
23
|
-
}
|
|
24
|
-
});
|
|
25
|
-
if (!verificationResult || !('ok' in verificationResult)) {
|
|
26
|
-
return respondWithStatus({ ok: false, error: 'error' in verificationResult ? verificationResult.error : 'Verification failed' }, response, HttpStatus.FORBIDDEN);
|
|
30
|
+
const rejected = yield rejectUnconfirmed({ body, adminUser, response, cookies, headers });
|
|
31
|
+
if (rejected) {
|
|
32
|
+
return rejected;
|
|
27
33
|
}
|
|
28
34
|
const registrationOptions = yield ctx.passkeyService.createRegistrationOptions(mode, adminUser, response);
|
|
29
35
|
if (!registrationOptions.ok) {
|
|
@@ -51,7 +57,11 @@ export function createPasskeyHandlers(ctx) {
|
|
|
51
57
|
getPasskeys: (_a) => __awaiter(this, [_a], void 0, function* ({ adminUser }) {
|
|
52
58
|
return ctx.passkeyService.getPasskeys(adminUser);
|
|
53
59
|
}),
|
|
54
|
-
deletePasskey: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response }) {
|
|
60
|
+
deletePasskey: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response, cookies, headers }) {
|
|
61
|
+
const rejected = yield rejectUnconfirmed({ body, adminUser, response, cookies, headers });
|
|
62
|
+
if (rejected) {
|
|
63
|
+
return rejected;
|
|
64
|
+
}
|
|
55
65
|
const deleteResult = yield ctx.passkeyService.deletePasskey(body.passkeyId, adminUser);
|
|
56
66
|
if (!deleteResult.ok) {
|
|
57
67
|
return respondWithStatus(deleteResult, response, HttpStatus.NOT_FOUND);
|
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
|
-
||
|
|
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(
|
|
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(
|
|
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
|
|
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(
|
|
28
|
-
return
|
|
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
|
-
|
|
35
|
-
|
|
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* () {
|
|
@@ -62,8 +62,8 @@ export function registerPasskeyEndpoints(server: IHttpServer, handlers: any): vo
|
|
|
62
62
|
},
|
|
63
63
|
noAuth: false,
|
|
64
64
|
request_schema: deletePasskeyBodySchema,
|
|
65
|
-
handler: async ({ body, adminUser, response }) => {
|
|
66
|
-
return handlers.deletePasskey({ body, adminUser, response });
|
|
65
|
+
handler: async ({ body, adminUser, response, cookies, headers }) => {
|
|
66
|
+
return handlers.deletePasskey({ body, adminUser, response, cookies, headers });
|
|
67
67
|
},
|
|
68
68
|
});
|
|
69
69
|
|
package/endpoints/validation.ts
CHANGED
|
@@ -30,6 +30,7 @@ export const finishRegistrationBodySchema = z.object({
|
|
|
30
30
|
|
|
31
31
|
export const deletePasskeyBodySchema = z.object({
|
|
32
32
|
passkeyId: z.string(),
|
|
33
|
+
confirmationResult: z.record(z.string(), z.any()),
|
|
33
34
|
}).strict();
|
|
34
35
|
|
|
35
36
|
export const renamePasskeyBodySchema = z.object({
|
|
@@ -3,26 +3,33 @@ import { HttpStatus, TwoFactorErrorCode, errorMessage, respondWithStatus } from
|
|
|
3
3
|
import type { VerificationResult } from "../utils/types.js";
|
|
4
4
|
|
|
5
5
|
export function createPasskeyHandlers(ctx: any) {
|
|
6
|
+
// returns a 403 response when the 2FA confirmation fails, nothing when it passes
|
|
7
|
+
const rejectUnconfirmed = async ({ body, adminUser, response, cookies, headers }) => {
|
|
8
|
+
const verificationResult = await ctx.verifyMfaConfirmation(body?.confirmationResult, {
|
|
9
|
+
adminUser: adminUser,
|
|
10
|
+
userPk: adminUser.pk,
|
|
11
|
+
cookies: cookies,
|
|
12
|
+
response: response,
|
|
13
|
+
extra: {
|
|
14
|
+
headers,
|
|
15
|
+
} as HttpExtra
|
|
16
|
+
});
|
|
17
|
+
if (!verificationResult || !('ok' in verificationResult)) {
|
|
18
|
+
return respondWithStatus(
|
|
19
|
+
{ ok: false, error: 'error' in verificationResult ? verificationResult.error : 'Verification failed' },
|
|
20
|
+
response,
|
|
21
|
+
HttpStatus.FORBIDDEN,
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
6
26
|
return {
|
|
7
27
|
createRegistrationOptions: async ({ body, adminUser, response, cookies, headers }) => {
|
|
8
28
|
const mode = body?.mode;
|
|
9
29
|
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
userPk: adminUser.pk,
|
|
14
|
-
cookies: cookies,
|
|
15
|
-
response: response,
|
|
16
|
-
extra: {
|
|
17
|
-
headers,
|
|
18
|
-
} as HttpExtra
|
|
19
|
-
});
|
|
20
|
-
if (!verificationResult || !('ok' in verificationResult)) {
|
|
21
|
-
return respondWithStatus(
|
|
22
|
-
{ ok: false, error: 'error' in verificationResult ? verificationResult.error : 'Verification failed' },
|
|
23
|
-
response,
|
|
24
|
-
HttpStatus.FORBIDDEN,
|
|
25
|
-
);
|
|
30
|
+
const rejected = await rejectUnconfirmed({ body, adminUser, response, cookies, headers });
|
|
31
|
+
if (rejected) {
|
|
32
|
+
return rejected;
|
|
26
33
|
}
|
|
27
34
|
|
|
28
35
|
const registrationOptions = await ctx.passkeyService.createRegistrationOptions(mode, adminUser, response);
|
|
@@ -55,7 +62,12 @@ export function createPasskeyHandlers(ctx: any) {
|
|
|
55
62
|
return ctx.passkeyService.getPasskeys(adminUser);
|
|
56
63
|
},
|
|
57
64
|
|
|
58
|
-
deletePasskey: async ({ body, adminUser, response }) => {
|
|
65
|
+
deletePasskey: async ({ body, adminUser, response, cookies, headers }) => {
|
|
66
|
+
const rejected = await rejectUnconfirmed({ body, adminUser, response, cookies, headers });
|
|
67
|
+
if (rejected) {
|
|
68
|
+
return rejected;
|
|
69
|
+
}
|
|
70
|
+
|
|
59
71
|
const deleteResult = await ctx.passkeyService.deletePasskey(body.passkeyId, adminUser);
|
|
60
72
|
if (!deleteResult.ok) {
|
|
61
73
|
return respondWithStatus(deleteResult, response, HttpStatus.NOT_FOUND);
|
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
|
-
||
|
|
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(
|
|
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.
|
|
3
|
+
"version": "7.5.0",
|
|
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
|
-
"
|
|
28
|
+
"otpauth": "^9.6.0",
|
|
29
29
|
"zod": "^4.3.6"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
package/services/totpService.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RateLimiter, type AdminUser, type HttpExtra, type IAdminForth, type RateLimitString } from "adminforth";
|
|
2
|
-
import
|
|
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(
|
|
27
|
-
return
|
|
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
|
-
|
|
36
|
-
|
|
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 =
|
|
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',
|
|
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' },
|
|
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
|
|
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
|
+
});
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import test from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
|
-
import { resolveVerifyAutoBodySchema } from '../dist/endpoints/validation.js';
|
|
3
|
+
import { resolveVerifyAutoBodySchema, deletePasskeyBodySchema } from '../dist/endpoints/validation.js';
|
|
4
4
|
|
|
5
5
|
test('resolveVerifyAuto accepts a cancelled confirmation, so the handler can release the waiting request', () => {
|
|
6
6
|
// TwoFAModal sends confirmationResult: undefined on Cancel, JSON drops it
|
|
7
7
|
const cancelBody = JSON.parse(JSON.stringify({ confirmationResult: undefined, sessionsIds: ['session'] }));
|
|
8
8
|
assert.equal(resolveVerifyAutoBodySchema.safeParse(cancelBody).success, true);
|
|
9
9
|
});
|
|
10
|
+
|
|
11
|
+
test('deletePasskey requires a 2FA confirmation result', () => {
|
|
12
|
+
assert.equal(deletePasskeyBodySchema.safeParse({ passkeyId: 'id' }).success, false);
|
|
13
|
+
assert.equal(deletePasskeyBodySchema.safeParse({ passkeyId: 'id', confirmationResult: { mode: 'totp', result: '123456' } }).success, true);
|
|
14
|
+
});
|