1 import {
2 AuthMfaProvider,
3 AuthTypes,
4 Context,
5 DAL,
6 ModulesSdkTypes,
7 } from "@medusajs/framework/types"
8 import { MedusaError } from "@medusajs/framework/utils"
9 import { AuthMfaFactor } from "@models"
10 import { TotpMfaProviderOptions } from "@types"
11 import { decryptSecret, encryptSecret } from "../../utils/mfa"
12 import {
13 generateTotpSecret,
14 generateTotpUri,
15 verifyTotpCode,
16 } from "../../utils/totp"
17
18 type InjectedDependencies = {
19 baseRepository: DAL.RepositoryService
20 authMfaFactorService: ModulesSdkTypes.IMedusaInternalService<
21 typeof AuthMfaFactor
22 >
23 }
24
25 type TotpConfig = {
26 issuer: string
27 digits: number
28 period: number
29 window: number
30 }
31
32 export class TotpMfaProvider implements AuthMfaProvider {
33 static identifier = "totp"
34
35 readonly method = TotpMfaProvider.identifier
36
37 protected baseRepository_: DAL.RepositoryService
38 protected authMfaFactorService_: ModulesSdkTypes.IMedusaInternalService<
39 typeof AuthMfaFactor
40 >
41
42 constructor(
43 { baseRepository, authMfaFactorService }: InjectedDependencies,
44 private readonly options_: TotpMfaProviderOptions = {}
45 ) {
46 this.baseRepository_ = baseRepository
47 this.authMfaFactorService_ = authMfaFactorService
48 }
49
50 async canVerifyForAuthIdentity(
51 data: { auth_identity_id: string },
52 sharedContext: Context = {}
53 ): Promise<boolean> {
54 const [factor] = await this.authMfaFactorService_.list(
55 {
56 auth_identity_id: data.auth_identity_id,
57 provider: this.method,
58 status: "enabled",
59 },
60 { select: ["id"] },
61 sharedContext
62 )
63
64 return !!factor
65 }
66
67 async start(
68 data: AuthTypes.AuthMfaStartDTO,
69 sharedContext: Context = {}
70 ): Promise<AuthTypes.AuthMfaStartResponse> {
71 const totpConfig = this.getTotpConfig_()
72 const issuer = data.issuer ?? totpConfig.issuer
73 const existingFactors = await this.authMfaFactorService_.list(
74 {
75 auth_identity_id: data.auth_identity_id,
76 provider: this.method,
77 status: ["pending", "enabled"],
78 },
79 { select: ["id"] },
80 sharedContext
81 )
82
83 if (existingFactors.length) {
84 throw new MedusaError(
85 MedusaError.Types.NOT_ALLOWED,
86 "An active TOTP factor already exists for this auth identity"
87 )
88 }
89
90 const secret = generateTotpSecret()
91 const factor = await this.authMfaFactorService_.create(
92 {
93 auth_identity_id: data.auth_identity_id,
94 provider: this.method,
95 status: "pending",
96 provider_metadata: {
97 secret: encryptSecret(secret, this.getEncryptionKey_()),
98 issuer,
99 },
100 metadata: {
101 ...(data.metadata ?? {}),
102 label: data.label ?? undefined,
103 },
104 },
105 sharedContext
106 )
107
108 return {
109 mfa: await this.serializeFactor_(factor),
110 secret,
111 otpauth_url: generateTotpUri({
112 issuer,
113 accountName: data.label ?? data.auth_identity_id,
114 secret,
115 digits: totpConfig.digits,
116 period: totpConfig.period,
117 }),
118 }
119 }
120
121 async verifySetup(
122 data: AuthTypes.AuthMfaVerifyDTO,
123 sharedContext: Context = {}
124 ): Promise<AuthTypes.AuthMfaDTO> {
125 const factor = await this.authMfaFactorService_.retrieve(
126 data.id,
127 {},
128 sharedContext
129 )
130
131 if (factor.provider !== this.method) {
132 throw new MedusaError(
133 MedusaError.Types.INVALID_DATA,
134 "Only TOTP MFA factors can be verified with this method"
135 )
136 }
137
138 if (factor.status === "disabled") {
139 throw new MedusaError(
140 MedusaError.Types.NOT_ALLOWED,
141 "Disabled MFA factors cannot be verified"
142 )
143 }
144
145 const valid = this.verifyCode_(factor, data.code)
146
147 if (!valid) {
148 throw new MedusaError(MedusaError.Types.NOT_ALLOWED, "Invalid TOTP code")
149 }
150
151 const verifiedFactor =
152 factor.status === "pending"
153 ? await this.authMfaFactorService_.update(
154 { id: factor.id, status: "enabled" },
155 sharedContext
156 )
157 : factor
158
159 return await this.serializeFactor_(verifiedFactor)
160 }
161
162 async verify(
163 data: { auth_identity_id: string; code: string },
164 sharedContext: Context = {}
165 ): Promise<boolean> {
166 const [factor] = await this.authMfaFactorService_.list(
167 {
168 auth_identity_id: data.auth_identity_id,
169 provider: this.method,
170 status: "enabled",
171 },
172 {},
173 sharedContext
174 )
175
176 return factor ? this.verifyCode_(factor, data.code) : false
177 }
178
179 protected async serializeFactor_(
180 factor: any
181 ): Promise<AuthTypes.AuthMfaDTO> {
182 const serialized = await this.baseRepository_.serialize<
183 AuthTypes.AuthMfaDTO & {
184 provider_metadata?: Record<string, unknown>
185 }
186 >(factor)
187
188 delete serialized.provider_metadata
189
190 return serialized
191 }
192
193 private verifyCode_(factor: any, code: string): boolean {
194 const totpConfig = this.getTotpConfig_()
195 const secret = decryptSecret(
196 factor.provider_metadata?.secret,
197 this.getEncryptionKey_()
198 )
199
200 return verifyTotpCode({
201 secret,
202 code,
203 digits: totpConfig.digits,
204 period: totpConfig.period,
205 window: totpConfig.window,
206 })
207 }
208
209 protected getEncryptionKey_(): string {
210 const encryptionKey = this.options_?.encryption_key
211
212 if (!encryptionKey) {
213 throw new MedusaError(
214 MedusaError.Types.INVALID_DATA,
215 "MFA encryption key is required to use MFA methods"
216 )
217 }
218
219 return encryptionKey
220 }
221
222 protected getTotpConfig_(): TotpConfig {
223 const config = {
224 issuer: this.options_?.issuer ?? "Medusa",
225 digits: this.options_?.digits ?? 6,
226 period: this.options_?.period ?? 30,
227 window: this.options_?.window ?? 1,
228 }
229
230 if (![6, 7, 8].includes(config.digits)) {
231 throw new MedusaError(
232 MedusaError.Types.INVALID_DATA,
233 "TOTP digits must be 6, 7, or 8"
234 )
235 }
236
237 if (!Number.isInteger(config.period) || config.period < 1) {
238 throw new MedusaError(
239 MedusaError.Types.INVALID_DATA,
240 "TOTP period must be a positive integer"
241 )
242 }
243
244 if (!Number.isInteger(config.window) || config.window < 0) {
245 throw new MedusaError(
246 MedusaError.Types.INVALID_DATA,
247 "TOTP window must be a non-negative integer"
248 )
249 }
250
251 return config
252 }
253 }