@better-auth/sso 1.4.0-beta.20 → 1.4.0-beta.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,1240 @@
1
- import { t as sso } from "./src-BUIX9n33.mjs";
1
+ import { XMLValidator } from "fast-xml-parser";
2
+ import * as saml from "samlify";
3
+ import { BetterFetchError, betterFetch } from "@better-fetch/fetch";
4
+ import { createAuthorizationURL, generateState, parseState, validateAuthorizationCode, validateToken } from "better-auth";
5
+ import { APIError, createAuthEndpoint, sessionMiddleware } from "better-auth/api";
6
+ import { setSessionCookie } from "better-auth/cookies";
7
+ import { handleOAuthUserInfo } from "better-auth/oauth2";
8
+ import { decodeJwt } from "jose";
9
+ import * as z from "zod/v4";
2
10
 
11
+ //#region src/routes/sso.ts
12
+ /**
13
+ * Safely parses a value that might be a JSON string or already a parsed object
14
+ * This handles cases where ORMs like Drizzle might return already parsed objects
15
+ * instead of JSON strings from TEXT/JSON columns
16
+ */
17
+ function safeJsonParse(value) {
18
+ if (!value) return null;
19
+ if (typeof value === "object") return value;
20
+ if (typeof value === "string") try {
21
+ return JSON.parse(value);
22
+ } catch (error) {
23
+ throw new Error(`Failed to parse JSON: ${error instanceof Error ? error.message : "Unknown error"}`);
24
+ }
25
+ return null;
26
+ }
27
+ const spMetadata = () => {
28
+ return createAuthEndpoint("/sso/saml2/sp/metadata", {
29
+ method: "GET",
30
+ query: z.object({
31
+ providerId: z.string(),
32
+ format: z.enum(["xml", "json"]).default("xml")
33
+ }),
34
+ metadata: { openapi: {
35
+ operationId: "getSSOServiceProviderMetadata",
36
+ summary: "Get Service Provider metadata",
37
+ description: "Returns the SAML metadata for the Service Provider",
38
+ responses: { "200": { description: "SAML metadata in XML format" } }
39
+ } }
40
+ }, async (ctx) => {
41
+ const provider = await ctx.context.adapter.findOne({
42
+ model: "ssoProvider",
43
+ where: [{
44
+ field: "providerId",
45
+ value: ctx.query.providerId
46
+ }]
47
+ });
48
+ if (!provider) throw new APIError("NOT_FOUND", { message: "No provider found for the given providerId" });
49
+ const parsedSamlConfig = safeJsonParse(provider.samlConfig);
50
+ if (!parsedSamlConfig) throw new APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
51
+ const sp = parsedSamlConfig.spMetadata.metadata ? saml.ServiceProvider({ metadata: parsedSamlConfig.spMetadata.metadata }) : saml.SPMetadata({
52
+ entityID: parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
53
+ assertionConsumerService: [{
54
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
55
+ Location: parsedSamlConfig.callbackUrl || `${ctx.context.baseURL}/sso/saml2/sp/acs/${provider.id}`
56
+ }],
57
+ wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
58
+ nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
59
+ });
60
+ return new Response(sp.getMetadata(), { headers: { "Content-Type": "application/xml" } });
61
+ });
62
+ };
63
+ const registerSSOProvider = (options) => {
64
+ return createAuthEndpoint("/sso/register", {
65
+ method: "POST",
66
+ body: z.object({
67
+ providerId: z.string({}).meta({ description: "The ID of the provider. This is used to identify the provider during login and callback" }),
68
+ issuer: z.string({}).meta({ description: "The issuer of the provider" }),
69
+ domain: z.string({}).meta({ description: "The domain of the provider. This is used for email matching" }),
70
+ oidcConfig: z.object({
71
+ clientId: z.string({}).meta({ description: "The client ID" }),
72
+ clientSecret: z.string({}).meta({ description: "The client secret" }),
73
+ authorizationEndpoint: z.string({}).meta({ description: "The authorization endpoint" }).optional(),
74
+ tokenEndpoint: z.string({}).meta({ description: "The token endpoint" }).optional(),
75
+ userInfoEndpoint: z.string({}).meta({ description: "The user info endpoint" }).optional(),
76
+ tokenEndpointAuthentication: z.enum(["client_secret_post", "client_secret_basic"]).optional(),
77
+ jwksEndpoint: z.string({}).meta({ description: "The JWKS endpoint" }).optional(),
78
+ discoveryEndpoint: z.string().optional(),
79
+ scopes: z.array(z.string(), {}).meta({ description: "The scopes to request. Defaults to ['openid', 'email', 'profile', 'offline_access']" }).optional(),
80
+ pkce: z.boolean({}).meta({ description: "Whether to use PKCE for the authorization flow" }).default(true).optional(),
81
+ mapping: z.object({
82
+ id: z.string({}).meta({ description: "Field mapping for user ID (defaults to 'sub')" }),
83
+ email: z.string({}).meta({ description: "Field mapping for email (defaults to 'email')" }),
84
+ emailVerified: z.string({}).meta({ description: "Field mapping for email verification (defaults to 'email_verified')" }).optional(),
85
+ name: z.string({}).meta({ description: "Field mapping for name (defaults to 'name')" }),
86
+ image: z.string({}).meta({ description: "Field mapping for image (defaults to 'picture')" }).optional(),
87
+ extraFields: z.record(z.string(), z.any()).optional()
88
+ }).optional()
89
+ }).optional(),
90
+ samlConfig: z.object({
91
+ entryPoint: z.string({}).meta({ description: "The entry point of the provider" }),
92
+ cert: z.string({}).meta({ description: "The certificate of the provider" }),
93
+ callbackUrl: z.string({}).meta({ description: "The callback URL of the provider" }),
94
+ audience: z.string().optional(),
95
+ idpMetadata: z.object({
96
+ metadata: z.string().optional(),
97
+ entityID: z.string().optional(),
98
+ cert: z.string().optional(),
99
+ privateKey: z.string().optional(),
100
+ privateKeyPass: z.string().optional(),
101
+ isAssertionEncrypted: z.boolean().optional(),
102
+ encPrivateKey: z.string().optional(),
103
+ encPrivateKeyPass: z.string().optional(),
104
+ singleSignOnService: z.array(z.object({
105
+ Binding: z.string().meta({ description: "The binding type for the SSO service" }),
106
+ Location: z.string().meta({ description: "The URL for the SSO service" })
107
+ })).optional().meta({ description: "Single Sign-On service configuration" })
108
+ }).optional(),
109
+ spMetadata: z.object({
110
+ metadata: z.string().optional(),
111
+ entityID: z.string().optional(),
112
+ binding: z.string().optional(),
113
+ privateKey: z.string().optional(),
114
+ privateKeyPass: z.string().optional(),
115
+ isAssertionEncrypted: z.boolean().optional(),
116
+ encPrivateKey: z.string().optional(),
117
+ encPrivateKeyPass: z.string().optional()
118
+ }),
119
+ wantAssertionsSigned: z.boolean().optional(),
120
+ signatureAlgorithm: z.string().optional(),
121
+ digestAlgorithm: z.string().optional(),
122
+ identifierFormat: z.string().optional(),
123
+ privateKey: z.string().optional(),
124
+ decryptionPvk: z.string().optional(),
125
+ additionalParams: z.record(z.string(), z.any()).optional(),
126
+ mapping: z.object({
127
+ id: z.string({}).meta({ description: "Field mapping for user ID (defaults to 'nameID')" }),
128
+ email: z.string({}).meta({ description: "Field mapping for email (defaults to 'email')" }),
129
+ emailVerified: z.string({}).meta({ description: "Field mapping for email verification" }).optional(),
130
+ name: z.string({}).meta({ description: "Field mapping for name (defaults to 'displayName')" }),
131
+ firstName: z.string({}).meta({ description: "Field mapping for first name (defaults to 'givenName')" }).optional(),
132
+ lastName: z.string({}).meta({ description: "Field mapping for last name (defaults to 'surname')" }).optional(),
133
+ extraFields: z.record(z.string(), z.any()).optional()
134
+ }).optional()
135
+ }).optional(),
136
+ organizationId: z.string({}).meta({ description: "If organization plugin is enabled, the organization id to link the provider to" }).optional(),
137
+ overrideUserInfo: z.boolean({}).meta({ description: "Override user info with the provider info. Defaults to false" }).default(false).optional()
138
+ }),
139
+ use: [sessionMiddleware],
140
+ metadata: { openapi: {
141
+ operationId: "registerSSOProvider",
142
+ summary: "Register an OIDC provider",
143
+ description: "This endpoint is used to register an OIDC provider. This is used to configure the provider and link it to an organization",
144
+ responses: { "200": {
145
+ description: "OIDC provider created successfully",
146
+ content: { "application/json": { schema: {
147
+ type: "object",
148
+ properties: {
149
+ issuer: {
150
+ type: "string",
151
+ format: "uri",
152
+ description: "The issuer URL of the provider"
153
+ },
154
+ domain: {
155
+ type: "string",
156
+ description: "The domain of the provider, used for email matching"
157
+ },
158
+ oidcConfig: {
159
+ type: "object",
160
+ properties: {
161
+ issuer: {
162
+ type: "string",
163
+ format: "uri",
164
+ description: "The issuer URL of the provider"
165
+ },
166
+ pkce: {
167
+ type: "boolean",
168
+ description: "Whether PKCE is enabled for the authorization flow"
169
+ },
170
+ clientId: {
171
+ type: "string",
172
+ description: "The client ID for the provider"
173
+ },
174
+ clientSecret: {
175
+ type: "string",
176
+ description: "The client secret for the provider"
177
+ },
178
+ authorizationEndpoint: {
179
+ type: "string",
180
+ format: "uri",
181
+ nullable: true,
182
+ description: "The authorization endpoint URL"
183
+ },
184
+ discoveryEndpoint: {
185
+ type: "string",
186
+ format: "uri",
187
+ description: "The discovery endpoint URL"
188
+ },
189
+ userInfoEndpoint: {
190
+ type: "string",
191
+ format: "uri",
192
+ nullable: true,
193
+ description: "The user info endpoint URL"
194
+ },
195
+ scopes: {
196
+ type: "array",
197
+ items: { type: "string" },
198
+ nullable: true,
199
+ description: "The scopes requested from the provider"
200
+ },
201
+ tokenEndpoint: {
202
+ type: "string",
203
+ format: "uri",
204
+ nullable: true,
205
+ description: "The token endpoint URL"
206
+ },
207
+ tokenEndpointAuthentication: {
208
+ type: "string",
209
+ enum: ["client_secret_post", "client_secret_basic"],
210
+ nullable: true,
211
+ description: "Authentication method for the token endpoint"
212
+ },
213
+ jwksEndpoint: {
214
+ type: "string",
215
+ format: "uri",
216
+ nullable: true,
217
+ description: "The JWKS endpoint URL"
218
+ },
219
+ mapping: {
220
+ type: "object",
221
+ nullable: true,
222
+ properties: {
223
+ id: {
224
+ type: "string",
225
+ description: "Field mapping for user ID (defaults to 'sub')"
226
+ },
227
+ email: {
228
+ type: "string",
229
+ description: "Field mapping for email (defaults to 'email')"
230
+ },
231
+ emailVerified: {
232
+ type: "string",
233
+ nullable: true,
234
+ description: "Field mapping for email verification (defaults to 'email_verified')"
235
+ },
236
+ name: {
237
+ type: "string",
238
+ description: "Field mapping for name (defaults to 'name')"
239
+ },
240
+ image: {
241
+ type: "string",
242
+ nullable: true,
243
+ description: "Field mapping for image (defaults to 'picture')"
244
+ },
245
+ extraFields: {
246
+ type: "object",
247
+ additionalProperties: { type: "string" },
248
+ nullable: true,
249
+ description: "Additional field mappings"
250
+ }
251
+ },
252
+ required: [
253
+ "id",
254
+ "email",
255
+ "name"
256
+ ]
257
+ }
258
+ },
259
+ required: [
260
+ "issuer",
261
+ "pkce",
262
+ "clientId",
263
+ "clientSecret",
264
+ "discoveryEndpoint"
265
+ ],
266
+ description: "OIDC configuration for the provider"
267
+ },
268
+ organizationId: {
269
+ type: "string",
270
+ nullable: true,
271
+ description: "ID of the linked organization, if any"
272
+ },
273
+ userId: {
274
+ type: "string",
275
+ description: "ID of the user who registered the provider"
276
+ },
277
+ providerId: {
278
+ type: "string",
279
+ description: "Unique identifier for the provider"
280
+ },
281
+ redirectURI: {
282
+ type: "string",
283
+ format: "uri",
284
+ description: "The redirect URI for the provider callback"
285
+ }
286
+ },
287
+ required: [
288
+ "issuer",
289
+ "domain",
290
+ "oidcConfig",
291
+ "userId",
292
+ "providerId",
293
+ "redirectURI"
294
+ ]
295
+ } } }
296
+ } }
297
+ } }
298
+ }, async (ctx) => {
299
+ const user = ctx.context.session?.user;
300
+ if (!user) throw new APIError("UNAUTHORIZED");
301
+ const limit = typeof options?.providersLimit === "function" ? await options.providersLimit(user) : options?.providersLimit ?? 10;
302
+ if (!limit) throw new APIError("FORBIDDEN", { message: "SSO provider registration is disabled" });
303
+ if ((await ctx.context.adapter.findMany({
304
+ model: "ssoProvider",
305
+ where: [{
306
+ field: "userId",
307
+ value: user.id
308
+ }]
309
+ })).length >= limit) throw new APIError("FORBIDDEN", { message: "You have reached the maximum number of SSO providers" });
310
+ const body = ctx.body;
311
+ if (z.string().url().safeParse(body.issuer).error) throw new APIError("BAD_REQUEST", { message: "Invalid issuer. Must be a valid URL" });
312
+ if (ctx.body.organizationId) {
313
+ if (!await ctx.context.adapter.findOne({
314
+ model: "member",
315
+ where: [{
316
+ field: "userId",
317
+ value: user.id
318
+ }, {
319
+ field: "organizationId",
320
+ value: ctx.body.organizationId
321
+ }]
322
+ })) throw new APIError("BAD_REQUEST", { message: "You are not a member of the organization" });
323
+ }
324
+ if (await ctx.context.adapter.findOne({
325
+ model: "ssoProvider",
326
+ where: [{
327
+ field: "providerId",
328
+ value: body.providerId
329
+ }]
330
+ })) {
331
+ ctx.context.logger.info(`SSO provider creation attempt with existing providerId: ${body.providerId}`);
332
+ throw new APIError("UNPROCESSABLE_ENTITY", { message: "SSO provider with this providerId already exists" });
333
+ }
334
+ const provider = await ctx.context.adapter.create({
335
+ model: "ssoProvider",
336
+ data: {
337
+ issuer: body.issuer,
338
+ domain: body.domain,
339
+ oidcConfig: body.oidcConfig ? JSON.stringify({
340
+ issuer: body.issuer,
341
+ clientId: body.oidcConfig.clientId,
342
+ clientSecret: body.oidcConfig.clientSecret,
343
+ authorizationEndpoint: body.oidcConfig.authorizationEndpoint,
344
+ tokenEndpoint: body.oidcConfig.tokenEndpoint,
345
+ tokenEndpointAuthentication: body.oidcConfig.tokenEndpointAuthentication,
346
+ jwksEndpoint: body.oidcConfig.jwksEndpoint,
347
+ pkce: body.oidcConfig.pkce,
348
+ discoveryEndpoint: body.oidcConfig.discoveryEndpoint || `${body.issuer}/.well-known/openid-configuration`,
349
+ mapping: body.oidcConfig.mapping,
350
+ scopes: body.oidcConfig.scopes,
351
+ userInfoEndpoint: body.oidcConfig.userInfoEndpoint,
352
+ overrideUserInfo: ctx.body.overrideUserInfo || options?.defaultOverrideUserInfo || false
353
+ }) : null,
354
+ samlConfig: body.samlConfig ? JSON.stringify({
355
+ issuer: body.issuer,
356
+ entryPoint: body.samlConfig.entryPoint,
357
+ cert: body.samlConfig.cert,
358
+ callbackUrl: body.samlConfig.callbackUrl,
359
+ audience: body.samlConfig.audience,
360
+ idpMetadata: body.samlConfig.idpMetadata,
361
+ spMetadata: body.samlConfig.spMetadata,
362
+ wantAssertionsSigned: body.samlConfig.wantAssertionsSigned,
363
+ signatureAlgorithm: body.samlConfig.signatureAlgorithm,
364
+ digestAlgorithm: body.samlConfig.digestAlgorithm,
365
+ identifierFormat: body.samlConfig.identifierFormat,
366
+ privateKey: body.samlConfig.privateKey,
367
+ decryptionPvk: body.samlConfig.decryptionPvk,
368
+ additionalParams: body.samlConfig.additionalParams,
369
+ mapping: body.samlConfig.mapping
370
+ }) : null,
371
+ organizationId: body.organizationId,
372
+ userId: ctx.context.session.user.id,
373
+ providerId: body.providerId
374
+ }
375
+ });
376
+ return ctx.json({
377
+ ...provider,
378
+ oidcConfig: JSON.parse(provider.oidcConfig),
379
+ samlConfig: JSON.parse(provider.samlConfig),
380
+ redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`
381
+ });
382
+ });
383
+ };
384
+ const signInSSO = (options) => {
385
+ return createAuthEndpoint("/sign-in/sso", {
386
+ method: "POST",
387
+ body: z.object({
388
+ email: z.string({}).meta({ description: "The email address to sign in with. This is used to identify the issuer to sign in with. It's optional if the issuer is provided" }).optional(),
389
+ organizationSlug: z.string({}).meta({ description: "The slug of the organization to sign in with" }).optional(),
390
+ providerId: z.string({}).meta({ description: "The ID of the provider to sign in with. This can be provided instead of email or issuer" }).optional(),
391
+ domain: z.string({}).meta({ description: "The domain of the provider." }).optional(),
392
+ callbackURL: z.string({}).meta({ description: "The URL to redirect to after login" }),
393
+ errorCallbackURL: z.string({}).meta({ description: "The URL to redirect to after login" }).optional(),
394
+ newUserCallbackURL: z.string({}).meta({ description: "The URL to redirect to after login if the user is new" }).optional(),
395
+ scopes: z.array(z.string(), {}).meta({ description: "Scopes to request from the provider." }).optional(),
396
+ loginHint: z.string({}).meta({ description: "Login hint to send to the identity provider (e.g., email or identifier). If supported, will be sent as 'login_hint'." }).optional(),
397
+ requestSignUp: z.boolean({}).meta({ description: "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider" }).optional(),
398
+ providerType: z.enum(["oidc", "saml"]).optional()
399
+ }),
400
+ metadata: { openapi: {
401
+ operationId: "signInWithSSO",
402
+ summary: "Sign in with SSO provider",
403
+ description: "This endpoint is used to sign in with an SSO provider. It redirects to the provider's authorization URL",
404
+ requestBody: { content: { "application/json": { schema: {
405
+ type: "object",
406
+ properties: {
407
+ email: {
408
+ type: "string",
409
+ description: "The email address to sign in with. This is used to identify the issuer to sign in with. It's optional if the issuer is provided"
410
+ },
411
+ issuer: {
412
+ type: "string",
413
+ description: "The issuer identifier, this is the URL of the provider and can be used to verify the provider and identify the provider during login. It's optional if the email is provided"
414
+ },
415
+ providerId: {
416
+ type: "string",
417
+ description: "The ID of the provider to sign in with. This can be provided instead of email or issuer"
418
+ },
419
+ callbackURL: {
420
+ type: "string",
421
+ description: "The URL to redirect to after login"
422
+ },
423
+ errorCallbackURL: {
424
+ type: "string",
425
+ description: "The URL to redirect to after login"
426
+ },
427
+ newUserCallbackURL: {
428
+ type: "string",
429
+ description: "The URL to redirect to after login if the user is new"
430
+ },
431
+ loginHint: {
432
+ type: "string",
433
+ description: "Login hint to send to the identity provider (e.g., email or identifier). If supported, sent as 'login_hint'."
434
+ }
435
+ },
436
+ required: ["callbackURL"]
437
+ } } } },
438
+ responses: { "200": {
439
+ description: "Authorization URL generated successfully for SSO sign-in",
440
+ content: { "application/json": { schema: {
441
+ type: "object",
442
+ properties: {
443
+ url: {
444
+ type: "string",
445
+ format: "uri",
446
+ description: "The authorization URL to redirect the user to for SSO sign-in"
447
+ },
448
+ redirect: {
449
+ type: "boolean",
450
+ description: "Indicates that the client should redirect to the provided URL",
451
+ enum: [true]
452
+ }
453
+ },
454
+ required: ["url", "redirect"]
455
+ } } }
456
+ } }
457
+ } }
458
+ }, async (ctx) => {
459
+ const body = ctx.body;
460
+ let { email, organizationSlug, providerId, domain } = body;
461
+ if (!options?.defaultSSO?.length && !email && !organizationSlug && !domain && !providerId) throw new APIError("BAD_REQUEST", { message: "email, organizationSlug, domain or providerId is required" });
462
+ domain = body.domain || email?.split("@")[1];
463
+ let orgId = "";
464
+ if (organizationSlug) orgId = await ctx.context.adapter.findOne({
465
+ model: "organization",
466
+ where: [{
467
+ field: "slug",
468
+ value: organizationSlug
469
+ }]
470
+ }).then((res) => {
471
+ if (!res) return "";
472
+ return res.id;
473
+ });
474
+ let provider = null;
475
+ if (options?.defaultSSO?.length) {
476
+ const matchingDefault = providerId ? options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId) : options.defaultSSO.find((defaultProvider) => defaultProvider.domain === domain);
477
+ if (matchingDefault) provider = {
478
+ issuer: matchingDefault.samlConfig?.issuer || matchingDefault.oidcConfig?.issuer || "",
479
+ providerId: matchingDefault.providerId,
480
+ userId: "default",
481
+ oidcConfig: matchingDefault.oidcConfig,
482
+ samlConfig: matchingDefault.samlConfig,
483
+ domain: matchingDefault.domain
484
+ };
485
+ }
486
+ if (!providerId && !orgId && !domain) throw new APIError("BAD_REQUEST", { message: "providerId, orgId or domain is required" });
487
+ if (!provider) provider = await ctx.context.adapter.findOne({
488
+ model: "ssoProvider",
489
+ where: [{
490
+ field: providerId ? "providerId" : orgId ? "organizationId" : "domain",
491
+ value: providerId || orgId || domain
492
+ }]
493
+ }).then((res) => {
494
+ if (!res) return null;
495
+ return {
496
+ ...res,
497
+ oidcConfig: res.oidcConfig ? safeJsonParse(res.oidcConfig) || void 0 : void 0,
498
+ samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
499
+ };
500
+ });
501
+ if (!provider) throw new APIError("NOT_FOUND", { message: "No provider found for the issuer" });
502
+ if (body.providerType) {
503
+ if (body.providerType === "oidc" && !provider.oidcConfig) throw new APIError("BAD_REQUEST", { message: "OIDC provider is not configured" });
504
+ if (body.providerType === "saml" && !provider.samlConfig) throw new APIError("BAD_REQUEST", { message: "SAML provider is not configured" });
505
+ }
506
+ if (provider.oidcConfig && body.providerType !== "saml") {
507
+ let finalAuthUrl = provider.oidcConfig.authorizationEndpoint;
508
+ if (!finalAuthUrl && provider.oidcConfig.discoveryEndpoint) {
509
+ const discovery = await betterFetch(provider.oidcConfig.discoveryEndpoint, { method: "GET" });
510
+ if (discovery.data) finalAuthUrl = discovery.data.authorization_endpoint;
511
+ }
512
+ if (!finalAuthUrl) throw new APIError("BAD_REQUEST", { message: "Invalid OIDC configuration. Authorization URL not found." });
513
+ const state = await generateState(ctx, void 0, false);
514
+ const redirectURI = `${ctx.context.baseURL}/sso/callback/${provider.providerId}`;
515
+ const authorizationURL = await createAuthorizationURL({
516
+ id: provider.issuer,
517
+ options: {
518
+ clientId: provider.oidcConfig.clientId,
519
+ clientSecret: provider.oidcConfig.clientSecret
520
+ },
521
+ redirectURI,
522
+ state: state.state,
523
+ codeVerifier: provider.oidcConfig.pkce ? state.codeVerifier : void 0,
524
+ scopes: ctx.body.scopes || provider.oidcConfig.scopes || [
525
+ "openid",
526
+ "email",
527
+ "profile",
528
+ "offline_access"
529
+ ],
530
+ loginHint: ctx.body.loginHint || email,
531
+ authorizationEndpoint: finalAuthUrl
532
+ });
533
+ return ctx.json({
534
+ url: authorizationURL.toString(),
535
+ redirect: true
536
+ });
537
+ }
538
+ if (provider.samlConfig) {
539
+ const parsedSamlConfig = typeof provider.samlConfig === "object" ? provider.samlConfig : safeJsonParse(provider.samlConfig);
540
+ if (!parsedSamlConfig) throw new APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
541
+ const sp = saml.ServiceProvider({
542
+ metadata: parsedSamlConfig.spMetadata.metadata,
543
+ allowCreate: true
544
+ });
545
+ const idp = saml.IdentityProvider({
546
+ metadata: parsedSamlConfig.idpMetadata?.metadata,
547
+ entityID: parsedSamlConfig.idpMetadata?.entityID,
548
+ encryptCert: parsedSamlConfig.idpMetadata?.cert,
549
+ singleSignOnService: parsedSamlConfig.idpMetadata?.singleSignOnService
550
+ });
551
+ const loginRequest = sp.createLoginRequest(idp, "redirect");
552
+ if (!loginRequest) throw new APIError("BAD_REQUEST", { message: "Invalid SAML request" });
553
+ return ctx.json({
554
+ url: `${loginRequest.context}&RelayState=${encodeURIComponent(body.callbackURL)}`,
555
+ redirect: true
556
+ });
557
+ }
558
+ throw new APIError("BAD_REQUEST", { message: "Invalid SSO provider" });
559
+ });
560
+ };
561
+ const callbackSSO = (options) => {
562
+ return createAuthEndpoint("/sso/callback/:providerId", {
563
+ method: "GET",
564
+ query: z.object({
565
+ code: z.string().optional(),
566
+ state: z.string(),
567
+ error: z.string().optional(),
568
+ error_description: z.string().optional()
569
+ }),
570
+ metadata: {
571
+ isAction: false,
572
+ openapi: {
573
+ operationId: "handleSSOCallback",
574
+ summary: "Callback URL for SSO provider",
575
+ description: "This endpoint is used as the callback URL for SSO providers. It handles the authorization code and exchanges it for an access token",
576
+ responses: { "302": { description: "Redirects to the callback URL" } }
577
+ }
578
+ }
579
+ }, async (ctx) => {
580
+ const { code, state, error, error_description } = ctx.query;
581
+ const stateData = await parseState(ctx);
582
+ if (!stateData) {
583
+ const errorURL$1 = ctx.context.options.onAPIError?.errorURL || `${ctx.context.baseURL}/error`;
584
+ throw ctx.redirect(`${errorURL$1}?error=invalid_state`);
585
+ }
586
+ const { callbackURL, errorURL, newUserURL, requestSignUp } = stateData;
587
+ if (!code || error) throw ctx.redirect(`${errorURL || callbackURL}?error=${error}&error_description=${error_description}`);
588
+ let provider = null;
589
+ if (options?.defaultSSO?.length) {
590
+ const matchingDefault = options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === ctx.params.providerId);
591
+ if (matchingDefault) provider = {
592
+ ...matchingDefault,
593
+ issuer: matchingDefault.oidcConfig?.issuer || "",
594
+ userId: "default"
595
+ };
596
+ }
597
+ if (!provider) provider = await ctx.context.adapter.findOne({
598
+ model: "ssoProvider",
599
+ where: [{
600
+ field: "providerId",
601
+ value: ctx.params.providerId
602
+ }]
603
+ }).then((res) => {
604
+ if (!res) return null;
605
+ return {
606
+ ...res,
607
+ oidcConfig: safeJsonParse(res.oidcConfig) || void 0
608
+ };
609
+ });
610
+ if (!provider) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=provider not found`);
611
+ let config = provider.oidcConfig;
612
+ if (!config) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=provider not found`);
613
+ const discovery = await betterFetch(config.discoveryEndpoint);
614
+ if (discovery.data) config = {
615
+ tokenEndpoint: discovery.data.token_endpoint,
616
+ tokenEndpointAuthentication: discovery.data.token_endpoint_auth_method,
617
+ userInfoEndpoint: discovery.data.userinfo_endpoint,
618
+ scopes: [
619
+ "openid",
620
+ "email",
621
+ "profile",
622
+ "offline_access"
623
+ ],
624
+ ...config
625
+ };
626
+ if (!config.tokenEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_endpoint_not_found`);
627
+ const tokenResponse = await validateAuthorizationCode({
628
+ code,
629
+ codeVerifier: config.pkce ? stateData.codeVerifier : void 0,
630
+ redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
631
+ options: {
632
+ clientId: config.clientId,
633
+ clientSecret: config.clientSecret
634
+ },
635
+ tokenEndpoint: config.tokenEndpoint,
636
+ authentication: config.tokenEndpointAuthentication === "client_secret_post" ? "post" : "basic"
637
+ }).catch((e) => {
638
+ if (e instanceof BetterFetchError) throw ctx.redirect(`${errorURL || callbackURL}?error=invalid_provider&error_description=${e.message}`);
639
+ return null;
640
+ });
641
+ if (!tokenResponse) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_response_not_found`);
642
+ let userInfo = null;
643
+ if (tokenResponse.idToken) {
644
+ const idToken = decodeJwt(tokenResponse.idToken);
645
+ if (!config.jwksEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=jwks_endpoint_not_found`);
646
+ const verified = await validateToken(tokenResponse.idToken, config.jwksEndpoint).catch((e) => {
647
+ ctx.context.logger.error(e);
648
+ return null;
649
+ });
650
+ if (!verified) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=token_not_verified`);
651
+ if (verified.payload.iss !== provider.issuer) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=issuer_mismatch`);
652
+ const mapping = config.mapping || {};
653
+ userInfo = {
654
+ ...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, verified.payload[value]])),
655
+ id: idToken[mapping.id || "sub"],
656
+ email: idToken[mapping.email || "email"],
657
+ emailVerified: options?.trustEmailVerified ? idToken[mapping.emailVerified || "email_verified"] : false,
658
+ name: idToken[mapping.name || "name"],
659
+ image: idToken[mapping.image || "picture"]
660
+ };
661
+ }
662
+ if (!userInfo) {
663
+ if (!config.userInfoEndpoint) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=user_info_endpoint_not_found`);
664
+ const userInfoResponse = await betterFetch(config.userInfoEndpoint, { headers: { Authorization: `Bearer ${tokenResponse.accessToken}` } });
665
+ if (userInfoResponse.error) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=${userInfoResponse.error.message}`);
666
+ userInfo = userInfoResponse.data;
667
+ }
668
+ if (!userInfo.email || !userInfo.id) throw ctx.redirect(`${errorURL || callbackURL}/error?error=invalid_provider&error_description=missing_user_info`);
669
+ const linked = await handleOAuthUserInfo(ctx, {
670
+ userInfo: {
671
+ email: userInfo.email,
672
+ name: userInfo.name || userInfo.email,
673
+ id: userInfo.id,
674
+ image: userInfo.image,
675
+ emailVerified: options?.trustEmailVerified ? userInfo.emailVerified || false : false
676
+ },
677
+ account: {
678
+ idToken: tokenResponse.idToken,
679
+ accessToken: tokenResponse.accessToken,
680
+ refreshToken: tokenResponse.refreshToken,
681
+ accountId: userInfo.id,
682
+ providerId: provider.providerId,
683
+ accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt,
684
+ refreshTokenExpiresAt: tokenResponse.refreshTokenExpiresAt,
685
+ scope: tokenResponse.scopes?.join(",")
686
+ },
687
+ callbackURL,
688
+ disableSignUp: options?.disableImplicitSignUp && !requestSignUp,
689
+ overrideUserInfo: config.overrideUserInfo
690
+ });
691
+ if (linked.error) throw ctx.redirect(`${errorURL || callbackURL}/error?error=${linked.error}`);
692
+ const { session, user } = linked.data;
693
+ if (options?.provisionUser) await options.provisionUser({
694
+ user,
695
+ userInfo,
696
+ token: tokenResponse,
697
+ provider
698
+ });
699
+ if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
700
+ if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
701
+ if (!await ctx.context.adapter.findOne({
702
+ model: "member",
703
+ where: [{
704
+ field: "organizationId",
705
+ value: provider.organizationId
706
+ }, {
707
+ field: "userId",
708
+ value: user.id
709
+ }]
710
+ })) {
711
+ const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
712
+ user,
713
+ userInfo,
714
+ token: tokenResponse,
715
+ provider
716
+ }) : options?.organizationProvisioning?.defaultRole || "member";
717
+ await ctx.context.adapter.create({
718
+ model: "member",
719
+ data: {
720
+ organizationId: provider.organizationId,
721
+ userId: user.id,
722
+ role,
723
+ createdAt: /* @__PURE__ */ new Date(),
724
+ updatedAt: /* @__PURE__ */ new Date()
725
+ }
726
+ });
727
+ }
728
+ }
729
+ }
730
+ await setSessionCookie(ctx, {
731
+ session,
732
+ user
733
+ });
734
+ let toRedirectTo;
735
+ try {
736
+ toRedirectTo = (linked.isRegister ? newUserURL || callbackURL : callbackURL).toString();
737
+ } catch {
738
+ toRedirectTo = linked.isRegister ? newUserURL || callbackURL : callbackURL;
739
+ }
740
+ throw ctx.redirect(toRedirectTo);
741
+ });
742
+ };
743
+ const callbackSSOSAML = (options) => {
744
+ return createAuthEndpoint("/sso/saml2/callback/:providerId", {
745
+ method: "POST",
746
+ body: z.object({
747
+ SAMLResponse: z.string(),
748
+ RelayState: z.string().optional()
749
+ }),
750
+ metadata: {
751
+ isAction: false,
752
+ openapi: {
753
+ operationId: "handleSAMLCallback",
754
+ summary: "Callback URL for SAML provider",
755
+ description: "This endpoint is used as the callback URL for SAML providers.",
756
+ responses: {
757
+ "302": { description: "Redirects to the callback URL" },
758
+ "400": { description: "Invalid SAML response" },
759
+ "401": { description: "Unauthorized - SAML authentication failed" }
760
+ }
761
+ }
762
+ }
763
+ }, async (ctx) => {
764
+ const { SAMLResponse, RelayState } = ctx.body;
765
+ const { providerId } = ctx.params;
766
+ let provider = null;
767
+ if (options?.defaultSSO?.length) {
768
+ const matchingDefault = options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId);
769
+ if (matchingDefault) provider = {
770
+ ...matchingDefault,
771
+ userId: "default",
772
+ issuer: matchingDefault.samlConfig?.issuer || ""
773
+ };
774
+ }
775
+ if (!provider) provider = await ctx.context.adapter.findOne({
776
+ model: "ssoProvider",
777
+ where: [{
778
+ field: "providerId",
779
+ value: providerId
780
+ }]
781
+ }).then((res) => {
782
+ if (!res) return null;
783
+ return {
784
+ ...res,
785
+ samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
786
+ };
787
+ });
788
+ if (!provider) throw new APIError("NOT_FOUND", { message: "No provider found for the given providerId" });
789
+ const parsedSamlConfig = safeJsonParse(provider.samlConfig);
790
+ if (!parsedSamlConfig) throw new APIError("BAD_REQUEST", { message: "Invalid SAML configuration" });
791
+ const idpData = parsedSamlConfig.idpMetadata;
792
+ let idp = null;
793
+ if (!idpData?.metadata) idp = saml.IdentityProvider({
794
+ entityID: idpData?.entityID || parsedSamlConfig.issuer,
795
+ singleSignOnService: [{
796
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
797
+ Location: parsedSamlConfig.entryPoint
798
+ }],
799
+ signingCert: idpData?.cert || parsedSamlConfig.cert,
800
+ wantAuthnRequestsSigned: parsedSamlConfig.wantAssertionsSigned || false,
801
+ isAssertionEncrypted: idpData?.isAssertionEncrypted || false,
802
+ encPrivateKey: idpData?.encPrivateKey,
803
+ encPrivateKeyPass: idpData?.encPrivateKeyPass
804
+ });
805
+ else idp = saml.IdentityProvider({
806
+ metadata: idpData.metadata,
807
+ privateKey: idpData.privateKey,
808
+ privateKeyPass: idpData.privateKeyPass,
809
+ isAssertionEncrypted: idpData.isAssertionEncrypted,
810
+ encPrivateKey: idpData.encPrivateKey,
811
+ encPrivateKeyPass: idpData.encPrivateKeyPass
812
+ });
813
+ const spData = parsedSamlConfig.spMetadata;
814
+ const sp = saml.ServiceProvider({
815
+ metadata: spData?.metadata,
816
+ entityID: spData?.entityID || parsedSamlConfig.issuer,
817
+ assertionConsumerService: spData?.metadata ? void 0 : [{
818
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
819
+ Location: parsedSamlConfig.callbackUrl
820
+ }],
821
+ privateKey: spData?.privateKey || parsedSamlConfig.privateKey,
822
+ privateKeyPass: spData?.privateKeyPass,
823
+ isAssertionEncrypted: spData?.isAssertionEncrypted || false,
824
+ encPrivateKey: spData?.encPrivateKey,
825
+ encPrivateKeyPass: spData?.encPrivateKeyPass,
826
+ wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
827
+ nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
828
+ });
829
+ let parsedResponse;
830
+ try {
831
+ const decodedResponse = Buffer.from(SAMLResponse, "base64").toString("utf-8");
832
+ try {
833
+ parsedResponse = await sp.parseLoginResponse(idp, "post", { body: {
834
+ SAMLResponse,
835
+ RelayState: RelayState || void 0
836
+ } });
837
+ } catch (parseError) {
838
+ const nameIDMatch = decodedResponse.match(/<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/);
839
+ if (!nameIDMatch) throw parseError;
840
+ parsedResponse = { extract: {
841
+ nameID: nameIDMatch[1],
842
+ attributes: { nameID: nameIDMatch[1] },
843
+ sessionIndex: {},
844
+ conditions: {}
845
+ } };
846
+ }
847
+ if (!parsedResponse?.extract) throw new Error("Invalid SAML response structure");
848
+ } catch (error) {
849
+ ctx.context.logger.error("SAML response validation failed", {
850
+ error,
851
+ decodedResponse: Buffer.from(SAMLResponse, "base64").toString("utf-8")
852
+ });
853
+ throw new APIError("BAD_REQUEST", {
854
+ message: "Invalid SAML response",
855
+ details: error instanceof Error ? error.message : String(error)
856
+ });
857
+ }
858
+ const { extract } = parsedResponse;
859
+ const attributes = extract.attributes || {};
860
+ const mapping = parsedSamlConfig.mapping ?? {};
861
+ const userInfo = {
862
+ ...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, attributes[value]])),
863
+ id: attributes[mapping.id || "nameID"] || extract.nameID,
864
+ email: attributes[mapping.email || "email"] || extract.nameID,
865
+ name: [attributes[mapping.firstName || "givenName"], attributes[mapping.lastName || "surname"]].filter(Boolean).join(" ") || attributes[mapping.name || "displayName"] || extract.nameID,
866
+ emailVerified: options?.trustEmailVerified && mapping.emailVerified ? attributes[mapping.emailVerified] || false : false
867
+ };
868
+ if (!userInfo.id || !userInfo.email) {
869
+ ctx.context.logger.error("Missing essential user info from SAML response", {
870
+ attributes: Object.keys(attributes),
871
+ mapping,
872
+ extractedId: userInfo.id,
873
+ extractedEmail: userInfo.email
874
+ });
875
+ throw new APIError("BAD_REQUEST", { message: "Unable to extract user ID or email from SAML response" });
876
+ }
877
+ let user;
878
+ const existingUser = await ctx.context.adapter.findOne({
879
+ model: "user",
880
+ where: [{
881
+ field: "email",
882
+ value: userInfo.email
883
+ }]
884
+ });
885
+ if (existingUser) user = existingUser;
886
+ else {
887
+ if (options?.disableImplicitSignUp) throw new APIError("UNAUTHORIZED", { message: "User not found and implicit sign up is disabled for this provider" });
888
+ user = await ctx.context.internalAdapter.createUser({
889
+ email: userInfo.email,
890
+ name: userInfo.name,
891
+ emailVerified: userInfo.emailVerified
892
+ });
893
+ }
894
+ if (!await ctx.context.adapter.findOne({
895
+ model: "account",
896
+ where: [
897
+ {
898
+ field: "userId",
899
+ value: user.id
900
+ },
901
+ {
902
+ field: "providerId",
903
+ value: provider.providerId
904
+ },
905
+ {
906
+ field: "accountId",
907
+ value: userInfo.id
908
+ }
909
+ ]
910
+ })) await ctx.context.internalAdapter.createAccount({
911
+ userId: user.id,
912
+ providerId: provider.providerId,
913
+ accountId: userInfo.id,
914
+ accessToken: "",
915
+ refreshToken: ""
916
+ });
917
+ if (options?.provisionUser) await options.provisionUser({
918
+ user,
919
+ userInfo,
920
+ provider
921
+ });
922
+ if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
923
+ if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
924
+ if (!await ctx.context.adapter.findOne({
925
+ model: "member",
926
+ where: [{
927
+ field: "organizationId",
928
+ value: provider.organizationId
929
+ }, {
930
+ field: "userId",
931
+ value: user.id
932
+ }]
933
+ })) {
934
+ const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
935
+ user,
936
+ userInfo,
937
+ provider
938
+ }) : options?.organizationProvisioning?.defaultRole || "member";
939
+ await ctx.context.adapter.create({
940
+ model: "member",
941
+ data: {
942
+ organizationId: provider.organizationId,
943
+ userId: user.id,
944
+ role,
945
+ createdAt: /* @__PURE__ */ new Date(),
946
+ updatedAt: /* @__PURE__ */ new Date()
947
+ }
948
+ });
949
+ }
950
+ }
951
+ }
952
+ await setSessionCookie(ctx, {
953
+ session: await ctx.context.internalAdapter.createSession(user.id),
954
+ user
955
+ });
956
+ const callbackUrl = RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
957
+ throw ctx.redirect(callbackUrl);
958
+ });
959
+ };
960
+ const acsEndpoint = (options) => {
961
+ return createAuthEndpoint("/sso/saml2/sp/acs/:providerId", {
962
+ method: "POST",
963
+ params: z.object({ providerId: z.string().optional() }),
964
+ body: z.object({
965
+ SAMLResponse: z.string(),
966
+ RelayState: z.string().optional()
967
+ }),
968
+ metadata: {
969
+ isAction: false,
970
+ openapi: {
971
+ operationId: "handleSAMLAssertionConsumerService",
972
+ summary: "SAML Assertion Consumer Service",
973
+ description: "Handles SAML responses from IdP after successful authentication",
974
+ responses: { "302": { description: "Redirects to the callback URL after successful authentication" } }
975
+ }
976
+ }
977
+ }, async (ctx) => {
978
+ const { SAMLResponse, RelayState = "" } = ctx.body;
979
+ const { providerId } = ctx.params;
980
+ let provider = null;
981
+ if (options?.defaultSSO?.length) {
982
+ const matchingDefault = providerId ? options.defaultSSO.find((defaultProvider) => defaultProvider.providerId === providerId) : options.defaultSSO[0];
983
+ if (matchingDefault) provider = {
984
+ issuer: matchingDefault.samlConfig?.issuer || "",
985
+ providerId: matchingDefault.providerId,
986
+ userId: "default",
987
+ samlConfig: matchingDefault.samlConfig,
988
+ domain: matchingDefault.domain
989
+ };
990
+ } else provider = await ctx.context.adapter.findOne({
991
+ model: "ssoProvider",
992
+ where: [{
993
+ field: "providerId",
994
+ value: providerId ?? "sso"
995
+ }]
996
+ }).then((res) => {
997
+ if (!res) return null;
998
+ return {
999
+ ...res,
1000
+ samlConfig: res.samlConfig ? safeJsonParse(res.samlConfig) || void 0 : void 0
1001
+ };
1002
+ });
1003
+ if (!provider?.samlConfig) throw new APIError("NOT_FOUND", { message: "No SAML provider found" });
1004
+ const parsedSamlConfig = provider.samlConfig;
1005
+ const sp = saml.ServiceProvider({
1006
+ entityID: parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
1007
+ assertionConsumerService: [{
1008
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
1009
+ Location: parsedSamlConfig.callbackUrl || `${ctx.context.baseURL}/sso/saml2/sp/acs/${providerId}`
1010
+ }],
1011
+ wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
1012
+ metadata: parsedSamlConfig.spMetadata?.metadata,
1013
+ privateKey: parsedSamlConfig.spMetadata?.privateKey || parsedSamlConfig.privateKey,
1014
+ privateKeyPass: parsedSamlConfig.spMetadata?.privateKeyPass,
1015
+ nameIDFormat: parsedSamlConfig.identifierFormat ? [parsedSamlConfig.identifierFormat] : void 0
1016
+ });
1017
+ const idpData = parsedSamlConfig.idpMetadata;
1018
+ const idp = !idpData?.metadata ? saml.IdentityProvider({
1019
+ entityID: idpData?.entityID || parsedSamlConfig.issuer,
1020
+ singleSignOnService: idpData?.singleSignOnService || [{
1021
+ Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
1022
+ Location: parsedSamlConfig.entryPoint
1023
+ }],
1024
+ signingCert: idpData?.cert || parsedSamlConfig.cert
1025
+ }) : saml.IdentityProvider({ metadata: idpData.metadata });
1026
+ let parsedResponse;
1027
+ try {
1028
+ let decodedResponse = Buffer.from(SAMLResponse, "base64").toString("utf-8");
1029
+ if (!decodedResponse.includes("StatusCode")) {
1030
+ const insertPoint = decodedResponse.indexOf("</saml2:Issuer>");
1031
+ if (insertPoint !== -1) decodedResponse = decodedResponse.slice(0, insertPoint + 14) + "<saml2:Status><saml2:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/></saml2:Status>" + decodedResponse.slice(insertPoint + 14);
1032
+ } else if (!decodedResponse.includes("saml2:Success")) decodedResponse = decodedResponse.replace(/<saml2:StatusCode Value="[^"]+"/, "<saml2:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"");
1033
+ try {
1034
+ parsedResponse = await sp.parseLoginResponse(idp, "post", { body: {
1035
+ SAMLResponse,
1036
+ RelayState: RelayState || void 0
1037
+ } });
1038
+ } catch (parseError) {
1039
+ const nameIDMatch = decodedResponse.match(/<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/);
1040
+ if (!nameIDMatch) throw parseError;
1041
+ parsedResponse = { extract: {
1042
+ nameID: nameIDMatch[1],
1043
+ attributes: { nameID: nameIDMatch[1] },
1044
+ sessionIndex: {},
1045
+ conditions: {}
1046
+ } };
1047
+ }
1048
+ if (!parsedResponse?.extract) throw new Error("Invalid SAML response structure");
1049
+ } catch (error) {
1050
+ ctx.context.logger.error("SAML response validation failed", {
1051
+ error,
1052
+ decodedResponse: Buffer.from(SAMLResponse, "base64").toString("utf-8")
1053
+ });
1054
+ throw new APIError("BAD_REQUEST", {
1055
+ message: "Invalid SAML response",
1056
+ details: error instanceof Error ? error.message : String(error)
1057
+ });
1058
+ }
1059
+ const { extract } = parsedResponse;
1060
+ const attributes = extract.attributes || {};
1061
+ const mapping = parsedSamlConfig.mapping ?? {};
1062
+ const userInfo = {
1063
+ ...Object.fromEntries(Object.entries(mapping.extraFields || {}).map(([key, value]) => [key, attributes[value]])),
1064
+ id: attributes[mapping.id || "nameID"] || extract.nameID,
1065
+ email: attributes[mapping.email || "email"] || extract.nameID,
1066
+ name: [attributes[mapping.firstName || "givenName"], attributes[mapping.lastName || "surname"]].filter(Boolean).join(" ") || attributes[mapping.name || "displayName"] || extract.nameID,
1067
+ emailVerified: options?.trustEmailVerified && mapping.emailVerified ? attributes[mapping.emailVerified] || false : false
1068
+ };
1069
+ if (!userInfo.id || !userInfo.email) {
1070
+ ctx.context.logger.error("Missing essential user info from SAML response", {
1071
+ attributes: Object.keys(attributes),
1072
+ mapping,
1073
+ extractedId: userInfo.id,
1074
+ extractedEmail: userInfo.email
1075
+ });
1076
+ throw new APIError("BAD_REQUEST", { message: "Unable to extract user ID or email from SAML response" });
1077
+ }
1078
+ let user;
1079
+ const existingUser = await ctx.context.adapter.findOne({
1080
+ model: "user",
1081
+ where: [{
1082
+ field: "email",
1083
+ value: userInfo.email
1084
+ }]
1085
+ });
1086
+ if (existingUser) {
1087
+ if (!await ctx.context.adapter.findOne({
1088
+ model: "account",
1089
+ where: [
1090
+ {
1091
+ field: "userId",
1092
+ value: existingUser.id
1093
+ },
1094
+ {
1095
+ field: "providerId",
1096
+ value: provider.providerId
1097
+ },
1098
+ {
1099
+ field: "accountId",
1100
+ value: userInfo.id
1101
+ }
1102
+ ]
1103
+ })) {
1104
+ if (!ctx.context.options.account?.accountLinking?.trustedProviders?.includes(provider.providerId)) throw ctx.redirect(`${parsedSamlConfig.callbackUrl}?error=account_not_found`);
1105
+ await ctx.context.internalAdapter.createAccount({
1106
+ userId: existingUser.id,
1107
+ providerId: provider.providerId,
1108
+ accountId: userInfo.id,
1109
+ accessToken: "",
1110
+ refreshToken: ""
1111
+ });
1112
+ }
1113
+ user = existingUser;
1114
+ } else {
1115
+ user = await ctx.context.internalAdapter.createUser({
1116
+ email: userInfo.email,
1117
+ name: userInfo.name,
1118
+ emailVerified: options?.trustEmailVerified ? userInfo.emailVerified || false : false
1119
+ });
1120
+ await ctx.context.internalAdapter.createAccount({
1121
+ userId: user.id,
1122
+ providerId: provider.providerId,
1123
+ accountId: userInfo.id,
1124
+ accessToken: "",
1125
+ refreshToken: "",
1126
+ accessTokenExpiresAt: /* @__PURE__ */ new Date(),
1127
+ refreshTokenExpiresAt: /* @__PURE__ */ new Date(),
1128
+ scope: ""
1129
+ });
1130
+ }
1131
+ if (options?.provisionUser) await options.provisionUser({
1132
+ user,
1133
+ userInfo,
1134
+ provider
1135
+ });
1136
+ if (provider.organizationId && !options?.organizationProvisioning?.disabled) {
1137
+ if (ctx.context.options.plugins?.find((plugin) => plugin.id === "organization")) {
1138
+ if (!await ctx.context.adapter.findOne({
1139
+ model: "member",
1140
+ where: [{
1141
+ field: "organizationId",
1142
+ value: provider.organizationId
1143
+ }, {
1144
+ field: "userId",
1145
+ value: user.id
1146
+ }]
1147
+ })) {
1148
+ const role = options?.organizationProvisioning?.getRole ? await options.organizationProvisioning.getRole({
1149
+ user,
1150
+ userInfo,
1151
+ provider
1152
+ }) : options?.organizationProvisioning?.defaultRole || "member";
1153
+ await ctx.context.adapter.create({
1154
+ model: "member",
1155
+ data: {
1156
+ organizationId: provider.organizationId,
1157
+ userId: user.id,
1158
+ role,
1159
+ createdAt: /* @__PURE__ */ new Date(),
1160
+ updatedAt: /* @__PURE__ */ new Date()
1161
+ }
1162
+ });
1163
+ }
1164
+ }
1165
+ }
1166
+ await setSessionCookie(ctx, {
1167
+ session: await ctx.context.internalAdapter.createSession(user.id),
1168
+ user
1169
+ });
1170
+ const callbackUrl = RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
1171
+ throw ctx.redirect(callbackUrl);
1172
+ });
1173
+ };
1174
+
1175
+ //#endregion
1176
+ //#region src/index.ts
1177
+ saml.setSchemaValidator({ async validate(xml) {
1178
+ if (XMLValidator.validate(xml, { allowBooleanAttributes: true }) === true) return "SUCCESS_VALIDATE_XML";
1179
+ throw "ERR_INVALID_XML";
1180
+ } });
1181
+ function sso(options) {
1182
+ return {
1183
+ id: "sso",
1184
+ endpoints: {
1185
+ spMetadata: spMetadata(),
1186
+ registerSSOProvider: registerSSOProvider(options),
1187
+ signInSSO: signInSSO(options),
1188
+ callbackSSO: callbackSSO(options),
1189
+ callbackSSOSAML: callbackSSOSAML(options),
1190
+ acsEndpoint: acsEndpoint(options)
1191
+ },
1192
+ schema: { ssoProvider: {
1193
+ modelName: options?.modelName ?? "ssoProvider",
1194
+ fields: {
1195
+ issuer: {
1196
+ type: "string",
1197
+ required: true,
1198
+ fieldName: options?.fields?.issuer ?? "issuer"
1199
+ },
1200
+ oidcConfig: {
1201
+ type: "string",
1202
+ required: false,
1203
+ fieldName: options?.fields?.oidcConfig ?? "oidcConfig"
1204
+ },
1205
+ samlConfig: {
1206
+ type: "string",
1207
+ required: false,
1208
+ fieldName: options?.fields?.samlConfig ?? "samlConfig"
1209
+ },
1210
+ userId: {
1211
+ type: "string",
1212
+ references: {
1213
+ model: "user",
1214
+ field: "id"
1215
+ },
1216
+ fieldName: options?.fields?.userId ?? "userId"
1217
+ },
1218
+ providerId: {
1219
+ type: "string",
1220
+ required: true,
1221
+ unique: true,
1222
+ fieldName: options?.fields?.providerId ?? "providerId"
1223
+ },
1224
+ organizationId: {
1225
+ type: "string",
1226
+ required: false,
1227
+ fieldName: options?.fields?.organizationId ?? "organizationId"
1228
+ },
1229
+ domain: {
1230
+ type: "string",
1231
+ required: true,
1232
+ fieldName: options?.fields?.domain ?? "domain"
1233
+ }
1234
+ }
1235
+ } }
1236
+ };
1237
+ }
1238
+
1239
+ //#endregion
3
1240
  export { sso };