@better-auth/sso 1.4.0-beta.9 → 1.4.0

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