1 import {
2 AuthenticationInput,
3 AuthenticationResponse,
4 AuthIdentityProviderService,
5 Logger,
6 } from "@medusajs/framework/types"
7 import {
8 AbstractAuthModuleProvider,
9 MedusaError,
10 } from "@medusajs/framework/utils"
11 import { MedusaCloudAuthProviderOptions } from "@types"
12 import crypto from "crypto"
13 import jwt, { type JwtHeader, type JwtPayload } from "jsonwebtoken"
14 import jwksClient, { JwksClient } from "jwks-rsa"
15 import { promisify } from "util"
16
17 const verifyJwt = promisify<
18 string,
19 jwt.Secret | jwt.GetPublicKeyOrSecret,
20 jwt.VerifyOptions,
21 JwtPayload | string | undefined
22 >(jwt.verify)
23
24 type InjectedDependencies = {
25 logger: Logger
26 }
27
28 export class MedusaCloudAuthService extends AbstractAuthModuleProvider {
29 static identifier = "cloud"
30 static DISPLAY_NAME = "Medusa Cloud Authentication"
31
32 protected config_: MedusaCloudAuthProviderOptions
33 protected logger_: Logger
34 protected jwks_?: JwksClient
35
36 constructor(
37 { logger }: InjectedDependencies,
38 options: MedusaCloudAuthProviderOptions
39 ) {
40 // @ts-ignore
41 super(...arguments)
42 this.config_ = options
43 this.logger_ = logger
44
45 if (!options.oauth_jwks_uri) {
46 throw new MedusaError(
47 MedusaError.Types.INVALID_DATA,
48 "Medusa Cloud auth provider requires 'oauth_jwks_uri' option to be set"
49 )
50 }
51
52 if (!options.oauth_audience) {
53 throw new MedusaError(
54 MedusaError.Types.INVALID_DATA,
55 "Medusa Cloud auth provider requires 'oauth_audience' option to be set"
56 )
57 }
58
59 this.jwks_ = jwksClient({
60 jwksUri: options.oauth_jwks_uri,
61 cache: true,
62 rateLimit: true,
63 })
64 }
65
66 protected getSigningKey_ = (
67 header: JwtHeader,
68 callback: (err: Error | null, key?: string) => void
69 ) => {
70 if (!this.jwks_) {
71 callback(
72 new Error(
73 "Medusa Cloud auth provider is missing required 'oauth_jwks_uri' option; cannot verify id_token signature"
74 )
75 )
76 return
77 }
78 if (!header.kid) {
79 callback(new Error("ID token is missing 'kid' header"))
80 return
81 }
82 this.jwks_.getSigningKey(header.kid, (err, key) => {
83 if (err || !key) {
84 callback(err ?? new Error("Unable to resolve signing key"))
85 return
86 }
87 callback(null, key.getPublicKey())
88 })
89 }
90
91 async register(_): Promise<AuthenticationResponse> {
92 throw new MedusaError(
93 MedusaError.Types.NOT_ALLOWED,
94 "Medusa Cloud does not support registration. Use method `authenticate` instead."
95 )
96 }
97
98 async authenticate(
99 req: AuthenticationInput,
100 authIdentityService: AuthIdentityProviderService
101 ): Promise<AuthenticationResponse> {
102 const query: Record<string, string> = req.query ?? {}
103 const body: Record<string, string> = req.body ?? {}
104
105 if (query.error) {
106 return {
107 success: false,
108 error: `${query.error}`,
109 }
110 }
111
112 const stateKey = crypto.randomBytes(32).toString("hex")
113 const state = {
114 callback_url: body?.callback_url ?? this.config_.callback_url,
115 }
116
117 await authIdentityService.setState(stateKey, state)
118 return this.getRedirect(this.getClientId(), state.callback_url, stateKey)
119 }
120
121 async validateCallback(
122 req: AuthenticationInput,
123 authIdentityService: AuthIdentityProviderService
124 ): Promise<AuthenticationResponse> {
125 const query: Record<string, string> = req.query ?? {}
126 const body: Record<string, string> = req.body ?? {}
127
128 if (query.error) {
129 return {
130 success: false,
131 error: `${query.error}`,
132 }
133 }
134
135 const code = query?.code ?? body?.code
136 if (!code) {
137 return { success: false, error: "No code provided" }
138 }
139
140 const state = await authIdentityService.getState(query?.state as string)
141 if (!state) {
142 return { success: false, error: "No state provided, or session expired" }
143 }
144
145 const clientId = this.getClientId()
146
147 try {
148 const response = await fetch(this.config_.oauth_token_endpoint, {
149 method: "POST",
150 headers: {
151 "Content-Type": "application/x-www-form-urlencoded",
152 },
153 body: new URLSearchParams({
154 client_id: clientId,
155 client_secret: this.config_.api_key,
156 code,
157 redirect_uri: state.callback_url as string,
158 grant_type: "authorization_code",
159 }),
160 }).then((r) => {
161 if (!r.ok) {
162 this.logger_.warn(
163 `Could not exchange token, ${r.status}, ${
164 r.statusText
165 }: response: ${JSON.stringify(r)}`
166 )
167 throw new MedusaError(
168 MedusaError.Types.INVALID_DATA,
169 `Could not exchange token, ${r.status}, ${r.statusText}`
170 )
171 }
172
173 return r.json()
174 })
175
176 const { authIdentity, success, error } = await this.verify_(
177 response.id_token as string,
178 authIdentityService
179 )
180
181 return {
182 success,
183 authIdentity,
184 error,
185 }
186 } catch (error) {
187 return { success: false, error: error.message }
188 }
189 }
190
191 async verify_(
192 idToken: string | undefined,
193 authIdentityService: AuthIdentityProviderService
194 ) {
195 if (!idToken) {
196 return { success: false, error: "No id_token" }
197 }
198
199 let payload: JwtPayload
200 try {
201 const decoded = await verifyJwt(idToken, this.getSigningKey_, {
202 algorithms: ["RS256"],
203 audience: this.config_.oauth_audience,
204 })
205 if (!decoded || typeof decoded === "string") {
206 throw new Error("Invalid id_token")
207 }
208 payload = decoded
209 } catch (err) {
210 return {
211 success: false,
212 error: `Could not verify id_token: ${err.message}`,
213 }
214 }
215
216 if (!payload.email_verified) {
217 throw new MedusaError(
218 MedusaError.Types.INVALID_DATA,
219 "Email not verified, cannot proceed with authentication"
220 )
221 }
222
223 if (!payload.sub) {
224 throw new MedusaError(
225 MedusaError.Types.INVALID_DATA,
226 "id_token is missing 'sub' claim"
227 )
228 }
229
230 const entity_id = payload.sub
231 const userMetadata = {
232 name: payload.name,
233 email: payload.email,
234 picture: payload.picture,
235 given_name: payload.given_name,
236 family_name: payload.family_name,
237 }
238
239 let authIdentity
240
241 try {
242 authIdentity = await authIdentityService.retrieve({
243 entity_id,
244 })
245 } catch (error) {
246 if (error.type === MedusaError.Types.NOT_FOUND) {
247 const createdAuthIdentity = await authIdentityService.create({
248 entity_id,
249 user_metadata: userMetadata,
250 })
251 authIdentity = createdAuthIdentity
252 } else {
253 return { success: false, error: error.message }
254 }
255 }
256
257 return {
258 success: true,
259 authIdentity,
260 }
261 }
262
263 private getRedirect(clientId: string, callbackUrl: string, stateKey: string) {
264 const authUrl = new URL(this.config_.oauth_authorize_endpoint)
265 authUrl.searchParams.set("redirect_uri", callbackUrl)
266 authUrl.searchParams.set("client_id", clientId)
267 authUrl.searchParams.set("response_type", "code")
268 authUrl.searchParams.set("scope", "email profile openid")
269 authUrl.searchParams.set("state", stateKey)
270
271 return { success: true, location: authUrl.toString() }
272 }
273
274 private getClientId() {
275 return this.config_.environment_handle || this.config_.sandbox_handle
276 }
277 }