1 import { AuthTypes, IAuthModuleService } from "@medusajs/framework/types"
2 import { Modules } from "@medusajs/framework/utils"
3 import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
4 import { resolve } from "path"
5 import { createAuthIdentities } from "../../__fixtures__/auth-identity"
6 import { generateTotpCode } from "../../../src/utils/totp"
7
8 jest.setTimeout(30000)
9
10 const mockCache = new Map()
11 const inMemoryCache = {
12 get: async (key: string) => mockCache.get(key) ?? null,
13 set: async (key: string, data: any) => {
14 mockCache.set(key, data)
15 },
16 invalidate: async (key: string) => {
17 mockCache.delete(key)
18 },
19 }
20
21 class TestMfaProvider {
22 static identifier = "test_mfa"
23
24 readonly method = TestMfaProvider.identifier
25
26 constructor(
27 _container: unknown,
28 private readonly options_: Record<string, unknown> = {}
29 ) {}
30
31 async canVerifyForAuthIdentity(): Promise<boolean> {
32 return true
33 }
34
35 async verify(data: { code: string }): Promise<boolean> {
36 return data.code === "123456"
37 }
38
39 async start(
40 data: AuthTypes.AuthMfaStartDTO
41 ): Promise<AuthTypes.AuthMfaStartResponse> {
42 return {
43 mfa: {
44 id: "test-mfa-factor",
45 auth_identity_id: data.auth_identity_id,
46 provider: this.method,
47 status: "pending",
48 metadata: {
49 option: this.options_.option,
50 },
51 },
52 secret: "test-secret",
53 }
54 }
55
56 async verifySetup(
57 data: AuthTypes.AuthMfaVerifyDTO
58 ): Promise<AuthTypes.AuthMfaDTO> {
59 return {
60 id: data.id,
61 provider: this.method,
62 status: "enabled",
63 }
64 }
65 }
66
67 moduleIntegrationTestRunner<IAuthModuleService>({
68 moduleName: Modules.AUTH,
69 moduleOptions: {
70 mfa: {
71 encryption_key: "test-mfa-encryption-key",
72 recovery_code_count: 2,
73 challenge_ttl_seconds: 60,
74 challenge_max_attempts: 2,
75 providers: [
76 {
77 id: "totp",
78 options: {
79 issuer: "Medusa Test",
80 window: 0,
81 },
82 },
83 ],
84 },
85 },
86 moduleDependencies: [Modules.CACHE],
87 injectedDependencies: {
88 [Modules.CACHE]: inMemoryCache,
89 },
90 testSuite: ({ MikroOrmWrapper, service }) => {
91 describe("AuthModuleService - MFA", () => {
92 beforeEach(async () => {
93 jest.spyOn(Date, "now").mockReturnValue(1_710_000_000_000)
94 await createAuthIdentities(service)
95 })
96
97 afterEach(() => {
98 mockCache.clear()
99 jest.restoreAllMocks()
100 })
101
102 it("provisions a pending TOTP factor without exposing the encrypted secret", async () => {
103 const setup = await service.startAuthMfa({
104 auth_identity_id: "test-id",
105 provider: "totp",
106 label: "Authenticator app",
107 })
108
109 expect(setup).toEqual({
110 mfa: expect.objectContaining({
111 auth_identity_id: "test-id",
112 metadata: expect.objectContaining({
113 label: "Authenticator app",
114 }),
115 provider: "totp",
116 status: "pending",
117 }),
118 otpauth_url: expect.stringContaining("otpauth://totp/"),
119 secret: expect.any(String),
120 })
121 expect(setup.otpauth_url).toContain("Medusa%20Test:Authenticator%20app")
122 expect(setup.otpauth_url).toContain("issuer=Medusa%20Test")
123 expect(setup.mfa).not.toHaveProperty("secret")
124 expect(setup.mfa).not.toHaveProperty("provider_metadata")
125
126 const [storedFactor] = await MikroOrmWrapper.forkManager().execute(
127 "select provider_metadata from auth_mfa_factor where id = ?",
128 [setup.mfa.id]
129 )
130 const providerMetadata =
131 typeof storedFactor.provider_metadata === "string"
132 ? JSON.parse(storedFactor.provider_metadata)
133 : storedFactor.provider_metadata
134
135 expect(providerMetadata.secret).not.toEqual(setup.secret)
136 expect(providerMetadata.secret).toMatch(/^v1:/)
137 expect(providerMetadata.issuer).toEqual("Medusa Test")
138
139 const factors = await service.listAuthMfa({
140 auth_identity_id: "test-id",
141 })
142
143 expect(factors).toEqual([
144 expect.objectContaining({
145 id: setup.mfa.id,
146 provider: "totp",
147 status: "pending",
148 }),
149 ])
150 expect(factors[0]).not.toHaveProperty("secret")
151 expect(factors[0]).not.toHaveProperty("provider_metadata")
152 })
153
154 it("retrieves an MFA factor without exposing provider metadata", async () => {
155 const setup = await service.startAuthMfa({
156 auth_identity_id: "test-id",
157 provider: "totp",
158 })
159
160 const retrievedById = await service.retrieveAuthMfa(setup.mfa.id)
161
162 expect(retrievedById).toEqual(
163 expect.objectContaining({
164 id: setup.mfa.id,
165 auth_identity_id: "test-id",
166 provider: "totp",
167 status: "pending",
168 })
169 )
170 expect(retrievedById).not.toHaveProperty("secret")
171 expect(retrievedById).not.toHaveProperty("provider_metadata")
172
173 const retrieved = await service.retrieveAuthMfa({
174 id: setup.mfa.id,
175 auth_identity_id: "test-id",
176 })
177
178 expect(retrieved).toEqual(
179 expect.objectContaining({
180 id: setup.mfa.id,
181 auth_identity_id: "test-id",
182 provider: "totp",
183 status: "pending",
184 })
185 )
186 expect(retrieved).not.toHaveProperty("secret")
187 expect(retrieved).not.toHaveProperty("provider_metadata")
188
189 await expect(
190 service.retrieveAuthMfa({
191 id: setup.mfa.id,
192 auth_identity_id: "test-id-1",
193 })
194 ).rejects.toThrow(`MFA factor with id "${setup.mfa.id}" was not found`)
195 })
196
197 it("enables a pending TOTP factor after a valid code", async () => {
198 const setup = await service.startAuthMfa({
199 auth_identity_id: "test-id",
200 provider: "totp",
201 })
202 const code = generateTotpCode({
203 secret: setup.secret,
204 timestamp: Date.now(),
205 })
206
207 const factor = await service.verifyAuthMfa({
208 id: setup.mfa.id,
209 code,
210 })
211
212 expect(factor).toEqual(
213 expect.objectContaining({
214 id: setup.mfa.id,
215 provider: "totp",
216 status: "enabled",
217 })
218 )
219 expect(factor).not.toHaveProperty("secret")
220 expect(factor).not.toHaveProperty("provider_metadata")
221 })
222
223 it("verifies setup only for factors owned by the auth identity", async () => {
224 const setup = await service.startAuthMfa({
225 auth_identity_id: "test-id",
226 provider: "totp",
227 })
228 const code = generateTotpCode({
229 secret: setup.secret,
230 timestamp: Date.now(),
231 })
232
233 await expect(
234 service.verifyAuthMfa({
235 id: setup.mfa.id,
236 auth_identity_id: "test-id-1",
237 code,
238 })
239 ).rejects.toThrow(`MFA factor with id "${setup.mfa.id}" was not found`)
240 })
241
242 it("rejects invalid TOTP codes", async () => {
243 const setup = await service.startAuthMfa({
244 auth_identity_id: "test-id",
245 provider: "totp",
246 })
247
248 await expect(
249 service.verifyAuthMfa({
250 id: setup.mfa.id,
251 code: "000000",
252 })
253 ).rejects.toThrow("Invalid TOTP code")
254 })
255
256 it("prevents duplicate active TOTP factors", async () => {
257 await service.startAuthMfa({
258 auth_identity_id: "test-id",
259 provider: "totp",
260 })
261
262 await expect(
263 service.startAuthMfa({
264 auth_identity_id: "test-id",
265 provider: "totp",
266 })
267 ).rejects.toThrow(
268 "An active TOTP factor already exists for this auth identity"
269 )
270 })
271
272 it("generates hashed single-use recovery codes", async () => {
273 const { codes } = await service.generateAuthMfaRecoveryCodes({
274 auth_identity_id: "test-id",
275 })
276
277 expect(codes).toHaveLength(2)
278
279 const storedCodes = await MikroOrmWrapper.forkManager().execute(
280 "select * from auth_mfa_recovery_code where auth_identity_id = ? and deleted_at is null",
281 ["test-id"]
282 )
283
284 expect(storedCodes).toHaveLength(2)
285 expect(storedCodes.map((code) => code.code_hash)).not.toContain(
286 codes[0]
287 )
288 expect(storedCodes.every((code) => !("salt" in code))).toBe(true)
289
290 await service.useAuthMfaRecoveryCode({
291 auth_identity_id: "test-id",
292 code: codes[0],
293 })
294
295 const remainingCodes = await MikroOrmWrapper.forkManager().execute(
296 "select id from auth_mfa_recovery_code where auth_identity_id = ? and deleted_at is null",
297 ["test-id"]
298 )
299
300 expect(remainingCodes).toHaveLength(1)
301
302 await expect(
303 service.useAuthMfaRecoveryCode({
304 auth_identity_id: "test-id",
305 code: codes[0],
306 })
307 ).rejects.toThrow("Recovery code is invalid or already used")
308 })
309
310 it("disables MFA factors", async () => {
311 const setup = await service.startAuthMfa({
312 auth_identity_id: "test-id",
313 provider: "totp",
314 })
315
316 const code = generateTotpCode({
317 secret: setup.secret,
318 timestamp: Date.now(),
319 })
320
321 await service.verifyAuthMfa({
322 id: setup.mfa.id,
323 code,
324 })
325
326 const factor = await service.disableAuthMfa({
327 id: setup.mfa.id,
328 method: "totp",
329 code,
330 })
331
332 expect(factor).toEqual(
333 expect.objectContaining({
334 id: setup.mfa.id,
335 status: "disabled",
336 })
337 )
338 })
339
340 it("disables MFA factors without an MFA challenge by default", async () => {
341 const setup = await service.startAuthMfa({
342 auth_identity_id: "test-id",
343 provider: "totp",
344 })
345 const code = generateTotpCode({
346 secret: setup.secret,
347 timestamp: Date.now(),
348 })
349
350 await service.verifyAuthMfa({
351 id: setup.mfa.id,
352 code,
353 })
354
355 const factor = await service.disableAuthMfa({
356 id: setup.mfa.id,
357 })
358
359 expect(factor).toEqual(
360 expect.objectContaining({
361 id: setup.mfa.id,
362 status: "disabled",
363 })
364 )
365 })
366
367 it("creates an MFA challenge for enabled methods", async () => {
368 const setup = await service.startAuthMfa({
369 auth_identity_id: "test-id",
370 provider: "totp",
371 })
372 const code = generateTotpCode({
373 secret: setup.secret,
374 timestamp: Date.now(),
375 })
376
377 await service.verifyAuthMfa({
378 id: setup.mfa.id,
379 code,
380 })
381 await service.generateAuthMfaRecoveryCodes({
382 auth_identity_id: "test-id",
383 })
384
385 const challenge = await service.createAuthMfaChallenge({
386 auth_identity_id: "test-id",
387 metadata: {
388 source: "auth",
389 },
390 })
391
392 expect(challenge).toEqual(
393 expect.objectContaining({
394 auth_identity_id: "test-id",
395 attempts: 0,
396 max_attempts: 2,
397 methods: ["totp", "recovery_code"],
398 completed_at: null,
399 metadata: {
400 source: "auth",
401 },
402 })
403 )
404 expect(new Date(challenge.expires_at).getTime()).toBe(
405 Date.now() + 60_000
406 )
407 })
408
409 it("does not create an MFA challenge from recovery codes alone", async () => {
410 await service.generateAuthMfaRecoveryCodes({
411 auth_identity_id: "test-id",
412 })
413
414 await expect(
415 service.createAuthMfaChallenge({
416 auth_identity_id: "test-id",
417 })
418 ).rejects.toThrow("Auth identity does not have any enabled MFA methods")
419 })
420
421 it("completes an MFA challenge with a valid method code", async () => {
422 const setup = await service.startAuthMfa({
423 auth_identity_id: "test-id",
424 provider: "totp",
425 })
426 const code = generateTotpCode({
427 secret: setup.secret,
428 timestamp: Date.now(),
429 })
430
431 await service.verifyAuthMfa({
432 id: setup.mfa.id,
433 code,
434 })
435 const challenge = await service.createAuthMfaChallenge({
436 auth_identity_id: "test-id",
437 })
438
439 const completed = await service.verifyAuthMfaChallenge({
440 id: challenge.id,
441 method: "totp",
442 code,
443 })
444
445 expect(completed).toEqual(
446 expect.objectContaining({
447 id: challenge.id,
448 attempts: 0,
449 completed_at: expect.any(Date),
450 })
451 )
452
453 await expect(
454 service.verifyAuthMfaChallenge({
455 id: challenge.id,
456 method: "totp",
457 code,
458 })
459 ).rejects.toThrow("MFA challenge has already been completed")
460 })
461
462 it("tracks failed MFA challenge attempts", async () => {
463 const setup = await service.startAuthMfa({
464 auth_identity_id: "test-id",
465 provider: "totp",
466 })
467 const code = generateTotpCode({
468 secret: setup.secret,
469 timestamp: Date.now(),
470 })
471
472 await service.verifyAuthMfa({
473 id: setup.mfa.id,
474 code,
475 })
476 const challenge = await service.createAuthMfaChallenge({
477 auth_identity_id: "test-id",
478 })
479
480 await expect(
481 service.verifyAuthMfaChallenge({
482 id: challenge.id,
483 method: "totp",
484 code: "000000",
485 })
486 ).rejects.toThrow("Invalid MFA challenge code")
487
488 await expect(
489 service.verifyAuthMfaChallenge({
490 id: challenge.id,
491 method: "totp",
492 code: "000000",
493 })
494 ).rejects.toThrow("MFA challenge has too many failed attempts")
495
496 await expect(
497 service.verifyAuthMfaChallenge({
498 id: challenge.id,
499 method: "totp",
500 code,
501 })
502 ).rejects.toThrow("MFA challenge has too many failed attempts")
503 })
504
505 it("rejects expired MFA challenges", async () => {
506 const setup = await service.startAuthMfa({
507 auth_identity_id: "test-id",
508 provider: "totp",
509 })
510 const code = generateTotpCode({
511 secret: setup.secret,
512 timestamp: Date.now(),
513 })
514
515 await service.verifyAuthMfa({
516 id: setup.mfa.id,
517 code,
518 })
519 const challenge = await service.createAuthMfaChallenge({
520 auth_identity_id: "test-id",
521 })
522
523 jest.spyOn(Date, "now").mockReturnValue(1_710_000_061_000)
524
525 await expect(
526 service.verifyAuthMfaChallenge({
527 id: challenge.id,
528 method: "totp",
529 code,
530 })
531 ).rejects.toThrow("MFA challenge has expired")
532 })
533 })
534 },
535 })
536
537 moduleIntegrationTestRunner<IAuthModuleService>({
538 moduleName: Modules.AUTH,
539 moduleOptions: {
540 mfa: {
541 encryption_key: "test-mfa-encryption-key",
542 disable_policy: "challenge",
543 },
544 },
545 testSuite: ({ service }) => {
546 describe("AuthModuleService - challenge MFA disable policy", () => {
547 beforeEach(async () => {
548 await createAuthIdentities(service)
549 })
550
551 it("requires an MFA challenge when disabling MFA factors", async () => {
552 const setup = await service.startAuthMfa({
553 auth_identity_id: "test-id",
554 provider: "totp",
555 })
556 const code = generateTotpCode({
557 secret: setup.secret,
558 timestamp: Date.now(),
559 })
560
561 await service.verifyAuthMfa({
562 id: setup.mfa.id,
563 code,
564 })
565
566 await expect(
567 service.disableAuthMfa({
568 id: setup.mfa.id,
569 })
570 ).rejects.toThrow("MFA verification code is required to disable MFA")
571 })
572
573 it("allows cancelling pending MFA setup without a challenge", async () => {
574 const setup = await service.startAuthMfa({
575 auth_identity_id: "test-id",
576 provider: "totp",
577 })
578
579 await expect(service.retrieveAuthMfa(setup.mfa.id)).resolves.toEqual(
580 expect.objectContaining({
581 status: "pending",
582 })
583 )
584
585 const factor = await service.disableAuthMfa({
586 id: setup.mfa.id,
587 })
588
589 expect(factor).toEqual(
590 expect.objectContaining({
591 id: setup.mfa.id,
592 status: "disabled",
593 })
594 )
595 })
596 })
597 },
598 })
599
600 moduleIntegrationTestRunner<IAuthModuleService>({
601 moduleName: Modules.AUTH,
602 moduleOptions: {
603 providers: [
604 {
605 resolve: resolve(
606 process.cwd() +
607 "/integration-tests/__fixtures__/providers/default-provider"
608 ),
609 id: "plaintextpass",
610 },
611 ],
612 mfa: {
613 encryption_key: "test-mfa-encryption-key",
614 challenge_ttl_seconds: 60,
615 challenge_max_attempts: 2,
616 },
617 },
618 moduleDependencies: [Modules.CACHE],
619 injectedDependencies: {
620 [Modules.CACHE]: inMemoryCache,
621 },
622 testSuite: ({ service }) => {
623 describe("AuthModuleService - MFA authentication flow", () => {
624 beforeEach(async () => {
625 jest.spyOn(Date, "now").mockReturnValue(1_710_000_000_000)
626 await service.createAuthIdentities({
627 provider_identities: [
628 {
629 entity_id: "test@admin.com",
630 provider: "plaintextpass",
631 provider_metadata: {
632 password: "plaintext",
633 },
634 },
635 ],
636 })
637 })
638
639 afterEach(() => {
640 mockCache.clear()
641 jest.restoreAllMocks()
642 })
643
644 it("returns the auth identity when MFA is not enabled", async () => {
645 const result = await service.authenticate("plaintextpass", {
646 body: {
647 email: "test@admin.com",
648 password: "plaintext",
649 },
650 })
651
652 expect(result).toEqual(
653 expect.objectContaining({
654 success: true,
655 authIdentity: expect.objectContaining({
656 provider_identities: [
657 expect.objectContaining({ entity_id: "test@admin.com" }),
658 ],
659 }),
660 })
661 )
662 expect(result.mfaChallenge).toBeUndefined()
663 })
664
665 it("returns an MFA challenge instead of the auth identity when MFA is enabled", async () => {
666 const initial = await service.authenticate("plaintextpass", {
667 body: {
668 email: "test@admin.com",
669 password: "plaintext",
670 },
671 })
672 const setup = await service.startAuthMfa({
673 auth_identity_id: initial.authIdentity!.id,
674 provider: "totp",
675 })
676 const code = generateTotpCode({
677 secret: setup.secret,
678 timestamp: Date.now(),
679 })
680
681 await service.verifyAuthMfa({
682 id: setup.mfa.id,
683 code,
684 })
685
686 const result = await service.authenticate("plaintextpass", {
687 body: {
688 email: "test@admin.com",
689 password: "plaintext",
690 },
691 })
692
693 expect(result).toEqual(
694 expect.objectContaining({
695 success: true,
696 mfaChallenge: expect.objectContaining({
697 auth_identity_id: initial.authIdentity!.id,
698 auth_provider: "plaintextpass",
699 methods: ["totp"],
700 attempts: 0,
701 max_attempts: 2,
702 }),
703 })
704 )
705 })
706 })
707 },
708 })
709
710 moduleIntegrationTestRunner<IAuthModuleService>({
711 moduleName: Modules.AUTH,
712 moduleOptions: {
713 mfa: {
714 providers: [
715 {
716 resolve: {
717 services: [TestMfaProvider],
718 },
719 id: TestMfaProvider.identifier,
720 options: {
721 option: "configured",
722 },
723 },
724 ],
725 },
726 },
727 testSuite: ({ service }) => {
728 describe("AuthModuleService - custom MFA providers", () => {
729 beforeEach(async () => {
730 await createAuthIdentities(service)
731 })
732
733 it("provisions factors through configured MFA providers", async () => {
734 const setup = await service.startAuthMfa({
735 auth_identity_id: "test-id",
736 provider: "test_mfa",
737 })
738
739 expect(setup).toEqual({
740 mfa: {
741 id: "test-mfa-factor",
742 auth_identity_id: "test-id",
743 provider: "test_mfa",
744 status: "pending",
745 metadata: {
746 option: "configured",
747 },
748 },
749 secret: "test-secret",
750 })
751 })
752 })
753 },
754 })
755
756 moduleIntegrationTestRunner<IAuthModuleService>({
757 moduleName: Modules.AUTH,
758 moduleOptions: {},
759 testSuite: ({ service }) => {
760 describe("AuthModuleService - MFA configuration", () => {
761 beforeEach(async () => {
762 await createAuthIdentities(service)
763 })
764
765 it("requires an encryption key before provisioning MFA factors", async () => {
766 await expect(
767 service.startAuthMfa({
768 auth_identity_id: "test-id",
769 provider: "totp",
770 })
771 ).rejects.toThrow("MFA encryption key is required to use MFA methods")
772 })
773 })
774 },
775 })