-
Notifications
You must be signed in to change notification settings - Fork 1k
/
DbAuthHandler.ts
1541 lines (1361 loc) · 45.2 KB
/
DbAuthHandler.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { PrismaClient } from '@prisma/client'
import type {
GenerateAuthenticationOptionsOpts,
GenerateRegistrationOptionsOpts,
VerifiedAuthenticationResponse,
VerifiedRegistrationResponse,
VerifyAuthenticationResponseOpts,
VerifyRegistrationResponseOpts,
} from '@simplewebauthn/server'
import type {
AuthenticationResponseJSON,
RegistrationResponseJSON,
} from '@simplewebauthn/typescript-types'
import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda'
import base64url from 'base64url'
import md5 from 'md5'
import { v4 as uuidv4 } from 'uuid'
import type { CorsConfig, CorsContext, CorsHeaders } from '@redwoodjs/api'
import { createCorsContext, normalizeRequest } from '@redwoodjs/api'
import * as DbAuthError from './errors'
import {
cookieName,
decryptSession,
encryptSession,
extractCookie,
getSession,
hashPassword,
legacyHashPassword,
isLegacySession,
hashToken,
webAuthnSession,
extractHashingOptions,
} from './shared'
type SetCookieHeader = { 'set-cookie': string }
type CsrfTokenHeader = { 'csrf-token': string }
interface SignupFlowOptions<TUserAttributes = Record<string, unknown>> {
/**
* Allow users to sign up. Defaults to true.
* Needs to be explicitly set to false to disable the flow
*/
enabled?: boolean
/**
* Whatever you want to happen to your data on new user signup. Redwood will
* check for duplicate usernames before calling this handler. At a minimum
* you need to save the `username`, `hashedPassword` and `salt` to your
* user table. `userAttributes` contains any additional object members that
* were included in the object given to the `signUp()` function you got
* from `useAuth()`
*/
handler: (signupHandlerOptions: SignupHandlerOptions<TUserAttributes>) => any
/**
* Validate the user-supplied password with whatever logic you want. Return
* `true` if valid, throw `PasswordValidationError` if not.
*/
passwordValidation?: (password: string) => boolean
/**
* Object containing error strings
*/
errors?: {
fieldMissing?: string
usernameTaken?: string
flowNotEnabled?: string
}
/**
* Allows the user to define if the UserCheck for their selected db provider should use case insensitive
*/
usernameMatch?: string
}
interface ForgotPasswordFlowOptions<TUser = UserType> {
/**
* Allow users to request a new password via a call to forgotPassword. Defaults to true.
* Needs to be explicitly set to false to disable the flow
*/
enabled?: boolean
handler: (user: TUser, token: string) => any
errors?: {
usernameNotFound?: string
usernameRequired?: string
flowNotEnabled?: string
}
expires: number
}
interface LoginFlowOptions<TUser = UserType> {
/**
* Allow users to login. Defaults to true.
* Needs to be explicitly set to false to disable the flow
*/
enabled?: boolean
/**
* Anything you want to happen before logging the user in. This can include
* throwing an error to prevent login. If you do want to allow login, this
* function must return an object representing the user you want to be logged
* in, containing at least an `id` field (whatever named field was provided
* for `authFields.id`). For example: `return { id: user.id }`
*/
handler: (user: TUser) => any
/**
* Object containing error strings
*/
errors?: {
usernameOrPasswordMissing?: string
usernameNotFound?: string
incorrectPassword?: string
flowNotEnabled?: string
}
/**
* How long a user will remain logged in, in seconds
*/
expires: number
/**
* Allows the user to define if the UserCheck for their selected db provider should use case insensitive
*/
usernameMatch?: string
}
interface ResetPasswordFlowOptions<TUser = UserType> {
/**
* Allow users to reset their password via a code from a call to forgotPassword. Defaults to true.
* Needs to be explicitly set to false to disable the flow
*/
enabled?: boolean
handler: (user: TUser) => boolean | Promise<boolean>
allowReusedPassword: boolean
errors?: {
resetTokenExpired?: string
resetTokenInvalid?: string
resetTokenRequired?: string
reusedPassword?: string
flowNotEnabled?: string
}
}
interface WebAuthnFlowOptions {
enabled: boolean
expires: number
name: string
domain: string
origin: string
timeout?: number
type: 'any' | 'platform' | 'cross-platform'
credentialFields: {
id: string
userId: string
publicKey: string
transports: string
counter: string
}
}
export type UserType = Record<string | number, any>
export interface DbAuthHandlerOptions<
TUser = UserType,
TUserAttributes = Record<string, unknown>
> {
/**
* Provide prisma db client
*/
db: PrismaClient
/**
* The name of the property you'd call on `db` to access your user table.
* ie. if your Prisma model is named `User` this value would be `user`, as in `db.user`
*/
authModelAccessor: keyof PrismaClient
/**
* The name of the property you'd call on `db` to access your user credentials table.
* ie. if your Prisma model is named `UserCredential` this value would be `userCredential`, as in `db.userCredential`
*/
credentialModelAccessor?: keyof PrismaClient
/**
* The fields that are allowed to be returned from the user table when
* invoking handlers that return a user object (like forgotPassword and signup)
* Defaults to `id` and `email` if not set at all.
*/
allowedUserFields?: string[]
/**
* A map of what dbAuth calls a field to what your database calls it.
* `id` is whatever column you use to uniquely identify a user (probably
* something like `id` or `userId` or even `email`)
*/
authFields: {
id: string
username: string
hashedPassword: string
salt: string
resetToken: string
resetTokenExpiresAt: string
challenge?: string
}
/**
* Object containing cookie config options
*/
cookie?: {
/** @deprecated set this option in `cookie.attributes` */
Path?: string
/** @deprecated set this option in `cookie.attributes` */
HttpOnly?: boolean
/** @deprecated set this option in `cookie.attributes` */
Secure?: boolean
/** @deprecated set this option in `cookie.attributes` */
SameSite?: string
/** @deprecated set this option in `cookie.attributes` */
Domain?: string
attributes?: {
Path?: string
HttpOnly?: boolean
Secure?: boolean
SameSite?: string
Domain?: string
}
/**
* The name of the cookie that dbAuth sets
*
* %port% will be replaced with the port the api server is running on.
* If you have multiple RW apps running on the same host, you'll need to
* make sure they all use unique cookie names
*/
name?: string
}
/**
* Object containing forgot password options
*/
forgotPassword: ForgotPasswordFlowOptions<TUser> | { enabled: false }
/**
* Object containing login options
*/
login: LoginFlowOptions<TUser> | { enabled: false }
/**
* Object containing reset password options
*/
resetPassword: ResetPasswordFlowOptions<TUser> | { enabled: false }
/**
* Object containing login options
*/
signup: SignupFlowOptions<TUserAttributes> | { enabled: false }
/**
* Object containing WebAuthn options
*/
webAuthn?: WebAuthnFlowOptions | { enabled: false }
/**
* CORS settings, same as in createGraphqlHandler
*/
cors?: CorsConfig
}
export interface SignupHandlerOptions<TUserAttributes> {
username: string
hashedPassword: string
salt: string
userAttributes?: TUserAttributes
}
export type AuthMethodNames =
| 'forgotPassword'
| 'getToken'
| 'login'
| 'logout'
| 'resetPassword'
| 'signup'
| 'validateResetToken'
| 'webAuthnRegOptions'
| 'webAuthnRegister'
| 'webAuthnAuthOptions'
| 'webAuthnAuthenticate'
type Params = AuthenticationResponseJSON &
RegistrationResponseJSON & {
username?: string
password?: string
method: AuthMethodNames
[key: string]: any
}
interface DbAuthSession<TIdType> {
id: TIdType
}
const DEFAULT_ALLOWED_USER_FIELDS = ['id', 'email']
export class DbAuthHandler<
TUser extends UserType,
TIdType = any,
TUserAttributes = Record<string, unknown>
> {
event: APIGatewayProxyEvent
context: LambdaContext
options: DbAuthHandlerOptions<TUser, TUserAttributes>
cookie: string | undefined
params: Params
db: PrismaClient
dbAccessor: any
dbCredentialAccessor: any
allowedUserFields: string[]
headerCsrfToken: string | undefined
hasInvalidSession: boolean
session: DbAuthSession<TIdType> | undefined
sessionCsrfToken: string | undefined
corsContext: CorsContext | undefined
sessionExpiresDate: string
webAuthnExpiresDate: string
// class constant: list of auth methods that are supported
static get METHODS(): AuthMethodNames[] {
return [
'forgotPassword',
'getToken',
'login',
'logout',
'resetPassword',
'signup',
'validateResetToken',
'webAuthnRegOptions',
'webAuthnRegister',
'webAuthnAuthOptions',
'webAuthnAuthenticate',
]
}
// class constant: maps the auth functions to their required HTTP verb for access
static get VERBS() {
return {
forgotPassword: 'POST',
getToken: 'GET',
login: 'POST',
logout: 'POST',
resetPassword: 'POST',
signup: 'POST',
validateResetToken: 'POST',
webAuthnRegOptions: 'GET',
webAuthnRegister: 'POST',
webAuthnAuthOptions: 'GET',
webAuthnAuthenticate: 'POST',
}
}
// default to epoch when we want to expire
static get PAST_EXPIRES_DATE() {
return new Date('1970-01-01T00:00:00.000+00:00').toUTCString()
}
// generate a new token (standard UUID)
static get CSRF_TOKEN() {
return uuidv4()
}
static get AVAILABLE_WEBAUTHN_TRANSPORTS() {
return ['usb', 'ble', 'nfc', 'internal']
}
/**
* Returns the set-cookie header to mark the cookie as expired ("deletes" the session)
*
* The header keys are case insensitive, but Fastify prefers these to be lowercase.
* Therefore, we want to ensure that the headers are always lowercase and unique
* for compliance with HTTP/2.
*
* @see: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2
*/
get _deleteSessionHeader() {
return {
'set-cookie': [
`${cookieName(this.options.cookie?.name)}=`,
...this._cookieAttributes({ expires: 'now' }),
].join(';'),
}
}
constructor(
event: APIGatewayProxyEvent,
context: LambdaContext,
options: DbAuthHandlerOptions<TUser, TUserAttributes>
) {
this.event = event
this.context = context
this.options = options
this.cookie = extractCookie(this.event)
this._validateOptions()
this.params = this._parseBody()
this.db = this.options.db
this.dbAccessor = this.db[this.options.authModelAccessor]
this.dbCredentialAccessor = this.options.credentialModelAccessor
? this.db[this.options.credentialModelAccessor]
: null
this.headerCsrfToken = this.event.headers['csrf-token']
this.hasInvalidSession = false
this.allowedUserFields =
this.options.allowedUserFields || DEFAULT_ALLOWED_USER_FIELDS
const sessionExpiresAt = new Date()
sessionExpiresAt.setSeconds(
sessionExpiresAt.getSeconds() +
(this.options.login as LoginFlowOptions).expires
)
this.sessionExpiresDate = sessionExpiresAt.toUTCString()
const webAuthnExpiresAt = new Date()
webAuthnExpiresAt.setSeconds(
webAuthnExpiresAt.getSeconds() +
((this.options?.webAuthn as WebAuthnFlowOptions)?.expires || 0)
)
this.webAuthnExpiresDate = webAuthnExpiresAt.toUTCString()
// Note that we handle these headers differently in functions/graphql.ts
// because it's handled by graphql-yoga, so we map the cors config to yoga config
// See packages/graphql-server/src/__tests__/mapRwCorsToYoga.test.ts
if (options.cors) {
this.corsContext = createCorsContext(options.cors)
}
try {
const [session, csrfToken] = decryptSession(
getSession(this.cookie, this.options.cookie?.name)
)
this.session = session
this.sessionCsrfToken = csrfToken
} catch (e) {
// if session can't be decrypted, keep track so we can log them out when
// the auth method is called
if (e instanceof DbAuthError.SessionDecryptionError) {
this.hasInvalidSession = true
} else {
throw e
}
}
}
// Actual function that triggers everything else to happen: `login`, `signup`,
// etc. is called from here, after some checks to make sure the request is good
async invoke() {
const request = normalizeRequest(this.event)
let corsHeaders = {}
if (this.corsContext) {
corsHeaders = this.corsContext.getRequestHeaders(request)
// Return CORS headers for OPTIONS requests
if (this.corsContext.shouldHandleCors(request)) {
return this._buildResponseWithCorsHeaders(
{ body: '', statusCode: 200 },
corsHeaders
)
}
}
// if there was a problem decryption the session, just return the logout
// response immediately
if (this.hasInvalidSession) {
return this._buildResponseWithCorsHeaders(
this._ok(...this._logoutResponse()),
corsHeaders
)
}
try {
const method = this._getAuthMethod()
// get the auth method the incoming request is trying to call
if (!DbAuthHandler.METHODS.includes(method)) {
return this._buildResponseWithCorsHeaders(this._notFound(), corsHeaders)
}
// make sure it's using the correct verb, GET vs POST
if (this.event.httpMethod !== DbAuthHandler.VERBS[method]) {
return this._buildResponseWithCorsHeaders(this._notFound(), corsHeaders)
}
// call whatever auth method was requested and return the body and headers
const [body, headers, options = { statusCode: 200 }] = await this[
method
]()
return this._buildResponseWithCorsHeaders(
this._ok(body, headers, options),
corsHeaders
)
} catch (e: any) {
if (e instanceof DbAuthError.WrongVerbError) {
return this._buildResponseWithCorsHeaders(this._notFound(), corsHeaders)
} else {
return this._buildResponseWithCorsHeaders(
this._badRequest(e.message || e),
corsHeaders
)
}
}
}
async forgotPassword() {
const { enabled = true } = this.options.forgotPassword
if (!enabled) {
throw new DbAuthError.FlowNotEnabledError(
(this.options.forgotPassword as ForgotPasswordFlowOptions)?.errors
?.flowNotEnabled || `Forgot password flow is not enabled`
)
}
const { username } = this.params
// was the username sent in at all?
if (!username || username.trim() === '') {
throw new DbAuthError.UsernameRequiredError(
(this.options.forgotPassword as ForgotPasswordFlowOptions)?.errors
?.usernameRequired || `Username is required`
)
}
let user
try {
user = await this.dbAccessor.findUnique({
where: { [this.options.authFields.username]: username },
})
} catch (e) {
throw new DbAuthError.GenericError()
}
if (user) {
const tokenExpires = new Date()
tokenExpires.setSeconds(
tokenExpires.getSeconds() +
(this.options.forgotPassword as ForgotPasswordFlowOptions).expires
)
// generate a token
let token = md5(uuidv4())
const buffer = Buffer.from(token)
token = buffer.toString('base64').replace('=', '').substring(0, 16)
// Store the token hash in the database so we can verify it later
const tokenHash = hashToken(token)
try {
// set token and expires time
user = await this.dbAccessor.update({
where: {
[this.options.authFields.id]: user[this.options.authFields.id],
},
data: {
[this.options.authFields.resetToken]: tokenHash,
[this.options.authFields.resetTokenExpiresAt]: tokenExpires,
},
})
} catch (e) {
throw new DbAuthError.GenericError()
}
// call user-defined handler in their functions/auth.js
const response = await (
this.options.forgotPassword as ForgotPasswordFlowOptions
).handler(this._sanitizeUser(user), token)
return [
response ? JSON.stringify(response) : '',
{
...this._deleteSessionHeader,
},
]
} else {
throw new DbAuthError.UsernameNotFoundError(
(this.options.forgotPassword as ForgotPasswordFlowOptions)?.errors
?.usernameNotFound || `Username '${username} not found`
)
}
}
async getToken() {
try {
const user = await this._getCurrentUser()
let headers = {}
// if the session was encrypted with the old algorithm, re-encrypt it
// with the new one
if (isLegacySession(this.cookie)) {
headers = this._loginResponse(user)[1]
}
return [user[this.options.authFields.id], headers]
} catch (e: any) {
if (e instanceof DbAuthError.NotLoggedInError) {
return this._logoutResponse()
} else {
return this._logoutResponse({ error: e.message })
}
}
}
async login() {
const { enabled = true } = this.options.login
if (!enabled) {
throw new DbAuthError.FlowNotEnabledError(
(this.options.login as LoginFlowOptions)?.errors?.flowNotEnabled ||
`Login flow is not enabled`
)
}
const { username, password } = this.params
const dbUser = await this._verifyUser(username, password)
const handlerUser = await (this.options.login as LoginFlowOptions).handler(
dbUser
)
if (
handlerUser == null ||
handlerUser[this.options.authFields.id] == null
) {
throw new DbAuthError.NoUserIdError()
}
return this._loginResponse(handlerUser)
}
logout() {
return this._logoutResponse()
}
async resetPassword() {
const { enabled = true } = this.options.resetPassword
if (!enabled) {
throw new DbAuthError.FlowNotEnabledError(
(this.options.resetPassword as ResetPasswordFlowOptions)?.errors
?.flowNotEnabled || `Reset password flow is not enabled`
)
}
const { password, resetToken } = this.params
// is the resetToken present?
if (resetToken == null || String(resetToken).trim() === '') {
throw new DbAuthError.ResetTokenRequiredError(
(
this.options.resetPassword as ResetPasswordFlowOptions
)?.errors?.resetTokenRequired
)
}
// is password present?
if (password == null || String(password).trim() === '') {
throw new DbAuthError.PasswordRequiredError()
}
let user = await this._findUserByToken(resetToken as string)
const [hashedPassword] = hashPassword(password, {
salt: user.salt,
})
const [legacyHashedPassword] = legacyHashPassword(password, user.salt)
if (
(!(this.options.resetPassword as ResetPasswordFlowOptions)
.allowReusedPassword &&
user.hashedPassword === hashedPassword) ||
user.hashedPassword === legacyHashedPassword
) {
throw new DbAuthError.ReusedPasswordError(
(
this.options.resetPassword as ResetPasswordFlowOptions
)?.errors?.reusedPassword
)
}
try {
// if we got here then we can update the password in the database
user = await this.dbAccessor.update({
where: {
[this.options.authFields.id]: user[this.options.authFields.id],
},
data: {
[this.options.authFields.hashedPassword]: hashedPassword,
},
})
} catch (e) {
throw new DbAuthError.GenericError()
}
await this._clearResetToken(user)
// call the user-defined handler so they can decide what to do with this user
const response = await (
this.options.resetPassword as ResetPasswordFlowOptions
).handler(this._sanitizeUser(user))
// returning the user from the handler means to log them in automatically
if (response) {
return this._loginResponse(user)
} else {
return this._logoutResponse({})
}
}
async signup() {
const { enabled = true } = this.options.signup
if (!enabled) {
throw new DbAuthError.FlowNotEnabledError(
(this.options.signup as SignupFlowOptions)?.errors?.flowNotEnabled ||
`Signup flow is not enabled`
)
}
// check if password is valid
const { password } = this.params
;(this.options.signup as SignupFlowOptions).passwordValidation?.(
password as string
)
const userOrMessage = await this._createUser()
// at this point `user` is either an actual user, in which case log the
// user in automatically, or it's a string, which is a message to show
// the user (something like "please verify your email")
if (typeof userOrMessage === 'object') {
const user = userOrMessage
return this._loginResponse(user, 201)
} else {
const message = userOrMessage
return [JSON.stringify({ message }), {}, { statusCode: 201 }]
}
}
async validateResetToken() {
// is token present at all?
if (
this.params.resetToken == null ||
String(this.params.resetToken).trim() === ''
) {
throw new DbAuthError.ResetTokenRequiredError(
(
this.options.resetPassword as ResetPasswordFlowOptions
)?.errors?.resetTokenRequired
)
}
const user = await this._findUserByToken(this.params.resetToken as string)
return [
JSON.stringify(this._sanitizeUser(user)),
{
...this._deleteSessionHeader,
},
]
}
// browser submits WebAuthn credentials
async webAuthnAuthenticate() {
const { verifyAuthenticationResponse } = require('@simplewebauthn/server')
const webAuthnOptions = this.options.webAuthn
if (!webAuthnOptions || !webAuthnOptions.enabled) {
throw new DbAuthError.WebAuthnError('WebAuthn is not enabled')
}
const credential = await this.dbCredentialAccessor.findFirst({
where: { id: this.params.rawId },
})
if (!credential) {
throw new DbAuthError.WebAuthnError('Credentials not found')
}
const user = await this.dbAccessor.findFirst({
where: {
[this.options.authFields.id]:
credential[webAuthnOptions.credentialFields.userId],
},
})
let verification: VerifiedAuthenticationResponse
try {
const opts: VerifyAuthenticationResponseOpts = {
response: this.params,
expectedChallenge: user[this.options.authFields.challenge as string],
expectedOrigin: webAuthnOptions.origin,
expectedRPID: webAuthnOptions.domain,
authenticator: {
credentialID: base64url.toBuffer(
credential[webAuthnOptions.credentialFields.id]
),
credentialPublicKey:
credential[webAuthnOptions.credentialFields.publicKey],
counter: credential[webAuthnOptions.credentialFields.counter],
transports: credential[webAuthnOptions.credentialFields.transports]
? JSON.parse(
credential[webAuthnOptions.credentialFields.transports]
)
: DbAuthHandler.AVAILABLE_WEBAUTHN_TRANSPORTS,
},
requireUserVerification: true,
}
verification = await verifyAuthenticationResponse(opts)
} catch (e: any) {
throw new DbAuthError.WebAuthnError(e.message)
} finally {
// whether it worked or errored, clear the challenge in the user record
// and user can get a new one next time they try to authenticate
await this._saveChallenge(user[this.options.authFields.id], null)
}
const { verified, authenticationInfo } = verification
if (verified) {
// update counter in credentials
await this.dbCredentialAccessor.update({
where: {
[webAuthnOptions.credentialFields.id]:
credential[webAuthnOptions.credentialFields.id],
},
data: {
[webAuthnOptions.credentialFields.counter]:
authenticationInfo.newCounter,
},
})
}
// get the regular `login` cookies
const [, loginHeaders] = this._loginResponse(user)
const cookies = [
this._webAuthnCookie(this.params.rawId, this.webAuthnExpiresDate),
loginHeaders['set-cookie'],
].flat()
return [verified, { 'set-cookie': cookies }]
}
// get options for a WebAuthn authentication
async webAuthnAuthOptions() {
const { generateAuthenticationOptions } = require('@simplewebauthn/server')
if (this.options.webAuthn === undefined || !this.options.webAuthn.enabled) {
throw new DbAuthError.WebAuthnError('WebAuthn is not enabled')
}
const webAuthnOptions = this.options.webAuthn
const credentialId = webAuthnSession(this.event)
let user
if (credentialId) {
user = await this.dbCredentialAccessor
.findFirst({
where: { [webAuthnOptions.credentialFields.id]: credentialId },
})
.user()
} else {
// webauthn session not present, fallback to getting user from regular
// session cookie
user = await this._getCurrentUser()
}
// webauthn cookie has been tampered with or UserCredential has been deleted
// from the DB, remove their cookie so it doesn't happen again
if (!user) {
return [
{ error: 'Log in with username and password to enable WebAuthn' },
{ 'set-cookie': this._webAuthnCookie('', 'now') },
{ statusCode: 400 },
]
}
const credentials = await this.dbCredentialAccessor.findMany({
where: {
[webAuthnOptions.credentialFields.userId]:
user[this.options.authFields.id],
},
})
const someOptions: GenerateAuthenticationOptionsOpts = {
timeout: webAuthnOptions.timeout || 60000,
allowCredentials: credentials.map((cred: Record<string, string>) => ({
id: base64url.toBuffer(cred[webAuthnOptions.credentialFields.id]),
type: 'public-key',
transports: cred[webAuthnOptions.credentialFields.transports]
? JSON.parse(cred[webAuthnOptions.credentialFields.transports])
: DbAuthHandler.AVAILABLE_WEBAUTHN_TRANSPORTS,
})),
userVerification: 'required',
rpID: webAuthnOptions.domain,
}
const authOptions = generateAuthenticationOptions(someOptions)
await this._saveChallenge(
user[this.options.authFields.id],
authOptions.challenge
)
return [authOptions]
}
// get options for WebAuthn registration
async webAuthnRegOptions() {
const { generateRegistrationOptions } = require('@simplewebauthn/server')
if (!this.options?.webAuthn?.enabled) {
throw new DbAuthError.WebAuthnError('WebAuthn is not enabled')
}
const webAuthnOptions = this.options.webAuthn
const user = await this._getCurrentUser()
const options: GenerateRegistrationOptionsOpts = {
rpName: webAuthnOptions.name,
rpID: webAuthnOptions.domain,
userID: user[this.options.authFields.id],
userName: user[this.options.authFields.username],
timeout: webAuthnOptions?.timeout || 60000,
excludeCredentials: [],
authenticatorSelection: {
userVerification: 'required',
},
// Support the two most common algorithms: ES256, and RS256
supportedAlgorithmIDs: [-7, -257],
}
// if a type is specified other than `any` assign it (the default behavior
// of this prop if `undefined` means to allow any authenticator)
if (webAuthnOptions.type && webAuthnOptions.type !== 'any') {
options.authenticatorSelection = Object.assign(
options.authenticatorSelection || {},
{ authenticatorAttachment: webAuthnOptions.type }
)
}
const regOptions = generateRegistrationOptions(options)
await this._saveChallenge(
user[this.options.authFields.id],
regOptions.challenge
)
return [regOptions]
}
// browser submits WebAuthn credentials for the first time on a new device
async webAuthnRegister() {
const { verifyRegistrationResponse } = require('@simplewebauthn/server')
if (this.options.webAuthn === undefined || !this.options.webAuthn.enabled) {
throw new DbAuthError.WebAuthnError('WebAuthn is not enabled')
}
const user = await this._getCurrentUser()
let verification: VerifiedRegistrationResponse
try {
const options: VerifyRegistrationResponseOpts = {
response: this.params,
expectedChallenge: user[this.options.authFields.challenge as string],
expectedOrigin: this.options.webAuthn.origin,
expectedRPID: this.options.webAuthn.domain,
requireUserVerification: true,
}
verification = await verifyRegistrationResponse(options)
} catch (e: any) {
throw new DbAuthError.WebAuthnError(e.message)
}
const { verified, registrationInfo } = verification
let plainCredentialId
if (verified && registrationInfo) {
const { credentialPublicKey, credentialID, counter } = registrationInfo
plainCredentialId = base64url.encode(Buffer.from(credentialID))
const existingDevice = await this.dbCredentialAccessor.findFirst({
where: {
id: plainCredentialId,
userId: user[this.options.authFields.id],
},
})
if (!existingDevice) {
await this.dbCredentialAccessor.create({
data: {
[this.options.webAuthn.credentialFields.id]: plainCredentialId,
[this.options.webAuthn.credentialFields.userId]:
user[this.options.authFields.id],
[this.options.webAuthn.credentialFields.publicKey]:
Buffer.from(credentialPublicKey),
[this.options.webAuthn.credentialFields.transports]: this.params
.transports
? JSON.stringify(this.params.transports)
: null,
[this.options.webAuthn.credentialFields.counter]: counter,
},
})
}
} else {
throw new DbAuthError.WebAuthnError('Registration failed')
}
// clear challenge
await this._saveChallenge(user[this.options.authFields.id], null)