-
-
Notifications
You must be signed in to change notification settings - Fork 517
/
Copy pathmfa-verifications.ts
152 lines (136 loc) · 4.52 KB
/
mfa-verifications.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import { MfaFactor, userMfaVerificationResponseGuard } from '@logto/schemas';
import { getUserDisplayName } from '@logto/shared';
import { authenticator } from 'otplib';
import qrcode from 'qrcode';
import { object, string, z } from 'zod';
import RequestError from '#src/errors/RequestError/index.js';
import koaGuard from '#src/middleware/koa-guard.js';
import assertThat from '#src/utils/assert-that.js';
import { transpileUserMfaVerifications } from '#src/utils/user.js';
import { generateBackupCodes } from '../interaction/utils/backup-code-validation.js';
import { generateTotpSecret } from '../interaction/utils/totp-validation.js';
import type { ManagementApiRouter, RouterInitArgs } from '../types.js';
export default function adminUserMfaVerificationsRoutes<T extends ManagementApiRouter>(
...args: RouterInitArgs<T>
) {
const [
router,
{
queries,
libraries: {
users: { addUserMfaVerification, updateUserById },
},
},
] = args;
const {
users: { findUserById },
} = queries;
router.get(
'/users/:userId/mfa-verifications',
koaGuard({
params: object({ userId: string() }),
response: userMfaVerificationResponseGuard,
status: [200, 404],
}),
async (ctx, next) => {
const user = await findUserById(ctx.guard.params.userId);
ctx.body = transpileUserMfaVerifications(user.mfaVerifications);
return next();
}
);
router.post(
'/users/:userId/mfa-verifications',
koaGuard({
params: object({ userId: string() }),
body: z.object({
type: z.literal(MfaFactor.TOTP).or(z.literal(MfaFactor.BackupCode)),
}),
response: z.discriminatedUnion('type', [
z.object({
type: z.literal(MfaFactor.TOTP),
secret: z.string(),
secretQrCode: z.string(),
}),
z.object({
type: z.literal(MfaFactor.BackupCode),
codes: z.string().array(),
}),
]),
status: [200, 404, 422],
}),
async (ctx, next) => {
const { id, mfaVerifications, username, primaryEmail, primaryPhone, name } =
await findUserById(ctx.guard.params.userId);
const { type } = ctx.guard.body;
if (type === MfaFactor.TOTP) {
// A user can only bind one TOTP factor
assertThat(
mfaVerifications.every(({ type }) => type !== MfaFactor.TOTP),
new RequestError({
code: 'user.totp_already_in_use',
status: 422,
})
);
const secret = generateTotpSecret();
const service = ctx.URL.hostname;
const user = getUserDisplayName({ username, primaryEmail, primaryPhone, name });
const keyUri = authenticator.keyuri(user ?? 'Unnamed User', service, secret);
await addUserMfaVerification(id, { type: MfaFactor.TOTP, secret });
ctx.body = {
type: MfaFactor.TOTP,
secret,
secretQrCode: await qrcode.toDataURL(keyUri),
};
return next();
}
// A user can only bind one available backup code factor
assertThat(
mfaVerifications.every(
(verification) =>
verification.type !== MfaFactor.BackupCode ||
verification.codes.every(({ usedAt }) => usedAt)
),
new RequestError({
code: 'user.backup_code_already_in_use',
status: 422,
})
);
assertThat(
mfaVerifications.some(({ type }) => type !== MfaFactor.BackupCode),
new RequestError({
code: 'session.mfa.backup_code_can_not_be_alone',
status: 422,
})
);
const codes = generateBackupCodes();
await addUserMfaVerification(id, { type: MfaFactor.BackupCode, codes });
ctx.body = { codes, type: MfaFactor.BackupCode };
return next();
}
);
router.delete(
'/users/:userId/mfa-verifications/:verificationId',
koaGuard({
params: object({ userId: string(), verificationId: string() }),
status: [204, 404],
}),
async (ctx, next) => {
const {
params: { userId, verificationId },
} = ctx.guard;
const { mfaVerifications } = await findUserById(userId);
const verification = mfaVerifications.find(({ id }) => id === verificationId);
if (!verification) {
throw new RequestError({
code: 'entity.not_found',
status: 404,
});
}
await updateUserById(userId, {
mfaVerifications: mfaVerifications.filter(({ id }) => id !== verification.id),
});
ctx.status = 204;
return next();
}
);
}