1 import {
2 AuthenticationInput,
3 AuthenticationResponse,
4 AuthIdentityProviderService,
5 AuthTypes,
6 Context,
7 DAL,
8 FindConfig,
9 ICacheService,
10 InferEntityType,
11 InternalModuleDeclaration,
12 Logger,
13 ModuleJoinerConfig,
14 ModulesSdkTypes,
15 } from "@medusajs/framework/types"
16 import crypto from "node:crypto"
17 import {
18 InjectTransactionManager,
19 InjectManager,
20 MedusaContext,
21 MedusaError,
22 MedusaService,
23 generateEntityId,
24 } from "@medusajs/framework/utils"
25 import {
26 AuthVerification,
27 AuthIdentity,
28 AuthMfaFactor,
29 AuthMfaRecoveryCode,
30 AuthPasswordResetToken,
31 ProviderIdentity,
32 } from "@models"
33 import { AuthModuleOptions } from "@types"
34 import { joinerConfig } from "../joiner-config"
35 import AuthProviderService from "./auth-provider"
36 import AuthMfaProviderService from "./mfa-provider"
37 import AuthVerificationProviderService from "./verification-provider"
38
39 type InjectedDependencies = {
40 baseRepository: DAL.RepositoryService
41 authIdentityService: ModulesSdkTypes.IMedusaInternalService<any>
42 authVerificationService: ModulesSdkTypes.IMedusaInternalService<any>
43 authPasswordResetTokenService: ModulesSdkTypes.IMedusaInternalService<any>
44 authMfaFactorService: ModulesSdkTypes.IMedusaInternalService<any>
45 authMfaRecoveryCodeService: ModulesSdkTypes.IMedusaInternalService<any>
46 providerIdentityService: ModulesSdkTypes.IMedusaInternalService<any>
47 authProviderService: AuthProviderService
48 authMfaProviderService: AuthMfaProviderService
49 authVerificationProviderService: AuthVerificationProviderService
50 logger?: Logger
51 cache?: ICacheService
52 }
53
54 export default class AuthModuleService
55 extends MedusaService<{
56 AuthIdentity: { dto: AuthTypes.AuthIdentityDTO }
57 ProviderIdentity: { dto: AuthTypes.ProviderIdentityDTO }
58 AuthVerification: { dto: AuthTypes.AuthVerificationDTO }
59 }>({ AuthIdentity, ProviderIdentity, AuthVerification })
60 implements AuthTypes.IAuthModuleService
61 {
62 protected baseRepository_: DAL.RepositoryService
63 protected authIdentityService_: ModulesSdkTypes.IMedusaInternalService<
64 InferEntityType<typeof AuthIdentity>
65 >
66 protected authVerificationService_: ModulesSdkTypes.IMedusaInternalService<
67 InferEntityType<typeof AuthVerification>
68 >
69 protected authPasswordResetTokenService_: ModulesSdkTypes.IMedusaInternalService<
70 InferEntityType<typeof AuthPasswordResetToken>
71 >
72 protected authMfaFactorService_: ModulesSdkTypes.IMedusaInternalService<
73 InferEntityType<typeof AuthMfaFactor>
74 >
75 protected authMfaRecoveryCodeService_: ModulesSdkTypes.IMedusaInternalService<
76 InferEntityType<typeof AuthMfaRecoveryCode>
77 >
78 protected providerIdentityService_: ModulesSdkTypes.IMedusaInternalService<
79 InferEntityType<typeof ProviderIdentity>
80 >
81 protected readonly authProviderService_: AuthProviderService
82 protected readonly authMfaProviderService_: AuthMfaProviderService
83 protected readonly authVerificationProviderService_: AuthVerificationProviderService
84 protected readonly cache_: ICacheService | undefined
85 protected readonly moduleOptions_: AuthModuleOptions
86
87 constructor(
88 {
89 authIdentityService,
90 authVerificationService,
91 authPasswordResetTokenService,
92 authMfaFactorService,
93 authMfaRecoveryCodeService,
94 providerIdentityService,
95 authProviderService,
96 authMfaProviderService,
97 authVerificationProviderService,
98 baseRepository,
99 cache,
100 }: InjectedDependencies,
101 moduleOptions: AuthModuleOptions = {},
102 protected readonly moduleDeclaration?: InternalModuleDeclaration
103 ) {
104 // @ts-ignore
105 super(...arguments)
106
107 this.baseRepository_ = baseRepository
108 this.authIdentityService_ = authIdentityService
109 this.authVerificationService_ = authVerificationService
110 this.authPasswordResetTokenService_ = authPasswordResetTokenService
111 this.authMfaFactorService_ = authMfaFactorService
112 this.authMfaRecoveryCodeService_ = authMfaRecoveryCodeService
113 this.authProviderService_ = authProviderService
114 this.authMfaProviderService_ = authMfaProviderService
115 this.authVerificationProviderService_ = authVerificationProviderService
116 this.providerIdentityService_ = providerIdentityService
117 this.cache_ = cache
118 this.moduleOptions_ = moduleOptions
119 }
120
121 __joinerConfig(): ModuleJoinerConfig {
122 return joinerConfig
123 }
124
125 // @ts-expect-error
126 createAuthIdentities(
127 data: AuthTypes.CreateAuthIdentityDTO[],
128 sharedContext?: Context
129 ): Promise<AuthTypes.AuthIdentityDTO[]>
130
131 createAuthIdentities(
132 data: AuthTypes.CreateAuthIdentityDTO,
133 sharedContext?: Context
134 ): Promise<AuthTypes.AuthIdentityDTO>
135
136 @InjectManager()
137 async createAuthIdentities(
138 data: AuthTypes.CreateAuthIdentityDTO[] | AuthTypes.CreateAuthIdentityDTO,
139 @MedusaContext() sharedContext: Context = {}
140 ): Promise<AuthTypes.AuthIdentityDTO | AuthTypes.AuthIdentityDTO[]> {
141 const authIdentities = await this.authIdentityService_.create(
142 data,
143 sharedContext
144 )
145
146 return await this.baseRepository_.serialize<AuthTypes.AuthIdentityDTO[]>(
147 authIdentities,
148 {
149 populate: true,
150 }
151 )
152 }
153
154 // TODO: Update to follow convention
155 // @ts-expect-error
156 updateAuthIdentities(
157 data: AuthTypes.UpdateAuthIdentityDTO[],
158 sharedContext?: Context
159 ): Promise<AuthTypes.AuthIdentityDTO[]>
160
161 // @ts-expect-error
162 updateAuthIdentities(
163 data: AuthTypes.UpdateAuthIdentityDTO,
164 sharedContext?: Context
165 ): Promise<AuthTypes.AuthIdentityDTO>
166
167 @InjectManager()
168 // @ts-expect-error
169 async updateAuthIdentities(
170 data: AuthTypes.UpdateAuthIdentityDTO | AuthTypes.UpdateAuthIdentityDTO[],
171 @MedusaContext() sharedContext: Context = {}
172 ): Promise<AuthTypes.AuthIdentityDTO | AuthTypes.AuthIdentityDTO[]> {
173 const updatedUsers = await this.authIdentityService_.update(
174 data,
175 sharedContext
176 )
177
178 const serializedUsers = await this.baseRepository_.serialize<
179 AuthTypes.AuthIdentityDTO[]
180 >(updatedUsers, {
181 populate: true,
182 })
183
184 return serializedUsers
185 }
186
187 async listAuthProviders(filters?: {
188 id: string | string[]
189 }): Promise<AuthTypes.AuthProviderInfoDTO[]> {
190 return this.authProviderService_.listProviders(filters)
191 }
192
193 async register(
194 provider: string,
195 authenticationData: AuthenticationInput
196 ): Promise<AuthenticationResponse> {
197 try {
198 const response = await this.authProviderService_.register(
199 provider,
200 authenticationData,
201 this.getAuthIdentityProviderService(provider)
202 )
203
204 return await this.applyMfaRequirement_(response, {
205 auth_provider: provider,
206 })
207 } catch (error) {
208 return { success: false, error: error.message }
209 }
210 }
211
212 // @ts-expect-error
213 createProviderIdentities(
214 data: AuthTypes.CreateProviderIdentityDTO[],
215 sharedContext?: Context
216 ): Promise<AuthTypes.ProviderIdentityDTO[]>
217
218 // @ts-expect-error
219 createProviderIdentities(
220 data: AuthTypes.CreateProviderIdentityDTO,
221 sharedContext?: Context
222 ): Promise<AuthTypes.ProviderIdentityDTO>
223
224 @InjectManager()
225 // @ts-expect-error
226 async createProviderIdentities(
227 data:
228 | AuthTypes.CreateProviderIdentityDTO[]
229 | AuthTypes.CreateProviderIdentityDTO,
230 @MedusaContext() sharedContext: Context = {}
231 ): Promise<AuthTypes.ProviderIdentityDTO | AuthTypes.ProviderIdentityDTO[]> {
232 const providerIdentities = await this.providerIdentityService_.create(
233 data,
234 sharedContext
235 )
236
237 return await this.baseRepository_.serialize<
238 AuthTypes.ProviderIdentityDTO | AuthTypes.ProviderIdentityDTO[]
239 >(providerIdentities)
240 }
241
242 // @ts-expect-error
243 updateProviderIdentities(
244 data: AuthTypes.UpdateProviderIdentityDTO[],
245 sharedContext?: Context
246 ): Promise<AuthTypes.ProviderIdentityDTO[]>
247
248 // @ts-expect-error
249 updateProviderIdentities(
250 data: AuthTypes.UpdateProviderIdentityDTO,
251 sharedContext?: Context
252 ): Promise<AuthTypes.ProviderIdentityDTO>
253
254 @InjectManager()
255 // @ts-expect-error
256 async updateProviderIdentities(
257 data:
258 | AuthTypes.UpdateProviderIdentityDTO
259 | AuthTypes.UpdateProviderIdentityDTO[],
260 @MedusaContext() sharedContext: Context = {}
261 ): Promise<AuthTypes.ProviderIdentityDTO | AuthTypes.ProviderIdentityDTO[]> {
262 const updatedProviders = await this.providerIdentityService_.update(
263 data,
264 sharedContext
265 )
266
267 const serializedProviders = await this.baseRepository_.serialize<
268 AuthTypes.ProviderIdentityDTO[]
269 >(updatedProviders)
270
271 return serializedProviders
272 }
273
274 async updateProvider(
275 provider: string,
276 data: Record<string, unknown>
277 ): Promise<AuthenticationResponse> {
278 try {
279 return await this.authProviderService_.update(
280 provider,
281 data,
282 this.getAuthIdentityProviderService(provider)
283 )
284 } catch (error) {
285 return { success: false, error: error.message }
286 }
287 }
288
289 async authenticate(
290 provider: string,
291 authenticationData: AuthenticationInput
292 ): Promise<AuthenticationResponse> {
293 try {
294 const response = await this.authProviderService_.authenticate(
295 provider,
296 authenticationData,
297 this.getAuthIdentityProviderService(provider)
298 )
299
300 return await this.applyMfaRequirement_(response, {
301 auth_provider: provider,
302 })
303 } catch (error) {
304 return { success: false, error: error.message }
305 }
306 }
307
308 async validateCallback(
309 provider: string,
310 authenticationData: AuthenticationInput
311 ): Promise<AuthenticationResponse> {
312 try {
313 const response = await this.authProviderService_.validateCallback(
314 provider,
315 authenticationData,
316 this.getAuthIdentityProviderService(provider)
317 )
318
319 return await this.applyMfaRequirement_(response, {
320 auth_provider: provider,
321 })
322 } catch (error) {
323 return { success: false, error: error.message }
324 }
325 }
326
327 async validateAuthIdentity(
328 id: string,
329 provider: string,
330 config?: FindConfig<AuthTypes.AuthIdentityDTO>,
331 sharedContext?: Context
332 ): Promise<AuthenticationResponse> {
333 try {
334 const authIdentity = await this.authIdentityService_.retrieve(
335 id,
336 config,
337 sharedContext
338 )
339
340 return await this.applyMfaRequirement_(
341 {
342 success: true,
343 authIdentity: authIdentity as AuthTypes.AuthIdentityDTO,
344 },
345 {
346 auth_provider: provider,
347 }
348 )
349 } catch (error) {
350 return { success: false, error: error.message }
351 }
352 }
353
354 @InjectManager()
355 async startAuthMfa(
356 data: AuthTypes.AuthMfaStartDTO,
357 @MedusaContext() sharedContext: Context = {}
358 ): Promise<AuthTypes.AuthMfaStartResponse> {
359 return await this.startAuthMfa_(data, sharedContext)
360 }
361
362 @InjectTransactionManager()
363 protected async startAuthMfa_(
364 data: AuthTypes.AuthMfaStartDTO,
365 @MedusaContext() sharedContext: Context = {}
366 ): Promise<AuthTypes.AuthMfaStartResponse> {
367 await this.authIdentityService_.retrieve(
368 data.auth_identity_id,
369 {},
370 sharedContext
371 )
372
373 return await this.authMfaProviderService_.start(
374 data.provider,
375 data,
376 sharedContext
377 )
378 }
379
380 @InjectManager()
381 async verifyAuthMfa(
382 data: AuthTypes.AuthMfaVerifyDTO,
383 @MedusaContext() sharedContext: Context = {}
384 ): Promise<AuthTypes.AuthMfaDTO> {
385 return await this.verifyAuthMfa_(data, sharedContext)
386 }
387
388 @InjectTransactionManager()
389 protected async verifyAuthMfa_(
390 data: AuthTypes.AuthMfaVerifyDTO,
391 @MedusaContext() sharedContext: Context = {}
392 ): Promise<AuthTypes.AuthMfaDTO> {
393 const factor = await this.authMfaFactorService_.retrieve(
394 data.id,
395 {},
396 sharedContext
397 )
398
399 if (
400 data.auth_identity_id &&
401 factor.auth_identity_id !== data.auth_identity_id
402 ) {
403 throw new MedusaError(
404 MedusaError.Types.NOT_FOUND,
405 `MFA factor with id "${data.id}" was not found`
406 )
407 }
408
409 const verifiedFactor = await this.authMfaProviderService_.verifySetup(
410 factor.provider,
411 data,
412 sharedContext
413 )
414
415 return verifiedFactor
416 }
417
418 @InjectManager()
419 async createAuthMfaChallenge(
420 data: AuthTypes.CreateAuthMfaChallengeDTO,
421 @MedusaContext() sharedContext: Context = {}
422 ): Promise<AuthTypes.AuthMfaChallengeDTO> {
423 return await this.createAuthMfaChallenge_(data, sharedContext)
424 }
425
426 @InjectTransactionManager()
427 protected async createAuthMfaChallenge_(
428 data: AuthTypes.CreateAuthMfaChallengeDTO,
429 @MedusaContext() sharedContext: Context = {}
430 ): Promise<AuthTypes.AuthMfaChallengeDTO> {
431 await this.authIdentityService_.retrieve(
432 data.auth_identity_id,
433 {},
434 sharedContext
435 )
436
437 const methods = await this.getAvailableMfaChallengeMethods_(
438 data.auth_identity_id,
439 sharedContext
440 )
441
442 if (!methods.length) {
443 throw new MedusaError(
444 MedusaError.Types.NOT_ALLOWED,
445 "Auth identity does not have any enabled MFA methods"
446 )
447 }
448
449 const challengeConfig = this.getMfaChallengeConfig_()
450 const challenge: AuthTypes.AuthMfaChallengeDTO = {
451 id: generateEntityId(undefined, "authmfachal"),
452 auth_identity_id: data.auth_identity_id,
453 auth_provider: data.auth_provider ?? null,
454 methods,
455 expires_at: new Date(Date.now() + challengeConfig.ttlSeconds * 1000),
456 attempts: 0,
457 max_attempts: challengeConfig.maxAttempts,
458 completed_at: null,
459 metadata: data.metadata ?? null,
460 }
461
462 await this.setMfaChallenge_(challenge, challengeConfig.ttlSeconds)
463
464 return challenge
465 }
466
467 @InjectManager()
468 async verifyAuthMfaChallenge(
469 data: AuthTypes.VerifyAuthMfaChallengeDTO,
470 @MedusaContext() sharedContext: Context = {}
471 ): Promise<AuthTypes.AuthMfaChallengeDTO> {
472 return await this.verifyAuthMfaChallenge_(data, sharedContext)
473 }
474
475 protected async verifyAuthMfaChallenge_(
476 data: AuthTypes.VerifyAuthMfaChallengeDTO,
477 @MedusaContext() sharedContext: Context = {}
478 ): Promise<AuthTypes.AuthMfaChallengeDTO> {
479 const challenge = await this.retrieveMfaChallenge_(data.id)
480
481 if (
482 data.auth_identity_id &&
483 challenge.auth_identity_id !== data.auth_identity_id
484 ) {
485 throw new MedusaError(
486 MedusaError.Types.NOT_FOUND,
487 `MFA challenge with id "${data.id}" was not found`
488 )
489 }
490
491 this.assertMfaChallengeCanBeVerified_(challenge, data.method)
492
493 const valid = await this.authMfaProviderService_.verify(
494 data.method,
495 {
496 auth_identity_id: challenge.auth_identity_id!,
497 code: data.code,
498 },
499 sharedContext
500 )
501
502 if (!valid) {
503 const attempts = challenge.attempts + 1
504
505 await this.setMfaChallenge_({
506 ...challenge,
507 attempts,
508 })
509
510 throw new MedusaError(
511 MedusaError.Types.NOT_ALLOWED,
512 attempts >= challenge.max_attempts
513 ? "MFA challenge has too many failed attempts"
514 : "Invalid MFA challenge code"
515 )
516 }
517
518 const completedChallenge: AuthTypes.AuthMfaChallengeDTO = {
519 ...challenge,
520 completed_at: new Date(),
521 }
522
523 await this.setMfaChallenge_(completedChallenge)
524
525 return completedChallenge
526 }
527
528 @InjectManager()
529 async disableAuthMfa(
530 data: AuthTypes.DisableAuthMfaDTO,
531 @MedusaContext() sharedContext: Context = {}
532 ): Promise<AuthTypes.AuthMfaDTO> {
533 const factor = await this.authMfaFactorService_.retrieve(
534 data.id,
535 {},
536 sharedContext
537 )
538
539 if (
540 factor.status === "enabled" &&
541 this.getMfaDisablePolicy_() === "challenge"
542 ) {
543 if (!data.method || !data.code) {
544 throw new MedusaError(
545 MedusaError.Types.INVALID_DATA,
546 "MFA verification code is required to disable MFA"
547 )
548 }
549
550 const valid = await this.authMfaProviderService_.verify(
551 data.method,
552 {
553 auth_identity_id: factor.auth_identity_id,
554 code: data.code,
555 },
556 sharedContext
557 )
558
559 if (!valid) {
560 throw new MedusaError(
561 MedusaError.Types.NOT_ALLOWED,
562 "Invalid MFA verification code"
563 )
564 }
565 }
566
567 const disabledFactor = await this.authMfaFactorService_.update(
568 {
569 id: data.id,
570 status: "disabled",
571 },
572 sharedContext
573 )
574
575 return await this.serializeMfaFactor_(disabledFactor)
576 }
577
578 @InjectManager()
579 async retrieveAuthMfa(
580 selector: string | AuthTypes.AuthMfaSelector,
581 config: FindConfig<AuthTypes.AuthMfaDTO> = {},
582 @MedusaContext() sharedContext: Context = {}
583 ): Promise<AuthTypes.AuthMfaDTO> {
584 const filters =
585 typeof selector === "string"
586 ? { id: [selector] }
587 : {
588 id: [selector.id],
589 auth_identity_id: selector.auth_identity_id,
590 }
591
592 const [factor] = await this.authMfaFactorService_.list(
593 filters,
594 config,
595 sharedContext
596 )
597
598 if (!factor) {
599 const id = typeof selector === "string" ? selector : selector.id
600
601 throw new MedusaError(
602 MedusaError.Types.NOT_FOUND,
603 `MFA factor with id "${id}" was not found`
604 )
605 }
606
607 return await this.serializeMfaFactor_(factor)
608 }
609
610 @InjectManager()
611 async listAuthMfa(
612 filters: AuthTypes.FilterableAuthMfaProps = {},
613 config: FindConfig<AuthTypes.AuthMfaDTO> = {},
614 @MedusaContext() sharedContext: Context = {}
615 ): Promise<AuthTypes.AuthMfaDTO[]> {
616 const factors = await this.authMfaFactorService_.list(
617 filters,
618 config,
619 sharedContext
620 )
621
622 return await Promise.all(
623 factors.map((factor) => this.serializeMfaFactor_(factor))
624 )
625 }
626
627 @InjectManager()
628 async generateAuthMfaRecoveryCodes(
629 data: AuthTypes.GenerateAuthMfaRecoveryCodesDTO,
630 @MedusaContext() sharedContext: Context = {}
631 ): Promise<AuthTypes.GenerateAuthMfaRecoveryCodesResponse> {
632 return await this.generateAuthMfaRecoveryCodes_(data, sharedContext)
633 }
634
635 @InjectTransactionManager()
636 protected async generateAuthMfaRecoveryCodes_(
637 data: AuthTypes.GenerateAuthMfaRecoveryCodesDTO,
638 @MedusaContext() sharedContext: Context = {}
639 ): Promise<AuthTypes.GenerateAuthMfaRecoveryCodesResponse> {
640 const count =
641 data.count ?? this.moduleOptions_.mfa?.recovery_code_count ?? 10
642
643 if (!Number.isInteger(count) || count < 1 || count > 50) {
644 throw new MedusaError(
645 MedusaError.Types.INVALID_DATA,
646 "Recovery code count must be between 1 and 50"
647 )
648 }
649
650 await this.authIdentityService_.retrieve(
651 data.auth_identity_id,
652 {},
653 sharedContext
654 )
655
656 const codes = await this.authMfaProviderService_.generateCodes(
657 "recovery_code",
658 {
659 auth_identity_id: data.auth_identity_id,
660 count,
661 },
662 sharedContext
663 )
664
665 return { codes }
666 }
667
668 @InjectManager()
669 async useAuthMfaRecoveryCode(
670 data: AuthTypes.UseAuthMfaRecoveryCodeDTO,
671 @MedusaContext() sharedContext: Context = {}
672 ): Promise<void> {
673 return await this.useAuthMfaRecoveryCode_(data, sharedContext)
674 }
675
676 @InjectTransactionManager()
677 protected async useAuthMfaRecoveryCode_(
678 data: AuthTypes.UseAuthMfaRecoveryCodeDTO,
679 @MedusaContext() sharedContext: Context = {}
680 ): Promise<void> {
681 const valid = await this.authMfaProviderService_.verify(
682 "recovery_code",
683 data,
684 sharedContext
685 )
686
687 if (!valid) {
688 throw new MedusaError(
689 MedusaError.Types.NOT_ALLOWED,
690 "Recovery code is invalid or already used"
691 )
692 }
693 }
694
695 @InjectManager()
696 async requestAuthVerification(
697 data: AuthTypes.RequestAuthVerificationDTO,
698 @MedusaContext() sharedContext: Context = {}
699 ): Promise<AuthTypes.RequestAuthVerificationResponse> {
700 if (!data.code_provider) {
701 throw new MedusaError(
702 MedusaError.Types.INVALID_DATA,
703 "Verification provider is required"
704 )
705 }
706
707 return await this.authVerificationProviderService_.request(
708 data.code_provider,
709 data,
710 sharedContext
711 )
712 }
713
714 @InjectManager()
715 async confirmAuthVerification(
716 data: AuthTypes.ConfirmAuthVerificationDTO,
717 @MedusaContext() sharedContext: Context = {}
718 ): Promise<AuthTypes.ConfirmAuthVerificationResponse> {
719 const codeProvider = data.code_provider ?? "token"
720
721 return await this.authVerificationProviderService_.confirm(
722 codeProvider,
723 { ...data, code_provider: codeProvider },
724 sharedContext
725 )
726 }
727
728 protected async applyMfaRequirement_(
729 response: AuthenticationResponse,
730 context: Pick<AuthTypes.CreateAuthMfaChallengeDTO, "auth_provider">
731 ): Promise<AuthenticationResponse> {
732 if (!response.success || !response.authIdentity || response.location) {
733 return response
734 }
735
736 const methods = await this.getAvailableMfaChallengeMethods_(
737 response.authIdentity.id
738 )
739
740 if (!methods.length) {
741 return response
742 }
743
744 const mfaChallenge = await this.createAuthMfaChallenge_({
745 auth_identity_id: response.authIdentity.id,
746 auth_provider: context.auth_provider ?? null,
747 })
748
749 return {
750 success: true,
751 mfaChallenge: mfaChallenge,
752 authIdentity: response.authIdentity,
753 }
754 }
755
756 protected async getAvailableMfaChallengeMethods_(
757 authIdentityId: string,
758 sharedContext: Context = {}
759 ): Promise<AuthTypes.AuthMfaChallengeMethod[]> {
760 const factors = await this.authMfaFactorService_.list(
761 {
762 auth_identity_id: authIdentityId,
763 status: "enabled",
764 },
765 { select: ["provider"] },
766 sharedContext
767 )
768
769 const factorMethods = Array.from(
770 new Set(
771 factors.map(
772 (factor) => factor.provider as AuthTypes.AuthMfaProviderMethod
773 )
774 )
775 )
776
777 if (!factorMethods.length) {
778 return factorMethods
779 }
780
781 const methods: AuthTypes.AuthMfaChallengeMethod[] = []
782
783 for (const method of factorMethods) {
784 const canVerify =
785 await this.authMfaProviderService_.canVerifyForAuthIdentity(
786 method,
787 {
788 auth_identity_id: authIdentityId,
789 },
790 sharedContext
791 )
792
793 if (canVerify) {
794 methods.push(method)
795 }
796 }
797
798 if (!methods.length) {
799 return methods
800 }
801
802 const hasRecoveryCodes =
803 await this.authMfaProviderService_.canVerifyForAuthIdentity(
804 "recovery_code",
805 {
806 auth_identity_id: authIdentityId,
807 },
808 sharedContext
809 )
810
811 if (hasRecoveryCodes) {
812 methods.push("recovery_code")
813 }
814
815 return methods
816 }
817
818 protected async serializeMfaFactor_(
819 factor: InferEntityType<typeof AuthMfaFactor>
820 ): Promise<AuthTypes.AuthMfaDTO> {
821 const serialized = await this.baseRepository_.serialize<
822 AuthTypes.AuthMfaDTO & {
823 provider_metadata?: Record<string, unknown>
824 }
825 >(factor)
826
827 delete serialized.provider_metadata
828
829 return serialized
830 }
831
832 protected assertMfaChallengeCanBeVerified_(
833 challenge: AuthTypes.AuthMfaChallengeDTO,
834 method: AuthTypes.AuthMfaChallengeMethod
835 ): void {
836 if (challenge.completed_at) {
837 throw new MedusaError(
838 MedusaError.Types.NOT_ALLOWED,
839 "MFA challenge has already been completed"
840 )
841 }
842
843 if (new Date(challenge.expires_at).getTime() <= Date.now()) {
844 throw new MedusaError(
845 MedusaError.Types.NOT_ALLOWED,
846 "MFA challenge has expired"
847 )
848 }
849
850 if (challenge.attempts >= challenge.max_attempts) {
851 throw new MedusaError(
852 MedusaError.Types.NOT_ALLOWED,
853 "MFA challenge has too many failed attempts"
854 )
855 }
856
857 if (!challenge.methods.includes(method)) {
858 throw new MedusaError(
859 MedusaError.Types.INVALID_DATA,
860 `MFA challenge does not support method "${method}"`
861 )
862 }
863 }
864
865 @InjectManager()
866 async createPasswordResetToken(
867 data: AuthTypes.CreatePasswordResetTokenDTO,
868 @MedusaContext() sharedContext: Context = {}
869 ): Promise<AuthTypes.CreatePasswordResetTokenResponse> {
870 return await this.createPasswordResetToken_(data, sharedContext)
871 }
872
873 @InjectTransactionManager()
874 protected async createPasswordResetToken_(
875 data: AuthTypes.CreatePasswordResetTokenDTO,
876 @MedusaContext() sharedContext: Context = {}
877 ): Promise<AuthTypes.CreatePasswordResetTokenResponse> {
878 const [providerIdentity] = await this.providerIdentityService_.list(
879 { provider: data.provider, entity_id: data.entity_id },
880 {},
881 sharedContext
882 )
883
884 if (!providerIdentity) {
885 throw new MedusaError(
886 MedusaError.Types.INVALID_DATA,
887 `Provider identity with entity_id ${data.entity_id} and provider ${data.provider} not found`
888 )
889 }
890
891 await this.invalidatePasswordResetTokens_(
892 providerIdentity.id,
893 sharedContext
894 )
895
896 const jti = crypto.randomUUID()
897 const expiresAt = new Date(
898 Date.now() + this.getPasswordResetTokenTtlMs_(data.ttl_seconds ?? 900)
899 )
900
901 await this.authPasswordResetTokenService_.create(
902 {
903 auth_identity_id: providerIdentity.auth_identity_id,
904 provider_identity_id: providerIdentity.id,
905 entity_id: providerIdentity.entity_id,
906 token_hash: this.hashVerificationToken_(jti),
907 expires_at: expiresAt,
908 },
909 sharedContext
910 )
911
912 return { jti, expires_at: expiresAt }
913 }
914
915 @InjectManager()
916 async consumePasswordResetToken(
917 data: AuthTypes.ConsumePasswordResetTokenDTO,
918 @MedusaContext() sharedContext: Context = {}
919 ): Promise<AuthTypes.ConsumePasswordResetTokenResponse> {
920 return await this.consumePasswordResetToken_(data, sharedContext)
921 }
922
923 @InjectTransactionManager()
924 protected async consumePasswordResetToken_(
925 data: AuthTypes.ConsumePasswordResetTokenDTO,
926 @MedusaContext() sharedContext: Context = {}
927 ): Promise<AuthTypes.ConsumePasswordResetTokenResponse> {
928 const [resetToken] = await this.authPasswordResetTokenService_.list(
929 { token_hash: this.hashVerificationToken_(data.jti) },
930 {},
931 sharedContext
932 )
933
934 if (!resetToken) {
935 throw new MedusaError(MedusaError.Types.UNAUTHORIZED, "Invalid token")
936 }
937
938 if (new Date(resetToken.expires_at).getTime() <= Date.now()) {
939 await this.authPasswordResetTokenService_.delete(
940 resetToken.id,
941 sharedContext
942 )
943 throw new MedusaError(MedusaError.Types.UNAUTHORIZED, "Invalid token")
944 }
945
946 const providerIdentity = await this.providerIdentityService_.retrieve(
947 resetToken.provider_identity_id,
948 {},
949 sharedContext
950 )
951
952 if (
953 providerIdentity.provider !== data.provider ||
954 providerIdentity.entity_id !== data.entity_id
955 ) {
956 throw new MedusaError(MedusaError.Types.UNAUTHORIZED, "Invalid token")
957 }
958
959 await this.authPasswordResetTokenService_.delete(
960 resetToken.id,
961 sharedContext
962 )
963
964 return {
965 auth_identity_id: resetToken.auth_identity_id!,
966 provider_identity_id: resetToken.provider_identity_id!,
967 entity_id: resetToken.entity_id,
968 }
969 }
970
971 protected async invalidatePasswordResetTokens_(
972 providerIdentityId: string,
973 sharedContext: Context = {}
974 ): Promise<void> {
975 const existing = await this.authPasswordResetTokenService_.list(
976 { provider_identity_id: providerIdentityId },
977 { select: ["id"] },
978 sharedContext
979 )
980 const ids = existing.map((token) => token.id)
981
982 if (ids.length) {
983 await this.authPasswordResetTokenService_.delete(ids, sharedContext)
984 }
985 }
986
987 protected getPasswordResetTokenTtlMs_(ttlSeconds: number): number {
988 if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) {
989 throw new MedusaError(
990 MedusaError.Types.INVALID_DATA,
991 "Password reset token TTL must be a positive integer"
992 )
993 }
994 return ttlSeconds * 1000
995 }
996
997 protected hashVerificationToken_(token: string): string {
998 return crypto.createHash("sha256").update(token).digest("hex")
999 }
1000
1001 protected getMfaChallengeConfig_(): {
1002 ttlSeconds: number
1003 maxAttempts: number
1004 } {
1005 const ttlSeconds = this.moduleOptions_.mfa?.challenge_ttl_seconds ?? 300
1006 const maxAttempts = this.moduleOptions_.mfa?.challenge_max_attempts ?? 5
1007
1008 if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) {
1009 throw new MedusaError(
1010 MedusaError.Types.INVALID_DATA,
1011 "MFA challenge TTL must be a positive integer"
1012 )
1013 }
1014
1015 if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
1016 throw new MedusaError(
1017 MedusaError.Types.INVALID_DATA,
1018 "MFA challenge max attempts must be a positive integer"
1019 )
1020 }
1021
1022 return {
1023 ttlSeconds,
1024 maxAttempts,
1025 }
1026 }
1027
1028 protected getMfaDisablePolicy_(): "challenge" | "session" {
1029 const policy = this.moduleOptions_.mfa?.disable_policy ?? "session"
1030
1031 if (policy !== "challenge" && policy !== "session") {
1032 throw new MedusaError(
1033 MedusaError.Types.INVALID_DATA,
1034 'MFA disable policy must be either "challenge" or "session"'
1035 )
1036 }
1037
1038 return policy
1039 }
1040
1041 protected async retrieveMfaChallenge_(
1042 id: string
1043 ): Promise<AuthTypes.AuthMfaChallengeDTO> {
1044 const challenge = await this.getCache_().get<AuthTypes.AuthMfaChallengeDTO>(
1045 this.getMfaChallengeCacheKey_(id)
1046 )
1047
1048 if (!challenge) {
1049 throw new MedusaError(
1050 MedusaError.Types.NOT_FOUND,
1051 `MFA challenge with id "${id}" was not found`
1052 )
1053 }
1054
1055 return {
1056 ...challenge,
1057 expires_at: new Date(challenge.expires_at),
1058 completed_at: challenge.completed_at
1059 ? new Date(challenge.completed_at)
1060 : null,
1061 }
1062 }
1063
1064 protected async setMfaChallenge_(
1065 challenge: AuthTypes.AuthMfaChallengeDTO,
1066 ttlSeconds?: number
1067 ): Promise<void> {
1068 const ttl =
1069 ttlSeconds ??
1070 Math.ceil((new Date(challenge.expires_at).getTime() - Date.now()) / 1000)
1071
1072 if (ttl < 1) {
1073 return
1074 }
1075
1076 await this.getCache_().set(
1077 this.getMfaChallengeCacheKey_(challenge.id),
1078 challenge,
1079 ttl
1080 )
1081 }
1082
1083 protected getMfaChallengeCacheKey_(id: string): string {
1084 return `auth:mfa:challenge:${id}`
1085 }
1086
1087 protected getCache_(): ICacheService {
1088 if (!this.cache_) {
1089 throw new MedusaError(
1090 MedusaError.Types.INVALID_ARGUMENT,
1091 "Cache module dependency is required when using MFA challenges"
1092 )
1093 }
1094
1095 return this.cache_
1096 }
1097
1098 getAuthIdentityProviderService(
1099 provider: string
1100 ): AuthIdentityProviderService {
1101 return {
1102 retrieve: async ({ entity_id }) => {
1103 const authIdentities = await this.authIdentityService_.list(
1104 {
1105 provider_identities: {
1106 entity_id,
1107 provider,
1108 },
1109 },
1110 {
1111 relations: ["provider_identities"],
1112 }
1113 )
1114
1115 if (!authIdentities.length) {
1116 throw new MedusaError(
1117 MedusaError.Types.NOT_FOUND,
1118 `AuthIdentity with entity_id "${entity_id}" not found`
1119 )
1120 }
1121
1122 if (authIdentities.length > 1) {
1123 throw new MedusaError(
1124 MedusaError.Types.INVALID_DATA,
1125 `Multiple authIdentities found for entity_id "${entity_id}"`
1126 )
1127 }
1128
1129 return await this.baseRepository_.serialize<AuthTypes.AuthIdentityDTO>(
1130 authIdentities[0]
1131 )
1132 },
1133
1134 create: async (data: {
1135 entity_id: string
1136 provider_metadata?: Record<string, unknown>
1137 user_metadata?: Record<string, unknown>
1138 }) => {
1139 const normalizedRequest = {
1140 provider_identities: [
1141 {
1142 entity_id: data.entity_id,
1143 provider_metadata: data.provider_metadata,
1144 user_metadata: data.user_metadata,
1145 provider,
1146 },
1147 ],
1148 }
1149
1150 const createdAuthIdentity = await this.authIdentityService_.create(
1151 normalizedRequest
1152 )
1153
1154 return await this.baseRepository_.serialize<AuthTypes.AuthIdentityDTO>(
1155 createdAuthIdentity
1156 )
1157 },
1158 update: async (
1159 entity_id: string,
1160 data: {
1161 provider_metadata?: Record<string, unknown>
1162 user_metadata?: Record<string, unknown>
1163 }
1164 ) => {
1165 const authIdentities = await this.authIdentityService_.list(
1166 {
1167 provider_identities: {
1168 entity_id,
1169 provider,
1170 },
1171 },
1172 {
1173 relations: ["provider_identities"],
1174 }
1175 )
1176
1177 if (!authIdentities.length) {
1178 throw new MedusaError(
1179 MedusaError.Types.NOT_FOUND,
1180 `AuthIdentity with entity_id "${entity_id}" not found`
1181 )
1182 }
1183
1184 if (authIdentities.length > 1) {
1185 throw new MedusaError(
1186 MedusaError.Types.INVALID_DATA,
1187 `Multiple authIdentities found for entity_id "${entity_id}"`
1188 )
1189 }
1190
1191 const providerIdentityData = authIdentities[0].provider_identities.find(
1192 (pi) => pi.provider === provider
1193 )
1194
1195 if (!providerIdentityData) {
1196 throw new MedusaError(
1197 MedusaError.Types.NOT_FOUND,
1198 `ProviderIdentity with entity_id "${entity_id}" not found`
1199 )
1200 }
1201
1202 const updatedProviderIdentity =
1203 await this.providerIdentityService_.update({
1204 id: providerIdentityData.id,
1205 ...data,
1206 })
1207
1208 const serializedResponse =
1209 await this.baseRepository_.serialize<AuthTypes.AuthIdentityDTO>(
1210 authIdentities[0]
1211 )
1212 const serializedProviderIdentity =
1213 await this.baseRepository_.serialize<AuthTypes.ProviderIdentityDTO>(
1214 updatedProviderIdentity
1215 )
1216
1217 serializedResponse.provider_identities = [
1218 ...(serializedResponse.provider_identities?.filter(
1219 (p) => p.provider !== provider
1220 ) ?? []),
1221 serializedProviderIdentity,
1222 ]
1223
1224 return serializedResponse
1225 },
1226 setState: async (
1227 key: string,
1228 value: Record<string, unknown>,
1229 ttlSeconds?: number
1230 ) => {
1231 if (!this.cache_) {
1232 throw new MedusaError(
1233 MedusaError.Types.INVALID_ARGUMENT,
1234 "Cache module dependency is required when using OAuth providers that require state"
1235 )
1236 }
1237
1238 // 20 minutes default. Can be overridden per call, but this is a good default.
1239 await this.cache_.set(key, value, ttlSeconds ?? 1200)
1240 },
1241 getState: async (key: string) => {
1242 if (!this.cache_) {
1243 throw new MedusaError(
1244 MedusaError.Types.INVALID_ARGUMENT,
1245 "Cache module dependency is required when using OAuth providers that require state"
1246 )
1247 }
1248
1249 const value = await this.cache_.get<Record<string, unknown>>(key)
1250
1251 // State is single-use: consume it on read so that a state value can't be replayed
1252 if (value !== null && value !== undefined) {
1253 await this.cache_.invalidate(key)
1254 }
1255
1256 return value
1257 },
1258 }
1259 }
1260 }