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

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