|
1
|
import { ICacheService } from "@medusajs/framework/types" |
|
2
|
import { isDefined, MedusaError } from "@medusajs/framework/utils" |
|
3
|
import { |
|
4
|
Client, |
|
5
|
custom, |
|
6
|
generators, |
|
7
|
Issuer, |
|
8
|
IssuerMetadata, |
|
9
|
TokenSet, |
|
10
|
} from "openid-client" |
|
11
|
import { |
|
12
|
OidcAuthorizationUrlResult, |
|
13
|
OidcBuildAuthorizationUrlInput, |
|
14
|
OidcClaimMappings, |
|
15
|
OidcEngineOptions, |
|
16
|
OidcExchangeCodeInput, |
|
17
|
OidcExchangeCodeResult, |
|
18
|
OidcMappedClaims, |
|
19
|
} from "./types" |
|
20
|
import { assertSecureUrl } from "../utils" |
|
21
|
|
|
22
|
const DEFAULT_SCOPES = ["openid", "email", "profile"] |
|
23
|
const DEFAULT_CLOCK_TOLERANCE_SECONDS = 5 |
|
24
|
const DEFAULT_DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000 // 1 hour |
|
25
|
const DEFAULT_HTTP_TIMEOUT_MS = 10_000 |
|
26
|
|
|
27
|
const DEFAULT_CLAIM_MAPPINGS: OidcClaimMappings = { |
|
28
|
entity_id: "sub", |
|
29
|
email: "email", |
|
30
|
name: "name", |
|
31
|
} |
|
32
|
|
|
33
|
// Cache-module key prefix for cached discovery documents. |
|
34
|
const DISCOVERY_CACHE_KEY_PREFIX = "oidc:discovery:" |
|
35
|
|
|
36
|
// Apply a sane default timeout to all outgoing HTTP requests (discovery, JWKS, |
|
37
|
// token exchange) so an IdP outage degrades to a login failure rather than a hang. |
|
38
|
custom.setHttpOptionsDefaults({ timeout: DEFAULT_HTTP_TIMEOUT_MS }) |
|
39
|
|
|
40
|
/** |
|
41
|
* A reusable OIDC engine built on `openid-client`. It handles discovery, |
|
42
|
* building the authorization URL (PKCE + nonce), exchanging the authorization |
|
43
|
* code with full ID-token validation, and mapping validated claims to an |
|
44
|
* auth-identity shape. |
|
45
|
*/ |
|
46
|
export class OidcEngine { |
|
47
|
protected readonly options_: OidcEngineOptions |
|
48
|
protected readonly discoveryCacheTtlMs_: number |
|
49
|
protected readonly httpTimeoutMs_: number |
|
50
|
protected readonly cache_?: ICacheService |
|
51
|
|
|
52
|
/** |
|
53
|
* The memoized OIDC client. `openid-client` v5 caches the JWKS keystore per |
|
54
|
* `Issuer` instance, so building a fresh client on every call would refetch |
|
55
|
* the JWKS over HTTP on every login callback. The client is built lazily and |
|
56
|
* reused until the discovery cache entry expires; when all endpoints are |
|
57
|
* configured explicitly (no discovery), it's cached indefinitely, since the |
|
58
|
* engine's options are immutable per instance. |
|
59
|
*/ |
|
60
|
protected clientPromise_?: Promise<Client> |
|
61
|
protected clientExpiresAt_ = 0 |
|
62
|
|
|
63
|
constructor(options: OidcEngineOptions, cache?: ICacheService) { |
|
64
|
if (!options?.issuer) { |
|
65
|
throw new MedusaError( |
|
66
|
MedusaError.Types.INVALID_DATA, |
|
67
|
"OIDC engine requires an 'issuer' option" |
|
68
|
) |
|
69
|
} |
|
70
|
if (!options.client_id) { |
|
71
|
throw new MedusaError( |
|
72
|
MedusaError.Types.INVALID_DATA, |
|
73
|
"OIDC engine requires a 'client_id' option" |
|
74
|
) |
|
75
|
} |
|
76
|
if (!options.callback_url) { |
|
77
|
throw new MedusaError( |
|
78
|
MedusaError.Types.INVALID_DATA, |
|
79
|
"OIDC engine requires a 'callback_url' option" |
|
80
|
) |
|
81
|
} |
|
82
|
|
|
83
|
assertSecureUrl(options.issuer, "issuer") |
|
84
|
for (const [key, value] of [ |
|
85
|
["authorization_endpoint", options.authorization_endpoint], |
|
86
|
["token_endpoint", options.token_endpoint], |
|
87
|
["jwks_uri", options.jwks_uri], |
|
88
|
] as const) { |
|
89
|
if (value) { |
|
90
|
assertSecureUrl(value, key) |
|
91
|
} |
|
92
|
} |
|
93
|
|
|
94
|
this.options_ = options |
|
95
|
this.discoveryCacheTtlMs_ = |
|
96
|
options.discovery_cache_ttl_ms ?? DEFAULT_DISCOVERY_CACHE_TTL_MS |
|
97
|
this.httpTimeoutMs_ = options.http_timeout_ms ?? DEFAULT_HTTP_TIMEOUT_MS |
|
98
|
this.cache_ = cache |
|
99
|
} |
|
100
|
|
|
101
|
/** |
|
102
|
* Builds the authorization URL to redirect the browser to, generating a fresh |
|
103
|
* PKCE code verifier/challenge (S256) and nonce. The returned `nonce` and |
|
104
|
* `codeVerifier` must be persisted alongside the state so they can be replayed |
|
105
|
* when validating the callback. |
|
106
|
*/ |
|
107
|
async buildAuthorizationUrl( |
|
108
|
input: OidcBuildAuthorizationUrlInput |
|
109
|
): Promise<OidcAuthorizationUrlResult> { |
|
110
|
if (!input?.state) { |
|
111
|
throw new MedusaError( |
|
112
|
MedusaError.Types.INVALID_DATA, |
|
113
|
"A 'state' value is required to build the authorization URL" |
|
114
|
) |
|
115
|
} |
|
116
|
|
|
117
|
const client = await this.getClient_() |
|
118
|
|
|
119
|
const codeVerifier = generators.codeVerifier() |
|
120
|
const codeChallenge = generators.codeChallenge(codeVerifier) |
|
121
|
const nonce = generators.nonce() |
|
122
|
|
|
123
|
const scopes = input.scopes ?? this.options_.scopes ?? DEFAULT_SCOPES |
|
124
|
|
|
125
|
const url = client.authorizationUrl({ |
|
126
|
scope: scopes.join(" "), |
|
127
|
redirect_uri: input.callbackUrl ?? this.options_.callback_url, |
|
128
|
state: input.state, |
|
129
|
nonce, |
|
130
|
code_challenge: codeChallenge, |
|
131
|
code_challenge_method: "S256", |
|
132
|
}) |
|
133
|
|
|
134
|
return { url, nonce, codeVerifier } |
|
135
|
} |
|
136
|
|
|
137
|
/** |
|
138
|
* Exchanges the authorization code for tokens and performs full ID-token |
|
139
|
* validation via `openid-client` (signature through JWKS, `iss`, `aud`/`azp`, |
|
140
|
* `exp`/`iat`/`nbf` with clock tolerance, and `nonce`). Returns the validated |
|
141
|
* claims plus the tokens. |
|
142
|
*/ |
|
143
|
async exchangeCode( |
|
144
|
input: OidcExchangeCodeInput |
|
145
|
): Promise<OidcExchangeCodeResult> { |
|
146
|
const params = input?.params ?? {} |
|
147
|
|
|
148
|
if (!params.code) { |
|
149
|
throw new MedusaError( |
|
150
|
MedusaError.Types.INVALID_DATA, |
|
151
|
"An authorization 'code' is required to exchange for tokens" |
|
152
|
) |
|
153
|
} |
|
154
|
|
|
155
|
const client = await this.getClient_() |
|
156
|
const redirectUri = input.callbackUrl ?? this.options_.callback_url |
|
157
|
|
|
158
|
let tokenSet: TokenSet |
|
159
|
try { |
|
160
|
// Forward every authorization-response parameter so |
|
161
|
// openid-client can enforce all applicable checks. The `checks` argument |
|
162
|
// carries the values we stored ourselves (PKCE verifier, nonce, state). |
|
163
|
tokenSet = await client.callback(redirectUri, params, { |
|
164
|
code_verifier: input.codeVerifier, |
|
165
|
nonce: input.nonce, |
|
166
|
state: input.state, |
|
167
|
}) |
|
168
|
} catch (error) { |
|
169
|
throw new MedusaError( |
|
170
|
MedusaError.Types.UNAUTHORIZED, |
|
171
|
`Could not validate the identity provider's response: ${error.message}` |
|
172
|
) |
|
173
|
} |
|
174
|
|
|
175
|
// Without the `openid` scope, the token endpoint returns no ID token and |
|
176
|
// `tokenSet.claims()` would throw an unhelpful TypeError. |
|
177
|
if (!tokenSet.id_token) { |
|
178
|
throw new MedusaError( |
|
179
|
MedusaError.Types.UNAUTHORIZED, |
|
180
|
"The identity provider did not return an ID token; ensure the 'openid' scope is requested" |
|
181
|
) |
|
182
|
} |
|
183
|
|
|
184
|
const claims = tokenSet.claims() |
|
185
|
|
|
186
|
return { |
|
187
|
claims: { ...claims }, |
|
188
|
tokens: { |
|
189
|
id_token: tokenSet.id_token, |
|
190
|
access_token: tokenSet.access_token, |
|
191
|
refresh_token: tokenSet.refresh_token, |
|
192
|
expires_at: tokenSet.expires_at, |
|
193
|
token_type: tokenSet.token_type, |
|
194
|
scope: tokenSet.scope, |
|
195
|
}, |
|
196
|
} |
|
197
|
} |
|
198
|
|
|
199
|
/** |
|
200
|
* Maps validated ID-token claims to an auth-identity shape, applying the |
|
201
|
* `require_verified_email` and `allowed_email_domains` policy checks. |
|
202
|
* |
|
203
|
* `entity_id` defaults to the `sub` claim (never the email, which is mutable |
|
204
|
* and reassignable). |
|
205
|
*/ |
|
206
|
mapClaims(claims: Record<string, unknown>): OidcMappedClaims { |
|
207
|
const mappings: OidcClaimMappings = { |
|
208
|
...DEFAULT_CLAIM_MAPPINGS, |
|
209
|
...this.options_.claim_mappings, |
|
210
|
} |
|
211
|
|
|
212
|
const entityIdClaim = mappings.entity_id ?? "sub" |
|
213
|
const entityIdValue = claims[entityIdClaim] |
|
214
|
|
|
215
|
if ( |
|
216
|
entityIdValue === undefined || |
|
217
|
entityIdValue === null || |
|
218
|
entityIdValue === "" |
|
219
|
) { |
|
220
|
throw new MedusaError( |
|
221
|
MedusaError.Types.INVALID_DATA, |
|
222
|
`The identity provider's ID token is missing the '${entityIdClaim}' claim used to identify the user` |
|
223
|
) |
|
224
|
} |
|
225
|
|
|
226
|
const emailClaim = mappings.email ?? "email" |
|
227
|
const email = claims[emailClaim] |
|
228
|
|
|
229
|
const requireVerifiedEmail = this.options_.require_verified_email ?? true |
|
230
|
if (requireVerifiedEmail && claims.email_verified !== true) { |
|
231
|
throw new MedusaError( |
|
232
|
MedusaError.Types.INVALID_DATA, |
|
233
|
"The identity provider did not confirm a verified email address" |
|
234
|
) |
|
235
|
} |
|
236
|
|
|
237
|
if (this.options_.allowed_email_domains?.length) { |
|
238
|
const allowedDomains = this.options_.allowed_email_domains.map((domain) => |
|
239
|
domain.toLowerCase() |
|
240
|
) |
|
241
|
const domain = |
|
242
|
typeof email === "string" |
|
243
|
? email.split("@")[1]?.toLowerCase() |
|
244
|
: undefined |
|
245
|
|
|
246
|
if (!domain || !allowedDomains.includes(domain)) { |
|
247
|
throw new MedusaError( |
|
248
|
MedusaError.Types.UNAUTHORIZED, |
|
249
|
"The email domain is not allowed to authenticate with this provider" |
|
250
|
) |
|
251
|
} |
|
252
|
} |
|
253
|
|
|
254
|
const userMetadata: Record<string, unknown> = {} |
|
255
|
for (const [field, claimName] of Object.entries(mappings)) { |
|
256
|
if (field === "entity_id" || !claimName) { |
|
257
|
continue |
|
258
|
} |
|
259
|
if (isDefined(claims[claimName])) { |
|
260
|
userMetadata[field] = claims[claimName] |
|
261
|
} |
|
262
|
} |
|
263
|
|
|
264
|
return { |
|
265
|
entityId: String(entityIdValue), |
|
266
|
userMetadata, |
|
267
|
} |
|
268
|
} |
|
269
|
|
|
270
|
protected async getClient_(): Promise<Client> { |
|
271
|
const now = Date.now() |
|
272
|
|
|
273
|
if ( |
|
274
|
this.clientPromise_ && |
|
275
|
(this.hasAllEndpointOverrides_() || now < this.clientExpiresAt_) |
|
276
|
) { |
|
277
|
return this.clientPromise_ |
|
278
|
} |
|
279
|
|
|
280
|
// Memoize the in-flight promise synchronously so concurrent first calls |
|
281
|
// share a single client build instead of racing. |
|
282
|
const promise = this.buildClient_() |
|
283
|
this.clientPromise_ = promise |
|
284
|
this.clientExpiresAt_ = now + this.discoveryCacheTtlMs_ |
|
285
|
|
|
286
|
try { |
|
287
|
return await promise |
|
288
|
} catch (error) { |
|
289
|
// Never cache a failed build; the next call retries. |
|
290
|
if (this.clientPromise_ === promise) { |
|
291
|
this.clientPromise_ = undefined |
|
292
|
this.clientExpiresAt_ = 0 |
|
293
|
} |
|
294
|
throw error |
|
295
|
} |
|
296
|
} |
|
297
|
|
|
298
|
protected async buildClient_(): Promise<Client> { |
|
299
|
const issuer = await this.resolveIssuer_() |
|
300
|
|
|
301
|
const client = new issuer.Client({ |
|
302
|
client_id: this.options_.client_id, |
|
303
|
...(this.options_.client_secret |
|
304
|
? { client_secret: this.options_.client_secret } |
|
305
|
: {}), |
|
306
|
redirect_uris: [this.options_.callback_url], |
|
307
|
response_types: ["code"], |
|
308
|
token_endpoint_auth_method: this.options_.client_secret |
|
309
|
? "client_secret_post" |
|
310
|
: "none", |
|
311
|
}) |
|
312
|
|
|
313
|
client[custom.clock_tolerance] = |
|
314
|
this.options_.clock_tolerance_seconds ?? DEFAULT_CLOCK_TOLERANCE_SECONDS |
|
315
|
client[custom.http_options] = () => ({ timeout: this.httpTimeoutMs_ }) |
|
316
|
|
|
317
|
return client |
|
318
|
} |
|
319
|
|
|
320
|
protected hasAllEndpointOverrides_(): boolean { |
|
321
|
return !!( |
|
322
|
this.options_.authorization_endpoint && |
|
323
|
this.options_.token_endpoint && |
|
324
|
this.options_.jwks_uri |
|
325
|
) |
|
326
|
} |
|
327
|
|
|
328
|
protected async resolveIssuer_(): Promise<Issuer> { |
|
329
|
let base: IssuerMetadata = { issuer: this.options_.issuer } |
|
330
|
if (!this.hasAllEndpointOverrides_()) { |
|
331
|
base = await this.discoverMetadata_() |
|
332
|
} |
|
333
|
|
|
334
|
// Explicit endpoint overrides take precedence over discovered values; the |
|
335
|
// configured issuer always wins so it matches the validated `iss` claim. |
|
336
|
return new Issuer({ |
|
337
|
...base, |
|
338
|
issuer: this.options_.issuer, |
|
339
|
authorization_endpoint: |
|
340
|
this.options_.authorization_endpoint ?? base.authorization_endpoint, |
|
341
|
token_endpoint: this.options_.token_endpoint ?? base.token_endpoint, |
|
342
|
jwks_uri: this.options_.jwks_uri ?? base.jwks_uri, |
|
343
|
end_session_endpoint: |
|
344
|
this.options_.end_session_endpoint ?? base.end_session_endpoint, |
|
345
|
}) |
|
346
|
} |
|
347
|
|
|
348
|
protected async discoverMetadata_(): Promise<IssuerMetadata> { |
|
349
|
const key = `${DISCOVERY_CACHE_KEY_PREFIX}${this.options_.issuer}` |
|
350
|
|
|
351
|
const cached = await this.cache_?.get<IssuerMetadata>(key) |
|
352
|
if (cached) { |
|
353
|
return cached |
|
354
|
} |
|
355
|
|
|
356
|
const metadata = (await Issuer.discover(this.options_.issuer)).metadata |
|
357
|
await this.cache_?.set( |
|
358
|
key, |
|
359
|
metadata, |
|
360
|
Math.floor(this.discoveryCacheTtlMs_ / 1000) |
|
361
|
) |
|
362
|
|
|
363
|
return metadata |
|
364
|
} |
|
365
|
} |