@better-auth/sso 1.3.0-beta.1

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