maxibase 1.5.0 → 1.6.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/README.md +12 -0
- package/layers/base/app/components/AuthCheck.vue +77 -16
- package/layers/base/app/pages/user/auth.vue +96 -0
- package/layers/base/server/api/auth/index.get.ts +1 -0
- package/layers/base/server/api/auth/options.post.ts +12 -9
- package/layers/base/server/api/auth/recovery/generate.post.ts +13 -0
- package/layers/base/server/api/auth/recovery/verify.post.ts +37 -0
- package/layers/base/server/api/auth/totp/verify.post.ts +22 -10
- package/layers/base/server/api/auth/webauthn/authenticate.post.ts +5 -0
- package/layers/base/server/api/auth/webauthn/register.post.ts +6 -1
- package/layers/base/server/database/relations.ts +10 -0
- package/layers/base/server/database/schema.ts +12 -0
- package/layers/base/server/utils/auth.ts +13 -0
- package/layers/base/server/utils/recoveryCodes.ts +56 -0
- package/locales/en.json +3 -1
- package/locales/fr.json +3 -1
- package/locales/pages/user-auth/en.json +11 -1
- package/locales/pages/user-auth/fr.json +11 -1
- package/nuxt.config.ts +2 -0
- package/package.json +1 -1
- package/server/assets/emails/en/recoveryCodeUsed.html +3 -0
- package/server/assets/emails/fr/recoveryCodeUsed.html +8 -0
package/README.md
CHANGED
|
@@ -25,6 +25,18 @@ The tenant defaults to `organizations`: any work or school account, no personal
|
|
|
25
25
|
`/auth/microsoft` signs in with the Microsoft account already signed in, link to
|
|
26
26
|
`/auth/microsoft?prompt=select_account` to let the user pick another one.
|
|
27
27
|
|
|
28
|
+
### Resetting a user's second factor
|
|
29
|
+
|
|
30
|
+
A user who lost their passkeys, authenticator app and recovery codes has no way back in. Remove
|
|
31
|
+
their factors in the database, they sign in with their password or an email code and, under
|
|
32
|
+
`NUXT_FORCE_MFA`, are asked to set up a new one:
|
|
33
|
+
|
|
34
|
+
```sql
|
|
35
|
+
UPDATE auth.users SET totp = NULL WHERE email = 'user@example.com';
|
|
36
|
+
DELETE FROM auth.credentials WHERE user_id = (SELECT id FROM auth.users WHERE email = 'user@example.com');
|
|
37
|
+
DELETE FROM auth.recovery_codes WHERE user_id = (SELECT id FROM auth.users WHERE email = 'user@example.com');
|
|
38
|
+
```
|
|
39
|
+
|
|
28
40
|
## Deployment
|
|
29
41
|
|
|
30
42
|
### On your server
|
|
@@ -11,6 +11,8 @@ const email = ref('')
|
|
|
11
11
|
const password = ref('')
|
|
12
12
|
const otpRequested = ref(false)
|
|
13
13
|
const totp = ref('')
|
|
14
|
+
const recoveryCode = ref('')
|
|
15
|
+
const useRecoveryCode = ref(false)
|
|
14
16
|
const optionsFetched = ref(false)
|
|
15
17
|
const showPassword = ref(false)
|
|
16
18
|
const options = ref({
|
|
@@ -67,22 +69,20 @@ async function signInWithOtp() {
|
|
|
67
69
|
}
|
|
68
70
|
}
|
|
69
71
|
|
|
72
|
+
function firstFactor(): { otp: string } | { password: string } {
|
|
73
|
+
if (password.value.length === 6 || password.value === route.query.token) {
|
|
74
|
+
return { otp: password.value }
|
|
75
|
+
}
|
|
76
|
+
return { password: password.value }
|
|
77
|
+
}
|
|
78
|
+
|
|
70
79
|
async function signInWithTOTP() {
|
|
71
80
|
if (!email.value || !totp.value || !password.value) return
|
|
72
81
|
isLoading.value = true
|
|
73
82
|
try {
|
|
74
|
-
const body: {
|
|
75
|
-
email: string
|
|
76
|
-
token: string
|
|
77
|
-
otp?: string
|
|
78
|
-
password?: string
|
|
79
|
-
} = { email: email.value, token: totp.value }
|
|
80
|
-
if (password.value.length === 6 || password.value === route.query.token) {
|
|
81
|
-
body.otp = password.value
|
|
82
|
-
} else body.password = password.value
|
|
83
83
|
await $fetch('/api/auth/totp/verify', {
|
|
84
84
|
method: 'POST',
|
|
85
|
-
body,
|
|
85
|
+
body: { email: email.value, token: totp.value, ...firstFactor() },
|
|
86
86
|
})
|
|
87
87
|
await refreshSession()
|
|
88
88
|
totp.value = ''
|
|
@@ -93,6 +93,28 @@ async function signInWithTOTP() {
|
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
+
async function signInWithRecoveryCode() {
|
|
97
|
+
if (!email.value || !recoveryCode.value || !password.value) return
|
|
98
|
+
isLoading.value = true
|
|
99
|
+
try {
|
|
100
|
+
await $fetch('/api/auth/recovery/verify', {
|
|
101
|
+
method: 'POST',
|
|
102
|
+
body: {
|
|
103
|
+
email: email.value,
|
|
104
|
+
code: recoveryCode.value,
|
|
105
|
+
locale: useI18n().$getLocale(),
|
|
106
|
+
...firstFactor(),
|
|
107
|
+
},
|
|
108
|
+
})
|
|
109
|
+
await refreshSession()
|
|
110
|
+
recoveryCode.value = ''
|
|
111
|
+
} catch (e: any) {
|
|
112
|
+
handleError(e)
|
|
113
|
+
} finally {
|
|
114
|
+
isLoading.value = false
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
96
118
|
async function signInWithPassword() {
|
|
97
119
|
if (!email.value || !password.value) return
|
|
98
120
|
isLoading.value = true
|
|
@@ -129,7 +151,8 @@ function signIn() {
|
|
|
129
151
|
if (!email.value || isLoading.value) return
|
|
130
152
|
// paste and change bypass the browser's check, which only guards the submit
|
|
131
153
|
if (!signInForm.value?.reportValidity()) return
|
|
132
|
-
if (
|
|
154
|
+
if (useRecoveryCode.value) signInWithRecoveryCode()
|
|
155
|
+
else if (totp.value) signInWithTOTP()
|
|
133
156
|
else if (password.value.length === 6) signInWithOtp()
|
|
134
157
|
else signInWithPassword()
|
|
135
158
|
}, 100)
|
|
@@ -180,7 +203,7 @@ async function getSignInOptions(email: string) {
|
|
|
180
203
|
}
|
|
181
204
|
}
|
|
182
205
|
|
|
183
|
-
const pasteFields = { password, totp }
|
|
206
|
+
const pasteFields = { password, totp, recoveryCode }
|
|
184
207
|
|
|
185
208
|
async function pasteTo(field: keyof typeof pasteFields) {
|
|
186
209
|
try {
|
|
@@ -260,7 +283,32 @@ onBeforeUnmount(() => WebAuthnAbortService.cancelCeremony())
|
|
|
260
283
|
</button>
|
|
261
284
|
</div>
|
|
262
285
|
</div>
|
|
263
|
-
<div v-if="
|
|
286
|
+
<div v-if="useRecoveryCode">
|
|
287
|
+
<label for="recovery-code">{{ $t('authCheck.recoveryCode') }}</label>
|
|
288
|
+
<div class="group flex-row">
|
|
289
|
+
<input
|
|
290
|
+
id="recovery-code"
|
|
291
|
+
v-model.trim="recoveryCode"
|
|
292
|
+
type="text"
|
|
293
|
+
:disabled="isLoading || !password"
|
|
294
|
+
autocomplete="off"
|
|
295
|
+
autocapitalize="none"
|
|
296
|
+
pattern="[0-9a-fA-F]{5}-?[0-9a-fA-F]{5}"
|
|
297
|
+
required
|
|
298
|
+
@paste="signIn"
|
|
299
|
+
/>
|
|
300
|
+
<button
|
|
301
|
+
type="button"
|
|
302
|
+
class="flex-center fg"
|
|
303
|
+
:title="$t('paste') as string"
|
|
304
|
+
:disabled="isLoading || !password"
|
|
305
|
+
@click="pasteTo('recoveryCode')"
|
|
306
|
+
>
|
|
307
|
+
<Icon name="lucide:clipboard-paste" />
|
|
308
|
+
</button>
|
|
309
|
+
</div>
|
|
310
|
+
</div>
|
|
311
|
+
<div v-else-if="options.hasTOTP">
|
|
264
312
|
<label for="totp">{{ $t('authCheck.authenticatorCode') }}</label>
|
|
265
313
|
<div class="group flex-row">
|
|
266
314
|
<input
|
|
@@ -288,7 +336,11 @@ onBeforeUnmount(() => WebAuthnAbortService.cancelCeremony())
|
|
|
288
336
|
</div>
|
|
289
337
|
<button
|
|
290
338
|
type="submit"
|
|
291
|
-
:disabled="
|
|
339
|
+
:disabled="
|
|
340
|
+
isLoading ||
|
|
341
|
+
(!password && !otpRequested) ||
|
|
342
|
+
(useRecoveryCode ? !recoveryCode : options.hasTOTP && !totp)
|
|
343
|
+
"
|
|
292
344
|
:class="['w mt1', isLoading ? 'spin' : '']"
|
|
293
345
|
>
|
|
294
346
|
{{ $t('authCheck.signin') }}
|
|
@@ -297,7 +349,7 @@ onBeforeUnmount(() => WebAuthnAbortService.cancelCeremony())
|
|
|
297
349
|
v-if="options.hasPasskey"
|
|
298
350
|
type="button"
|
|
299
351
|
:disabled="isLoading"
|
|
300
|
-
class="flex-center
|
|
352
|
+
class="flex-center g2 w mt1 bg bg-border"
|
|
301
353
|
@click="signInWithPasskey(email)"
|
|
302
354
|
>
|
|
303
355
|
<Icon name="lucide:key-round" />
|
|
@@ -312,6 +364,16 @@ onBeforeUnmount(() => WebAuthnAbortService.cancelCeremony())
|
|
|
312
364
|
>
|
|
313
365
|
{{ $t('authCheck.getCode') }}
|
|
314
366
|
</button>
|
|
367
|
+
<button
|
|
368
|
+
v-if="options.hasTOTP || options.hasPasskey"
|
|
369
|
+
type="button"
|
|
370
|
+
class="w"
|
|
371
|
+
style="background: none; border: none; color: inherit"
|
|
372
|
+
:disabled="isLoading"
|
|
373
|
+
@click="useRecoveryCode = !useRecoveryCode"
|
|
374
|
+
>
|
|
375
|
+
{{ useRecoveryCode ? $t('cancel') : $t('authCheck.useRecoveryCode') }}
|
|
376
|
+
</button>
|
|
315
377
|
<p
|
|
316
378
|
v-if="otpRequested"
|
|
317
379
|
class="text-center"
|
|
@@ -349,7 +411,6 @@ onBeforeUnmount(() => WebAuthnAbortService.cancelCeremony())
|
|
|
349
411
|
<span class="text-center muted-text my1">{{ $t('or') }}</span>
|
|
350
412
|
<button
|
|
351
413
|
type="button"
|
|
352
|
-
:disabled="isLoading"
|
|
353
414
|
class="provider flex-center g2 w mb1 fg b"
|
|
354
415
|
style="font-weight: normal"
|
|
355
416
|
@click="signInWithPasskey()"
|
|
@@ -12,6 +12,7 @@ type AuthInfo = {
|
|
|
12
12
|
credentials: { id: string; name: string }[]
|
|
13
13
|
hasPassword: boolean
|
|
14
14
|
hasTOTP: boolean
|
|
15
|
+
recoveryCodes: number
|
|
15
16
|
forceMfa: boolean
|
|
16
17
|
}
|
|
17
18
|
|
|
@@ -19,8 +20,10 @@ const auth = ref<AuthInfo>({
|
|
|
19
20
|
credentials: [],
|
|
20
21
|
hasPassword: false,
|
|
21
22
|
hasTOTP: false,
|
|
23
|
+
recoveryCodes: 0,
|
|
22
24
|
forceMfa: false,
|
|
23
25
|
})
|
|
26
|
+
const recoveryCodes = ref<string[]>([])
|
|
24
27
|
const TOTPSecret = ref('')
|
|
25
28
|
const TOTPCode = ref('')
|
|
26
29
|
const password1 = ref('')
|
|
@@ -54,6 +57,7 @@ const canRemovePasskey = computed(
|
|
|
54
57
|
() => !auth.value?.forceMfa || auth.value.hasTOTP || auth.value.credentials.length > 1,
|
|
55
58
|
)
|
|
56
59
|
const canDisableTOTP = computed(() => !auth.value?.forceMfa || auth.value.credentials.length > 0)
|
|
60
|
+
const hasSecondFactor = computed(() => auth.value.hasTOTP || auth.value.credentials.length > 0)
|
|
57
61
|
|
|
58
62
|
async function getAuth() {
|
|
59
63
|
try {
|
|
@@ -70,9 +74,11 @@ const { register } = useWebAuthn({
|
|
|
70
74
|
async function registerPasskey() {
|
|
71
75
|
try {
|
|
72
76
|
if (!(await checkAuth())) return
|
|
77
|
+
const isFirstFactor = !hasSecondFactor.value
|
|
73
78
|
await register({ userName: user.value!.email! })
|
|
74
79
|
await getAuth()
|
|
75
80
|
appStore.notify('saved', 'success')
|
|
81
|
+
if (isFirstFactor) await offerRecoveryCodes()
|
|
76
82
|
if (isMfaSetup.value) {
|
|
77
83
|
await fetchUserSession()
|
|
78
84
|
if (!user.value?.requiresMfaSetup) await navigateTo('/', { replace: true })
|
|
@@ -189,6 +195,7 @@ async function confirmTOTP() {
|
|
|
189
195
|
if (TOTPCode.value.length !== 6) return
|
|
190
196
|
try {
|
|
191
197
|
if (!(await checkAuth())) return
|
|
198
|
+
const isFirstFactor = !hasSecondFactor.value
|
|
192
199
|
await $fetch('/api/auth/totp/confirm', {
|
|
193
200
|
method: 'POST',
|
|
194
201
|
body: { secret: TOTPSecret.value, token: TOTPCode.value },
|
|
@@ -197,6 +204,7 @@ async function confirmTOTP() {
|
|
|
197
204
|
TOTPCode.value = ''
|
|
198
205
|
auth.value.hasTOTP = true
|
|
199
206
|
showTOTP.value = false
|
|
207
|
+
if (isFirstFactor) await offerRecoveryCodes()
|
|
200
208
|
if (isMfaSetup.value) {
|
|
201
209
|
await fetchUserSession()
|
|
202
210
|
if (!user.value?.requiresMfaSetup) await navigateTo('/', { replace: true })
|
|
@@ -218,6 +226,38 @@ async function disableTOTP() {
|
|
|
218
226
|
}
|
|
219
227
|
}
|
|
220
228
|
|
|
229
|
+
async function generateRecoveryCodes() {
|
|
230
|
+
try {
|
|
231
|
+
if (auth.value.recoveryCodes && !(await appStore.confirm($t('replaceRecoveryCodes') as string)))
|
|
232
|
+
return
|
|
233
|
+
if (!(await checkAuth())) return
|
|
234
|
+
const response = await $fetch<{ codes: string[] }>('/api/auth/recovery/generate', {
|
|
235
|
+
method: 'POST',
|
|
236
|
+
})
|
|
237
|
+
recoveryCodes.value = response.codes
|
|
238
|
+
auth.value.recoveryCodes = response.codes.length
|
|
239
|
+
} catch (e: any) {
|
|
240
|
+
appStore.notify(e?.data?.message || e?.message, 'error')
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
let recoveryCodesClosed: (() => void) | undefined
|
|
245
|
+
|
|
246
|
+
function closeRecoveryCodes() {
|
|
247
|
+
recoveryCodes.value = []
|
|
248
|
+
recoveryCodesClosed?.()
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Resolves once the codes are closed, so the MFA setup redirect does not hide them
|
|
252
|
+
async function offerRecoveryCodes() {
|
|
253
|
+
if (auth.value.recoveryCodes) return
|
|
254
|
+
if (!(await appStore.confirm($t('offerRecoveryCodes') as string))) return
|
|
255
|
+
await generateRecoveryCodes()
|
|
256
|
+
if (!recoveryCodes.value.length) return
|
|
257
|
+
await new Promise<void>((resolve) => (recoveryCodesClosed = resolve))
|
|
258
|
+
recoveryCodesClosed = undefined
|
|
259
|
+
}
|
|
260
|
+
|
|
221
261
|
async function deleteRefreshTokens() {
|
|
222
262
|
if (!(await checkAuth())) return
|
|
223
263
|
appStore.setLoading(true)
|
|
@@ -453,6 +493,25 @@ onMounted(getAuth)
|
|
|
453
493
|
:title="canDisableTOTP ? '' : $t('lastFactor')"
|
|
454
494
|
@click.prevent="toggleTOTP"
|
|
455
495
|
/>
|
|
496
|
+
|
|
497
|
+
<h3 class="mt2 mb0">{{ $t('recoveryCodes') }}</h3>
|
|
498
|
+
<p class="muted-text mt0">
|
|
499
|
+
{{ $t('recoveryCodesDescription') }}
|
|
500
|
+
<span
|
|
501
|
+
v-if="hasSecondFactor"
|
|
502
|
+
:class="auth.recoveryCodes < 5 ? 'danger-text' : ''"
|
|
503
|
+
>
|
|
504
|
+
{{ $t('recoveryCodesLeft', { count: auth.recoveryCodes }) }}
|
|
505
|
+
</span>
|
|
506
|
+
</p>
|
|
507
|
+
<button
|
|
508
|
+
class="flex"
|
|
509
|
+
:disabled="!hasSecondFactor"
|
|
510
|
+
:title="hasSecondFactor ? '' : $t('recoveryCodesRequireFactor')"
|
|
511
|
+
@click="generateRecoveryCodes"
|
|
512
|
+
>
|
|
513
|
+
{{ $t('generateRecoveryCodes') }}
|
|
514
|
+
</button>
|
|
456
515
|
</section>
|
|
457
516
|
<div class="flex-row my3">
|
|
458
517
|
<button
|
|
@@ -464,6 +523,43 @@ onMounted(getAuth)
|
|
|
464
523
|
</div>
|
|
465
524
|
</template>
|
|
466
525
|
|
|
526
|
+
<div
|
|
527
|
+
v-if="recoveryCodes.length"
|
|
528
|
+
class="modal"
|
|
529
|
+
>
|
|
530
|
+
<div
|
|
531
|
+
class="p3"
|
|
532
|
+
style="max-width: min(400px, 90vw)"
|
|
533
|
+
>
|
|
534
|
+
<p class="mt0">{{ $t('recoveryCodesSave') }}</p>
|
|
535
|
+
<ul
|
|
536
|
+
class="text-center p0"
|
|
537
|
+
style="list-style: none; font-family: monospace; columns: 2"
|
|
538
|
+
>
|
|
539
|
+
<li
|
|
540
|
+
v-for="code in recoveryCodes"
|
|
541
|
+
:key="code"
|
|
542
|
+
>
|
|
543
|
+
{{ code }}
|
|
544
|
+
</li>
|
|
545
|
+
</ul>
|
|
546
|
+
<div class="flex-row g1">
|
|
547
|
+
<button
|
|
548
|
+
class="fg fg-border"
|
|
549
|
+
@click="copyToClipboard(recoveryCodes.join('\n'))"
|
|
550
|
+
>
|
|
551
|
+
{{ $t('copy') }}
|
|
552
|
+
</button>
|
|
553
|
+
<button
|
|
554
|
+
class="ml"
|
|
555
|
+
@click="closeRecoveryCodes"
|
|
556
|
+
>
|
|
557
|
+
{{ $t('recoveryCodesSaved') }}
|
|
558
|
+
</button>
|
|
559
|
+
</div>
|
|
560
|
+
</div>
|
|
561
|
+
</div>
|
|
562
|
+
|
|
467
563
|
<div
|
|
468
564
|
v-if="showTOTP && TOTPSecret"
|
|
469
565
|
class="modal"
|
|
@@ -5,6 +5,7 @@ export default defineEventHandler(async (event) => {
|
|
|
5
5
|
credentials: user.credentials!.map(({ id, name }) => ({ id, name })),
|
|
6
6
|
hasPassword: !!user.password,
|
|
7
7
|
hasTOTP: !!user.totp,
|
|
8
|
+
recoveryCodes: await countRecoveryCodes(user.id),
|
|
8
9
|
forceMfa: useRuntimeConfig().forceMfa,
|
|
9
10
|
}
|
|
10
11
|
})
|
|
@@ -7,15 +7,11 @@ const bodySchema = z.object({
|
|
|
7
7
|
export default defineEventHandler(async (event) => {
|
|
8
8
|
const { email } = await readValidatedBody(event, bodySchema.parse)
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
hasTOTP: !!user.totp,
|
|
16
|
-
hasPasskey: user.credentials!.length > 0,
|
|
17
|
-
}
|
|
18
|
-
} catch {
|
|
10
|
+
const user = await getAuth(event, email, true).catch((error: any) => {
|
|
11
|
+
if (error?.statusCode === 404) return null
|
|
12
|
+
throw error
|
|
13
|
+
})
|
|
14
|
+
if (!user) {
|
|
19
15
|
return {
|
|
20
16
|
hasOTP: true,
|
|
21
17
|
hasPassword: false,
|
|
@@ -23,4 +19,11 @@ export default defineEventHandler(async (event) => {
|
|
|
23
19
|
hasPasskey: false,
|
|
24
20
|
}
|
|
25
21
|
}
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
hasOTP: true,
|
|
25
|
+
hasPassword: !!user.password,
|
|
26
|
+
hasTOTP: !!user.totp,
|
|
27
|
+
hasPasskey: user.credentials!.length > 0,
|
|
28
|
+
}
|
|
26
29
|
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export default defineEventHandler(async (event) => {
|
|
2
|
+
await requireRecentAuth(event)
|
|
3
|
+
const user = await getAuth(event, undefined, true)
|
|
4
|
+
|
|
5
|
+
if (!user.totp && !user.credentials!.length) {
|
|
6
|
+
throw createError({ status: 400, message: 'Set up a second factor first.' })
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const codes = await generateRecoveryCodes(user.id)
|
|
10
|
+
await log('Recovery codes generated', undefined, undefined, 'security', event)
|
|
11
|
+
|
|
12
|
+
return { codes }
|
|
13
|
+
})
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { verifyFirstFactor } from '../totp/verify.post'
|
|
3
|
+
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const {
|
|
6
|
+
email,
|
|
7
|
+
password,
|
|
8
|
+
otp,
|
|
9
|
+
code,
|
|
10
|
+
locale = 'en',
|
|
11
|
+
} = await readValidatedBody(
|
|
12
|
+
event,
|
|
13
|
+
z.object({
|
|
14
|
+
email: emailSchema,
|
|
15
|
+
password: passwordSchema().optional(),
|
|
16
|
+
otp: otpSchema.optional(),
|
|
17
|
+
code: z.string().min(10).max(16),
|
|
18
|
+
locale: z.string().optional(),
|
|
19
|
+
}).parse,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
const user = await verifyFirstFactor(event, email, { password, otp })
|
|
23
|
+
if (!user) throw createError({ status: 400, message: 'Invalid recovery code.' })
|
|
24
|
+
|
|
25
|
+
await enforceRateLimit(event, 'recovery', { limit: 5, window: 900 }, user.id)
|
|
26
|
+
|
|
27
|
+
const remaining = await consumeRecoveryCode(user.id, code)
|
|
28
|
+
if (remaining === null) throw createError({ status: 400, message: 'Invalid recovery code.' })
|
|
29
|
+
|
|
30
|
+
if (otp) await useStorage('auth').removeItem(email)
|
|
31
|
+
const session = await setSession(event, user)
|
|
32
|
+
|
|
33
|
+
await log('Recovery code used', { remaining }, undefined, 'security', event)
|
|
34
|
+
await sendEmailTemplate('recoveryCodeUsed', locale, { remaining }, user.email!).catch(() => {})
|
|
35
|
+
|
|
36
|
+
return session
|
|
37
|
+
})
|
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { verify } from 'otplib'
|
|
3
|
+
import type { H3Event } from 'h3'
|
|
3
4
|
import { verifyOTP } from '../otp/verify.post'
|
|
4
5
|
|
|
5
|
-
export
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
password: passwordSchema().optional(),
|
|
11
|
-
otp: otpSchema.optional(),
|
|
12
|
-
token: z.string().length(6),
|
|
13
|
-
}).parse,
|
|
14
|
-
)
|
|
6
|
+
export async function verifyFirstFactor(
|
|
7
|
+
event: H3Event,
|
|
8
|
+
email: string,
|
|
9
|
+
{ password, otp }: { password?: string; otp?: string },
|
|
10
|
+
) {
|
|
15
11
|
if (!otp && !password) {
|
|
16
12
|
throw createError({
|
|
17
13
|
status: 400,
|
|
@@ -32,6 +28,22 @@ export default defineEventHandler(async (event) => {
|
|
|
32
28
|
throw createError({ status: 400, message: 'Invalid password.' })
|
|
33
29
|
}
|
|
34
30
|
|
|
31
|
+
return user
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export default defineEventHandler(async (event) => {
|
|
35
|
+
const { email, password, otp, token } = await readValidatedBody(
|
|
36
|
+
event,
|
|
37
|
+
z.object({
|
|
38
|
+
email: emailSchema,
|
|
39
|
+
password: passwordSchema().optional(),
|
|
40
|
+
otp: otpSchema.optional(),
|
|
41
|
+
token: z.string().length(6),
|
|
42
|
+
}).parse,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
const user = await verifyFirstFactor(event, email, { password, otp })
|
|
46
|
+
|
|
35
47
|
if (!user?.totp) {
|
|
36
48
|
throw createError({ status: 400, message: 'TOTP is not enabled.' })
|
|
37
49
|
}
|
|
@@ -14,6 +14,9 @@ export default defineWebAuthnAuthenticateEventHandler({
|
|
|
14
14
|
|
|
15
15
|
return challenge as string
|
|
16
16
|
},
|
|
17
|
+
getOptions() {
|
|
18
|
+
return { userVerification: passkeyUserVerification() }
|
|
19
|
+
},
|
|
17
20
|
async allowCredentials(event, userName) {
|
|
18
21
|
const user = await getAuth(event, userName, true)
|
|
19
22
|
return (user as any).credentials || []
|
|
@@ -29,6 +32,8 @@ export default defineWebAuthnAuthenticateEventHandler({
|
|
|
29
32
|
return credential as any
|
|
30
33
|
},
|
|
31
34
|
async onSuccess(event, { credential, authenticationInfo }) {
|
|
35
|
+
requireUserVerification(authenticationInfo.userVerified)
|
|
36
|
+
|
|
32
37
|
// the next assertion must report a higher counter, which exposes a cloned authenticator
|
|
33
38
|
await db
|
|
34
39
|
.update(credentials)
|
|
@@ -14,6 +14,9 @@ const registerHandler = defineWebAuthnRegisterEventHandler({
|
|
|
14
14
|
|
|
15
15
|
return challenge as string
|
|
16
16
|
},
|
|
17
|
+
getOptions() {
|
|
18
|
+
return { authenticatorSelection: { userVerification: passkeyUserVerification() } }
|
|
19
|
+
},
|
|
17
20
|
async validateUser(userBody, event) {
|
|
18
21
|
const session = await requireUserSession(event)
|
|
19
22
|
const parsed = z
|
|
@@ -28,7 +31,9 @@ const registerHandler = defineWebAuthnRegisterEventHandler({
|
|
|
28
31
|
|
|
29
32
|
return parsed.data
|
|
30
33
|
},
|
|
31
|
-
async onSuccess(event, { credential }) {
|
|
34
|
+
async onSuccess(event, { credential, registrationInfo }) {
|
|
35
|
+
requireUserVerification(registrationInfo.userVerified)
|
|
36
|
+
|
|
32
37
|
const session = await requireUserSession(event)
|
|
33
38
|
await db.insert(credentials).values({
|
|
34
39
|
name: new Date().toISOString().substring(0, 10),
|
|
@@ -13,6 +13,10 @@ export const authRelations = defineRelationsPart(schema, (r) => ({
|
|
|
13
13
|
from: r.auth.id,
|
|
14
14
|
to: r.credentials.userId,
|
|
15
15
|
}),
|
|
16
|
+
recoveryCodes: r.many.recoveryCodes({
|
|
17
|
+
from: r.auth.id,
|
|
18
|
+
to: r.recoveryCodes.userId,
|
|
19
|
+
}),
|
|
16
20
|
},
|
|
17
21
|
refreshTokens: {
|
|
18
22
|
auth: r.one.auth({
|
|
@@ -26,6 +30,12 @@ export const authRelations = defineRelationsPart(schema, (r) => ({
|
|
|
26
30
|
to: r.auth.id,
|
|
27
31
|
}),
|
|
28
32
|
},
|
|
33
|
+
recoveryCodes: {
|
|
34
|
+
auth: r.one.auth({
|
|
35
|
+
from: r.recoveryCodes.userId,
|
|
36
|
+
to: r.auth.id,
|
|
37
|
+
}),
|
|
38
|
+
},
|
|
29
39
|
logs: {
|
|
30
40
|
auth: r.one.auth({
|
|
31
41
|
from: r.logs.userId,
|
|
@@ -49,6 +49,18 @@ export const credentials = authSchema.table(
|
|
|
49
49
|
(table) => [primaryKey({ columns: [table.userId, table.id] })],
|
|
50
50
|
)
|
|
51
51
|
|
|
52
|
+
export const recoveryCodes = authSchema.table(
|
|
53
|
+
'recovery_codes',
|
|
54
|
+
{
|
|
55
|
+
userId: uuid()
|
|
56
|
+
.notNull()
|
|
57
|
+
.references(() => auth.id, { onDelete: 'cascade' }),
|
|
58
|
+
code: text().notNull(),
|
|
59
|
+
createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
|
|
60
|
+
},
|
|
61
|
+
(table) => [primaryKey({ columns: [table.userId, table.code] })],
|
|
62
|
+
)
|
|
63
|
+
|
|
52
64
|
export const logs = authSchema.table(
|
|
53
65
|
'logs',
|
|
54
66
|
{
|
|
@@ -32,6 +32,19 @@ export function requireSecondFactor(user: Pick<AuthUser, 'totp'> & { credentials
|
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
export function passkeyUserVerification(): 'required' | 'preferred' {
|
|
36
|
+
return useRuntimeConfig().forceMfa ? 'required' : 'preferred'
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function requireUserVerification(userVerified: boolean) {
|
|
40
|
+
if (useRuntimeConfig().forceMfa && !userVerified) {
|
|
41
|
+
throw createError({
|
|
42
|
+
status: 400,
|
|
43
|
+
message: 'Set a PIN on your security key to use it.',
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
35
48
|
export async function createAuth(user: Pick<AuthUser, 'email'>) {
|
|
36
49
|
const insertedUsers = await db
|
|
37
50
|
.insert(auth)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { and, eq } from 'drizzle-orm'
|
|
2
|
+
import { randomBytes } from 'crypto'
|
|
3
|
+
import { recoveryCodes } from '#server/database/schema'
|
|
4
|
+
|
|
5
|
+
const RECOVERY_CODE_COUNT = 10
|
|
6
|
+
|
|
7
|
+
function generateRecoveryCode() {
|
|
8
|
+
const code = randomBytes(5).toString('hex')
|
|
9
|
+
return `${code.slice(0, 5)}-${code.slice(5)}`
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function normalizeRecoveryCode(code: string) {
|
|
13
|
+
return code.toLowerCase().replace(/[^0-9a-f]/g, '')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function generateRecoveryCodes(userId: string) {
|
|
17
|
+
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, generateRecoveryCode)
|
|
18
|
+
const hashes = await Promise.all(codes.map((code) => hashPassword(normalizeRecoveryCode(code))))
|
|
19
|
+
|
|
20
|
+
await db.transaction(async (tx) => {
|
|
21
|
+
await tx.delete(recoveryCodes).where(eq(recoveryCodes.userId, userId))
|
|
22
|
+
await tx.insert(recoveryCodes).values(hashes.map((code) => ({ userId, code })))
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
return codes
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function consumeRecoveryCode(userId: string, code: string) {
|
|
29
|
+
const normalized = normalizeRecoveryCode(code)
|
|
30
|
+
const rows = await db
|
|
31
|
+
.select({ code: recoveryCodes.code })
|
|
32
|
+
.from(recoveryCodes)
|
|
33
|
+
.where(eq(recoveryCodes.userId, userId))
|
|
34
|
+
|
|
35
|
+
let match: string | undefined
|
|
36
|
+
for (const row of rows) {
|
|
37
|
+
if (await verifyPassword(row.code, normalized)) {
|
|
38
|
+
match = row.code
|
|
39
|
+
break
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (!match) return null
|
|
43
|
+
|
|
44
|
+
const deleted = await db
|
|
45
|
+
.delete(recoveryCodes)
|
|
46
|
+
.where(and(eq(recoveryCodes.userId, userId), eq(recoveryCodes.code, match)))
|
|
47
|
+
.returning()
|
|
48
|
+
// a concurrent request used it first
|
|
49
|
+
if (!deleted.length) return null
|
|
50
|
+
|
|
51
|
+
return rows.length - 1
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function countRecoveryCodes(userId: string) {
|
|
55
|
+
return db.$count(recoveryCodes, eq(recoveryCodes.userId, userId))
|
|
56
|
+
}
|
package/locales/en.json
CHANGED
package/locales/fr.json
CHANGED
|
@@ -32,6 +32,8 @@
|
|
|
32
32
|
"otpSent": "Code envoyé à {email}",
|
|
33
33
|
"passkey": "Utiliser une passkey",
|
|
34
34
|
"password": "Mot de passe",
|
|
35
|
-
"
|
|
35
|
+
"recoveryCode": "Code de récupération",
|
|
36
|
+
"signin": "Se connecter",
|
|
37
|
+
"useRecoveryCode": "Utiliser un code de récupération"
|
|
36
38
|
}
|
|
37
39
|
}
|
|
@@ -17,5 +17,15 @@
|
|
|
17
17
|
"registerPasskey": "Add a passkey",
|
|
18
18
|
"settings": "Settings",
|
|
19
19
|
"setupTotp": "Use an authenticator app",
|
|
20
|
-
"totpSecret": "Scan this QR code with your authenticator app or copy the code manually."
|
|
20
|
+
"totpSecret": "Scan this QR code with your authenticator app or copy the code manually.",
|
|
21
|
+
"copy": "Copy",
|
|
22
|
+
"generateRecoveryCodes": "Generate recovery codes",
|
|
23
|
+
"recoveryCodes": "Recovery codes",
|
|
24
|
+
"recoveryCodesDescription": "Single-use codes to sign in if you lose your passkey or authenticator app.",
|
|
25
|
+
"recoveryCodesLeft": "Codes left: {count}.",
|
|
26
|
+
"recoveryCodesRequireFactor": "Add a passkey or an authenticator app first.",
|
|
27
|
+
"recoveryCodesSave": "Save these codes somewhere safe, they will not be shown again. Each code works once.",
|
|
28
|
+
"recoveryCodesSaved": "I saved them",
|
|
29
|
+
"replaceRecoveryCodes": "Your current recovery codes will stop working. Generate new ones?",
|
|
30
|
+
"offerRecoveryCodes": "Generate recovery codes now? They let you sign in if you lose this device."
|
|
21
31
|
}
|
|
@@ -17,5 +17,15 @@
|
|
|
17
17
|
"registerPasskey": "Ajouter une passkey",
|
|
18
18
|
"settings": "Paramètres",
|
|
19
19
|
"setupTotp": "Utiliser une application d'authentification",
|
|
20
|
-
"totpSecret": "Scannez ce code QR avec votre application d'authentification ou copiez le code manuellement."
|
|
20
|
+
"totpSecret": "Scannez ce code QR avec votre application d'authentification ou copiez le code manuellement.",
|
|
21
|
+
"copy": "Copier",
|
|
22
|
+
"generateRecoveryCodes": "Générer des codes de récupération",
|
|
23
|
+
"recoveryCodes": "Codes de récupération",
|
|
24
|
+
"recoveryCodesDescription": "Codes à usage unique pour vous connecter si vous perdez votre passkey ou votre application d'authentification.",
|
|
25
|
+
"recoveryCodesLeft": "Codes restants : {count}.",
|
|
26
|
+
"recoveryCodesRequireFactor": "Ajoutez d'abord une passkey ou une application d'authentification.",
|
|
27
|
+
"recoveryCodesSave": "Conservez ces codes en lieu sûr, ils ne seront plus affichés. Chaque code ne fonctionne qu'une fois.",
|
|
28
|
+
"recoveryCodesSaved": "Je les ai sauvegardés",
|
|
29
|
+
"replaceRecoveryCodes": "Vos codes de récupération actuels ne fonctionneront plus. En générer de nouveaux ?",
|
|
30
|
+
"offerRecoveryCodes": "Générer des codes de récupération maintenant ? Ils vous permettent de vous connecter si vous perdez cet appareil."
|
|
21
31
|
}
|
package/nuxt.config.ts
CHANGED
|
@@ -34,6 +34,8 @@ export default defineNuxtConfig({
|
|
|
34
34
|
'/api/auth/email/verify': { limit: 10, window: 60 },
|
|
35
35
|
'/api/auth/otp/verify': { limit: 10, window: 60 },
|
|
36
36
|
'/api/auth/totp/verify': { limit: 10, window: 60 },
|
|
37
|
+
'/api/auth/recovery/verify': { limit: 10, window: 60 },
|
|
38
|
+
'/api/auth/recovery/generate': { limit: 5, window: 900 },
|
|
37
39
|
'/api/auth/webauthn/authenticate': { limit: 10, window: 60 },
|
|
38
40
|
'/api/auth/webauthn/register': { limit: 10, window: 60 },
|
|
39
41
|
'/api/auth/anonymous': { limit: 5, window: 3600 },
|
package/package.json
CHANGED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
<title>Code de récupération utilisé</title>
|
|
2
|
+
<p>
|
|
3
|
+
Un code de récupération a été utilisé pour vous connecter à votre compte. Codes restants :
|
|
4
|
+
{{remaining}}.
|
|
5
|
+
</p>
|
|
6
|
+
<p>
|
|
7
|
+
Si ce n'était pas vous, changez votre mot de passe et générez de nouveaux codes de récupération.
|
|
8
|
+
</p>
|