|
1
|
{"slug":"/references/auth/mfa-module-provider","title":"How to Create a Multi-Factor Authentication (MFA) Module Provider","frontmatter":{"slug":"/references/auth/mfa-module-provider","tags":["auth","server","how to"],"sidebar_label":"Create MFA Provider","keywords":["mfa","provider","integration"]},"toc":[{"title":"What is an MFA Module Provider?","id":"what-is-an-mfa-module-provider","level":2},{"title":"Implementation Example","id":"implementation-example","level":2},{"title":"1. Create Module Provider Directory","id":"1-create-module-provider-directory","level":2},{"title":"2. Create the MFA Module Provider Service","id":"2-create-the-mfa-module-provider-service","level":2},{"title":"constructor","id":"constructor","level":3},{"title":"Example","id":"example","level":4},{"title":"Identifier","id":"identifier","level":3},{"title":"method","id":"method","level":3},{"title":"canVerifyForAuthIdentity","id":"canverifyforauthidentity","level":3},{"title":"Example","id":"example-1","level":4},{"title":"Parameters","id":"canverifyforauthidentity-parameters","level":4},{"title":"Returns","id":"canverifyforauthidentity-returns","level":4},{"title":"start","id":"start","level":3},{"title":"Example","id":"example-2","level":4},{"title":"Parameters","id":"start-parameters","level":4},{"title":"Returns","id":"start-returns","level":4},{"title":"verify","id":"verify","level":3},{"title":"Example","id":"example-3","level":4},{"title":"Parameters","id":"verify-parameters","level":4},{"title":"Returns","id":"verify-returns","level":4},{"title":"verifySetup","id":"verifysetup","level":3},{"title":"Example","id":"example-4","level":4},{"title":"Parameters","id":"verifysetup-parameters","level":4},{"title":"Returns","id":"verifysetup-returns","level":4},{"title":"3. Create Module Definition File","id":"3-create-module-definition-file","level":2},{"title":"4. Use Module Provider","id":"4-use-module-provider","level":2},{"title":"5. Test it Out","id":"5-test-it-out","level":2}],"blocks":[{"kind":"markdown","html":"In this guide, you’ll learn how to create a Multi-Factor Authentication (MFA) Auth Module Provider and the methods you must implement in its main service."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"What is an MFA Module Provider?","id":"what-is-an-mfa-module-provider"},{"kind":"markdown","html":"An MFA Module Provider is a provider that implements the `AuthMfaProvider` interface. It allows you to integrate a new MFA provider into the Medusa Auth Module, enabling users to enroll and authenticate with MFA factors beyond the built-in TOTP provider.\n\nMedusa provides a built-in Totp MFA Module Provider that you can use out-of-the-box. You can also\noverride it or create your own custom MFA Module Provider by following the instructions in this guide."},{"kind":"note","variant":"note","title":"Creating a Recovery Code MFA Module Provider Instead?","html":"Refer to the [Create a Recovery Code MFA Module Provider](/references/recovery-code-mfa-module-provider) guide instead."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"Implementation Example","id":"implementation-example"},{"kind":"markdown","html":"As you implement your MFA Auth Module Provider, it can be useful to refer to an existing provider and how it's implemeted.\n\nIf you need to refer to an existing implementation as an example, check the [Totp MFA Module Provider in the Medusa repository](https://github.com/medusajs/medusa/blob/develop/packages/modules/auth/src/providers/mfa/totp.ts).\n\n---"},{"kind":"heading","level":2,"text":"1. Create Module Provider Directory","id":"1-create-module-provider-directory"},{"kind":"markdown","html":"Start by creating a new directory for your module provider.\n\nIf you're creating the module provider in a Medusa application, create it under the `src/modules` directory. For example, `src/modules/my-mfa`.\n\nIf you're creating the module provider in a plugin, create it under the `src/providers` directory. For example, `src/providers/my-mfa`."},{"kind":"note","variant":"note","html":"The rest of this guide always uses the `src/modules/my-mfa` directory as an example."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"2. Create the MFA Module Provider Service","id":"2-create-the-mfa-module-provider-service"},{"kind":"markdown","html":"Create the file `src/modules/my-mfa/service.ts` that holds the module provider's main service. It must implement the `AuthMfaProvider` interface imported from `@medusajs/framework/types`:\n\n```ts title=\"src/modules/my-mfa/service.ts\"\nimport { AuthMfaProvider } from \"@medusajs/framework/types\"\n\ntype Options = {\n // define any options your provider needs here\n}\n\nclass MyAuthMfaProviderService implements AuthMfaProvider {\n // TODO implement methods\n}\n\nexport default MyAuthMfaProviderService\n```"},{"kind":"heading","level":3,"text":"constructor","id":"constructor"},{"kind":"markdown","html":"The constructor allows you to access resources from the module's container using the first parameter,\nand the provider's options using the second parameter.\n\nThe Auth Module injects `authMfaFactorService` into your provider's container. This is the\ndata service for the `AuthMfaFactor` model, and you should store it as a class property so\nthe rest of the provider's methods can use it to retrieve and manage MFA factors (for\nexample, to look up enabled factors for an auth identity, or to create a pending factor\nduring setup).\n\nIf you're creating a client or establishing a connection with a third-party service, do it in the constructor."},{"kind":"heading","level":4,"text":"Example","id":"example"},{"kind":"markdown","html":"```ts\nimport { AuthMfaProvider } from \"@medusajs/framework/types\"\nimport { Logger, ModulesSdkTypes } from \"@medusajs/framework/types\"\n\ntype InjectedDependencies = {\n logger: Logger\n authMfaFactorService: ModulesSdkTypes.IMedusaInternalService<any>\n}\n\ntype Options = {\n issuer?: string\n}\n\nclass MyAuthMfaProviderService implements AuthMfaProvider {\n static identifier = \"my-mfa\"\n readonly method = MyAuthMfaProviderService.identifier\n\n protected logger_: Logger\n protected authMfaFactorService_: ModulesSdkTypes.IMedusaInternalService<any>\n protected options_: Options\n // assuming you're initializing a client\n protected client\n\n constructor (\n { logger, authMfaFactorService }: InjectedDependencies,\n options: Options\n ) {\n this.logger_ = logger\n this.authMfaFactorService_ = authMfaFactorService\n this.options_ = options\n\n // assuming you're initializing a client\n this.client = new Client(options)\n }\n\n // ...\n}\n\nexport default MyAuthMfaProviderService\n```"},{"kind":"heading","level":3,"text":"Identifier","id":"identifier"},{"kind":"markdown","html":"Every MFA auth module provider must have an `identifier` static property. The provider's ID\nwill be stored as `mfa_{identifier}`.\n\nFor example:\n\n```ts\nclass MyAuthMfaProviderService implements AuthMfaProvider {\n static identifier = \"my-mfa\"\n // ...\n}\n```"},{"kind":"heading","level":3,"text":"method","id":"method"},{"kind":"markdown","html":"The MFA method that the provider implements. For example, `totp`."},{"kind":"heading","level":3,"text":"canVerifyForAuthIdentity","id":"canverifyforauthidentity"},{"kind":"markdown","html":"This method checks whether the auth identity has an enabled factor managed by this\nprovider. The Auth Module uses it to determine whether a verification attempt should\nbe routed to the provider.\n\nUse the injected `authMfaFactorService` to look up factors for the auth identity,\nscoped to this provider's `method`. You can alternatively check with third-party services if the provider manages factors remotely."},{"kind":"heading","level":4,"text":"Example","id":"example-1"},{"kind":"markdown","html":"```ts\nclass MyAuthMfaProvider implements AuthMfaProvider {\n // ...\n async canVerifyForAuthIdentity(\n data: { auth_identity_id: string },\n sharedContext?: Context\n ): Promise<boolean> {\n const [factor] = await this.authMfaFactorService_.list(\n {\n auth_identity_id: data.auth_identity_id,\n provider: this.method,\n status: \"enabled\",\n },\n { select: [\"id\"] },\n sharedContext\n )\n\n return !!factor\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"canverifyforauthidentity-parameters"},{"kind":"typeList","sectionTitle":"canVerifyForAuthIdentity","types":[{"name":"data","type":"`object`","description":"The auth identity to check.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"auth_identity_id","type":"`string`","description":"The ID of the auth identity to check.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"sharedContext","type":"[Context](/references/types/interfaces/types.Context)","description":"A context used to share resources, such as transaction manager, between the application and the module.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"transactionManager","type":"TManager","description":"An instance of a transaction manager of type `TManager`, which is a typed parameter passed to the context to specify the type of the `transactionManager`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"manager","type":"TManager","description":"An instance of a manager, typically an entity manager, of type `TManager`, which is a typed parameter passed to the context to specify the type of the `manager`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"isolationLevel","type":"`string`","description":"A string indicating the isolation level of the context. Possible values are `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, or `SERIALIZABLE`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"enableNestedTransactions","type":"`boolean`","description":"A boolean value indicating whether nested transactions are enabled.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"eventGroupId","type":"`string`","description":"A string indicating the ID of the group to aggregate the events to be emitted at a later point.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"transactionId","type":"`string`","description":"A string indicating the ID of the current transaction.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"runId","type":"`string`","description":"A string indicating the ID of the current run.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"messageAggregator","type":"[IMessageAggregator](/references/types/interfaces/types.IMessageAggregator)","description":"An instance of a message aggregator, which is used to aggregate messages to be emitted at a later point.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"requestId","type":"`string`","description":"A string indicating the ID of the current request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"idempotencyKey","type":"`string`","description":"A string indicating the idempotencyKey of the current workflow execution.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"parentStepIdempotencyKey","type":"`string`","description":"A string indicating the idempotencyKey of the parent workflow execution.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"preventReleaseEvents","type":"`boolean`","description":"preventReleaseEvents","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"isCancelling","type":"`boolean`","description":"A boolean value indicating whether the current workflow execution is being cancelled.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"cancelingFromParentStep","type":"`boolean`","description":"Weither or not a sub workflow cancellation is being triggered from a parent step.\nIf true, the parent step will not be triggered by the sub workflow.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"canverifyforauthidentity-returns"},{"kind":"typeList","sectionTitle":"canVerifyForAuthIdentity","types":[{"name":"Promise","type":"Promise<boolean>","optional":false,"defaultValue":"","description":"Whether the provider has an enabled factor for the auth identity.","expandable":false,"children":[{"name":"boolean","type":"`boolean`","optional":false,"defaultValue":"","description":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"start","id":"start"},{"kind":"markdown","html":"This method initiates the MFA setup flow for an auth identity. It typically creates a\npending factor and returns the data the user needs in order to complete the setup, such\nas a TOTP secret and `otpauth_url` that can be rendered as a QR code.\n\nThe Auth Module uses this method when an auth identity starts enrolling into MFA with\nthe provider.\n\nTo create the factor in a pending state within Medusa, use the injected `authMfaFactorService` and\nset the `status` of the factor to `\"pending\"` when creating it. You can store any provider-specific data \nneeded for the setup in the factor's `provider_metadata`.\n\nAlternatively, you can manage the entire setup flow with third-party services if the provider manages factors remotely.\nIn that case, make sure to return any data needed to complete the setup in the response, and to create a pending factor \nin Medusa once the setup is verified in `verifySetup`."},{"kind":"heading","level":4,"text":"Example","id":"example-2"},{"kind":"markdown","html":"```ts\nclass MyAuthMfaProvider implements AuthMfaProvider {\n // ...\n async start(\n data: AuthTypes.AuthMfaStartDTO,\n sharedContext?: Context\n ): Promise<AuthTypes.AuthMfaStartResponse> {\n const secret = this.generateSecret_()\n const factor = await this.authMfaFactorService_.create(\n {\n auth_identity_id: data.auth_identity_id,\n provider: this.method,\n status: \"pending\",\n provider_metadata: { secret },\n },\n sharedContext\n )\n\n return {\n mfa: await this.serializeFactor_(factor),\n secret,\n otpauth_url: this.buildOtpAuthUrl_(secret, data),\n }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"start-parameters"},{"kind":"typeList","sectionTitle":"start","types":[{"name":"data","type":"[AuthMfaStartDTO](/references/auth/types/auth.AuthMfaStartDTO)","description":"The details of the MFA factor to set up.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"auth_identity_id","type":"`string`","description":"The ID of the authentication identity to set up multi-factor authentication (MFA) for.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider","type":"[AuthMfaProviderMethod](/references/auth/types/auth.AuthMfaProviderMethod)","description":"The multi-factor authentication (MFA) provider to use.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"label","type":"`string` \\| `null`","description":"Optional label for the multi-factor authentication (MFA) configuration.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"issuer","type":"`string`","description":"The issuer name for time-based one-time password (TOTP) apps.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"metadata","type":"`Record<string, unknown>` \\| `null`","description":"Additional metadata for the multi-factor authentication (MFA) setup.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"sharedContext","type":"[Context](/references/types/interfaces/types.Context)","description":"A context used to share resources, such as transaction manager, between the application and the module.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"transactionManager","type":"TManager","description":"An instance of a transaction manager of type `TManager`, which is a typed parameter passed to the context to specify the type of the `transactionManager`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"manager","type":"TManager","description":"An instance of a manager, typically an entity manager, of type `TManager`, which is a typed parameter passed to the context to specify the type of the `manager`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"isolationLevel","type":"`string`","description":"A string indicating the isolation level of the context. Possible values are `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, or `SERIALIZABLE`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"enableNestedTransactions","type":"`boolean`","description":"A boolean value indicating whether nested transactions are enabled.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"eventGroupId","type":"`string`","description":"A string indicating the ID of the group to aggregate the events to be emitted at a later point.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"transactionId","type":"`string`","description":"A string indicating the ID of the current transaction.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"runId","type":"`string`","description":"A string indicating the ID of the current run.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"messageAggregator","type":"[IMessageAggregator](/references/types/interfaces/types.IMessageAggregator)","description":"An instance of a message aggregator, which is used to aggregate messages to be emitted at a later point.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"requestId","type":"`string`","description":"A string indicating the ID of the current request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"idempotencyKey","type":"`string`","description":"A string indicating the idempotencyKey of the current workflow execution.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"parentStepIdempotencyKey","type":"`string`","description":"A string indicating the idempotencyKey of the parent workflow execution.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"preventReleaseEvents","type":"`boolean`","description":"preventReleaseEvents","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"isCancelling","type":"`boolean`","description":"A boolean value indicating whether the current workflow execution is being cancelled.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"cancelingFromParentStep","type":"`boolean`","description":"Weither or not a sub workflow cancellation is being triggered from a parent step.\nIf true, the parent step will not be triggered by the sub workflow.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"start-returns"},{"kind":"typeList","sectionTitle":"start","types":[{"name":"Promise","type":"Promise<[AuthMfaStartResponse](/references/auth/types/auth.AuthMfaStartResponse)>","optional":false,"defaultValue":"","description":"The data required to complete the MFA setup, including the pending factor.","expandable":false,"children":[{"name":"mfa","type":"[AuthMfaDTO](/references/auth/types/auth.AuthMfaDTO)","description":"The created multi-factor authentication (MFA) configuration.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The multi-factor authentication (MFA) configuration's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity_id","type":"`string`","description":"The ID of the authentication identity this multi-factor authentication (MFA) belongs to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authentication identity this multi-factor authentication (MFA) belongs to.","optional":true,"defaultValue":"","expandable":true,"children":[]},{"name":"provider","type":"[AuthMfaProviderMethod](/references/auth/types/auth.AuthMfaProviderMethod)","description":"The multi-factor authentication (MFA) provider used.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[AuthMfaStatus](/references/auth/types/auth.AuthMfaStatus)","description":"The status of this multi-factor authentication (MFA) configuration.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"metadata","type":"`Record<string, unknown>` \\| `null`","description":"Additional metadata for the multi-factor authentication (MFA) configuration.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"secret","type":"`string`","description":"The secret key for manual time-based one-time password (TOTP) app setup.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"otpauth_url","type":"`string`","description":"The QR code URL for easy time-based one-time password (TOTP) app setup.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"verify","id":"verify"},{"kind":"markdown","html":"This method verifies a code submitted during an MFA challenge against the auth identity's\nenabled factor for this provider (for example, by checking a TOTP code against the secret\nstored on the factor).\n\nUse the injected `authMfaFactorService` to retrieve the enabled factor for the auth identity,\nthen validate the code against the factor's provider-specific metadata.\n\nYou can alternatively verify the code with third-party services if the provider manages factors remotely."},{"kind":"heading","level":4,"text":"Example","id":"example-3"},{"kind":"markdown","html":"```ts\nclass MyAuthMfaProvider implements AuthMfaProvider {\n // ...\n async verify(\n data: { auth_identity_id: string; code: string },\n sharedContext?: Context\n ): Promise<boolean> {\n const [factor] = await this.authMfaFactorService_.list(\n {\n auth_identity_id: data.auth_identity_id,\n provider: this.method,\n status: \"enabled\",\n },\n {},\n sharedContext\n )\n\n // assuming you have a `verifyCode_` method that verifies the code\n return factor ? this.verifyCode_(factor, data.code) : false\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"verify-parameters"},{"kind":"typeList","sectionTitle":"verify","types":[{"name":"data","type":"`object`","description":"The auth identity and code to verify.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"auth_identity_id","type":"`string`","description":"The ID of the auth identity to verify the code for.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The MFA code to verify.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"sharedContext","type":"[Context](/references/types/interfaces/types.Context)","description":"A context used to share resources, such as transaction manager, between the application and the module.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"transactionManager","type":"TManager","description":"An instance of a transaction manager of type `TManager`, which is a typed parameter passed to the context to specify the type of the `transactionManager`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"manager","type":"TManager","description":"An instance of a manager, typically an entity manager, of type `TManager`, which is a typed parameter passed to the context to specify the type of the `manager`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"isolationLevel","type":"`string`","description":"A string indicating the isolation level of the context. Possible values are `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, or `SERIALIZABLE`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"enableNestedTransactions","type":"`boolean`","description":"A boolean value indicating whether nested transactions are enabled.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"eventGroupId","type":"`string`","description":"A string indicating the ID of the group to aggregate the events to be emitted at a later point.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"transactionId","type":"`string`","description":"A string indicating the ID of the current transaction.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"runId","type":"`string`","description":"A string indicating the ID of the current run.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"messageAggregator","type":"[IMessageAggregator](/references/types/interfaces/types.IMessageAggregator)","description":"An instance of a message aggregator, which is used to aggregate messages to be emitted at a later point.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"requestId","type":"`string`","description":"A string indicating the ID of the current request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"idempotencyKey","type":"`string`","description":"A string indicating the idempotencyKey of the current workflow execution.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"parentStepIdempotencyKey","type":"`string`","description":"A string indicating the idempotencyKey of the parent workflow execution.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"preventReleaseEvents","type":"`boolean`","description":"preventReleaseEvents","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"isCancelling","type":"`boolean`","description":"A boolean value indicating whether the current workflow execution is being cancelled.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"cancelingFromParentStep","type":"`boolean`","description":"Weither or not a sub workflow cancellation is being triggered from a parent step.\nIf true, the parent step will not be triggered by the sub workflow.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"verify-returns"},{"kind":"typeList","sectionTitle":"verify","types":[{"name":"Promise","type":"Promise<boolean>","optional":false,"defaultValue":"","description":"Whether the code was successfully verified.","expandable":false,"children":[{"name":"boolean","type":"`boolean`","optional":false,"defaultValue":"","description":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"verifySetup","id":"verifysetup"},{"kind":"markdown","html":"This method verifies a code submitted during the MFA setup flow and, if valid, activates\nthe pending factor.\n\nThe Auth Module uses this method after [start](/references/auth/mfa-module-provider#start) to confirm that the user has correctly\nconfigured their authenticator before the factor is enabled.\n\nYou can retrieve the pending factor created in `start` using the injected `authMfaFactorService`, \nverify the submitted code against the provider-specific metadata stored on the factor, and \nthen update the factor's status to `\"enabled\"` if the verification is successful.\n\nAlternatively, you can manage the entire setup flow with third-party services if the provider manages factors remotely.\nIn that case, make sure to verify the setup with the third-party service in this method, and to update the factor's status \nto `\"enabled\"` in Medusa once the setup is verified."},{"kind":"heading","level":4,"text":"Example","id":"example-4"},{"kind":"markdown","html":"```ts\nclass MyAuthMfaProvider implements AuthMfaProvider {\n // ...\n async verifySetup(\n data: AuthTypes.AuthMfaVerifyDTO,\n sharedContext?: Context\n ): Promise<AuthTypes.AuthMfaDTO> {\n const factor = await this.authMfaFactorService_.retrieve(\n data.id,\n {},\n sharedContext\n )\n\n if (!this.verifyCode_(factor, data.code)) {\n throw new Error(\"Invalid MFA code\")\n }\n\n const enabled = await this.authMfaFactorService_.update(\n { id: factor.id, status: \"enabled\" },\n sharedContext\n )\n\n return await this.serializeFactor_(enabled)\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"verifysetup-parameters"},{"kind":"typeList","sectionTitle":"verifySetup","types":[{"name":"data","type":"[AuthMfaVerifyDTO](/references/auth/types/auth.AuthMfaVerifyDTO)","description":"The details of the factor and the code to verify.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID of the multi-factor authentication (MFA) configuration to verify.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity_id","type":"`string`","description":"The ID of the authentication identity this multi-factor authentication (MFA) belongs to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"code","type":"`string`","description":"The verification code from the multi-factor authentication (MFA) provider.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"name":"sharedContext","type":"[Context](/references/types/interfaces/types.Context)","description":"A context used to share resources, such as transaction manager, between the application and the module.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"transactionManager","type":"TManager","description":"An instance of a transaction manager of type `TManager`, which is a typed parameter passed to the context to specify the type of the `transactionManager`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"manager","type":"TManager","description":"An instance of a manager, typically an entity manager, of type `TManager`, which is a typed parameter passed to the context to specify the type of the `manager`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"isolationLevel","type":"`string`","description":"A string indicating the isolation level of the context. Possible values are `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, or `SERIALIZABLE`.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"enableNestedTransactions","type":"`boolean`","description":"A boolean value indicating whether nested transactions are enabled.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"eventGroupId","type":"`string`","description":"A string indicating the ID of the group to aggregate the events to be emitted at a later point.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"transactionId","type":"`string`","description":"A string indicating the ID of the current transaction.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"runId","type":"`string`","description":"A string indicating the ID of the current run.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"messageAggregator","type":"[IMessageAggregator](/references/types/interfaces/types.IMessageAggregator)","description":"An instance of a message aggregator, which is used to aggregate messages to be emitted at a later point.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"requestId","type":"`string`","description":"A string indicating the ID of the current request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"idempotencyKey","type":"`string`","description":"A string indicating the idempotencyKey of the current workflow execution.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"parentStepIdempotencyKey","type":"`string`","description":"A string indicating the idempotencyKey of the parent workflow execution.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"preventReleaseEvents","type":"`boolean`","description":"preventReleaseEvents","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"isCancelling","type":"`boolean`","description":"A boolean value indicating whether the current workflow execution is being cancelled.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"cancelingFromParentStep","type":"`boolean`","description":"Weither or not a sub workflow cancellation is being triggered from a parent step.\nIf true, the parent step will not be triggered by the sub workflow.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"verifysetup-returns"},{"kind":"typeList","sectionTitle":"verifySetup","types":[{"name":"Promise","type":"Promise<[AuthMfaDTO](/references/auth/types/auth.AuthMfaDTO)>","optional":false,"defaultValue":"","description":"The verified (and now enabled) MFA factor.","expandable":false,"children":[{"name":"id","type":"`string`","description":"The multi-factor authentication (MFA) configuration's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity_id","type":"`string`","description":"The ID of the authentication identity this multi-factor authentication (MFA) belongs to.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authentication identity this multi-factor authentication (MFA) belongs to.","optional":true,"defaultValue":"","expandable":true,"children":[{"name":"id","type":"`string`","description":"The ID of the auth identity.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider_identities","type":"[ProviderIdentityDTO](/references/auth/interfaces/auth.ProviderIdentityDTO)[]","description":"The list of provider identities linked to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"app_metadata","type":"`Record<string, unknown>`","description":"Holds information related to the actor IDs tied to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"provider","type":"[AuthMfaProviderMethod](/references/auth/types/auth.AuthMfaProviderMethod)","description":"The multi-factor authentication (MFA) provider used.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"status","type":"[AuthMfaStatus](/references/auth/types/auth.AuthMfaStatus)","description":"The status of this multi-factor authentication (MFA) configuration.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"metadata","type":"`Record<string, unknown>` \\| `null`","description":"Additional metadata for the multi-factor authentication (MFA) configuration.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"3. Create Module Definition File","id":"3-create-module-definition-file"},{"kind":"markdown","html":"Create the file `src/modules/my-mfa/index.ts` with the following content:\n\n```ts title=\"src/modules/my-mfa/index.ts\"\nimport { ModuleProvider, Modules } from \"@medusajs/framework/utils\"\nimport MyAuthMfaProviderService from \"./service\"\n\nexport default ModuleProvider(Modules.AUTH, {\n services: [MyAuthMfaProviderService],\n})\n```\n\nThis exports the module provider's definition, indicating that the `MyAuthMfaProviderService` is the module provider's service.\n\n---"},{"kind":"heading","level":2,"text":"4. Use Module Provider","id":"4-use-module-provider"},{"kind":"markdown","html":"To use your MFA Module Provider, add it to the `mfa.providers` array of the Auth Module in `medusa-config.ts`:\n\n```ts title=\"medusa-config.ts\"\nmodule.exports = defineConfig({\n // ...\n modules: [\n {\n resolve: \"@medusajs/medusa/auth\",\n dependencies: [Modules.CACHE, ContainerRegistrationKeys.LOGGER],\n options: {\n mfa: {\n encryption_key: process.env.AUTH_MFA_ENCRYPTION_KEY,\n providers: [\n {\n // if module provider is in a plugin, use `plugin-name/providers/my-mfa`\n resolve: \"./src/modules/my-mfa\",\n // if you're overriding the totp provider, set this to \"totp\"\n id: \"my-mfa\",\n options: {\n // provider options...\n }\n }\n ]\n },\n providers: [\n {\n resolve: \"@medusajs/medusa/auth-emailpass\",\n id: \"emailpass\",\n },\n ],\n },\n },\n ]\n})\n```\n\n\n---"},{"kind":"heading","level":2,"text":"5. Test it Out","id":"5-test-it-out"},{"kind":"markdown","html":"There are two ways to test out your MFA Module Provider:\n\n1. **Custom Provider:** Use it with the MFA API routes to enroll and authenticate users with MFA. See the [MFA guide](/commerce-modules/auth/mfa) for more details.\n2. **Overriding Totp Provider:** If your provider overrides the Totp provider, you can test it out in the admin dashboard by managing your profile's [two-factor authentication settings from the admin dashboard](!user-guide!/settings/profile#manage-two-factor-authentication)."}]} |