@better-auth/sso 1.3.27 → 1.4.0-beta.10

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