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