1 import crypto from "crypto"
2 import {
3 AuthenticationInput,
4 AuthenticationResponse,
5 AuthIdentityProviderService,
6 ICacheService,
7 Logger,
8 OidcAuthProviderOptions,
9 } from "@medusajs/framework/types"
10 import {
11 AbstractAuthModuleProvider,
12 MedusaError,
13 } from "@medusajs/framework/utils"
14 import { OidcEngine } from "../engine"
15 import { assertSecureUrl } from "../utils"
16
17 type InjectedDependencies = {
18 logger: Logger
19 cache?: ICacheService
20 }
21
22 // A generic failure message returned to the client; the detailed cause is only ever logged server-side.
23 const GENERIC_AUTH_ERROR = "Authentication failed"
24
25 export class OidcAuthService extends AbstractAuthModuleProvider {
26 static identifier = "oidc"
27 static DISPLAY_NAME = "OpenID Connect"
28
29 protected readonly config_: OidcAuthProviderOptions
30 protected readonly logger_: Logger
31 protected readonly engine_: OidcEngine
32
33 static validateOptions(options: OidcAuthProviderOptions) {
34 if (!options.issuer) {
35 throw new MedusaError(
36 MedusaError.Types.INVALID_DATA,
37 "OIDC provider requires an 'issuer' option"
38 )
39 }
40
41 assertSecureUrl(options.issuer, "issuer")
42
43 if (!options.client_id) {
44 throw new MedusaError(
45 MedusaError.Types.INVALID_DATA,
46 "OIDC provider requires a 'client_id' option"
47 )
48 }
49
50 if (!options.callback_url) {
51 throw new MedusaError(
52 MedusaError.Types.INVALID_DATA,
53 "OIDC provider requires a 'callback_url' option"
54 )
55 }
56 }
57
58 constructor(
59 { logger, cache }: InjectedDependencies,
60 options: OidcAuthProviderOptions
61 ) {
62 // @ts-ignore
63 super(...arguments)
64 this.config_ = options
65 this.logger_ = logger
66 this.engine_ = new OidcEngine(options, cache)
67 }
68
69 // The same OIDC package is registered once per IdP (okta, auth0, ...), so the
70 // display name is instance-specific.
71 get displayName() {
72 return this.config_.display_name ?? OidcAuthService.DISPLAY_NAME
73 }
74
75 async register(_: AuthenticationInput): Promise<AuthenticationResponse> {
76 throw new MedusaError(
77 MedusaError.Types.NOT_ALLOWED,
78 "OIDC does not support registration. Use method `authenticate` instead."
79 )
80 }
81
82 async authenticate(
83 req: AuthenticationInput,
84 authIdentityService: AuthIdentityProviderService
85 ): Promise<AuthenticationResponse> {
86 const body: Record<string, string> = req.body ?? {}
87
88 const callbackUrl = body?.callback_url ?? this.config_.callback_url
89
90 // The allowlist is opt-in: when it isn't configured, validating the callback
91 // URL is left entirely to the identity provider.
92 const allowedCallbackUrls = this.config_.allowed_callback_urls
93
94 if (
95 allowedCallbackUrls?.length &&
96 !allowedCallbackUrls.includes(callbackUrl)
97 ) {
98 this.logger_?.warn(
99 `[auth-oidc] Rejected authentication with a callback URL (${callbackUrl}) that is not in the allowlist`
100 )
101 return {
102 success: false,
103 error: "The provided callback URL is not allowed",
104 }
105 }
106
107 try {
108 const stateKey = crypto.randomBytes(32).toString("hex")
109
110 const { url, nonce, codeVerifier } =
111 await this.engine_.buildAuthorizationUrl({
112 state: stateKey,
113 callbackUrl,
114 scopes: this.config_.scopes,
115 })
116
117 await authIdentityService.setState(
118 stateKey,
119 {
120 callback_url: callbackUrl,
121 nonce,
122 code_verifier: codeVerifier,
123 },
124 this.config_.state_ttl_seconds ?? 600
125 )
126
127 return { success: true, location: url }
128 } catch (error) {
129 this.logger_?.error(
130 `[auth-oidc] Could not initiate authentication: ${error.message}`
131 )
132 return { success: false, error: GENERIC_AUTH_ERROR }
133 }
134 }
135
136 async validateCallback(
137 req: AuthenticationInput,
138 authIdentityService: AuthIdentityProviderService
139 ): Promise<AuthenticationResponse> {
140 const query: Record<string, string> = req.query ?? {}
141 const body: Record<string, string> = req.body ?? {}
142
143 if (query.error) {
144 // Not an application fault (e.g. the user canceled, or `access_denied`),
145 // so it's only logged for debugging purposes.
146 this.logger_?.debug(
147 `[auth-oidc] Identity provider returned an error on callback: ${query.error}`
148 )
149 return { success: false, error: GENERIC_AUTH_ERROR }
150 }
151
152 const code = query?.code ?? body?.code
153 if (!code) {
154 return { success: false, error: "No code provided" }
155 }
156
157 const stateKey = (query?.state ?? body?.state) as string | undefined
158 if (!stateKey) {
159 return { success: false, error: "No state provided, or session expired" }
160 }
161
162 const state = await authIdentityService.getState(stateKey)
163 if (!state) {
164 return { success: false, error: "No state provided, or session expired" }
165 }
166
167 try {
168 const { claims } = await this.engine_.exchangeCode({
169 // Forward the full authorization-response params.
170 params: { ...body, ...query },
171 nonce: state.nonce as string,
172 codeVerifier: state.code_verifier as string,
173 callbackUrl: state.callback_url as string,
174 state: stateKey,
175 })
176
177 const { entityId, userMetadata } = this.engine_.mapClaims(claims)
178
179 let authIdentity
180 try {
181 authIdentity = await authIdentityService.retrieve({
182 entity_id: entityId,
183 })
184
185 // Refresh the stored profile claims on every login.
186 authIdentity = await authIdentityService.update(entityId, {
187 user_metadata: userMetadata,
188 })
189 } catch (error) {
190 if (error.type === MedusaError.Types.NOT_FOUND) {
191 authIdentity = await authIdentityService.create({
192 entity_id: entityId,
193 user_metadata: userMetadata,
194 })
195 } else {
196 throw error
197 }
198 }
199
200 return { success: true, authIdentity }
201 } catch (error) {
202 this.logger_?.error(
203 `[auth-oidc] Could not validate authentication callback: ${error.message}`
204 )
205 return { success: false, error: GENERIC_AUTH_ERROR }
206 }
207 }
208 }