@better-auth/sso 1.4.0-beta.19 → 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/src/index.ts CHANGED
@@ -1,29 +1,17 @@
1
- import { BetterFetchError, betterFetch } from "@better-fetch/fetch";
2
- import {
3
- type Account,
4
- type BetterAuthPlugin,
5
- generateState,
6
- type OAuth2Tokens,
7
- type Session,
8
- type User,
9
- } from "better-auth";
10
- import { APIError, sessionMiddleware } from "better-auth/api";
11
- import { setSessionCookie } from "better-auth/cookies";
12
- import {
13
- createAuthorizationURL,
14
- handleOAuthUserInfo,
15
- parseState,
16
- validateAuthorizationCode,
17
- validateToken,
18
- } from "better-auth/oauth2";
19
- import { createAuthEndpoint } from "better-auth/plugins";
1
+ import { type BetterAuthPlugin } from "better-auth";
20
2
  import { XMLValidator } from "fast-xml-parser";
21
- import { decodeJwt } from "jose";
22
3
  import * as saml from "samlify";
23
- import type { BindingContext } from "samlify/types/src/entity";
24
- import type { IdentityProvider } from "samlify/types/src/entity-idp";
25
- import type { FlowResult } from "samlify/types/src/flow";
26
- import * as z from "zod/v4";
4
+ import {
5
+ acsEndpoint,
6
+ callbackSSO,
7
+ callbackSSOSAML,
8
+ registerSSOProvider,
9
+ signInSSO,
10
+ spMetadata,
11
+ } from "./routes/sso";
12
+ import type { OIDCConfig, SAMLConfig, SSOOptions } from "./types";
13
+
14
+ export type { SAMLConfig, OIDCConfig, SSOOptions };
27
15
 
28
16
  const fastValidator = {
29
17
  async validate(xml: string) {
@@ -37,2231 +25,32 @@ const fastValidator = {
37
25
 
38
26
  saml.setSchemaValidator(fastValidator);
39
27
 
40
- /**
41
- * Safely parses a value that might be a JSON string or already a parsed object
42
- * This handles cases where ORMs like Drizzle might return already parsed objects
43
- * instead of JSON strings from TEXT/JSON columns
44
- */
45
- function safeJsonParse<T>(value: string | T | null | undefined): T | null {
46
- if (!value) return null;
47
-
48
- // If it's already an object (not a string), return it as-is
49
- if (typeof value === "object") {
50
- return value as T;
51
- }
52
-
53
- // If it's a string, try to parse it
54
- if (typeof value === "string") {
55
- try {
56
- return JSON.parse(value) as T;
57
- } catch (error) {
58
- // If parsing fails, this might indicate the string is not valid JSON
59
- throw new Error(
60
- `Failed to parse JSON: ${error instanceof Error ? error.message : "Unknown error"}`,
61
- );
62
- }
63
- }
64
-
65
- return null;
66
- }
67
-
68
- export interface OIDCMapping {
69
- id?: string | undefined;
70
- email?: string | undefined;
71
- emailVerified?: string | undefined;
72
- name?: string | undefined;
73
- image?: string | undefined;
74
- extraFields?: Record<string, string> | undefined;
75
- }
76
-
77
- export interface SAMLMapping {
78
- id?: string | undefined;
79
- email?: string | undefined;
80
- emailVerified?: string | undefined;
81
- name?: string | undefined;
82
- firstName?: string | undefined;
83
- lastName?: string | undefined;
84
- extraFields?: Record<string, string> | undefined;
85
- }
86
-
87
- export interface OIDCConfig {
88
- issuer: string;
89
- pkce: boolean;
90
- clientId: string;
91
- clientSecret: string;
92
- authorizationEndpoint?: string | undefined;
93
- discoveryEndpoint: string;
94
- userInfoEndpoint?: string | undefined;
95
- scopes?: string[] | undefined;
96
- overrideUserInfo?: boolean | undefined;
97
- tokenEndpoint?: string | undefined;
98
- tokenEndpointAuthentication?:
99
- | ("client_secret_post" | "client_secret_basic")
100
- | undefined;
101
- jwksEndpoint?: string | undefined;
102
- mapping?: OIDCMapping | undefined;
103
- }
104
-
105
- export interface SAMLConfig {
106
- issuer: string;
107
- entryPoint: string;
108
- cert: string;
109
- callbackUrl: string;
110
- audience?: string | undefined;
111
- idpMetadata?:
112
- | {
113
- metadata?: string;
114
- entityID?: string;
115
- entityURL?: string;
116
- redirectURL?: string;
117
- cert?: string;
118
- privateKey?: string;
119
- privateKeyPass?: string;
120
- isAssertionEncrypted?: boolean;
121
- encPrivateKey?: string;
122
- encPrivateKeyPass?: string;
123
- singleSignOnService?: Array<{
124
- Binding: string;
125
- Location: string;
126
- }>;
127
- }
128
- | undefined;
129
- spMetadata: {
130
- metadata?: string | undefined;
131
- entityID?: string | undefined;
132
- binding?: string | undefined;
133
- privateKey?: string | undefined;
134
- privateKeyPass?: string | undefined;
135
- isAssertionEncrypted?: boolean | undefined;
136
- encPrivateKey?: string | undefined;
137
- encPrivateKeyPass?: string | undefined;
138
- };
139
- wantAssertionsSigned?: boolean | undefined;
140
- signatureAlgorithm?: string | undefined;
141
- digestAlgorithm?: string | undefined;
142
- identifierFormat?: string | undefined;
143
- privateKey?: string | undefined;
144
- decryptionPvk?: string | undefined;
145
- additionalParams?: Record<string, any> | undefined;
146
- mapping?: SAMLMapping | undefined;
147
- }
148
-
149
- export interface SSOProvider {
150
- issuer: string;
151
- oidcConfig?: OIDCConfig | undefined;
152
- samlConfig?: SAMLConfig | undefined;
153
- userId: string;
154
- providerId: string;
155
- organizationId?: string | undefined;
156
- }
28
+ type SSOEndpoints = {
29
+ spMetadata: ReturnType<typeof spMetadata>;
30
+ registerSSOProvider: ReturnType<typeof registerSSOProvider>;
31
+ signInSSO: ReturnType<typeof signInSSO>;
32
+ callbackSSO: ReturnType<typeof callbackSSO>;
33
+ callbackSSOSAML: ReturnType<typeof callbackSSOSAML>;
34
+ acsEndpoint: ReturnType<typeof acsEndpoint>;
35
+ };
157
36
 
158
- export interface SSOOptions {
159
- /**
160
- * custom function to provision a user when they sign in with an SSO provider.
161
- */
162
- provisionUser?:
163
- | ((data: {
164
- /**
165
- * The user object from the database
166
- */
167
- user: User & Record<string, any>;
168
- /**
169
- * The user info object from the provider
170
- */
171
- userInfo: Record<string, any>;
172
- /**
173
- * The OAuth2 tokens from the provider
174
- */
175
- token?: OAuth2Tokens;
176
- /**
177
- * The SSO provider
178
- */
179
- provider: SSOProvider;
180
- }) => Promise<void>)
181
- | undefined;
182
- /**
183
- * Organization provisioning options
184
- */
185
- organizationProvisioning?:
186
- | {
187
- disabled?: boolean;
188
- defaultRole?: "member" | "admin";
189
- getRole?: (data: {
190
- /**
191
- * The user object from the database
192
- */
193
- user: User & Record<string, any>;
194
- /**
195
- * The user info object from the provider
196
- */
197
- userInfo: Record<string, any>;
198
- /**
199
- * The OAuth2 tokens from the provider
200
- */
201
- token?: OAuth2Tokens;
202
- /**
203
- * The SSO provider
204
- */
205
- provider: SSOProvider;
206
- }) => Promise<"member" | "admin">;
207
- }
208
- | undefined;
209
- /**
210
- * Default SSO provider configurations for testing.
211
- * These will take the precedence over the database providers.
212
- */
213
- defaultSSO?:
214
- | Array<{
215
- /**
216
- * The domain to match for this default provider.
217
- * This is only used to match incoming requests to this default provider.
218
- */
219
- domain: string;
220
- /**
221
- * The provider ID to use
222
- */
223
- providerId: string;
224
- /**
225
- * SAML configuration
226
- */
227
- samlConfig?: SAMLConfig;
228
- /**
229
- * OIDC configuration
230
- */
231
- oidcConfig?: OIDCConfig;
232
- }>
233
- | undefined;
234
- /**
235
- * Override user info with the provider info.
236
- * @default false
237
- */
238
- defaultOverrideUserInfo?: boolean | undefined;
239
- /**
240
- * Disable implicit sign up for new users. When set to true for the provider,
241
- * sign-in need to be called with with requestSignUp as true to create new users.
242
- */
243
- disableImplicitSignUp?: boolean | undefined;
244
- /**
245
- * Configure the maximum number of SSO providers a user can register.
246
- * You can also pass a function that returns a number.
247
- * Set to 0 to disable SSO provider registration.
248
- *
249
- * @example
250
- * ```ts
251
- * providersLimit: async (user) => {
252
- * const plan = await getUserPlan(user);
253
- * return plan.name === "pro" ? 10 : 1;
254
- * }
255
- * ```
256
- * @default 10
257
- */
258
- providersLimit?:
259
- | (number | ((user: User) => Promise<number> | number))
260
- | undefined;
261
- /**
262
- * Trust the email verified flag from the provider.
263
- *
264
- * ⚠️ Use this with caution — it can lead to account takeover if misused. Only enable it if users **cannot freely register new providers**. You can
265
- * prevent that by using `disabledPaths` or other safeguards to block provider registration from the client.
266
- *
267
- * If you want to allow account linking for specific trusted providers, enable the `accountLinking` option in your auth config and specify those
268
- * providers in the `trustedProviders` list.
269
- * @default false
270
- */
271
- trustEmailVerified?: boolean | undefined;
272
- }
37
+ export function sso<O extends SSOOptions>(
38
+ options?: O | undefined,
39
+ ): {
40
+ id: "sso";
41
+ endpoints: SSOEndpoints;
42
+ };
273
43
 
274
- export const sso = (options?: SSOOptions | undefined) => {
44
+ export function sso<O extends SSOOptions>(options?: O | undefined): any {
275
45
  return {
276
46
  id: "sso",
277
47
  endpoints: {
278
- spMetadata: createAuthEndpoint(
279
- "/sso/saml2/sp/metadata",
280
- {
281
- method: "GET",
282
- query: z.object({
283
- providerId: z.string(),
284
- format: z.enum(["xml", "json"]).default("xml"),
285
- }),
286
- metadata: {
287
- openapi: {
288
- summary: "Get Service Provider metadata",
289
- description: "Returns the SAML metadata for the Service Provider",
290
- responses: {
291
- "200": {
292
- description: "SAML metadata in XML format",
293
- },
294
- },
295
- },
296
- },
297
- },
298
- async (ctx) => {
299
- const provider = await ctx.context.adapter.findOne<{
300
- id: string;
301
- samlConfig: string;
302
- }>({
303
- model: "ssoProvider",
304
- where: [
305
- {
306
- field: "providerId",
307
- value: ctx.query.providerId,
308
- },
309
- ],
310
- });
311
- if (!provider) {
312
- throw new APIError("NOT_FOUND", {
313
- message: "No provider found for the given providerId",
314
- });
315
- }
316
-
317
- const parsedSamlConfig = safeJsonParse<SAMLConfig>(
318
- provider.samlConfig,
319
- );
320
- if (!parsedSamlConfig) {
321
- throw new APIError("BAD_REQUEST", {
322
- message: "Invalid SAML configuration",
323
- });
324
- }
325
- const sp = parsedSamlConfig.spMetadata.metadata
326
- ? saml.ServiceProvider({
327
- metadata: parsedSamlConfig.spMetadata.metadata,
328
- })
329
- : saml.SPMetadata({
330
- entityID:
331
- parsedSamlConfig.spMetadata?.entityID ||
332
- parsedSamlConfig.issuer,
333
- assertionConsumerService: [
334
- {
335
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
336
- Location:
337
- parsedSamlConfig.callbackUrl ||
338
- `${ctx.context.baseURL}/sso/saml2/sp/acs/${provider.id}`,
339
- },
340
- ],
341
- wantMessageSigned:
342
- parsedSamlConfig.wantAssertionsSigned || false,
343
- nameIDFormat: parsedSamlConfig.identifierFormat
344
- ? [parsedSamlConfig.identifierFormat]
345
- : undefined,
346
- });
347
- return new Response(sp.getMetadata(), {
348
- headers: {
349
- "Content-Type": "application/xml",
350
- },
351
- });
352
- },
353
- ),
354
- registerSSOProvider: createAuthEndpoint(
355
- "/sso/register",
356
- {
357
- method: "POST",
358
- body: z.object({
359
- providerId: z.string({}).meta({
360
- description:
361
- "The ID of the provider. This is used to identify the provider during login and callback",
362
- }),
363
- issuer: z.string({}).meta({
364
- description: "The issuer of the provider",
365
- }),
366
- domain: z.string({}).meta({
367
- description:
368
- "The domain of the provider. This is used for email matching",
369
- }),
370
- oidcConfig: z
371
- .object({
372
- clientId: z.string({}).meta({
373
- description: "The client ID",
374
- }),
375
- clientSecret: z.string({}).meta({
376
- description: "The client secret",
377
- }),
378
- authorizationEndpoint: z
379
- .string({})
380
- .meta({
381
- description: "The authorization endpoint",
382
- })
383
- .optional(),
384
- tokenEndpoint: z
385
- .string({})
386
- .meta({
387
- description: "The token endpoint",
388
- })
389
- .optional(),
390
- userInfoEndpoint: z
391
- .string({})
392
- .meta({
393
- description: "The user info endpoint",
394
- })
395
- .optional(),
396
- tokenEndpointAuthentication: z
397
- .enum(["client_secret_post", "client_secret_basic"])
398
- .optional(),
399
- jwksEndpoint: z
400
- .string({})
401
- .meta({
402
- description: "The JWKS endpoint",
403
- })
404
- .optional(),
405
- discoveryEndpoint: z.string().optional(),
406
- scopes: z
407
- .array(z.string(), {})
408
- .meta({
409
- description:
410
- "The scopes to request. Defaults to ['openid', 'email', 'profile', 'offline_access']",
411
- })
412
- .optional(),
413
- pkce: z
414
- .boolean({})
415
- .meta({
416
- description:
417
- "Whether to use PKCE for the authorization flow",
418
- })
419
- .default(true)
420
- .optional(),
421
- mapping: z
422
- .object({
423
- id: z.string({}).meta({
424
- description:
425
- "Field mapping for user ID (defaults to 'sub')",
426
- }),
427
- email: z.string({}).meta({
428
- description:
429
- "Field mapping for email (defaults to 'email')",
430
- }),
431
- emailVerified: z
432
- .string({})
433
- .meta({
434
- description:
435
- "Field mapping for email verification (defaults to 'email_verified')",
436
- })
437
- .optional(),
438
- name: z.string({}).meta({
439
- description:
440
- "Field mapping for name (defaults to 'name')",
441
- }),
442
- image: z
443
- .string({})
444
- .meta({
445
- description:
446
- "Field mapping for image (defaults to 'picture')",
447
- })
448
- .optional(),
449
- extraFields: z.record(z.string(), z.any()).optional(),
450
- })
451
- .optional(),
452
- })
453
- .optional(),
454
- samlConfig: z
455
- .object({
456
- entryPoint: z.string({}).meta({
457
- description: "The entry point of the provider",
458
- }),
459
- cert: z.string({}).meta({
460
- description: "The certificate of the provider",
461
- }),
462
- callbackUrl: z.string({}).meta({
463
- description: "The callback URL of the provider",
464
- }),
465
- audience: z.string().optional(),
466
- idpMetadata: z
467
- .object({
468
- metadata: z.string().optional(),
469
- entityID: z.string().optional(),
470
- cert: z.string().optional(),
471
- privateKey: z.string().optional(),
472
- privateKeyPass: z.string().optional(),
473
- isAssertionEncrypted: z.boolean().optional(),
474
- encPrivateKey: z.string().optional(),
475
- encPrivateKeyPass: z.string().optional(),
476
- singleSignOnService: z
477
- .array(
478
- z.object({
479
- Binding: z.string().meta({
480
- description: "The binding type for the SSO service",
481
- }),
482
- Location: z.string().meta({
483
- description: "The URL for the SSO service",
484
- }),
485
- }),
486
- )
487
- .optional()
488
- .meta({
489
- description: "Single Sign-On service configuration",
490
- }),
491
- })
492
- .optional(),
493
- spMetadata: z.object({
494
- metadata: z.string().optional(),
495
- entityID: z.string().optional(),
496
- binding: z.string().optional(),
497
- privateKey: z.string().optional(),
498
- privateKeyPass: z.string().optional(),
499
- isAssertionEncrypted: z.boolean().optional(),
500
- encPrivateKey: z.string().optional(),
501
- encPrivateKeyPass: z.string().optional(),
502
- }),
503
- wantAssertionsSigned: z.boolean().optional(),
504
- signatureAlgorithm: z.string().optional(),
505
- digestAlgorithm: z.string().optional(),
506
- identifierFormat: z.string().optional(),
507
- privateKey: z.string().optional(),
508
- decryptionPvk: z.string().optional(),
509
- additionalParams: z.record(z.string(), z.any()).optional(),
510
- mapping: z
511
- .object({
512
- id: z.string({}).meta({
513
- description:
514
- "Field mapping for user ID (defaults to 'nameID')",
515
- }),
516
- email: z.string({}).meta({
517
- description:
518
- "Field mapping for email (defaults to 'email')",
519
- }),
520
- emailVerified: z
521
- .string({})
522
- .meta({
523
- description: "Field mapping for email verification",
524
- })
525
- .optional(),
526
- name: z.string({}).meta({
527
- description:
528
- "Field mapping for name (defaults to 'displayName')",
529
- }),
530
- firstName: z
531
- .string({})
532
- .meta({
533
- description:
534
- "Field mapping for first name (defaults to 'givenName')",
535
- })
536
- .optional(),
537
- lastName: z
538
- .string({})
539
- .meta({
540
- description:
541
- "Field mapping for last name (defaults to 'surname')",
542
- })
543
- .optional(),
544
- extraFields: z.record(z.string(), z.any()).optional(),
545
- })
546
- .optional(),
547
- })
548
- .optional(),
549
- organizationId: z
550
- .string({})
551
- .meta({
552
- description:
553
- "If organization plugin is enabled, the organization id to link the provider to",
554
- })
555
- .optional(),
556
- overrideUserInfo: z
557
- .boolean({})
558
- .meta({
559
- description:
560
- "Override user info with the provider info. Defaults to false",
561
- })
562
- .default(false)
563
- .optional(),
564
- }),
565
- use: [sessionMiddleware],
566
- metadata: {
567
- openapi: {
568
- summary: "Register an OIDC provider",
569
- description:
570
- "This endpoint is used to register an OIDC provider. This is used to configure the provider and link it to an organization",
571
- responses: {
572
- "200": {
573
- description: "OIDC provider created successfully",
574
- content: {
575
- "application/json": {
576
- schema: {
577
- type: "object",
578
- properties: {
579
- issuer: {
580
- type: "string",
581
- format: "uri",
582
- description: "The issuer URL of the provider",
583
- },
584
- domain: {
585
- type: "string",
586
- description:
587
- "The domain of the provider, used for email matching",
588
- },
589
- oidcConfig: {
590
- type: "object",
591
- properties: {
592
- issuer: {
593
- type: "string",
594
- format: "uri",
595
- description: "The issuer URL of the provider",
596
- },
597
- pkce: {
598
- type: "boolean",
599
- description:
600
- "Whether PKCE is enabled for the authorization flow",
601
- },
602
- clientId: {
603
- type: "string",
604
- description: "The client ID for the provider",
605
- },
606
- clientSecret: {
607
- type: "string",
608
- description:
609
- "The client secret for the provider",
610
- },
611
- authorizationEndpoint: {
612
- type: "string",
613
- format: "uri",
614
- nullable: true,
615
- description: "The authorization endpoint URL",
616
- },
617
- discoveryEndpoint: {
618
- type: "string",
619
- format: "uri",
620
- description: "The discovery endpoint URL",
621
- },
622
- userInfoEndpoint: {
623
- type: "string",
624
- format: "uri",
625
- nullable: true,
626
- description: "The user info endpoint URL",
627
- },
628
- scopes: {
629
- type: "array",
630
- items: { type: "string" },
631
- nullable: true,
632
- description:
633
- "The scopes requested from the provider",
634
- },
635
- tokenEndpoint: {
636
- type: "string",
637
- format: "uri",
638
- nullable: true,
639
- description: "The token endpoint URL",
640
- },
641
- tokenEndpointAuthentication: {
642
- type: "string",
643
- enum: [
644
- "client_secret_post",
645
- "client_secret_basic",
646
- ],
647
- nullable: true,
648
- description:
649
- "Authentication method for the token endpoint",
650
- },
651
- jwksEndpoint: {
652
- type: "string",
653
- format: "uri",
654
- nullable: true,
655
- description: "The JWKS endpoint URL",
656
- },
657
- mapping: {
658
- type: "object",
659
- nullable: true,
660
- properties: {
661
- id: {
662
- type: "string",
663
- description:
664
- "Field mapping for user ID (defaults to 'sub')",
665
- },
666
- email: {
667
- type: "string",
668
- description:
669
- "Field mapping for email (defaults to 'email')",
670
- },
671
- emailVerified: {
672
- type: "string",
673
- nullable: true,
674
- description:
675
- "Field mapping for email verification (defaults to 'email_verified')",
676
- },
677
- name: {
678
- type: "string",
679
- description:
680
- "Field mapping for name (defaults to 'name')",
681
- },
682
- image: {
683
- type: "string",
684
- nullable: true,
685
- description:
686
- "Field mapping for image (defaults to 'picture')",
687
- },
688
- extraFields: {
689
- type: "object",
690
- additionalProperties: { type: "string" },
691
- nullable: true,
692
- description: "Additional field mappings",
693
- },
694
- },
695
- required: ["id", "email", "name"],
696
- },
697
- },
698
- required: [
699
- "issuer",
700
- "pkce",
701
- "clientId",
702
- "clientSecret",
703
- "discoveryEndpoint",
704
- ],
705
- description: "OIDC configuration for the provider",
706
- },
707
- organizationId: {
708
- type: "string",
709
- nullable: true,
710
- description:
711
- "ID of the linked organization, if any",
712
- },
713
- userId: {
714
- type: "string",
715
- description:
716
- "ID of the user who registered the provider",
717
- },
718
- providerId: {
719
- type: "string",
720
- description: "Unique identifier for the provider",
721
- },
722
- redirectURI: {
723
- type: "string",
724
- format: "uri",
725
- description:
726
- "The redirect URI for the provider callback",
727
- },
728
- },
729
- required: [
730
- "issuer",
731
- "domain",
732
- "oidcConfig",
733
- "userId",
734
- "providerId",
735
- "redirectURI",
736
- ],
737
- },
738
- },
739
- },
740
- },
741
- },
742
- },
743
- },
744
- },
745
- async (ctx) => {
746
- const user = ctx.context.session?.user;
747
- if (!user) {
748
- throw new APIError("UNAUTHORIZED");
749
- }
750
-
751
- const limit =
752
- typeof options?.providersLimit === "function"
753
- ? await options.providersLimit(user)
754
- : (options?.providersLimit ?? 10);
755
-
756
- if (!limit) {
757
- throw new APIError("FORBIDDEN", {
758
- message: "SSO provider registration is disabled",
759
- });
760
- }
761
-
762
- const providers = await ctx.context.adapter.findMany({
763
- model: "ssoProvider",
764
- where: [{ field: "userId", value: user.id }],
765
- });
766
-
767
- if (providers.length >= limit) {
768
- throw new APIError("FORBIDDEN", {
769
- message: "You have reached the maximum number of SSO providers",
770
- });
771
- }
772
-
773
- const body = ctx.body;
774
- const issuerValidator = z.string().url();
775
- if (issuerValidator.safeParse(body.issuer).error) {
776
- throw new APIError("BAD_REQUEST", {
777
- message: "Invalid issuer. Must be a valid URL",
778
- });
779
- }
780
- if (ctx.body.organizationId) {
781
- const organization = await ctx.context.adapter.findOne({
782
- model: "member",
783
- where: [
784
- {
785
- field: "userId",
786
- value: user.id,
787
- },
788
- {
789
- field: "organizationId",
790
- value: ctx.body.organizationId,
791
- },
792
- ],
793
- });
794
- if (!organization) {
795
- throw new APIError("BAD_REQUEST", {
796
- message: "You are not a member of the organization",
797
- });
798
- }
799
- }
800
-
801
- const existingProvider = await ctx.context.adapter.findOne({
802
- model: "ssoProvider",
803
- where: [
804
- {
805
- field: "providerId",
806
- value: body.providerId,
807
- },
808
- ],
809
- });
810
-
811
- if (existingProvider) {
812
- ctx.context.logger.info(
813
- `SSO provider creation attempt with existing providerId: ${body.providerId}`,
814
- );
815
- throw new APIError("UNPROCESSABLE_ENTITY", {
816
- message: "SSO provider with this providerId already exists",
817
- });
818
- }
819
-
820
- const provider = await ctx.context.adapter.create<
821
- Record<string, any>,
822
- SSOProvider
823
- >({
824
- model: "ssoProvider",
825
- data: {
826
- issuer: body.issuer,
827
- domain: body.domain,
828
- oidcConfig: body.oidcConfig
829
- ? JSON.stringify({
830
- issuer: body.issuer,
831
- clientId: body.oidcConfig.clientId,
832
- clientSecret: body.oidcConfig.clientSecret,
833
- authorizationEndpoint:
834
- body.oidcConfig.authorizationEndpoint,
835
- tokenEndpoint: body.oidcConfig.tokenEndpoint,
836
- tokenEndpointAuthentication:
837
- body.oidcConfig.tokenEndpointAuthentication,
838
- jwksEndpoint: body.oidcConfig.jwksEndpoint,
839
- pkce: body.oidcConfig.pkce,
840
- discoveryEndpoint:
841
- body.oidcConfig.discoveryEndpoint ||
842
- `${body.issuer}/.well-known/openid-configuration`,
843
- mapping: body.oidcConfig.mapping,
844
- scopes: body.oidcConfig.scopes,
845
- userInfoEndpoint: body.oidcConfig.userInfoEndpoint,
846
- overrideUserInfo:
847
- ctx.body.overrideUserInfo ||
848
- options?.defaultOverrideUserInfo ||
849
- false,
850
- })
851
- : null,
852
- samlConfig: body.samlConfig
853
- ? JSON.stringify({
854
- issuer: body.issuer,
855
- entryPoint: body.samlConfig.entryPoint,
856
- cert: body.samlConfig.cert,
857
- callbackUrl: body.samlConfig.callbackUrl,
858
- audience: body.samlConfig.audience,
859
- idpMetadata: body.samlConfig.idpMetadata,
860
- spMetadata: body.samlConfig.spMetadata,
861
- wantAssertionsSigned: body.samlConfig.wantAssertionsSigned,
862
- signatureAlgorithm: body.samlConfig.signatureAlgorithm,
863
- digestAlgorithm: body.samlConfig.digestAlgorithm,
864
- identifierFormat: body.samlConfig.identifierFormat,
865
- privateKey: body.samlConfig.privateKey,
866
- decryptionPvk: body.samlConfig.decryptionPvk,
867
- additionalParams: body.samlConfig.additionalParams,
868
- mapping: body.samlConfig.mapping,
869
- })
870
- : null,
871
- organizationId: body.organizationId,
872
- userId: ctx.context.session.user.id,
873
- providerId: body.providerId,
874
- },
875
- });
876
-
877
- return ctx.json({
878
- ...provider,
879
- oidcConfig: JSON.parse(
880
- provider.oidcConfig as unknown as string,
881
- ) as OIDCConfig,
882
- samlConfig: JSON.parse(
883
- provider.samlConfig as unknown as string,
884
- ) as SAMLConfig,
885
- redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
886
- });
887
- },
888
- ),
889
- signInSSO: createAuthEndpoint(
890
- "/sign-in/sso",
891
- {
892
- method: "POST",
893
- body: z.object({
894
- email: z
895
- .string({})
896
- .meta({
897
- description:
898
- "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",
899
- })
900
- .optional(),
901
- organizationSlug: z
902
- .string({})
903
- .meta({
904
- description: "The slug of the organization to sign in with",
905
- })
906
- .optional(),
907
- providerId: z
908
- .string({})
909
- .meta({
910
- description:
911
- "The ID of the provider to sign in with. This can be provided instead of email or issuer",
912
- })
913
- .optional(),
914
- domain: z
915
- .string({})
916
- .meta({
917
- description: "The domain of the provider.",
918
- })
919
- .optional(),
920
- callbackURL: z.string({}).meta({
921
- description: "The URL to redirect to after login",
922
- }),
923
- errorCallbackURL: z
924
- .string({})
925
- .meta({
926
- description: "The URL to redirect to after login",
927
- })
928
- .optional(),
929
- newUserCallbackURL: z
930
- .string({})
931
- .meta({
932
- description:
933
- "The URL to redirect to after login if the user is new",
934
- })
935
- .optional(),
936
- scopes: z
937
- .array(z.string(), {})
938
- .meta({
939
- description: "Scopes to request from the provider.",
940
- })
941
- .optional(),
942
- loginHint: z
943
- .string({})
944
- .meta({
945
- description:
946
- "Login hint to send to the identity provider (e.g., email or identifier). If supported, will be sent as 'login_hint'.",
947
- })
948
- .optional(),
949
- requestSignUp: z
950
- .boolean({})
951
- .meta({
952
- description:
953
- "Explicitly request sign-up. Useful when disableImplicitSignUp is true for this provider",
954
- })
955
- .optional(),
956
- providerType: z.enum(["oidc", "saml"]).optional(),
957
- }),
958
- metadata: {
959
- openapi: {
960
- summary: "Sign in with SSO provider",
961
- description:
962
- "This endpoint is used to sign in with an SSO provider. It redirects to the provider's authorization URL",
963
- requestBody: {
964
- content: {
965
- "application/json": {
966
- schema: {
967
- type: "object",
968
- properties: {
969
- email: {
970
- type: "string",
971
- description:
972
- "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",
973
- },
974
- issuer: {
975
- type: "string",
976
- description:
977
- "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",
978
- },
979
- providerId: {
980
- type: "string",
981
- description:
982
- "The ID of the provider to sign in with. This can be provided instead of email or issuer",
983
- },
984
- callbackURL: {
985
- type: "string",
986
- description: "The URL to redirect to after login",
987
- },
988
- errorCallbackURL: {
989
- type: "string",
990
- description: "The URL to redirect to after login",
991
- },
992
- newUserCallbackURL: {
993
- type: "string",
994
- description:
995
- "The URL to redirect to after login if the user is new",
996
- },
997
- loginHint: {
998
- type: "string",
999
- description:
1000
- "Login hint to send to the identity provider (e.g., email or identifier). If supported, sent as 'login_hint'.",
1001
- },
1002
- },
1003
- required: ["callbackURL"],
1004
- },
1005
- },
1006
- },
1007
- },
1008
- responses: {
1009
- "200": {
1010
- description:
1011
- "Authorization URL generated successfully for SSO sign-in",
1012
- content: {
1013
- "application/json": {
1014
- schema: {
1015
- type: "object",
1016
- properties: {
1017
- url: {
1018
- type: "string",
1019
- format: "uri",
1020
- description:
1021
- "The authorization URL to redirect the user to for SSO sign-in",
1022
- },
1023
- redirect: {
1024
- type: "boolean",
1025
- description:
1026
- "Indicates that the client should redirect to the provided URL",
1027
- enum: [true],
1028
- },
1029
- },
1030
- required: ["url", "redirect"],
1031
- },
1032
- },
1033
- },
1034
- },
1035
- },
1036
- },
1037
- },
1038
- },
1039
- async (ctx) => {
1040
- const body = ctx.body;
1041
- let { email, organizationSlug, providerId, domain } = body;
1042
- if (
1043
- !options?.defaultSSO?.length &&
1044
- !email &&
1045
- !organizationSlug &&
1046
- !domain &&
1047
- !providerId
1048
- ) {
1049
- throw new APIError("BAD_REQUEST", {
1050
- message:
1051
- "email, organizationSlug, domain or providerId is required",
1052
- });
1053
- }
1054
- domain = body.domain || email?.split("@")[1];
1055
- let orgId = "";
1056
- if (organizationSlug) {
1057
- orgId = await ctx.context.adapter
1058
- .findOne<{ id: string }>({
1059
- model: "organization",
1060
- where: [
1061
- {
1062
- field: "slug",
1063
- value: organizationSlug,
1064
- },
1065
- ],
1066
- })
1067
- .then((res) => {
1068
- if (!res) {
1069
- return "";
1070
- }
1071
- return res.id;
1072
- });
1073
- }
1074
- let provider: SSOProvider | null = null;
1075
- if (options?.defaultSSO?.length) {
1076
- // Find matching default SSO provider by providerId
1077
- const matchingDefault = providerId
1078
- ? options.defaultSSO.find(
1079
- (defaultProvider) =>
1080
- defaultProvider.providerId === providerId,
1081
- )
1082
- : options.defaultSSO.find(
1083
- (defaultProvider) => defaultProvider.domain === domain,
1084
- );
1085
-
1086
- if (matchingDefault) {
1087
- provider = {
1088
- issuer:
1089
- matchingDefault.samlConfig?.issuer ||
1090
- matchingDefault.oidcConfig?.issuer ||
1091
- "",
1092
- providerId: matchingDefault.providerId,
1093
- userId: "default",
1094
- oidcConfig: matchingDefault.oidcConfig,
1095
- samlConfig: matchingDefault.samlConfig,
1096
- };
1097
- }
1098
- }
1099
- if (!providerId && !orgId && !domain) {
1100
- throw new APIError("BAD_REQUEST", {
1101
- message: "providerId, orgId or domain is required",
1102
- });
1103
- }
1104
- // Try to find provider in database
1105
- if (!provider) {
1106
- provider = await ctx.context.adapter
1107
- .findOne<SSOProvider>({
1108
- model: "ssoProvider",
1109
- where: [
1110
- {
1111
- field: providerId
1112
- ? "providerId"
1113
- : orgId
1114
- ? "organizationId"
1115
- : "domain",
1116
- value: providerId || orgId || domain!,
1117
- },
1118
- ],
1119
- })
1120
- .then((res) => {
1121
- if (!res) {
1122
- return null;
1123
- }
1124
- return {
1125
- ...res,
1126
- oidcConfig: res.oidcConfig
1127
- ? safeJsonParse<OIDCConfig>(
1128
- res.oidcConfig as unknown as string,
1129
- ) || undefined
1130
- : undefined,
1131
- samlConfig: res.samlConfig
1132
- ? safeJsonParse<SAMLConfig>(
1133
- res.samlConfig as unknown as string,
1134
- ) || undefined
1135
- : undefined,
1136
- };
1137
- });
1138
- }
1139
-
1140
- if (!provider) {
1141
- throw new APIError("NOT_FOUND", {
1142
- message: "No provider found for the issuer",
1143
- });
1144
- }
1145
- if (body.providerType) {
1146
- if (body.providerType === "oidc" && !provider.oidcConfig) {
1147
- throw new APIError("BAD_REQUEST", {
1148
- message: "OIDC provider is not configured",
1149
- });
1150
- }
1151
- if (body.providerType === "saml" && !provider.samlConfig) {
1152
- throw new APIError("BAD_REQUEST", {
1153
- message: "SAML provider is not configured",
1154
- });
1155
- }
1156
- }
1157
- if (provider.oidcConfig && body.providerType !== "saml") {
1158
- const state = await generateState(ctx, undefined, false);
1159
- const redirectURI = `${ctx.context.baseURL}/sso/callback/${provider.providerId}`;
1160
- const authorizationURL = await createAuthorizationURL({
1161
- id: provider.issuer,
1162
- options: {
1163
- clientId: provider.oidcConfig.clientId,
1164
- clientSecret: provider.oidcConfig.clientSecret,
1165
- },
1166
- redirectURI,
1167
- state: state.state,
1168
- codeVerifier: provider.oidcConfig.pkce
1169
- ? state.codeVerifier
1170
- : undefined,
1171
- scopes: ctx.body.scopes ||
1172
- provider.oidcConfig.scopes || [
1173
- "openid",
1174
- "email",
1175
- "profile",
1176
- "offline_access",
1177
- ],
1178
- loginHint: ctx.body.loginHint || email,
1179
- authorizationEndpoint: provider.oidcConfig.authorizationEndpoint!,
1180
- });
1181
- return ctx.json({
1182
- url: authorizationURL.toString(),
1183
- redirect: true,
1184
- });
1185
- }
1186
- if (provider.samlConfig) {
1187
- const parsedSamlConfig =
1188
- typeof provider.samlConfig === "object"
1189
- ? provider.samlConfig
1190
- : safeJsonParse<SAMLConfig>(
1191
- provider.samlConfig as unknown as string,
1192
- );
1193
- if (!parsedSamlConfig) {
1194
- throw new APIError("BAD_REQUEST", {
1195
- message: "Invalid SAML configuration",
1196
- });
1197
- }
1198
- const sp = saml.ServiceProvider({
1199
- metadata: parsedSamlConfig.spMetadata.metadata,
1200
- allowCreate: true,
1201
- });
1202
-
1203
- const idp = saml.IdentityProvider({
1204
- metadata: parsedSamlConfig.idpMetadata?.metadata,
1205
- entityID: parsedSamlConfig.idpMetadata?.entityID,
1206
- encryptCert: parsedSamlConfig.idpMetadata?.cert,
1207
- singleSignOnService:
1208
- parsedSamlConfig.idpMetadata?.singleSignOnService,
1209
- });
1210
- const loginRequest = sp.createLoginRequest(
1211
- idp,
1212
- "redirect",
1213
- ) as BindingContext & { entityEndpoint: string; type: string };
1214
- if (!loginRequest) {
1215
- throw new APIError("BAD_REQUEST", {
1216
- message: "Invalid SAML request",
1217
- });
1218
- }
1219
- return ctx.json({
1220
- url: `${loginRequest.context}&RelayState=${encodeURIComponent(
1221
- body.callbackURL,
1222
- )}`,
1223
- redirect: true,
1224
- });
1225
- }
1226
- throw new APIError("BAD_REQUEST", {
1227
- message: "Invalid SSO provider",
1228
- });
1229
- },
1230
- ),
1231
- callbackSSO: createAuthEndpoint(
1232
- "/sso/callback/:providerId",
1233
- {
1234
- method: "GET",
1235
- query: z.object({
1236
- code: z.string().optional(),
1237
- state: z.string(),
1238
- error: z.string().optional(),
1239
- error_description: z.string().optional(),
1240
- }),
1241
- metadata: {
1242
- isAction: false,
1243
- openapi: {
1244
- summary: "Callback URL for SSO provider",
1245
- description:
1246
- "This endpoint is used as the callback URL for SSO providers. It handles the authorization code and exchanges it for an access token",
1247
- responses: {
1248
- "302": {
1249
- description: "Redirects to the callback URL",
1250
- },
1251
- },
1252
- },
1253
- },
1254
- },
1255
- async (ctx) => {
1256
- const { code, state, error, error_description } = ctx.query;
1257
- const stateData = await parseState(ctx);
1258
- if (!stateData) {
1259
- const errorURL =
1260
- ctx.context.options.onAPIError?.errorURL ||
1261
- `${ctx.context.baseURL}/error`;
1262
- throw ctx.redirect(`${errorURL}?error=invalid_state`);
1263
- }
1264
- const { callbackURL, errorURL, newUserURL, requestSignUp } =
1265
- stateData;
1266
- if (!code || error) {
1267
- throw ctx.redirect(
1268
- `${
1269
- errorURL || callbackURL
1270
- }?error=${error}&error_description=${error_description}`,
1271
- );
1272
- }
1273
- let provider: SSOProvider | null = null;
1274
- if (options?.defaultSSO?.length) {
1275
- const matchingDefault = options.defaultSSO.find(
1276
- (defaultProvider) =>
1277
- defaultProvider.providerId === ctx.params.providerId,
1278
- );
1279
- if (matchingDefault) {
1280
- provider = {
1281
- ...matchingDefault,
1282
- issuer: matchingDefault.oidcConfig?.issuer || "",
1283
- userId: "default",
1284
- };
1285
- }
1286
- }
1287
- if (!provider) {
1288
- provider = await ctx.context.adapter
1289
- .findOne<{
1290
- oidcConfig: string;
1291
- }>({
1292
- model: "ssoProvider",
1293
- where: [
1294
- {
1295
- field: "providerId",
1296
- value: ctx.params.providerId,
1297
- },
1298
- ],
1299
- })
1300
- .then((res) => {
1301
- if (!res) {
1302
- return null;
1303
- }
1304
- return {
1305
- ...res,
1306
- oidcConfig:
1307
- safeJsonParse<OIDCConfig>(res.oidcConfig) || undefined,
1308
- } as SSOProvider;
1309
- });
1310
- }
1311
- if (!provider) {
1312
- throw ctx.redirect(
1313
- `${
1314
- errorURL || callbackURL
1315
- }/error?error=invalid_provider&error_description=provider not found`,
1316
- );
1317
- }
1318
- let config = provider.oidcConfig;
1319
-
1320
- if (!config) {
1321
- throw ctx.redirect(
1322
- `${
1323
- errorURL || callbackURL
1324
- }/error?error=invalid_provider&error_description=provider not found`,
1325
- );
1326
- }
1327
-
1328
- const discovery = await betterFetch<{
1329
- token_endpoint: string;
1330
- userinfo_endpoint: string;
1331
- token_endpoint_auth_method:
1332
- | "client_secret_basic"
1333
- | "client_secret_post";
1334
- }>(config.discoveryEndpoint);
1335
-
1336
- if (discovery.data) {
1337
- config = {
1338
- tokenEndpoint: discovery.data.token_endpoint,
1339
- tokenEndpointAuthentication:
1340
- discovery.data.token_endpoint_auth_method,
1341
- userInfoEndpoint: discovery.data.userinfo_endpoint,
1342
- scopes: ["openid", "email", "profile", "offline_access"],
1343
- ...config,
1344
- };
1345
- }
1346
-
1347
- if (!config.tokenEndpoint) {
1348
- throw ctx.redirect(
1349
- `${
1350
- errorURL || callbackURL
1351
- }/error?error=invalid_provider&error_description=token_endpoint_not_found`,
1352
- );
1353
- }
1354
-
1355
- const tokenResponse = await validateAuthorizationCode({
1356
- code,
1357
- codeVerifier: config.pkce ? stateData.codeVerifier : undefined,
1358
- redirectURI: `${ctx.context.baseURL}/sso/callback/${provider.providerId}`,
1359
- options: {
1360
- clientId: config.clientId,
1361
- clientSecret: config.clientSecret,
1362
- },
1363
- tokenEndpoint: config.tokenEndpoint,
1364
- authentication:
1365
- config.tokenEndpointAuthentication === "client_secret_post"
1366
- ? "post"
1367
- : "basic",
1368
- }).catch((e) => {
1369
- if (e instanceof BetterFetchError) {
1370
- throw ctx.redirect(
1371
- `${
1372
- errorURL || callbackURL
1373
- }?error=invalid_provider&error_description=${e.message}`,
1374
- );
1375
- }
1376
- return null;
1377
- });
1378
- if (!tokenResponse) {
1379
- throw ctx.redirect(
1380
- `${
1381
- errorURL || callbackURL
1382
- }/error?error=invalid_provider&error_description=token_response_not_found`,
1383
- );
1384
- }
1385
- let userInfo: {
1386
- id?: string;
1387
- email?: string;
1388
- name?: string;
1389
- image?: string;
1390
- emailVerified?: boolean;
1391
- [key: string]: any;
1392
- } | null = null;
1393
- if (tokenResponse.idToken) {
1394
- const idToken = decodeJwt(tokenResponse.idToken);
1395
- if (!config.jwksEndpoint) {
1396
- throw ctx.redirect(
1397
- `${
1398
- errorURL || callbackURL
1399
- }/error?error=invalid_provider&error_description=jwks_endpoint_not_found`,
1400
- );
1401
- }
1402
- const verified = await validateToken(
1403
- tokenResponse.idToken,
1404
- config.jwksEndpoint,
1405
- ).catch((e) => {
1406
- ctx.context.logger.error(e);
1407
- return null;
1408
- });
1409
- if (!verified) {
1410
- throw ctx.redirect(
1411
- `${
1412
- errorURL || callbackURL
1413
- }/error?error=invalid_provider&error_description=token_not_verified`,
1414
- );
1415
- }
1416
- if (verified.payload.iss !== provider.issuer) {
1417
- throw ctx.redirect(
1418
- `${
1419
- errorURL || callbackURL
1420
- }/error?error=invalid_provider&error_description=issuer_mismatch`,
1421
- );
1422
- }
1423
-
1424
- const mapping = config.mapping || {};
1425
- userInfo = {
1426
- ...Object.fromEntries(
1427
- Object.entries(mapping.extraFields || {}).map(
1428
- ([key, value]) => [key, verified.payload[value]],
1429
- ),
1430
- ),
1431
- id: idToken[mapping.id || "sub"],
1432
- email: idToken[mapping.email || "email"],
1433
- emailVerified: options?.trustEmailVerified
1434
- ? idToken[mapping.emailVerified || "email_verified"]
1435
- : false,
1436
- name: idToken[mapping.name || "name"],
1437
- image: idToken[mapping.image || "picture"],
1438
- } as {
1439
- id?: string;
1440
- email?: string;
1441
- name?: string;
1442
- image?: string;
1443
- emailVerified?: boolean;
1444
- };
1445
- }
1446
-
1447
- if (!userInfo) {
1448
- if (!config.userInfoEndpoint) {
1449
- throw ctx.redirect(
1450
- `${
1451
- errorURL || callbackURL
1452
- }/error?error=invalid_provider&error_description=user_info_endpoint_not_found`,
1453
- );
1454
- }
1455
- const userInfoResponse = await betterFetch<{
1456
- email?: string;
1457
- name?: string;
1458
- id?: string;
1459
- image?: string;
1460
- emailVerified?: boolean;
1461
- }>(config.userInfoEndpoint, {
1462
- headers: {
1463
- Authorization: `Bearer ${tokenResponse.accessToken}`,
1464
- },
1465
- });
1466
- if (userInfoResponse.error) {
1467
- throw ctx.redirect(
1468
- `${
1469
- errorURL || callbackURL
1470
- }/error?error=invalid_provider&error_description=${
1471
- userInfoResponse.error.message
1472
- }`,
1473
- );
1474
- }
1475
- userInfo = userInfoResponse.data;
1476
- }
1477
-
1478
- if (!userInfo.email || !userInfo.id) {
1479
- throw ctx.redirect(
1480
- `${
1481
- errorURL || callbackURL
1482
- }/error?error=invalid_provider&error_description=missing_user_info`,
1483
- );
1484
- }
1485
- const linked = await handleOAuthUserInfo(ctx, {
1486
- userInfo: {
1487
- email: userInfo.email,
1488
- name: userInfo.name || userInfo.email,
1489
- id: userInfo.id,
1490
- image: userInfo.image,
1491
- emailVerified: options?.trustEmailVerified
1492
- ? userInfo.emailVerified || false
1493
- : false,
1494
- },
1495
- account: {
1496
- idToken: tokenResponse.idToken,
1497
- accessToken: tokenResponse.accessToken,
1498
- refreshToken: tokenResponse.refreshToken,
1499
- accountId: userInfo.id,
1500
- providerId: provider.providerId,
1501
- accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt,
1502
- refreshTokenExpiresAt: tokenResponse.refreshTokenExpiresAt,
1503
- scope: tokenResponse.scopes?.join(","),
1504
- },
1505
- callbackURL,
1506
- disableSignUp: options?.disableImplicitSignUp && !requestSignUp,
1507
- overrideUserInfo: config.overrideUserInfo,
1508
- });
1509
- if (linked.error) {
1510
- throw ctx.redirect(
1511
- `${errorURL || callbackURL}/error?error=${linked.error}`,
1512
- );
1513
- }
1514
- const { session, user } = linked.data!;
1515
-
1516
- if (options?.provisionUser) {
1517
- await options.provisionUser({
1518
- user,
1519
- userInfo,
1520
- token: tokenResponse,
1521
- provider,
1522
- });
1523
- }
1524
- if (
1525
- provider.organizationId &&
1526
- !options?.organizationProvisioning?.disabled
1527
- ) {
1528
- const isOrgPluginEnabled = ctx.context.options.plugins?.find(
1529
- (plugin) => plugin.id === "organization",
1530
- );
1531
- if (isOrgPluginEnabled) {
1532
- const isAlreadyMember = await ctx.context.adapter.findOne({
1533
- model: "member",
1534
- where: [
1535
- { field: "organizationId", value: provider.organizationId },
1536
- { field: "userId", value: user.id },
1537
- ],
1538
- });
1539
- if (!isAlreadyMember) {
1540
- const role = options?.organizationProvisioning?.getRole
1541
- ? await options.organizationProvisioning.getRole({
1542
- user,
1543
- userInfo,
1544
- token: tokenResponse,
1545
- provider,
1546
- })
1547
- : options?.organizationProvisioning?.defaultRole || "member";
1548
- await ctx.context.adapter.create({
1549
- model: "member",
1550
- data: {
1551
- organizationId: provider.organizationId,
1552
- userId: user.id,
1553
- role,
1554
- createdAt: new Date(),
1555
- updatedAt: new Date(),
1556
- },
1557
- });
1558
- }
1559
- }
1560
- }
1561
- await setSessionCookie(ctx, {
1562
- session,
1563
- user,
1564
- });
1565
- let toRedirectTo: string;
1566
- try {
1567
- const url = linked.isRegister
1568
- ? newUserURL || callbackURL
1569
- : callbackURL;
1570
- toRedirectTo = url.toString();
1571
- } catch {
1572
- toRedirectTo = linked.isRegister
1573
- ? newUserURL || callbackURL
1574
- : callbackURL;
1575
- }
1576
- throw ctx.redirect(toRedirectTo);
1577
- },
1578
- ),
1579
- callbackSSOSAML: createAuthEndpoint(
1580
- "/sso/saml2/callback/:providerId",
1581
- {
1582
- method: "POST",
1583
- body: z.object({
1584
- SAMLResponse: z.string(),
1585
- RelayState: z.string().optional(),
1586
- }),
1587
- metadata: {
1588
- isAction: false,
1589
- openapi: {
1590
- summary: "Callback URL for SAML provider",
1591
- description:
1592
- "This endpoint is used as the callback URL for SAML providers.",
1593
- responses: {
1594
- "302": {
1595
- description: "Redirects to the callback URL",
1596
- },
1597
- "400": {
1598
- description: "Invalid SAML response",
1599
- },
1600
- "401": {
1601
- description: "Unauthorized - SAML authentication failed",
1602
- },
1603
- },
1604
- },
1605
- },
1606
- },
1607
- async (ctx) => {
1608
- const { SAMLResponse, RelayState } = ctx.body;
1609
- const { providerId } = ctx.params;
1610
- let provider: SSOProvider | null = null;
1611
- if (options?.defaultSSO?.length) {
1612
- const matchingDefault = options.defaultSSO.find(
1613
- (defaultProvider) => defaultProvider.providerId === providerId,
1614
- );
1615
- if (matchingDefault) {
1616
- provider = {
1617
- ...matchingDefault,
1618
- userId: "default",
1619
- issuer: matchingDefault.samlConfig?.issuer || "",
1620
- };
1621
- }
1622
- }
1623
- if (!provider) {
1624
- provider = await ctx.context.adapter
1625
- .findOne<SSOProvider>({
1626
- model: "ssoProvider",
1627
- where: [{ field: "providerId", value: providerId }],
1628
- })
1629
- .then((res) => {
1630
- if (!res) return null;
1631
- return {
1632
- ...res,
1633
- samlConfig: res.samlConfig
1634
- ? safeJsonParse<SAMLConfig>(
1635
- res.samlConfig as unknown as string,
1636
- ) || undefined
1637
- : undefined,
1638
- };
1639
- });
1640
- }
1641
-
1642
- if (!provider) {
1643
- throw new APIError("NOT_FOUND", {
1644
- message: "No provider found for the given providerId",
1645
- });
1646
- }
1647
- const parsedSamlConfig = safeJsonParse<SAMLConfig>(
1648
- provider.samlConfig as unknown as string,
1649
- );
1650
- if (!parsedSamlConfig) {
1651
- throw new APIError("BAD_REQUEST", {
1652
- message: "Invalid SAML configuration",
1653
- });
1654
- }
1655
- const idpData = parsedSamlConfig.idpMetadata;
1656
- let idp: IdentityProvider | null = null;
1657
-
1658
- // Construct IDP with fallback to manual configuration
1659
- if (!idpData?.metadata) {
1660
- idp = saml.IdentityProvider({
1661
- entityID: idpData?.entityID || parsedSamlConfig.issuer,
1662
- singleSignOnService: [
1663
- {
1664
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
1665
- Location: parsedSamlConfig.entryPoint,
1666
- },
1667
- ],
1668
- signingCert: idpData?.cert || parsedSamlConfig.cert,
1669
- wantAuthnRequestsSigned:
1670
- parsedSamlConfig.wantAssertionsSigned || false,
1671
- isAssertionEncrypted: idpData?.isAssertionEncrypted || false,
1672
- encPrivateKey: idpData?.encPrivateKey,
1673
- encPrivateKeyPass: idpData?.encPrivateKeyPass,
1674
- });
1675
- } else {
1676
- idp = saml.IdentityProvider({
1677
- metadata: idpData.metadata,
1678
- privateKey: idpData.privateKey,
1679
- privateKeyPass: idpData.privateKeyPass,
1680
- isAssertionEncrypted: idpData.isAssertionEncrypted,
1681
- encPrivateKey: idpData.encPrivateKey,
1682
- encPrivateKeyPass: idpData.encPrivateKeyPass,
1683
- });
1684
- }
1685
-
1686
- // Construct SP with fallback to manual configuration
1687
- const spData = parsedSamlConfig.spMetadata;
1688
- const sp = saml.ServiceProvider({
1689
- metadata: spData?.metadata,
1690
- entityID: spData?.entityID || parsedSamlConfig.issuer,
1691
- assertionConsumerService: spData?.metadata
1692
- ? undefined
1693
- : [
1694
- {
1695
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
1696
- Location: parsedSamlConfig.callbackUrl,
1697
- },
1698
- ],
1699
- privateKey: spData?.privateKey || parsedSamlConfig.privateKey,
1700
- privateKeyPass: spData?.privateKeyPass,
1701
- isAssertionEncrypted: spData?.isAssertionEncrypted || false,
1702
- encPrivateKey: spData?.encPrivateKey,
1703
- encPrivateKeyPass: spData?.encPrivateKeyPass,
1704
- wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
1705
- nameIDFormat: parsedSamlConfig.identifierFormat
1706
- ? [parsedSamlConfig.identifierFormat]
1707
- : undefined,
1708
- });
1709
-
1710
- let parsedResponse: FlowResult;
1711
- try {
1712
- const decodedResponse = Buffer.from(
1713
- SAMLResponse,
1714
- "base64",
1715
- ).toString("utf-8");
1716
-
1717
- try {
1718
- parsedResponse = await sp.parseLoginResponse(idp, "post", {
1719
- body: {
1720
- SAMLResponse,
1721
- RelayState: RelayState || undefined,
1722
- },
1723
- });
1724
- } catch (parseError) {
1725
- const nameIDMatch = decodedResponse.match(
1726
- /<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/,
1727
- );
1728
- if (!nameIDMatch) throw parseError;
1729
- parsedResponse = {
1730
- extract: {
1731
- nameID: nameIDMatch[1],
1732
- attributes: { nameID: nameIDMatch[1] },
1733
- sessionIndex: {},
1734
- conditions: {},
1735
- },
1736
- } as FlowResult;
1737
- }
1738
-
1739
- if (!parsedResponse?.extract) {
1740
- throw new Error("Invalid SAML response structure");
1741
- }
1742
- } catch (error) {
1743
- ctx.context.logger.error("SAML response validation failed", {
1744
- error,
1745
- decodedResponse: Buffer.from(SAMLResponse, "base64").toString(
1746
- "utf-8",
1747
- ),
1748
- });
1749
- throw new APIError("BAD_REQUEST", {
1750
- message: "Invalid SAML response",
1751
- details: error instanceof Error ? error.message : String(error),
1752
- });
1753
- }
1754
-
1755
- const { extract } = parsedResponse!;
1756
- const attributes = extract.attributes || {};
1757
- const mapping = parsedSamlConfig.mapping ?? {};
1758
-
1759
- const userInfo = {
1760
- ...Object.fromEntries(
1761
- Object.entries(mapping.extraFields || {}).map(([key, value]) => [
1762
- key,
1763
- attributes[value as string],
1764
- ]),
1765
- ),
1766
- id: attributes[mapping.id || "nameID"] || extract.nameID,
1767
- email: attributes[mapping.email || "email"] || extract.nameID,
1768
- name:
1769
- [
1770
- attributes[mapping.firstName || "givenName"],
1771
- attributes[mapping.lastName || "surname"],
1772
- ]
1773
- .filter(Boolean)
1774
- .join(" ") ||
1775
- attributes[mapping.name || "displayName"] ||
1776
- extract.nameID,
1777
- emailVerified:
1778
- options?.trustEmailVerified && mapping.emailVerified
1779
- ? ((attributes[mapping.emailVerified] || false) as boolean)
1780
- : false,
1781
- };
1782
- if (!userInfo.id || !userInfo.email) {
1783
- ctx.context.logger.error(
1784
- "Missing essential user info from SAML response",
1785
- {
1786
- attributes: Object.keys(attributes),
1787
- mapping,
1788
- extractedId: userInfo.id,
1789
- extractedEmail: userInfo.email,
1790
- },
1791
- );
1792
- throw new APIError("BAD_REQUEST", {
1793
- message: "Unable to extract user ID or email from SAML response",
1794
- });
1795
- }
1796
-
1797
- // Find or create user
1798
- let user: User;
1799
- const existingUser = await ctx.context.adapter.findOne<User>({
1800
- model: "user",
1801
- where: [
1802
- {
1803
- field: "email",
1804
- value: userInfo.email,
1805
- },
1806
- ],
1807
- });
1808
-
1809
- if (existingUser) {
1810
- user = existingUser;
1811
- } else {
1812
- user = await ctx.context.adapter.create({
1813
- model: "user",
1814
- data: {
1815
- email: userInfo.email,
1816
- name: userInfo.name,
1817
- emailVerified: userInfo.emailVerified,
1818
- createdAt: new Date(),
1819
- updatedAt: new Date(),
1820
- },
1821
- });
1822
- }
1823
-
1824
- // Create or update account link
1825
- const account = await ctx.context.adapter.findOne<Account>({
1826
- model: "account",
1827
- where: [
1828
- { field: "userId", value: user.id },
1829
- { field: "providerId", value: provider.providerId },
1830
- { field: "accountId", value: userInfo.id },
1831
- ],
1832
- });
1833
-
1834
- if (!account) {
1835
- await ctx.context.adapter.create<Account>({
1836
- model: "account",
1837
- data: {
1838
- userId: user.id,
1839
- providerId: provider.providerId,
1840
- accountId: userInfo.id,
1841
- createdAt: new Date(),
1842
- updatedAt: new Date(),
1843
- accessToken: "",
1844
- refreshToken: "",
1845
- },
1846
- });
1847
- }
1848
-
1849
- // Run provision hooks
1850
- if (options?.provisionUser) {
1851
- await options.provisionUser({
1852
- user: user as User & Record<string, any>,
1853
- userInfo,
1854
- provider,
1855
- });
1856
- }
1857
-
1858
- // Handle organization provisioning
1859
- if (
1860
- provider.organizationId &&
1861
- !options?.organizationProvisioning?.disabled
1862
- ) {
1863
- const isOrgPluginEnabled = ctx.context.options.plugins?.find(
1864
- (plugin) => plugin.id === "organization",
1865
- );
1866
- if (isOrgPluginEnabled) {
1867
- const isAlreadyMember = await ctx.context.adapter.findOne({
1868
- model: "member",
1869
- where: [
1870
- { field: "organizationId", value: provider.organizationId },
1871
- { field: "userId", value: user.id },
1872
- ],
1873
- });
1874
- if (!isAlreadyMember) {
1875
- const role = options?.organizationProvisioning?.getRole
1876
- ? await options.organizationProvisioning.getRole({
1877
- user,
1878
- userInfo,
1879
- provider,
1880
- })
1881
- : options?.organizationProvisioning?.defaultRole || "member";
1882
- await ctx.context.adapter.create({
1883
- model: "member",
1884
- data: {
1885
- organizationId: provider.organizationId,
1886
- userId: user.id,
1887
- role,
1888
- createdAt: new Date(),
1889
- updatedAt: new Date(),
1890
- },
1891
- });
1892
- }
1893
- }
1894
- }
1895
-
1896
- // Create session and set cookie
1897
- let session: Session =
1898
- await ctx.context.internalAdapter.createSession(user.id);
1899
- await setSessionCookie(ctx, { session, user });
1900
-
1901
- // Redirect to callback URL
1902
- const callbackUrl =
1903
- RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
1904
- throw ctx.redirect(callbackUrl);
1905
- },
1906
- ),
1907
- acsEndpoint: createAuthEndpoint(
1908
- "/sso/saml2/sp/acs/:providerId",
1909
- {
1910
- method: "POST",
1911
- params: z.object({
1912
- providerId: z.string().optional(),
1913
- }),
1914
- body: z.object({
1915
- SAMLResponse: z.string(),
1916
- RelayState: z.string().optional(),
1917
- }),
1918
- metadata: {
1919
- isAction: false,
1920
- openapi: {
1921
- summary: "SAML Assertion Consumer Service",
1922
- description:
1923
- "Handles SAML responses from IdP after successful authentication",
1924
- responses: {
1925
- "302": {
1926
- description:
1927
- "Redirects to the callback URL after successful authentication",
1928
- },
1929
- },
1930
- },
1931
- },
1932
- },
1933
- async (ctx) => {
1934
- const { SAMLResponse, RelayState = "" } = ctx.body;
1935
- const { providerId } = ctx.params;
1936
-
1937
- // If defaultSSO is configured, use it as the provider
1938
- let provider: SSOProvider | null = null;
1939
-
1940
- if (options?.defaultSSO?.length) {
1941
- // For ACS endpoint, we can use the first default provider or try to match by providerId
1942
- const matchingDefault = providerId
1943
- ? options.defaultSSO.find(
1944
- (defaultProvider) =>
1945
- defaultProvider.providerId === providerId,
1946
- )
1947
- : options.defaultSSO[0]; // Use first default provider if no specific providerId
1948
-
1949
- if (matchingDefault) {
1950
- provider = {
1951
- issuer: matchingDefault.samlConfig?.issuer || "",
1952
- providerId: matchingDefault.providerId,
1953
- userId: "default",
1954
- samlConfig: matchingDefault.samlConfig,
1955
- };
1956
- }
1957
- } else {
1958
- provider = await ctx.context.adapter
1959
- .findOne<SSOProvider>({
1960
- model: "ssoProvider",
1961
- where: [
1962
- {
1963
- field: "providerId",
1964
- value: providerId ?? "sso",
1965
- },
1966
- ],
1967
- })
1968
- .then((res) => {
1969
- if (!res) return null;
1970
- return {
1971
- ...res,
1972
- samlConfig: res.samlConfig
1973
- ? safeJsonParse<SAMLConfig>(
1974
- res.samlConfig as unknown as string,
1975
- ) || undefined
1976
- : undefined,
1977
- };
1978
- });
1979
- }
1980
-
1981
- if (!provider?.samlConfig) {
1982
- throw new APIError("NOT_FOUND", {
1983
- message: "No SAML provider found",
1984
- });
1985
- }
1986
-
1987
- const parsedSamlConfig = provider.samlConfig;
1988
- // Configure SP and IdP
1989
- const sp = saml.ServiceProvider({
1990
- entityID:
1991
- parsedSamlConfig.spMetadata?.entityID || parsedSamlConfig.issuer,
1992
- assertionConsumerService: [
1993
- {
1994
- Binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",
1995
- Location:
1996
- parsedSamlConfig.callbackUrl ||
1997
- `${ctx.context.baseURL}/sso/saml2/sp/acs/${providerId}`,
1998
- },
1999
- ],
2000
- wantMessageSigned: parsedSamlConfig.wantAssertionsSigned || false,
2001
- metadata: parsedSamlConfig.spMetadata?.metadata,
2002
- privateKey:
2003
- parsedSamlConfig.spMetadata?.privateKey ||
2004
- parsedSamlConfig.privateKey,
2005
- privateKeyPass: parsedSamlConfig.spMetadata?.privateKeyPass,
2006
- nameIDFormat: parsedSamlConfig.identifierFormat
2007
- ? [parsedSamlConfig.identifierFormat]
2008
- : undefined,
2009
- });
2010
-
2011
- // Update where we construct the IdP
2012
- const idpData = parsedSamlConfig.idpMetadata;
2013
- const idp = !idpData?.metadata
2014
- ? saml.IdentityProvider({
2015
- entityID: idpData?.entityID || parsedSamlConfig.issuer,
2016
- singleSignOnService: idpData?.singleSignOnService || [
2017
- {
2018
- Binding:
2019
- "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
2020
- Location: parsedSamlConfig.entryPoint,
2021
- },
2022
- ],
2023
- signingCert: idpData?.cert || parsedSamlConfig.cert,
2024
- })
2025
- : saml.IdentityProvider({
2026
- metadata: idpData.metadata,
2027
- });
2028
-
2029
- // Parse and validate SAML response
2030
- let parsedResponse: FlowResult;
2031
- try {
2032
- let decodedResponse = Buffer.from(SAMLResponse, "base64").toString(
2033
- "utf-8",
2034
- );
2035
-
2036
- // Patch the SAML response if status is missing or not success
2037
- if (!decodedResponse.includes("StatusCode")) {
2038
- // Insert a success status if missing
2039
- const insertPoint = decodedResponse.indexOf("</saml2:Issuer>");
2040
- if (insertPoint !== -1) {
2041
- decodedResponse =
2042
- decodedResponse.slice(0, insertPoint + 14) +
2043
- '<saml2:Status><saml2:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></saml2:Status>' +
2044
- decodedResponse.slice(insertPoint + 14);
2045
- }
2046
- } else if (!decodedResponse.includes("saml2:Success")) {
2047
- // Replace existing non-success status with success
2048
- decodedResponse = decodedResponse.replace(
2049
- /<saml2:StatusCode Value="[^"]+"/,
2050
- '<saml2:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"',
2051
- );
2052
- }
2053
-
2054
- try {
2055
- parsedResponse = await sp.parseLoginResponse(idp, "post", {
2056
- body: {
2057
- SAMLResponse,
2058
- RelayState: RelayState || undefined,
2059
- },
2060
- });
2061
- } catch (parseError) {
2062
- const nameIDMatch = decodedResponse.match(
2063
- /<saml2:NameID[^>]*>([^<]+)<\/saml2:NameID>/,
2064
- );
2065
- // due to different spec. we have to make sure to handle that.
2066
- if (!nameIDMatch) throw parseError;
2067
- parsedResponse = {
2068
- extract: {
2069
- nameID: nameIDMatch[1],
2070
- attributes: { nameID: nameIDMatch[1] },
2071
- sessionIndex: {},
2072
- conditions: {},
2073
- },
2074
- } as FlowResult;
2075
- }
2076
-
2077
- if (!parsedResponse?.extract) {
2078
- throw new Error("Invalid SAML response structure");
2079
- }
2080
- } catch (error) {
2081
- ctx.context.logger.error("SAML response validation failed", {
2082
- error,
2083
- decodedResponse: Buffer.from(SAMLResponse, "base64").toString(
2084
- "utf-8",
2085
- ),
2086
- });
2087
- throw new APIError("BAD_REQUEST", {
2088
- message: "Invalid SAML response",
2089
- details: error instanceof Error ? error.message : String(error),
2090
- });
2091
- }
2092
-
2093
- const { extract } = parsedResponse!;
2094
- const attributes = extract.attributes || {};
2095
- const mapping = parsedSamlConfig.mapping ?? {};
2096
-
2097
- const userInfo = {
2098
- ...Object.fromEntries(
2099
- Object.entries(mapping.extraFields || {}).map(([key, value]) => [
2100
- key,
2101
- attributes[value as string],
2102
- ]),
2103
- ),
2104
- id: attributes[mapping.id || "nameID"] || extract.nameID,
2105
- email: attributes[mapping.email || "email"] || extract.nameID,
2106
- name:
2107
- [
2108
- attributes[mapping.firstName || "givenName"],
2109
- attributes[mapping.lastName || "surname"],
2110
- ]
2111
- .filter(Boolean)
2112
- .join(" ") ||
2113
- attributes[mapping.name || "displayName"] ||
2114
- extract.nameID,
2115
- emailVerified:
2116
- options?.trustEmailVerified && mapping.emailVerified
2117
- ? ((attributes[mapping.emailVerified] || false) as boolean)
2118
- : false,
2119
- };
2120
-
2121
- if (!userInfo.id || !userInfo.email) {
2122
- ctx.context.logger.error(
2123
- "Missing essential user info from SAML response",
2124
- {
2125
- attributes: Object.keys(attributes),
2126
- mapping,
2127
- extractedId: userInfo.id,
2128
- extractedEmail: userInfo.email,
2129
- },
2130
- );
2131
- throw new APIError("BAD_REQUEST", {
2132
- message: "Unable to extract user ID or email from SAML response",
2133
- });
2134
- }
2135
-
2136
- // Find or create user
2137
- let user: User;
2138
- const existingUser = await ctx.context.adapter.findOne<User>({
2139
- model: "user",
2140
- where: [
2141
- {
2142
- field: "email",
2143
- value: userInfo.email,
2144
- },
2145
- ],
2146
- });
2147
-
2148
- if (existingUser) {
2149
- const account = await ctx.context.adapter.findOne<Account>({
2150
- model: "account",
2151
- where: [
2152
- { field: "userId", value: existingUser.id },
2153
- { field: "providerId", value: provider.providerId },
2154
- { field: "accountId", value: userInfo.id },
2155
- ],
2156
- });
2157
- if (!account) {
2158
- const isTrustedProvider =
2159
- ctx.context.options.account?.accountLinking?.trustedProviders?.includes(
2160
- provider.providerId,
2161
- );
2162
- if (!isTrustedProvider) {
2163
- throw ctx.redirect(
2164
- `${parsedSamlConfig.callbackUrl}?error=account_not_found`,
2165
- );
2166
- }
2167
- await ctx.context.adapter.create<Account>({
2168
- model: "account",
2169
- data: {
2170
- userId: existingUser.id,
2171
- providerId: provider.providerId,
2172
- accountId: userInfo.id,
2173
- createdAt: new Date(),
2174
- updatedAt: new Date(),
2175
- accessToken: "",
2176
- refreshToken: "",
2177
- },
2178
- });
2179
- }
2180
- user = existingUser;
2181
- } else {
2182
- user = await ctx.context.adapter.create({
2183
- model: "user",
2184
- data: {
2185
- email: userInfo.email,
2186
- name: userInfo.name,
2187
- emailVerified: options?.trustEmailVerified
2188
- ? userInfo.emailVerified || false
2189
- : false,
2190
- createdAt: new Date(),
2191
- updatedAt: new Date(),
2192
- },
2193
- });
2194
- await ctx.context.adapter.create<Account>({
2195
- model: "account",
2196
- data: {
2197
- userId: user.id,
2198
- providerId: provider.providerId,
2199
- accountId: userInfo.id,
2200
- accessToken: "",
2201
- refreshToken: "",
2202
- accessTokenExpiresAt: new Date(),
2203
- refreshTokenExpiresAt: new Date(),
2204
- scope: "",
2205
- createdAt: new Date(),
2206
- updatedAt: new Date(),
2207
- },
2208
- });
2209
- }
2210
-
2211
- if (options?.provisionUser) {
2212
- await options.provisionUser({
2213
- user: user as User & Record<string, any>,
2214
- userInfo,
2215
- provider,
2216
- });
2217
- }
2218
-
2219
- if (
2220
- provider.organizationId &&
2221
- !options?.organizationProvisioning?.disabled
2222
- ) {
2223
- const isOrgPluginEnabled = ctx.context.options.plugins?.find(
2224
- (plugin) => plugin.id === "organization",
2225
- );
2226
- if (isOrgPluginEnabled) {
2227
- const isAlreadyMember = await ctx.context.adapter.findOne({
2228
- model: "member",
2229
- where: [
2230
- { field: "organizationId", value: provider.organizationId },
2231
- { field: "userId", value: user.id },
2232
- ],
2233
- });
2234
- if (!isAlreadyMember) {
2235
- const role = options?.organizationProvisioning?.getRole
2236
- ? await options.organizationProvisioning.getRole({
2237
- user,
2238
- userInfo,
2239
- provider,
2240
- })
2241
- : options?.organizationProvisioning?.defaultRole || "member";
2242
- await ctx.context.adapter.create({
2243
- model: "member",
2244
- data: {
2245
- organizationId: provider.organizationId,
2246
- userId: user.id,
2247
- role,
2248
- createdAt: new Date(),
2249
- updatedAt: new Date(),
2250
- },
2251
- });
2252
- }
2253
- }
2254
- }
2255
-
2256
- let session: Session =
2257
- await ctx.context.internalAdapter.createSession(user.id);
2258
- await setSessionCookie(ctx, { session, user });
2259
-
2260
- const callbackUrl =
2261
- RelayState || parsedSamlConfig.callbackUrl || ctx.context.baseURL;
2262
- throw ctx.redirect(callbackUrl);
2263
- },
2264
- ),
48
+ spMetadata: spMetadata(),
49
+ registerSSOProvider: registerSSOProvider(options),
50
+ signInSSO: signInSSO(options),
51
+ callbackSSO: callbackSSO(options),
52
+ callbackSSOSAML: callbackSSOSAML(options),
53
+ acsEndpoint: acsEndpoint(options),
2265
54
  },
2266
55
  schema: {
2267
56
  ssoProvider: {
@@ -2302,4 +91,4 @@ export const sso = (options?: SSOOptions | undefined) => {
2302
91
  },
2303
92
  },
2304
93
  } satisfies BetterAuthPlugin;
2305
- };
94
+ }