-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
838 lines (727 loc) · 23 KB
/
Copy pathauth.ts
File metadata and controls
838 lines (727 loc) · 23 KB
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
import jwt from "jsonwebtoken"
import crypto from "node:crypto"
export type AuthTokenPayload = {
type: "access" | "refresh" | "password-reset"
userId: string
}
export type AuthUser = {
id: string
email: string
password: string
verified?: boolean
}
export type AuthSession = {
userId: string
refreshTokenHash: string
expiresAt: Date
agent?: string
}
export type AuthAdapter<
AuthAdditionalTokenPayload extends AdditionalAuthTokenPayloadGuardObject = undefined
> = {
findUser: (
data: Pick<AuthUser, "email">
) => Promise<AuthUser | null | undefined>
updateUser: (
userId: string,
data: Partial<Omit<AuthUser, "id">>
) => Promise<void>
createUser: (data: Pick<AuthUser, "email" | "password">) => Promise<AuthUser>
findSession: (
data: Pick<AuthSession, "refreshTokenHash">
) => Promise<AuthSession | null | undefined>
deleteSession: (
data: Pick<AuthSession, "userId" | "refreshTokenHash">
) => Promise<void>
deleteSessions: (data: Pick<AuthSession, "userId">) => Promise<void>
createSession: (data: AuthSession) => Promise<AuthSession>
// Optional: validate the email address.
// If not provided, the email will be validated using a regular expression.
validateEmail?: (email: string) => Promise<boolean>
// Optional: rate limit the login and register operations.
isLoginRateLimited?: (data: {
ip?: string
email: string
}) => Promise<boolean>
isRegisterRateLimited?: (data: {
ip?: string
email: string
}) => Promise<boolean>
} & (AuthAdditionalTokenPayload extends undefined // If the payload type is provided, the adapter must implement the enrichTokenPayload method.
? {}
: {
enrichTokenPayload: (data: {
userId: string
}) => Promise<AuthAdditionalTokenPayload>
})
type AdditionalAuthTokenPayloadGuardObject =
| (object & NeverKeys<AuthTokenPayload>)
| undefined
// Simplify error handling by returning error as values.
// Functions return a tuple of [result, error].
type ResultTuple<Result, E extends string> = Promise<
[Result, undefined] | [undefined, E]
>
type ResultTupleErrorExtractor<Fn extends (...args: any[]) => any> =
Fn extends (...args: any[]) => Promise<[unknown, infer E]>
? NonNullable<E>
: never
// Utility type that maps all keys to never.
type NeverKeys<T> = {
[K in keyof T]?: never
}
/**
* This file does not require Prisma, but just for reference:
* Prisma models
* | model User {
* | id String @id @default(cuid())
* | email String @unique
* | password String
* | verified Boolean @default(false)
* | authSessions AuthSession[]
* | }
* |
* | model AuthSession {
* | refreshTokenHash String @id
* | userId String
* | user User @relation(fields: [userId], references: [id])
* | agent String
* | expiresAt DateTime
* | createdAt DateTime @default(now())
* | updatedAt DateTime @updatedAt
* | }
*
* Flow:
* 1. User provides their email and password to register.
* 2. If the user does not exist, a new user is created.
* 3. A new session is created, including:
* - an access token (short-lived), used for authenticated requests
* - a refresh token (long-lived), used for refreshing the access token
* 4. When the user forgets their password, a password reset token is generated and sent to the user's email.
* - the password reset token can only be used once to reset the password
* - once the password is reset, all the previous user sessions are invalidated
**/
export class Auth<
// Additional Auth Token Payload
AdditionalAuthTokenPayload extends AdditionalAuthTokenPayloadGuardObject = undefined,
// Combined Additional Token Payload
CombinedAuthTokenPayload = AdditionalAuthTokenPayload extends undefined
? AuthTokenPayload
: AdditionalAuthTokenPayload & AuthTokenPayload
> {
// The secret used to sign the JWT tokens
private readonly jwtSecret: string
// The expiration time for each type of token.
// See constructor for defaults.
private readonly refreshTokenExpiresInMs: number
private readonly accessTokenExpiresInMs: number
private readonly passwordResetTokenExpiresInMs: number
// We use an adapter model
private readonly adapter: AuthAdapter<AdditionalAuthTokenPayload>
// Whether to log debug information.
private readonly isDebugLoggingEnabled: boolean
constructor(config: {
jwtSecret: string
refreshTokenExpiresInMs?: number
accessTokenExpiresInMs?: number
passwordResetTokenExpiresInMs?: number
adapter: AuthAdapter<AdditionalAuthTokenPayload>
isDebugLoggingEnabled?: boolean
}) {
this.jwtSecret = config.jwtSecret
this.refreshTokenExpiresInMs =
config.refreshTokenExpiresInMs || 14 * 24 * 60 * 60 * 1000 // default to 14 days
this.accessTokenExpiresInMs =
config.accessTokenExpiresInMs || 60 * 60 * 1000 // default to 1 hour
this.passwordResetTokenExpiresInMs =
config.passwordResetTokenExpiresInMs || 10 * 60 * 1000 // default to 10 minutes
this.adapter = config.adapter
this.isDebugLoggingEnabled = config.isDebugLoggingEnabled ?? false
}
/**
* Register a new user with the given email and password.
*/
async register({
email,
password,
ip
}: {
email: string
password: string
ip?: string
}): ResultTuple<
{
userId: string
session: AuthSession
accessToken: string
refreshToken: string
},
| "INVALID_EMAIL"
| "TOO_MANY_REQUESTS"
| "USER_ALREADY_EXISTS"
| "FAILED_TO_CREATE_SESSION"
| ResultTupleErrorExtractor<typeof this.enrichTokenPayload>
> {
const DEBUG_TAG = "Register"
this.logDebug("info", DEBUG_TAG, "Registering new user", { email })
const [isEmailValid, maybeErrorCheckEmailValidity] =
await this.checkEmailValidity(email)
if (!isEmailValid || maybeErrorCheckEmailValidity) {
return [undefined, maybeErrorCheckEmailValidity ?? "INVALID_EMAIL"]
}
if (this.adapter.isRegisterRateLimited) {
const [isRateLimited, maybeErrorIsRateLimited] =
await this.wrapPromiseToResultTuple(
this.adapter.isRegisterRateLimited({ ip, email }),
"TOO_MANY_REQUESTS"
)
if (isRateLimited || maybeErrorIsRateLimited) {
this.logDebug("error", DEBUG_TAG, "Rate limited", { ip, email })
return [undefined, maybeErrorIsRateLimited ?? "TOO_MANY_REQUESTS"]
}
}
const [user, maybeErrorFindUser] = await this.wrapPromiseToResultTuple(
this.adapter.findUser({ email }),
"USER_ALREADY_EXISTS"
)
if (user || maybeErrorFindUser) {
this.logDebug("error", DEBUG_TAG, `User "${email}" already exists`)
return [undefined, maybeErrorFindUser ?? "USER_ALREADY_EXISTS"]
}
const hashedPassword = this.scrypt(password)
const [newUser, maybeErrorCreateUser] = await this.wrapPromiseToResultTuple(
this.adapter.createUser({ email, password: hashedPassword }),
"USER_ALREADY_EXISTS"
)
if (!newUser || maybeErrorCreateUser) {
this.logDebug("error", DEBUG_TAG, "Failed to create user", {
email,
error: maybeErrorCreateUser
})
return [undefined, maybeErrorCreateUser ?? "USER_ALREADY_EXISTS"]
}
const userId = newUser.id
const [enrichedPayload, enrichedPayloadError] =
await this.enrichTokenPayload({ userId })
if (enrichedPayloadError) {
return [undefined, enrichedPayloadError]
}
const refreshToken = this.generateRefreshToken({
...enrichedPayload,
userId
} as CombinedAuthTokenPayload)
const accessToken = this.generateAccessToken({
...enrichedPayload,
userId
} as CombinedAuthTokenPayload)
const refreshTokenHash = this.sha256(refreshToken)
const expiresAt = new Date(Date.now() + this.refreshTokenExpiresInMs)
const [session, maybeErrorCreateSession] =
await this.wrapPromiseToResultTuple(
this.adapter.createSession({
userId,
refreshTokenHash,
expiresAt
}),
"FAILED_TO_CREATE_SESSION"
)
if (!session || maybeErrorCreateSession) {
this.logDebug("error", DEBUG_TAG, "Failed to create session", {
userId,
error: maybeErrorCreateSession
})
return [undefined, maybeErrorCreateSession ?? "FAILED_TO_CREATE_SESSION"]
}
this.logDebug("info", DEBUG_TAG, "User registered successfully", { userId })
return [{ userId, session, accessToken, refreshToken }, undefined]
}
/**
* Sign in a user with the given email and password.
*/
async login({
email,
password,
ip
}: {
email: string
password: string
ip?: string
}): ResultTuple<
{
userId: string
session: AuthSession
accessToken: string
refreshToken: string
},
| "INVALID_EMAIL"
| "TOO_MANY_REQUESTS"
| "INVALID_CREDENTIALS"
| "FAILED_TO_CREATE_SESSION"
| ResultTupleErrorExtractor<typeof this.verifyPassword>
| ResultTupleErrorExtractor<typeof this.enrichTokenPayload>
> {
const DEBUG_TAG = "Login"
this.logDebug("info", DEBUG_TAG, "Logging in user", { email })
const [isEmailValid, maybeErrorCheckEmailValidity] =
await this.checkEmailValidity(email)
if (!isEmailValid || maybeErrorCheckEmailValidity) {
return [undefined, maybeErrorCheckEmailValidity ?? "INVALID_CREDENTIALS"]
}
if (this.adapter.isLoginRateLimited) {
const [isRateLimited, maybeErrorIsRateLimited] =
await this.wrapPromiseToResultTuple(
this.adapter.isLoginRateLimited({ ip, email }),
"TOO_MANY_REQUESTS"
)
if (isRateLimited || maybeErrorIsRateLimited) {
this.logDebug("error", DEBUG_TAG, "Rate limited", { ip, email })
return [undefined, maybeErrorIsRateLimited ?? "TOO_MANY_REQUESTS"]
}
}
const [user, maybeErrorFindUser] = await this.wrapPromiseToResultTuple(
this.adapter.findUser({ email }),
"INVALID_CREDENTIALS"
)
if (!user || maybeErrorFindUser) {
this.logDebug("error", DEBUG_TAG, `User "${email}" not found`)
return [undefined, maybeErrorFindUser ?? "INVALID_CREDENTIALS"]
}
const [isPasswordValid, maybeErrorVerifyPassword] =
await this.verifyPassword(password, user.password)
if (!isPasswordValid || maybeErrorVerifyPassword) {
return [undefined, maybeErrorVerifyPassword ?? "INVALID_CREDENTIALS"]
}
const userId = user.id
const [enrichedPayload, enrichedPayloadError] =
await this.enrichTokenPayload({ userId })
if (enrichedPayloadError) {
return [undefined, enrichedPayloadError]
}
const refreshToken = this.generateRefreshToken({
...enrichedPayload,
userId
} as CombinedAuthTokenPayload)
const accessToken = this.generateAccessToken({
...enrichedPayload,
userId
} as CombinedAuthTokenPayload)
const [session, maybeErrorCreateSession] =
await this.wrapPromiseToResultTuple(
this.adapter.createSession({
userId,
refreshTokenHash: this.sha256(refreshToken),
expiresAt: new Date(Date.now() + this.refreshTokenExpiresInMs)
}),
"FAILED_TO_CREATE_SESSION"
)
if (!session || maybeErrorCreateSession) {
this.logDebug("error", DEBUG_TAG, "Failed to create session", {
userId,
error: maybeErrorCreateSession
})
return [undefined, maybeErrorCreateSession ?? "FAILED_TO_CREATE_SESSION"]
}
this.logDebug("info", DEBUG_TAG, "User logged in successfully", { userId })
return [{ userId, session, accessToken, refreshToken }, undefined]
}
/**
* Get a password reset token for the user.
* Make sure to always return the same API response to avoid leaking information:
* - an attacker might be able to check if an email address exists in the database.
*/
async forgotPassword({
email
}: {
email: string
}): ResultTuple<
{ passwordResetToken: string },
| "INVALID_EMAIL"
| "USER_NOT_FOUND"
| ResultTupleErrorExtractor<typeof this.enrichTokenPayload>
> {
const DEBUG_TAG = "ForgotPassword"
this.logDebug("info", DEBUG_TAG, "Forgot password")
const [isEmailValid, maybeErrorCheckEmailValidity] =
await this.checkEmailValidity(email)
if (!isEmailValid || maybeErrorCheckEmailValidity) {
return [undefined, maybeErrorCheckEmailValidity ?? "INVALID_EMAIL"]
}
const [user, maybeErrorFindUser] = await this.wrapPromiseToResultTuple(
this.adapter.findUser({ email }),
"USER_NOT_FOUND"
)
if (!user || maybeErrorFindUser) {
this.logDebug("error", DEBUG_TAG, `User "${email}" not found`)
return [undefined, maybeErrorFindUser ?? "USER_NOT_FOUND"]
}
const [enrichedPayload, enrichedPayloadError] =
await this.enrichTokenPayload({ userId: user.id })
if (enrichedPayloadError) {
return [undefined, enrichedPayloadError]
}
const passwordResetToken = this.generatePasswordResetToken({
...enrichedPayload,
userId: user.id
} as CombinedAuthTokenPayload)
this.logDebug(
"info",
DEBUG_TAG,
"Password reset token generated successfully",
{ userId: user.id }
)
return [{ passwordResetToken }, undefined]
}
/**
* Reset the password for the user.
* Requires the password reset token generated by the `forgotPassword` method.
*/
async resetPassword({
passwordResetToken,
newPassword,
closePreviousSessions = true
}: {
passwordResetToken: string
newPassword: string
closePreviousSessions?: boolean
}): ResultTuple<
undefined,
| "FAILED_TO_UPDATE_USER"
| "FAILED_TO_DELETE_SESSIONS"
| ResultTupleErrorExtractor<typeof this.getTokenPayload>
> {
const DEBUG_TAG = "ResetPassword"
this.logDebug("info", DEBUG_TAG, "Resetting password")
const [tokenPayload, errorTokenPayload] = await this.getTokenPayload(
passwordResetToken,
"password-reset"
)
if (errorTokenPayload) {
return [undefined, errorTokenPayload]
}
const userId = tokenPayload?.["userId"]
if (!userId) {
this.logDebug("error", DEBUG_TAG, "Invalid token (no user ID)")
return [undefined, "INVALID_TOKEN"]
}
const [, maybeErrorUpdateUser] = await this.wrapPromiseToResultTuple(
this.adapter.updateUser(userId, {
password: this.scrypt(newPassword)
}),
"FAILED_TO_UPDATE_USER"
)
if (maybeErrorUpdateUser) {
this.logDebug("error", DEBUG_TAG, "Failed to update password", {
userId,
error: maybeErrorUpdateUser
})
} else {
this.logDebug("info", DEBUG_TAG, "Password updated successfully", {
userId
})
}
if (closePreviousSessions) {
const [, maybeErrorDeleteSessions] = await this.wrapPromiseToResultTuple(
this.adapter.deleteSessions({ userId }),
"FAILED_TO_DELETE_SESSIONS"
)
if (maybeErrorDeleteSessions) {
this.logDebug("error", DEBUG_TAG, "Failed to close previous sessions", {
userId,
error: maybeErrorDeleteSessions
})
} else {
this.logDebug(
"info",
DEBUG_TAG,
"Previous sessions closed successfully",
{ userId }
)
}
}
return [undefined, undefined]
}
/**
* Logout the user.
*
* `refreshToken` is required to make sure the operation is done by the owner of the session.
* `refreshTokenHash` is optional to allow the client to logout from a specific session. If not provided, the current session will be closed.
*/
async closeSession({
refreshToken,
refreshTokenHash
}: {
refreshToken: string
refreshTokenHash?: string
}): ResultTuple<
void,
"SESSION_NOT_FOUND" | ResultTupleErrorExtractor<typeof this.getTokenPayload>
> {
const DEBUG_TAG = "CloseSession"
this.logDebug("info", DEBUG_TAG, "Closing session")
const [tokenPayload, errorTokenPayload] = await this.getTokenPayload(
refreshToken,
"refresh"
)
if (errorTokenPayload) {
return [undefined, errorTokenPayload]
}
const userId = tokenPayload?.["userId"]
if (!userId) {
return [undefined, "INVALID_TOKEN"]
}
const actualRefreshTokenHash = refreshTokenHash ?? this.sha256(refreshToken)
const [, maybeErrorDeleteSession] = await this.wrapPromiseToResultTuple(
this.adapter.deleteSession({
refreshTokenHash: actualRefreshTokenHash,
userId
}),
"SESSION_NOT_FOUND"
)
if (maybeErrorDeleteSession) {
return [undefined, maybeErrorDeleteSession]
}
this.logDebug("info", DEBUG_TAG, "Session closed successfully", {
userId
})
return [undefined, undefined]
}
/**
* Since access tokens are short-lived, they need to be refreshed before they expire.
*/
async refreshAccessToken({
refreshToken
}: {
refreshToken: string
}): ResultTuple<
{ accessToken: string },
| "SESSION_NOT_FOUND"
| "SESSION_EXPIRED"
| ResultTupleErrorExtractor<typeof this.getTokenPayload>
| ResultTupleErrorExtractor<typeof this.enrichTokenPayload>
> {
const DEBUG_TAG = "RefreshAccessToken"
this.logDebug("info", DEBUG_TAG, "Refreshing access token")
const [tokenPayload, errorTokenPayload] = await this.getTokenPayload(
refreshToken,
"refresh"
)
if (errorTokenPayload) {
return [undefined, errorTokenPayload]
}
const userId = tokenPayload?.["userId"]
if (!userId) {
return [undefined, "INVALID_TOKEN"]
}
const refreshTokenHash = this.sha256(refreshToken)
const [session, maybeErrorSession] = await this.wrapPromiseToResultTuple(
this.adapter.findSession({ refreshTokenHash }),
"SESSION_NOT_FOUND"
)
if (!session || maybeErrorSession) {
this.logDebug(
"error",
DEBUG_TAG,
"Session doesn't exist or is blacklisted"
)
return [undefined, maybeErrorSession ?? "SESSION_NOT_FOUND"]
}
// Should never happen since the expiration is handled when decoding the token.
// Check the expiration here as well in case the expiration has been changed in the database
if (session.expiresAt < new Date()) {
this.logDebug("error", DEBUG_TAG, "Session expired")
return [undefined, "SESSION_EXPIRED"]
}
const [enrichedPayload, enrichedPayloadError] =
await this.enrichTokenPayload({ userId })
if (enrichedPayloadError) {
return [undefined, enrichedPayloadError]
}
const accessToken = this.generateAccessToken({
...enrichedPayload,
userId
} as CombinedAuthTokenPayload)
this.logDebug("info", DEBUG_TAG, "Access token refreshed successfully", {
userId
})
return [{ accessToken }, undefined]
}
generateRefreshToken(
payload: Omit<CombinedAuthTokenPayload, "type">
): string {
const expiresInSeconds = Math.floor(this.refreshTokenExpiresInMs / 1000)
return jwt.sign({ ...payload, type: "refresh" }, this.jwtSecret, {
expiresIn: expiresInSeconds
})
}
generateAccessToken(payload: Omit<CombinedAuthTokenPayload, "type">): string {
const expiresInSeconds = Math.floor(this.accessTokenExpiresInMs / 1000)
return jwt.sign({ ...payload, type: "access" }, this.jwtSecret, {
expiresIn: expiresInSeconds
})
}
generatePasswordResetToken(
payload: Omit<CombinedAuthTokenPayload, "type">
): string {
const expiresInSeconds = Math.floor(
this.passwordResetTokenExpiresInMs / 1000
)
return jwt.sign({ ...payload, type: "password-reset" }, this.jwtSecret, {
expiresIn: expiresInSeconds
})
}
async getTokenPayload(
token: string,
typeOrTypes: AuthTokenPayload["type"] | Array<AuthTokenPayload["type"]>
): ResultTuple<
CombinedAuthTokenPayload,
"INVALID_TOKEN" | "INVALID_TOKEN_TYPE"
> {
let tokenPayload: CombinedAuthTokenPayload
try {
tokenPayload = jwt.verify(
token,
this.jwtSecret
) as CombinedAuthTokenPayload
} catch {
return [undefined, "INVALID_TOKEN"]
}
const tokenPayloadType = tokenPayload?.["type"]
if (!tokenPayloadType) {
return [undefined, "INVALID_TOKEN"]
}
if (Array.isArray(typeOrTypes)) {
const types = typeOrTypes
if (!types.includes(tokenPayloadType)) {
return [undefined, "INVALID_TOKEN_TYPE"]
}
} else {
const type = typeOrTypes
if (tokenPayloadType !== type) {
return [undefined, "INVALID_TOKEN_TYPE"]
}
}
return [tokenPayload, undefined]
}
private async enrichTokenPayload<
O = AdditionalAuthTokenPayload extends undefined
? undefined
: AdditionalAuthTokenPayload
>(payload: {
userId: string
}): ResultTuple<O, "FAILED_TO_ENRICH_TOKEN_PAYLOAD"> {
const DEBUG_TAG = "EnrichTokenPayload"
if (!("enrichTokenPayload" in this.adapter)) {
return [undefined as O, undefined]
}
const [enrichedPayload, errorEnrichTokenPayload] =
await this.wrapPromiseToResultTuple(
this.adapter.enrichTokenPayload({ userId: payload.userId }),
"FAILED_TO_ENRICH_TOKEN_PAYLOAD"
)
if (errorEnrichTokenPayload) {
this.logDebug("error", DEBUG_TAG, "Failed to enrich token payload", {
userId: payload.userId,
error: errorEnrichTokenPayload
})
return [undefined, errorEnrichTokenPayload]
}
// Make sure the basic token payload fields don't get overridden by the enriched payload.
delete enrichedPayload?.["type"]
delete enrichedPayload?.["userId"]
return [enrichedPayload as O, undefined]
}
private async checkEmailValidity(
email: string
): ResultTuple<boolean, "INVALID_EMAIL"> {
const DEBUG_TAG = "CheckEmailValidity"
if (this.adapter.validateEmail) {
const [isValid, maybeError] = await this.wrapPromiseToResultTuple(
this.adapter.validateEmail(email),
"INVALID_EMAIL"
)
if (!isValid || maybeError) {
this.logDebug("error", DEBUG_TAG, "Invalid email", {
email,
error: maybeError
})
return [undefined, maybeError ?? "INVALID_EMAIL"]
}
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const isValid = emailRegex.test(email)
if (!isValid) {
this.logDebug("error", DEBUG_TAG, "Invalid email format")
return [undefined, "INVALID_EMAIL"]
}
return [true, undefined]
}
// For token hashing
private sha256(input: string): string {
return crypto.createHash("sha256").update(input).digest("hex")
}
// For password hashing
private scrypt(input: string): string {
const salt = crypto.randomBytes(16).toString("hex")
const hash = crypto.scryptSync(input, salt, 64).toString("hex")
// store: algorithm + salt + hash
return `scrypt$${salt}$${hash}`
}
// Compare password hashes in a secure way.
private async verifyPassword(
password: string,
hashedPassword: string
): ResultTuple<boolean, "INVALID_PASSWORD"> {
const DEBUG_TAG = "VerifyPassword"
const parts = hashedPassword.split("$")
if (parts.length !== 3 || parts[0] !== "scrypt") {
this.logDebug("error", DEBUG_TAG, "Invalid password format")
return [undefined, "INVALID_PASSWORD"]
}
const [, salt, originalHash] = parts
if (
!salt ||
!originalHash ||
!/^[0-9a-f]+$/i.test(salt) ||
!/^[0-9a-f]+$/i.test(originalHash)
) {
this.logDebug("error", DEBUG_TAG, "Invalid password")
return [undefined, "INVALID_PASSWORD"]
}
try {
const hash = crypto.scryptSync(password, salt, 64).toString("hex")
const hashBuf = Buffer.from(hash, "hex")
const originalBuf = Buffer.from(originalHash, "hex")
if (hashBuf.length !== originalBuf.length) {
this.logDebug("error", DEBUG_TAG, "Invalid password hash length")
return [undefined, "INVALID_PASSWORD"]
}
return [crypto.timingSafeEqual(hashBuf, originalBuf), undefined]
} catch (error) {
this.logDebug("error", DEBUG_TAG, "Invalid password hash", { error })
return [undefined, "INVALID_PASSWORD"]
}
}
// Log debug information if debugging is enabled.
private logDebug(
level: "info" | "error",
tag: string,
...args: unknown[]
): void {
if (!this.isDebugLoggingEnabled) {
return
}
console[level](`[${tag}]`, ...args)
}
// Tiny helper to wrap a promise to return a ResultTuple.
private async wrapPromiseToResultTuple<R, E extends string>(
promise: Promise<R>,
error: E
): ResultTuple<R, E> {
try {
const result = await promise
return [result, undefined]
} catch (e) {
return [undefined, error]
}
}
}